title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
How to Hide API and Secret Keys in Android Studio? - GeeksforGeeks
|
15 May, 2021
API (Application Programming Interface) is a set of codes that helps in propagating information from one software or an application to the other. Tech companies create their software and APIs, which can be used to build new applications and features by their employees, making them private to use. However, some companies lease their APIs to third parties (can be other companies, developers, contributors) to implement features from their software in their projects, at some minimal cost and restricted use. So if you purchase or lease an API from a company, the company will provide you with an API key, which you must declare in your project to validate the API permission and access the features.
So it becomes crucial to hide API keys while using them to build applications as you have purchased or leased them. There are several ways of wrapping them within the application. We want to share with you an ethical way to secure your API key while building applications in Android Studio through this article. Refer to the flowchart below and try understanding the approach.
Approach
To hide a key, follow the steps below:
Step 1: Create a New Project in Android Studio
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project.
Step 2: Go to the .gitignore file in the projects in the menu
In the left top corner of the Android Studio IDE, you will find a menu where you can view the same project in different views. Click it and select the project option.
Select the Project option in the menu
In the project option, you will find the Gradle folder in which you need to open the .gitignore file.
Click on the .gitignore file to open it
Step 3: Check if local.properties is listed in the .gitignore file
In the .gitignore file, check if local.properties is listed. .gitignore will ignore every file listed in it during the build.
Step 4: Go to local.properties file in the gradle folder and declare the API/Secret key
In the same gradle folder, you will find the local.properties file. Open it and declare the key as shown.
Step 5: Go to build.gradle in the app > src folder and append the following Google plugin
Now go to the build.gradle file and add the below plugin in the plugins as shown.
plugins {
id 'com.google.secrets_gradle_plugin' version '0.4'
}
After adding the plugin, click on the Sync Now option.
Step 6: Go to AndroidManifest.xml and create a meta-data
Now go to the AndroidManifest.xml file and declare a meta-data. Meta-data must be declared between the activity and application finishing tags.
XML
<application> . . . . <activity> . . . . </activity> <meta-data android:name = "keyValue" android:value = "${KEY}"/> </application>
Step 7: Go to MainActivity.kt and type in the below code to get the KEY value from the meta-data in AndroidManifest.xml
Add the following code in the main program to call the key. To check if the key is fetched, we will generate a toast displaying the key value.
Kotlin
XML
package com.geeksforgeeks.hidingapikeysandroid import android.content.pm.ApplicationInfoimport android.content.pm.PackageManagerimport android.os.Bundleimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val ai: ApplicationInfo = applicationContext.packageManager .getApplicationInfo(applicationContext.packageName, PackageManager.GET_META_DATA) val value = ai.metaData["keyValue"] val key = value.toString() Toast.makeText(applicationContext,key,Toast.LENGTH_LONG).show() }}
<!--There's nothing to change in the front-end--><?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="GeeksforGeeks" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout>
Output:
Screenshot when the program runs
We are able to see a Toast with the same key value. This means everything worked fine and we could successfully fetch the key. Now we can use the key validating the API and implement its features.
Android-Studio
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Create and Add Data to SQLite Database in Android?
Broadcast Receiver in Android With Example
Resource Raw Folder in Android Studio
CardView in Android With Example
Services in Android with Example
Broadcast Receiver in Android With Example
Android UI Layouts
Services in Android with Example
Android RecyclerView in Kotlin
Content Providers in Android with Example
|
[
{
"code": null,
"e": 26481,
"s": 26453,
"text": "\n15 May, 2021"
},
{
"code": null,
"e": 27182,
"s": 26481,
"text": "API (Application Programming Interface) is a set of codes that helps in propagating information from one software or an application to the other. Tech companies create their software and APIs, which can be used to build new applications and features by their employees, making them private to use. However, some companies lease their APIs to third parties (can be other companies, developers, contributors) to implement features from their software in their projects, at some minimal cost and restricted use. So if you purchase or lease an API from a company, the company will provide you with an API key, which you must declare in your project to validate the API permission and access the features."
},
{
"code": null,
"e": 27559,
"s": 27182,
"text": "So it becomes crucial to hide API keys while using them to build applications as you have purchased or leased them. There are several ways of wrapping them within the application. We want to share with you an ethical way to secure your API key while building applications in Android Studio through this article. Refer to the flowchart below and try understanding the approach."
},
{
"code": null,
"e": 27568,
"s": 27559,
"text": "Approach"
},
{
"code": null,
"e": 27607,
"s": 27568,
"text": "To hide a key, follow the steps below:"
},
{
"code": null,
"e": 27654,
"s": 27607,
"text": "Step 1: Create a New Project in Android Studio"
},
{
"code": null,
"e": 27893,
"s": 27654,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project."
},
{
"code": null,
"e": 27955,
"s": 27893,
"text": "Step 2: Go to the .gitignore file in the projects in the menu"
},
{
"code": null,
"e": 28122,
"s": 27955,
"text": "In the left top corner of the Android Studio IDE, you will find a menu where you can view the same project in different views. Click it and select the project option."
},
{
"code": null,
"e": 28160,
"s": 28122,
"text": "Select the Project option in the menu"
},
{
"code": null,
"e": 28262,
"s": 28160,
"text": "In the project option, you will find the Gradle folder in which you need to open the .gitignore file."
},
{
"code": null,
"e": 28302,
"s": 28262,
"text": "Click on the .gitignore file to open it"
},
{
"code": null,
"e": 28369,
"s": 28302,
"text": "Step 3: Check if local.properties is listed in the .gitignore file"
},
{
"code": null,
"e": 28495,
"s": 28369,
"text": "In the .gitignore file, check if local.properties is listed. .gitignore will ignore every file listed in it during the build."
},
{
"code": null,
"e": 28584,
"s": 28495,
"text": "Step 4: Go to local.properties file in the gradle folder and declare the API/Secret key"
},
{
"code": null,
"e": 28690,
"s": 28584,
"text": "In the same gradle folder, you will find the local.properties file. Open it and declare the key as shown."
},
{
"code": null,
"e": 28781,
"s": 28690,
"text": "Step 5: Go to build.gradle in the app > src folder and append the following Google plugin"
},
{
"code": null,
"e": 28863,
"s": 28781,
"text": "Now go to the build.gradle file and add the below plugin in the plugins as shown."
},
{
"code": null,
"e": 28931,
"s": 28863,
"text": "plugins {\n id 'com.google.secrets_gradle_plugin' version '0.4'\n}"
},
{
"code": null,
"e": 28986,
"s": 28931,
"text": "After adding the plugin, click on the Sync Now option."
},
{
"code": null,
"e": 29043,
"s": 28986,
"text": "Step 6: Go to AndroidManifest.xml and create a meta-data"
},
{
"code": null,
"e": 29187,
"s": 29043,
"text": "Now go to the AndroidManifest.xml file and declare a meta-data. Meta-data must be declared between the activity and application finishing tags."
},
{
"code": null,
"e": 29191,
"s": 29187,
"text": "XML"
},
{
"code": "<application> . . . . <activity> . . . . </activity> <meta-data android:name = \"keyValue\" android:value = \"${KEY}\"/> </application>",
"e": 29441,
"s": 29191,
"text": null
},
{
"code": null,
"e": 29562,
"s": 29441,
"text": "Step 7: Go to MainActivity.kt and type in the below code to get the KEY value from the meta-data in AndroidManifest.xml"
},
{
"code": null,
"e": 29705,
"s": 29562,
"text": "Add the following code in the main program to call the key. To check if the key is fetched, we will generate a toast displaying the key value."
},
{
"code": null,
"e": 29712,
"s": 29705,
"text": "Kotlin"
},
{
"code": null,
"e": 29716,
"s": 29712,
"text": "XML"
},
{
"code": "package com.geeksforgeeks.hidingapikeysandroid import android.content.pm.ApplicationInfoimport android.content.pm.PackageManagerimport android.os.Bundleimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val ai: ApplicationInfo = applicationContext.packageManager .getApplicationInfo(applicationContext.packageName, PackageManager.GET_META_DATA) val value = ai.metaData[\"keyValue\"] val key = value.toString() Toast.makeText(applicationContext,key,Toast.LENGTH_LONG).show() }}",
"e": 30452,
"s": 29716,
"text": null
},
{
"code": "<!--There's nothing to change in the front-end--><?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"GeeksforGeeks\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintLeft_toLeftOf=\"parent\" app:layout_constraintRight_toRightOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> </androidx.constraintlayout.widget.ConstraintLayout>",
"e": 31274,
"s": 30452,
"text": null
},
{
"code": null,
"e": 31282,
"s": 31274,
"text": "Output:"
},
{
"code": null,
"e": 31315,
"s": 31282,
"text": "Screenshot when the program runs"
},
{
"code": null,
"e": 31512,
"s": 31315,
"text": "We are able to see a Toast with the same key value. This means everything worked fine and we could successfully fetch the key. Now we can use the key validating the API and implement its features."
},
{
"code": null,
"e": 31527,
"s": 31512,
"text": "Android-Studio"
},
{
"code": null,
"e": 31535,
"s": 31527,
"text": "Android"
},
{
"code": null,
"e": 31542,
"s": 31535,
"text": "Kotlin"
},
{
"code": null,
"e": 31550,
"s": 31542,
"text": "Android"
},
{
"code": null,
"e": 31648,
"s": 31550,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31706,
"s": 31648,
"text": "How to Create and Add Data to SQLite Database in Android?"
},
{
"code": null,
"e": 31749,
"s": 31706,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 31787,
"s": 31749,
"text": "Resource Raw Folder in Android Studio"
},
{
"code": null,
"e": 31820,
"s": 31787,
"text": "CardView in Android With Example"
},
{
"code": null,
"e": 31853,
"s": 31820,
"text": "Services in Android with Example"
},
{
"code": null,
"e": 31896,
"s": 31853,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 31915,
"s": 31896,
"text": "Android UI Layouts"
},
{
"code": null,
"e": 31948,
"s": 31915,
"text": "Services in Android with Example"
},
{
"code": null,
"e": 31979,
"s": 31948,
"text": "Android RecyclerView in Kotlin"
}
] |
C++ Program to Perform Left Rotation on a Binary Search Tree
|
A Binary Search Tree is a sorted binary tree in which all the nodes have following two properties −
The right sub-tree of a node has all keys greater than to its parent node's key.
The left sub-tree of a node has all keys less than to its parent node's key. Each node should not have more than two children.
Tree rotation is an operation that changes the structure without interfering with the order of the elements on a binary tree. It moves one node up in the tree and one node down. It is used to change the shape of the tree, and to decrease its height by moving smaller subtrees down and larger subtrees up, resulting in improved performance of many tree operations. The direction of a rotation depends on the side which the tree nodes are shifted upon whilst others say that it depends on which child takes the root’s place. This is a C++ program to perform Left Rotation on a Binary Search Tree.
height(avl *) : It calculate the height of the given AVL tree.
difference(avl *): It calculate the difference between height of sub trees of given tree
avl *rr_rotat(avl *): A right-right rotation is a combination of right rotation followed by right rotation.
avl *ll_rotat(avl *): A left-left rotation is a combination of left rotation followed by left rotation.
avl *lr_rotat(avl*): A left-right rotation is a combination of left rotation followed by right rotation.
avl *rl_rotat(avl *): It is a combination of right rotation followed by left rotation.
avl * balance(avl *): It perform balance operation to the tree by getting balance factor
avl * insert(avl*, int): It perform insert operation. Insert values in the tree using this function.
show(avl*, int): It display the values of the tree.
inorder(avl *): Traverses a tree in an in-order manner.
preorder(avl *): Traverses a tree in a pre-order manner.
postorder(avl*): Traverses a tree in a post-order manner.
#include<iostream>
#include<cstdio>
#include<sstream>
#include<algorithm>
#define pow2(n) (1 << (n))
using namespace std;
struct avl {
int d;
struct avl *l;
struct avl *r;
}*r;
class avl_tree {
public:
int height(avl *);
int difference(avl *);
avl *rr_rotat(avl *);
avl *ll_rotat(avl *);
avl *lr_rotat(avl*);
avl *rl_rotat(avl *);
avl * balance(avl *);
avl * insert(avl*, int);
void show(avl*, int);
void inorder(avl *);
void preorder(avl *);
void postorder(avl*);
avl_tree() {
r = NULL;
}
};
int avl_tree::height(avl *t) {
int h = 0;
if (t != NULL) {
int l_height = height(t->l);
int r_height = height(t->r);
int max_height = max(l_height, r_height);
h = max_height + 1;
}
return h;
}
int avl_tree::difference(avl *t) {
int l_height = height(t->l);
int r_height = height(t->r);
int b_factor = l_height - r_height;
return b_factor;
}
avl *avl_tree::rr_rotat(avl *parent) {
avl *t;
t = parent->r;
parent->r = t->l;
t->l = parent;
cout<<"Right-Right Rotation";
return t;
}
avl *avl_tree::ll_rotat(avl *parent) {
avl *t;
t = parent->l;
parent->l = t->r;
t->r = parent;
cout<<"Left-Left Rotation";
return t;
}
avl *avl_tree::lr_rotat(avl *parent) {
avl *t;
t = parent->l;
parent->l = rr_rotat(t);
cout<<"Left-Right Rotation";
return ll_rotat(parent);
}
avl *avl_tree::rl_rotat(avl *parent) {
avl *t;
t= parent->r;
parent->r = ll_rotat(t);
cout<<"Right-Left Rotation";
return rr_rotat(parent);
}
avl *avl_tree::balance(avl *t) {
int bal_factor = difference(t);
if (bal_factor > 1) {
if (difference(t->l) > 0)
t = ll_rotat(t);
else
t = lr_rotat(t);
}
else if (bal_factor < -1) {
if (difference(t->r) > 0)
t= rl_rotat(t);
else
t = rr_rotat(t);
}
return t;
}
avl *avl_tree::insert(avl *r, int v) {
if (r == NULL) {
r= new avl;
r->d = v;
r->l = NULL;
r->r= NULL;
return r;
}
else if (v< r->d) {
r->l= insert(r->l, v);
r = balance(r);
}
else if (v >= r->d) {
r->r= insert(r->r, v);
r = balance(r);
}
return r;
}
void avl_tree::show(avl *p, int l) {
int i;
if (p != NULL) {
show(p->r, l+ 1);
cout<<" ";
if (p == r)
cout << "Root -> ";
for (i = 0; i < l&& p != r; i++)
cout << " ";
cout << p->d;
show(p->l, l + 1);
}
}
void avl_tree::inorder(avl *t) {
if (t == NULL)
return;
inorder(t->l);
cout << t->d << " ";
inorder(t->r);
}
void avl_tree::preorder(avl *t) {
if (t == NULL)
return;
cout << t->d << " ";
preorder(t->l);
preorder(t->r);
}
void avl_tree::postorder(avl *t) {
if (t == NULL)
return;
postorder(t ->l);
postorder(t ->r);
cout << t->d << " ";
}
int main() {
int c, i;
avl_tree avl;
while (1) {
cout << "1.Insert Element into the tree" << endl;
cout << "2.show Balanced AVL Tree" << endl;
cout << "3.InOrder traversal" << endl;
cout << "4.PreOrder traversal" << endl;
cout << "5.PostOrder traversal" << endl;
cout << "6.Exit" << endl;
cout << "Enter your Choice: ";
cin >> c;
switch (c) {
case 1:
cout << "Enter value to be inserted: ";
cin >> i;
r= avl.insert(r, i);
break;
case 2:
if (r == NULL) {
cout << "Tree is Empty" << endl;
continue;
}
cout << "Balanced AVL Tree:" << endl;
avl.show(r, 1);
cout<<endl;
break;
case 3:
cout << "Inorder Traversal:" << endl;
avl.inorder(r);
cout << endl;
break;
case 4:
cout << "Preorder Traversal:" << endl;
avl.preorder(r);
cout << endl;
break;
case 5:
cout << "Postorder Traversal:" << endl;
avl.postorder(r);
cout << endl;
break;
case 6:
exit(1);
break;
default:
cout << "Wrong Choice" << endl;
}
}
return 0;
}
1.Insert Element into the tree
2.show Balanced AVL Tree
3.InOrder traversal
4.PreOrder traversal
5.PostOrder traversal
6.Exit
Enter your Choice: 1
Enter value to be inserted: 13
1.Insert Element into the tree
2.show Balanced AVL Tree
3.InOrder traversal
4.PreOrder traversal
5.PostOrder traversal
6.Exit
Enter your Choice: 1
Enter value to be inserted: 10
1.Insert Element into the tree
2.show Balanced AVL Tree
3.InOrder traversal
4.PreOrder traversal
5.PostOrder traversal
6.Exit
Enter your Choice: 1
Enter value to be inserted: 15
1.Insert Element into the tree
2.show Balanced AVL Tree
3.InOrder traversal
4.PreOrder traversal
5.PostOrder traversal
6.Exit
Enter your Choice: 1
Enter value to be inserted: 5
1.Insert Element into the tree
2.show Balanced AVL Tree
3.InOrder traversal
4.PreOrder traversal
5.PostOrder traversal
6.Exit
Enter your Choice: 1
Enter value to be inserted: 11
1.Insert Element into the tree
2.show Balanced AVL Tree
3.InOrder traversal
4.PreOrder traversal
5.PostOrder traversal
6.Exit
Enter your Choice: 1
Enter value to be inserted: 4
Left-Left Rotation1.Insert Element into the tree
2.show Balanced AVL Tree
3.InOrder traversal
4.PreOrder traversal
5.PostOrder traversal
6.Exit
Enter your Choice: 1
Enter value to be inserted: 8
1.Insert Element into the tree
2.show Balanced AVL Tree
3.InOrder traversal
4.PreOrder traversal
5.PostOrder traversal
6.Exit
Enter your Choice: 1
Enter value to be inserted: 16
1.Insert Element into the tree
2.show Balanced AVL Tree
3.InOrder traversal
4.PreOrder traversal
5.PostOrder traversal
6.Exit
Enter your Choice: 3
Inorder Traversal:
4 5 8 10 11 13 15 16
1.Insert Element into the tree
2.show Balanced AVL Tree
3.InOrder traversal
4.PreOrder traversal
5.PostOrder traversal
6.Exit
Enter your Choice: 4
Preorder Traversal:
10 5 4 8 13 11 15 16
1.Insert Element into the tree
2.show Balanced AVL Tree
3.InOrder traversal
4.PreOrder traversal
5.PostOrder traversal
6.Exit
Enter your Choice: 5
Postorder Traversal:
4 8 5 11 16 15 13 10
1.Insert Element into the tree
2.show Balanced AVL Tree
3.InOrder traversal
4.PreOrder traversal
5.PostOrder traversal
6.Exit
Enter your Choice: 1
Enter value to be inserted: 14
1.Insert Element into the tree
2.show Balanced AVL Tree
3.InOrder traversal
4.PreOrder traversal
5.PostOrder traversal
6.Exit
Enter your Choice: 1
Enter value to be inserted: 3
1.Insert Element into the tree
2.show Balanced AVL Tree
3.InOrder traversal
4.PreOrder traversal
5.PostOrder traversal
6.Exit
Enter your Choice: 1
Enter value to be inserted: 7
1.Insert Element into the tree
2.show Balanced AVL Tree
3.InOrder traversal
4.PreOrder traversal
5.PostOrder traversal
6.Exit
Enter your Choice: 1
Enter value to be inserted: 9
1.Insert Element into the tree
2.show Balanced AVL Tree
3.InOrder traversal
4.PreOrder traversal
5.PostOrder traversal
6.Exit
Enter your Choice: 1
Enter value to be inserted: 52
Right-Right
1.Insert Element into the tree
2.show Balanced AVL Tree
3.InOrder traversal
4.PreOrder traversal
5.PostOrder traversal
6.Exit
Enter your Choice: 6
|
[
{
"code": null,
"e": 1163,
"s": 1062,
"text": "A Binary Search Tree is a sorted binary tree in which all the nodes have following two properties − "
},
{
"code": null,
"e": 1245,
"s": 1163,
"text": "The right sub-tree of a node has all keys greater than to its parent node's key. "
},
{
"code": null,
"e": 1373,
"s": 1245,
"text": "The left sub-tree of a node has all keys less than to its parent node's key. Each node should not have more than two children. "
},
{
"code": null,
"e": 1968,
"s": 1373,
"text": "Tree rotation is an operation that changes the structure without interfering with the order of the elements on a binary tree. It moves one node up in the tree and one node down. It is used to change the shape of the tree, and to decrease its height by moving smaller subtrees down and larger subtrees up, resulting in improved performance of many tree operations. The direction of a rotation depends on the side which the tree nodes are shifted upon whilst others say that it depends on which child takes the root’s place. This is a C++ program to perform Left Rotation on a Binary Search Tree."
},
{
"code": null,
"e": 2032,
"s": 1968,
"text": "height(avl *) : It calculate the height of the given AVL tree. "
},
{
"code": null,
"e": 2121,
"s": 2032,
"text": "difference(avl *): It calculate the difference between height of sub trees of given tree"
},
{
"code": null,
"e": 2230,
"s": 2121,
"text": " avl *rr_rotat(avl *): A right-right rotation is a combination of right rotation followed by right rotation."
},
{
"code": null,
"e": 2335,
"s": 2230,
"text": "avl *ll_rotat(avl *): A left-left rotation is a combination of left rotation followed by left rotation. "
},
{
"code": null,
"e": 2440,
"s": 2335,
"text": "avl *lr_rotat(avl*): A left-right rotation is a combination of left rotation followed by right rotation."
},
{
"code": null,
"e": 2527,
"s": 2440,
"text": "avl *rl_rotat(avl *): It is a combination of right rotation followed by left rotation."
},
{
"code": null,
"e": 2616,
"s": 2527,
"text": "avl * balance(avl *): It perform balance operation to the tree by getting balance factor"
},
{
"code": null,
"e": 2718,
"s": 2616,
"text": "avl * insert(avl*, int): It perform insert operation. Insert values in the tree using this function. "
},
{
"code": null,
"e": 2771,
"s": 2718,
"text": "show(avl*, int): It display the values of the tree. "
},
{
"code": null,
"e": 2828,
"s": 2771,
"text": "inorder(avl *): Traverses a tree in an in-order manner. "
},
{
"code": null,
"e": 2885,
"s": 2828,
"text": "preorder(avl *): Traverses a tree in a pre-order manner."
},
{
"code": null,
"e": 2943,
"s": 2885,
"text": "postorder(avl*): Traverses a tree in a post-order manner."
},
{
"code": null,
"e": 7235,
"s": 2943,
"text": "#include<iostream>\n#include<cstdio>\n#include<sstream>\n#include<algorithm>\n#define pow2(n) (1 << (n))\nusing namespace std;\nstruct avl {\n int d;\n struct avl *l;\n struct avl *r;\n}*r;\nclass avl_tree {\n public:\n int height(avl *);\n int difference(avl *);\n avl *rr_rotat(avl *);\n avl *ll_rotat(avl *);\n avl *lr_rotat(avl*);\n avl *rl_rotat(avl *);\n avl * balance(avl *);\n avl * insert(avl*, int);\n void show(avl*, int);\n void inorder(avl *);\n void preorder(avl *);\n void postorder(avl*);\n avl_tree() {\n r = NULL;\n }\n};\nint avl_tree::height(avl *t) {\n int h = 0;\n if (t != NULL) {\n int l_height = height(t->l);\n int r_height = height(t->r);\n int max_height = max(l_height, r_height);\n h = max_height + 1;\n }\n return h;\n}\nint avl_tree::difference(avl *t) {\n int l_height = height(t->l);\n int r_height = height(t->r);\n int b_factor = l_height - r_height;\n return b_factor;\n}\navl *avl_tree::rr_rotat(avl *parent) {\n avl *t;\n t = parent->r;\n parent->r = t->l;\n t->l = parent;\n cout<<\"Right-Right Rotation\";\n return t;\n}\navl *avl_tree::ll_rotat(avl *parent) {\n avl *t;\n t = parent->l;\n parent->l = t->r;\n t->r = parent;\n cout<<\"Left-Left Rotation\";\n return t;\n}\navl *avl_tree::lr_rotat(avl *parent) {\n avl *t;\n t = parent->l;\n parent->l = rr_rotat(t);\n cout<<\"Left-Right Rotation\";\n return ll_rotat(parent);\n}\navl *avl_tree::rl_rotat(avl *parent) {\n avl *t;\n t= parent->r;\n parent->r = ll_rotat(t);\n cout<<\"Right-Left Rotation\";\n return rr_rotat(parent);\n}\navl *avl_tree::balance(avl *t) {\n int bal_factor = difference(t);\n if (bal_factor > 1) {\n if (difference(t->l) > 0)\n t = ll_rotat(t);\n else\n t = lr_rotat(t);\n }\n else if (bal_factor < -1) {\n if (difference(t->r) > 0)\n t= rl_rotat(t);\n else\n t = rr_rotat(t);\n }\n return t;\n}\navl *avl_tree::insert(avl *r, int v) {\n if (r == NULL) {\n r= new avl;\n r->d = v;\n r->l = NULL;\n r->r= NULL;\n return r;\n }\n else if (v< r->d) {\n r->l= insert(r->l, v);\n r = balance(r);\n }\n else if (v >= r->d) {\n r->r= insert(r->r, v);\n r = balance(r);\n }\n return r;\n}\nvoid avl_tree::show(avl *p, int l) {\n int i;\n if (p != NULL) {\n show(p->r, l+ 1);\n cout<<\" \";\n if (p == r)\n cout << \"Root -> \";\n for (i = 0; i < l&& p != r; i++)\n cout << \" \";\n cout << p->d;\n show(p->l, l + 1);\n }\n}\nvoid avl_tree::inorder(avl *t) {\n if (t == NULL)\n return;\n inorder(t->l);\n cout << t->d << \" \";\n inorder(t->r);\n}\nvoid avl_tree::preorder(avl *t) {\n if (t == NULL)\n return;\n cout << t->d << \" \";\n preorder(t->l);\n preorder(t->r);\n}\nvoid avl_tree::postorder(avl *t) {\n if (t == NULL)\n return;\n postorder(t ->l);\n postorder(t ->r);\n cout << t->d << \" \";\n}\nint main() {\n int c, i;\n avl_tree avl;\n while (1) {\n cout << \"1.Insert Element into the tree\" << endl;\n cout << \"2.show Balanced AVL Tree\" << endl;\n cout << \"3.InOrder traversal\" << endl;\n cout << \"4.PreOrder traversal\" << endl;\n cout << \"5.PostOrder traversal\" << endl;\n cout << \"6.Exit\" << endl;\n cout << \"Enter your Choice: \";\n cin >> c;\n switch (c) {\n case 1:\n cout << \"Enter value to be inserted: \";\n cin >> i;\n r= avl.insert(r, i);\n break;\n case 2:\n if (r == NULL) {\n cout << \"Tree is Empty\" << endl;\n continue;\n }\n cout << \"Balanced AVL Tree:\" << endl;\n avl.show(r, 1);\n cout<<endl;\n break;\n case 3:\n cout << \"Inorder Traversal:\" << endl;\n avl.inorder(r);\n cout << endl;\n break;\n case 4:\n cout << \"Preorder Traversal:\" << endl;\n avl.preorder(r);\n cout << endl;\n break;\n case 5:\n cout << \"Postorder Traversal:\" << endl;\n avl.postorder(r);\n cout << endl;\n break;\n case 6:\n exit(1);\n break;\n default:\n cout << \"Wrong Choice\" << endl;\n }\n }\n return 0;\n}"
},
{
"code": null,
"e": 10284,
"s": 7235,
"text": "1.Insert Element into the tree\n2.show Balanced AVL Tree\n3.InOrder traversal\n4.PreOrder traversal\n5.PostOrder traversal\n6.Exit\nEnter your Choice: 1\nEnter value to be inserted: 13\n1.Insert Element into the tree\n2.show Balanced AVL Tree\n3.InOrder traversal\n4.PreOrder traversal\n5.PostOrder traversal\n6.Exit\nEnter your Choice: 1\nEnter value to be inserted: 10\n1.Insert Element into the tree\n2.show Balanced AVL Tree\n3.InOrder traversal\n4.PreOrder traversal\n5.PostOrder traversal\n6.Exit\nEnter your Choice: 1\nEnter value to be inserted: 15\n1.Insert Element into the tree\n2.show Balanced AVL Tree\n3.InOrder traversal\n4.PreOrder traversal\n5.PostOrder traversal\n6.Exit\nEnter your Choice: 1\nEnter value to be inserted: 5\n1.Insert Element into the tree\n2.show Balanced AVL Tree\n3.InOrder traversal\n4.PreOrder traversal\n5.PostOrder traversal\n6.Exit\nEnter your Choice: 1\nEnter value to be inserted: 11\n1.Insert Element into the tree\n2.show Balanced AVL Tree\n3.InOrder traversal\n4.PreOrder traversal\n5.PostOrder traversal\n6.Exit\nEnter your Choice: 1\nEnter value to be inserted: 4\nLeft-Left Rotation1.Insert Element into the tree\n2.show Balanced AVL Tree\n3.InOrder traversal\n4.PreOrder traversal\n5.PostOrder traversal\n6.Exit\nEnter your Choice: 1\nEnter value to be inserted: 8\n1.Insert Element into the tree\n2.show Balanced AVL Tree\n3.InOrder traversal\n4.PreOrder traversal\n5.PostOrder traversal\n6.Exit\nEnter your Choice: 1\nEnter value to be inserted: 16\n1.Insert Element into the tree\n2.show Balanced AVL Tree\n3.InOrder traversal\n4.PreOrder traversal\n5.PostOrder traversal\n6.Exit\nEnter your Choice: 3\nInorder Traversal:\n4 5 8 10 11 13 15 16\n1.Insert Element into the tree\n2.show Balanced AVL Tree\n3.InOrder traversal\n4.PreOrder traversal\n5.PostOrder traversal\n6.Exit\nEnter your Choice: 4\nPreorder Traversal:\n10 5 4 8 13 11 15 16\n1.Insert Element into the tree\n2.show Balanced AVL Tree\n3.InOrder traversal\n4.PreOrder traversal\n5.PostOrder traversal\n6.Exit\nEnter your Choice: 5\nPostorder Traversal:\n4 8 5 11 16 15 13 10\n1.Insert Element into the tree\n2.show Balanced AVL Tree\n3.InOrder traversal\n4.PreOrder traversal\n5.PostOrder traversal\n6.Exit\nEnter your Choice: 1\nEnter value to be inserted: 14\n1.Insert Element into the tree\n2.show Balanced AVL Tree\n3.InOrder traversal\n4.PreOrder traversal\n5.PostOrder traversal\n6.Exit\nEnter your Choice: 1\nEnter value to be inserted: 3\n1.Insert Element into the tree\n2.show Balanced AVL Tree\n3.InOrder traversal\n4.PreOrder traversal\n5.PostOrder traversal\n6.Exit\nEnter your Choice: 1\nEnter value to be inserted: 7\n1.Insert Element into the tree\n2.show Balanced AVL Tree\n3.InOrder traversal\n4.PreOrder traversal\n5.PostOrder traversal\n6.Exit\nEnter your Choice: 1\nEnter value to be inserted: 9\n1.Insert Element into the tree\n2.show Balanced AVL Tree\n3.InOrder traversal\n4.PreOrder traversal\n5.PostOrder traversal\n6.Exit\nEnter your Choice: 1\nEnter value to be inserted: 52\nRight-Right\n1.Insert Element into the tree\n2.show Balanced AVL Tree\n3.InOrder traversal\n4.PreOrder traversal\n5.PostOrder traversal\n6.Exit\nEnter your Choice: 6"
}
] |
Java Examples - String Reverse
|
How to reverse a String?
Following example shows how to reverse a String after taking it from command line argument .The program buffers the input String using StringBuffer(String string) method, reverse the buffer and then converts the buffer into a String with the help of toString() method.
public class StringReverseExample{
public static void main(String[] args) {
String string = "abcdef";
String reverse = new StringBuffer(string).reverse().toString();
System.out.println("\nString before reverse: "+string);
System.out.println("String after reverse: "+reverse);
}
}
The above code sample will produce the following result.
String before reverse:abcdef
String after reverse:fedcba
Following another example shows how to reverse a String after taking it from command line argument
import java.io.*;
import java.util.*;
public class HelloWorld {
public static void main(String[] args) {
String input = "tutorialspoint";
char[] try1 = input.toCharArray();
for (int i = try1.length-1;i >= 0; i--) System.out.print(try1[i]);
}
}
The above code sample will produce the following result.
tniopslairotut
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2093,
"s": 2068,
"text": "How to reverse a String?"
},
{
"code": null,
"e": 2362,
"s": 2093,
"text": "Following example shows how to reverse a String after taking it from command line argument .The program buffers the input String using StringBuffer(String string) method, reverse the buffer and then converts the buffer into a String with the help of toString() method."
},
{
"code": null,
"e": 2672,
"s": 2362,
"text": "public class StringReverseExample{\n public static void main(String[] args) {\n String string = \"abcdef\";\n String reverse = new StringBuffer(string).reverse().toString();\n System.out.println(\"\\nString before reverse: \"+string);\n System.out.println(\"String after reverse: \"+reverse);\n }\n}"
},
{
"code": null,
"e": 2729,
"s": 2672,
"text": "The above code sample will produce the following result."
},
{
"code": null,
"e": 2787,
"s": 2729,
"text": "String before reverse:abcdef\nString after reverse:fedcba\n"
},
{
"code": null,
"e": 2886,
"s": 2787,
"text": "Following another example shows how to reverse a String after taking it from command line argument"
},
{
"code": null,
"e": 3155,
"s": 2886,
"text": "import java.io.*;\nimport java.util.*;\n\npublic class HelloWorld {\n public static void main(String[] args) {\n String input = \"tutorialspoint\";\n char[] try1 = input.toCharArray();\n for (int i = try1.length-1;i >= 0; i--) System.out.print(try1[i]);\n }\n}"
},
{
"code": null,
"e": 3212,
"s": 3155,
"text": "The above code sample will produce the following result."
},
{
"code": null,
"e": 3229,
"s": 3212,
"text": "tniopslairotut \n"
},
{
"code": null,
"e": 3236,
"s": 3229,
"text": " Print"
},
{
"code": null,
"e": 3247,
"s": 3236,
"text": " Add Notes"
}
] |
AtomicInteger updateAndGet() method in Java with Examples - GeeksforGeeks
|
17 Jun, 2019
The Java.AtomicInteger.updateAndGet() method is an inbuilt method, which updates the current value of the object by applying the specified operation on the current value. It takes an object of IntUnaryOperator interface as its parameter and applies the operation specified in the object to the current value. It returns the updated value.
Syntax:
public final int updateAndGet(IntUnaryOperator function)
Parameters: This method accepts as parameter an IntUnaryOperator function.It applies the given function to the current value of the object.
Return Value: The function returns the updated value of the current object.
Example to demonstrate the function.
Program 1:
// Java program to demonstrate the above function import java.util.concurrent.atomic.AtomicInteger;import java.util.function.IntUnaryOperator; public class Demo { public static void main(String[] args) { // Atomic Integer initialized with a value of 10 AtomicInteger ai = new AtomicInteger(10); // Unary operator defined to negate the value IntUnaryOperator unaryOperator = (x) -> - x; System.out.println("Initial Value is " + ai); // Function called and the unary operator // is passed as an argument int x = ai.updateAndGet(unaryOperator); System.out.println("Updated value is " + x); }}
Initial Value is 10
Updated value is -10
Reference: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicInteger.html
Java-AtomicInteger
Java-Functions
Java-util-concurrent-atomic package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Initialize an ArrayList in Java
HashMap in Java with Examples
Object Oriented Programming (OOPs) Concept in Java
ArrayList in Java
How to iterate any Map in Java
Multidimensional Arrays in Java
LinkedList in Java
Stack Class in Java
Overriding in Java
Set in Java
|
[
{
"code": null,
"e": 24506,
"s": 24478,
"text": "\n17 Jun, 2019"
},
{
"code": null,
"e": 24845,
"s": 24506,
"text": "The Java.AtomicInteger.updateAndGet() method is an inbuilt method, which updates the current value of the object by applying the specified operation on the current value. It takes an object of IntUnaryOperator interface as its parameter and applies the operation specified in the object to the current value. It returns the updated value."
},
{
"code": null,
"e": 24853,
"s": 24845,
"text": "Syntax:"
},
{
"code": null,
"e": 24911,
"s": 24853,
"text": "public final int updateAndGet(IntUnaryOperator function)\n"
},
{
"code": null,
"e": 25051,
"s": 24911,
"text": "Parameters: This method accepts as parameter an IntUnaryOperator function.It applies the given function to the current value of the object."
},
{
"code": null,
"e": 25127,
"s": 25051,
"text": "Return Value: The function returns the updated value of the current object."
},
{
"code": null,
"e": 25164,
"s": 25127,
"text": "Example to demonstrate the function."
},
{
"code": null,
"e": 25175,
"s": 25164,
"text": "Program 1:"
},
{
"code": "// Java program to demonstrate the above function import java.util.concurrent.atomic.AtomicInteger;import java.util.function.IntUnaryOperator; public class Demo { public static void main(String[] args) { // Atomic Integer initialized with a value of 10 AtomicInteger ai = new AtomicInteger(10); // Unary operator defined to negate the value IntUnaryOperator unaryOperator = (x) -> - x; System.out.println(\"Initial Value is \" + ai); // Function called and the unary operator // is passed as an argument int x = ai.updateAndGet(unaryOperator); System.out.println(\"Updated value is \" + x); }}",
"e": 25847,
"s": 25175,
"text": null
},
{
"code": null,
"e": 25889,
"s": 25847,
"text": "Initial Value is 10\nUpdated value is -10\n"
},
{
"code": null,
"e": 25989,
"s": 25889,
"text": "Reference: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicInteger.html"
},
{
"code": null,
"e": 26008,
"s": 25989,
"text": "Java-AtomicInteger"
},
{
"code": null,
"e": 26023,
"s": 26008,
"text": "Java-Functions"
},
{
"code": null,
"e": 26059,
"s": 26023,
"text": "Java-util-concurrent-atomic package"
},
{
"code": null,
"e": 26064,
"s": 26059,
"text": "Java"
},
{
"code": null,
"e": 26069,
"s": 26064,
"text": "Java"
},
{
"code": null,
"e": 26167,
"s": 26069,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26176,
"s": 26167,
"text": "Comments"
},
{
"code": null,
"e": 26189,
"s": 26176,
"text": "Old Comments"
},
{
"code": null,
"e": 26221,
"s": 26189,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 26251,
"s": 26221,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 26302,
"s": 26251,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 26320,
"s": 26302,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 26351,
"s": 26320,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 26383,
"s": 26351,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 26402,
"s": 26383,
"text": "LinkedList in Java"
},
{
"code": null,
"e": 26422,
"s": 26402,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 26441,
"s": 26422,
"text": "Overriding in Java"
}
] |
How can we extract a substring from the value of a column in MySQL table?
|
We can apply any of the functions like SUBSTRING(), MID() or SUBSTR() to extract a substring from the value of a column. In this case, we must have to provide the name of the column as the first argument of the function i.e. at the place of string we have to give the name of the column. Following example will demonstrate it.
Suppose we want to extract a substring from the ‘Name’ column of ‘Student’ table then it can be done by using the different functions as follows −
mysql> Select name, SUBSTR(name,2,4) from student;
+---------+------------------+
| name | SUBSTR(name,2,4) |
+---------+------------------+
| Gaurav | aura |
| Aarav | arav |
| Harshit | arsh |
| Gaurav | aura |
| Yashraj | ashr |
+---------+------------------+
5 rows in set (0.00 sec)
mysql> Select name, MID(name,2,4) from student;
+---------+---------------+
| name | MID(name,2,4) |
+---------+---------------+
| Gaurav | aura |
| Aarav | arav |
| Harshit | arsh |
| Gaurav | aura |
| Yashraj | ashr |
+---------+---------------+
5 rows in set (0.00 sec)
mysql> Select name, substring(name,2,4) from student;
+---------+---------------------+
| name | substring(name,2,4) |
+---------+---------------------+
| Gaurav | aura |
| Aarav | arav |
| Harshit | arsh |
| Gaurav | aura |
| Yashraj | ashr |
+---------+---------------------+
5 rows in set (0.00 sec)
We can also apply condition/s in the above queries as follows −
mysql> Select name, substring(name,2,4) from student WHERE address = 'delhi';
+---------+---------------------+
| name | substring(name,2,4) |
+---------+---------------------+
| Gaurav | aura |
| Harshit | arsh |
+---------+---------------------+
2 rows in set (0.16 sec)
mysql> Select name, MID(name,2,4) from student WHERE address = 'delhi';
+---------+---------------+
| name | MID(name,2,4) |
+---------+---------------+
| Gaurav | aura |
| Harshit | arsh |
+---------+---------------+
2 rows in set (0.00 sec)
mysql> Select name, SUBSTR(name,2,4) from student WHERE address = 'delhi';
+---------+------------------+
| name | SUBSTR(name,2,4) |
+---------+------------------+
| Gaurav | aura |
| Harshit | arsh |
+---------+------------------+
2 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1389,
"s": 1062,
"text": "We can apply any of the functions like SUBSTRING(), MID() or SUBSTR() to extract a substring from the value of a column. In this case, we must have to provide the name of the column as the first argument of the function i.e. at the place of string we have to give the name of the column. Following example will demonstrate it."
},
{
"code": null,
"e": 1536,
"s": 1389,
"text": "Suppose we want to extract a substring from the ‘Name’ column of ‘Student’ table then it can be done by using the different functions as follows −"
},
{
"code": null,
"e": 2603,
"s": 1536,
"text": "mysql> Select name, SUBSTR(name,2,4) from student;\n+---------+------------------+\n| name | SUBSTR(name,2,4) |\n+---------+------------------+\n| Gaurav | aura |\n| Aarav | arav |\n| Harshit | arsh |\n| Gaurav | aura |\n| Yashraj | ashr |\n+---------+------------------+\n5 rows in set (0.00 sec)\n\nmysql> Select name, MID(name,2,4) from student;\n+---------+---------------+\n| name | MID(name,2,4) |\n+---------+---------------+\n| Gaurav | aura |\n| Aarav | arav |\n| Harshit | arsh |\n| Gaurav | aura |\n| Yashraj | ashr |\n+---------+---------------+\n5 rows in set (0.00 sec)\n\nmysql> Select name, substring(name,2,4) from student;\n+---------+---------------------+\n| name | substring(name,2,4) |\n+---------+---------------------+\n| Gaurav | aura |\n| Aarav | arav |\n| Harshit | arsh |\n| Gaurav | aura |\n| Yashraj | ashr |\n+---------+---------------------+\n5 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2667,
"s": 2603,
"text": "We can also apply condition/s in the above queries as follows −"
},
{
"code": null,
"e": 3527,
"s": 2667,
"text": "mysql> Select name, substring(name,2,4) from student WHERE address = 'delhi';\n+---------+---------------------+\n| name | substring(name,2,4) |\n+---------+---------------------+\n| Gaurav | aura |\n| Harshit | arsh |\n+---------+---------------------+\n2 rows in set (0.16 sec)\n\nmysql> Select name, MID(name,2,4) from student WHERE address = 'delhi';\n+---------+---------------+\n| name | MID(name,2,4) |\n+---------+---------------+\n| Gaurav | aura |\n| Harshit | arsh |\n+---------+---------------+\n2 rows in set (0.00 sec)\n\nmysql> Select name, SUBSTR(name,2,4) from student WHERE address = 'delhi';\n+---------+------------------+\n| name | SUBSTR(name,2,4) |\n+---------+------------------+\n| Gaurav | aura |\n| Harshit | arsh |\n+---------+------------------+\n2 rows in set (0.00 sec)"
}
] |
Relational Set Operators in DBMS
|
DBMS supports relational set operators as well. The major relational set operators are union, intersection and set difference. All of these can be implemented in DBMS using different queries.
The relational set operators in detail using given example are as follows as follows −
Union combines two different results obtained by a query into a single result in the form of a table. However, the results should be similar if union is to be applied on them. Union removes all duplicates, if any from the data and only displays distinct values. If duplicate values are required in the resultant data, then UNION ALL is used.
An example of union is −
Select Student_Name from Art_Students
UNION
Select Student_Name from Dance_Students
This will display the names of all the students in the table Art_Students and Dance_Students i.e John, Mary, Damon and Matt.
The intersection operator gives the common data values between the two data sets that are intersected. The two data sets that are intersected should be similar for the intersection operator to work. Intersection also removes all duplicates before displaying the result.
An example of intersection is −
Select Student_Name from Art_Students
INTERSECT
Select Student_Name from Dance_Students
This will display the names of the students in the table Art_Students and in the table Dance_Students i.e all the students that have taken both art and dance classes .Those are Mary and Damon in this example.
The set difference operators takes the two sets and returns the values that are in the first set but not the second set.
An example of set difference is −
Select Student_Name from Art_Students
MINUS
Select Student_Name from Dance_Students
This will display the names of all the students in table Art_Students but not in table Dance_Students i.e the students who are taking art classes but not dance classes.
That is John in this example.
|
[
{
"code": null,
"e": 1254,
"s": 1062,
"text": "DBMS supports relational set operators as well. The major relational set operators are union, intersection and set difference. All of these can be implemented in DBMS using different queries."
},
{
"code": null,
"e": 1341,
"s": 1254,
"text": "The relational set operators in detail using given example are as follows as follows −"
},
{
"code": null,
"e": 1683,
"s": 1341,
"text": "Union combines two different results obtained by a query into a single result in the form of a table. However, the results should be similar if union is to be applied on them. Union removes all duplicates, if any from the data and only displays distinct values. If duplicate values are required in the resultant data, then UNION ALL is used."
},
{
"code": null,
"e": 1708,
"s": 1683,
"text": "An example of union is −"
},
{
"code": null,
"e": 1792,
"s": 1708,
"text": "Select Student_Name from Art_Students\nUNION\nSelect Student_Name from Dance_Students"
},
{
"code": null,
"e": 1917,
"s": 1792,
"text": "This will display the names of all the students in the table Art_Students and Dance_Students i.e John, Mary, Damon and Matt."
},
{
"code": null,
"e": 2187,
"s": 1917,
"text": "The intersection operator gives the common data values between the two data sets that are intersected. The two data sets that are intersected should be similar for the intersection operator to work. Intersection also removes all duplicates before displaying the result."
},
{
"code": null,
"e": 2219,
"s": 2187,
"text": "An example of intersection is −"
},
{
"code": null,
"e": 2307,
"s": 2219,
"text": "Select Student_Name from Art_Students\nINTERSECT\nSelect Student_Name from Dance_Students"
},
{
"code": null,
"e": 2516,
"s": 2307,
"text": "This will display the names of the students in the table Art_Students and in the table Dance_Students i.e all the students that have taken both art and dance classes .Those are Mary and Damon in this example."
},
{
"code": null,
"e": 2637,
"s": 2516,
"text": "The set difference operators takes the two sets and returns the values that are in the first set but not the second set."
},
{
"code": null,
"e": 2671,
"s": 2637,
"text": "An example of set difference is −"
},
{
"code": null,
"e": 2755,
"s": 2671,
"text": "Select Student_Name from Art_Students\nMINUS\nSelect Student_Name from Dance_Students"
},
{
"code": null,
"e": 2924,
"s": 2755,
"text": "This will display the names of all the students in table Art_Students but not in table Dance_Students i.e the students who are taking art classes but not dance classes."
},
{
"code": null,
"e": 2954,
"s": 2924,
"text": "That is John in this example."
}
] |
How to set the Location of the Button in C#? - GeeksforGeeks
|
26 Jun, 2019
A Button is an essential part of an application, or software, or webpage. It allows the user to interact with the application or software. In windows form, you are allowed to set the location of the button in your forms by using Location Property. It is provided by Button class and it helps us to set the coordinates of the upper-left corner of the Button control relative to the upper-left corner of its form. You can use this property in two different methods:
1. Design-Time: It is the easiest method to set the location of the button. Using the following steps:
Step 1: Create a windows form a shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp
Step 2: Drag the Button control from the ToolBox and drop it on the windows form. You are allowed to place a Button control anywhere on the windows form according to your need.
Step 3: After drag and drop you will go to the properties of the Button control to set the Location property of the Button.Output:
Output:
2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the Location property of the Button programmatically with the help of given syntax:
public System.Drawing.Point Location { get; set; }
Here, the Point is used to represent the upper-left corner of the button relative to the upper-left corner of its container or form. Following steps are used to set the Location property of the Button:
Step 1: Create a button using the Button() constructor is provided by the Button class.// Creating Button using Button class
Button MyButton = new Button();
// Creating Button using Button class
Button MyButton = new Button();
Step 2: After creating Button, set the Location property of the Button provided by the Button class.// Set the location of the button
Mybutton.Location = new Point(225, 198);
// Set the location of the button
Mybutton.Location = new Point(225, 198);
Step 3: And last add this button control to from using Add() method.// Add this Button to form
this.Controls.Add(Mybutton);
Example:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp8 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of label Label l = new Label(); l.AutoSize = true; l.Text = "Do you want to submit this form?"; l.Location = new Point(222, 145); // Adding this label to form this.Controls.Add(l); // Creating and setting the properties of Button Button Mybutton = new Button(); Mybutton.Location = new Point(225, 198); Mybutton.Text = "Submit"; Mybutton.AutoSize = true; Mybutton.BackColor = Color.LightBlue; // Adding this button to form this.Controls.Add(Mybutton); // Creating and setting the properties of Button Button Mybutton1 = new Button(); Mybutton1.Location = new Point(438, 198); Mybutton1.Text = "Cancel"; Mybutton1.AutoSize = true; Mybutton1.BackColor = Color.LightPink; // Adding this button to form this.Controls.Add(Mybutton1); }}}Output:
// Add this Button to form
this.Controls.Add(Mybutton);
Example:
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp8 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of label Label l = new Label(); l.AutoSize = true; l.Text = "Do you want to submit this form?"; l.Location = new Point(222, 145); // Adding this label to form this.Controls.Add(l); // Creating and setting the properties of Button Button Mybutton = new Button(); Mybutton.Location = new Point(225, 198); Mybutton.Text = "Submit"; Mybutton.AutoSize = true; Mybutton.BackColor = Color.LightBlue; // Adding this button to form this.Controls.Add(Mybutton); // Creating and setting the properties of Button Button Mybutton1 = new Button(); Mybutton1.Location = new Point(438, 198); Mybutton1.Text = "Cancel"; Mybutton1.AutoSize = true; Mybutton1.BackColor = Color.LightPink; // Adding this button to form this.Controls.Add(Mybutton1); }}}
Output:
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C# Dictionary with examples
C# | Method Overriding
Extension Method in C#
Difference between Ref and Out keywords in C#
C# | Delegates
Introduction to .NET Framework
Top 50 C# Interview Questions & Answers
Partial Classes in C#
Basic CRUD (Create, Read, Update, Delete) in ASP.NET MVC Using C# and Entity Framework
C# | String.IndexOf( ) Method | Set - 1
|
[
{
"code": null,
"e": 23914,
"s": 23886,
"text": "\n26 Jun, 2019"
},
{
"code": null,
"e": 24378,
"s": 23914,
"text": "A Button is an essential part of an application, or software, or webpage. It allows the user to interact with the application or software. In windows form, you are allowed to set the location of the button in your forms by using Location Property. It is provided by Button class and it helps us to set the coordinates of the upper-left corner of the Button control relative to the upper-left corner of its form. You can use this property in two different methods:"
},
{
"code": null,
"e": 24481,
"s": 24378,
"text": "1. Design-Time: It is the easiest method to set the location of the button. Using the following steps:"
},
{
"code": null,
"e": 24596,
"s": 24481,
"text": "Step 1: Create a windows form a shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp"
},
{
"code": null,
"e": 24773,
"s": 24596,
"text": "Step 2: Drag the Button control from the ToolBox and drop it on the windows form. You are allowed to place a Button control anywhere on the windows form according to your need."
},
{
"code": null,
"e": 24904,
"s": 24773,
"text": "Step 3: After drag and drop you will go to the properties of the Button control to set the Location property of the Button.Output:"
},
{
"code": null,
"e": 24912,
"s": 24904,
"text": "Output:"
},
{
"code": null,
"e": 25088,
"s": 24912,
"text": "2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the Location property of the Button programmatically with the help of given syntax:"
},
{
"code": null,
"e": 25139,
"s": 25088,
"text": "public System.Drawing.Point Location { get; set; }"
},
{
"code": null,
"e": 25341,
"s": 25139,
"text": "Here, the Point is used to represent the upper-left corner of the button relative to the upper-left corner of its container or form. Following steps are used to set the Location property of the Button:"
},
{
"code": null,
"e": 25499,
"s": 25341,
"text": "Step 1: Create a button using the Button() constructor is provided by the Button class.// Creating Button using Button class\nButton MyButton = new Button();\n"
},
{
"code": null,
"e": 25570,
"s": 25499,
"text": "// Creating Button using Button class\nButton MyButton = new Button();\n"
},
{
"code": null,
"e": 25746,
"s": 25570,
"text": "Step 2: After creating Button, set the Location property of the Button provided by the Button class.// Set the location of the button\nMybutton.Location = new Point(225, 198);\n"
},
{
"code": null,
"e": 25822,
"s": 25746,
"text": "// Set the location of the button\nMybutton.Location = new Point(225, 198);\n"
},
{
"code": null,
"e": 27304,
"s": 25822,
"text": "Step 3: And last add this button control to from using Add() method.// Add this Button to form\nthis.Controls.Add(Mybutton);\nExample:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp8 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of label Label l = new Label(); l.AutoSize = true; l.Text = \"Do you want to submit this form?\"; l.Location = new Point(222, 145); // Adding this label to form this.Controls.Add(l); // Creating and setting the properties of Button Button Mybutton = new Button(); Mybutton.Location = new Point(225, 198); Mybutton.Text = \"Submit\"; Mybutton.AutoSize = true; Mybutton.BackColor = Color.LightBlue; // Adding this button to form this.Controls.Add(Mybutton); // Creating and setting the properties of Button Button Mybutton1 = new Button(); Mybutton1.Location = new Point(438, 198); Mybutton1.Text = \"Cancel\"; Mybutton1.AutoSize = true; Mybutton1.BackColor = Color.LightPink; // Adding this button to form this.Controls.Add(Mybutton1); }}}Output:"
},
{
"code": null,
"e": 27361,
"s": 27304,
"text": "// Add this Button to form\nthis.Controls.Add(Mybutton);\n"
},
{
"code": null,
"e": 27370,
"s": 27361,
"text": "Example:"
},
{
"code": "using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp8 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of label Label l = new Label(); l.AutoSize = true; l.Text = \"Do you want to submit this form?\"; l.Location = new Point(222, 145); // Adding this label to form this.Controls.Add(l); // Creating and setting the properties of Button Button Mybutton = new Button(); Mybutton.Location = new Point(225, 198); Mybutton.Text = \"Submit\"; Mybutton.AutoSize = true; Mybutton.BackColor = Color.LightBlue; // Adding this button to form this.Controls.Add(Mybutton); // Creating and setting the properties of Button Button Mybutton1 = new Button(); Mybutton1.Location = new Point(438, 198); Mybutton1.Text = \"Cancel\"; Mybutton1.AutoSize = true; Mybutton1.BackColor = Color.LightPink; // Adding this button to form this.Controls.Add(Mybutton1); }}}",
"e": 28713,
"s": 27370,
"text": null
},
{
"code": null,
"e": 28721,
"s": 28713,
"text": "Output:"
},
{
"code": null,
"e": 28724,
"s": 28721,
"text": "C#"
},
{
"code": null,
"e": 28822,
"s": 28724,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28831,
"s": 28822,
"text": "Comments"
},
{
"code": null,
"e": 28844,
"s": 28831,
"text": "Old Comments"
},
{
"code": null,
"e": 28872,
"s": 28844,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 28895,
"s": 28872,
"text": "C# | Method Overriding"
},
{
"code": null,
"e": 28918,
"s": 28895,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 28964,
"s": 28918,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 28979,
"s": 28964,
"text": "C# | Delegates"
},
{
"code": null,
"e": 29010,
"s": 28979,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 29050,
"s": 29010,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 29072,
"s": 29050,
"text": "Partial Classes in C#"
},
{
"code": null,
"e": 29159,
"s": 29072,
"text": "Basic CRUD (Create, Read, Update, Delete) in ASP.NET MVC Using C# and Entity Framework"
}
] |
C++ Tutorial
|
C++ is a middle-level programming language developed by Bjarne Stroustrup starting in 1979 at Bell Labs. C++ runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX. This C++ tutorial adopts a simple and practical approach to describe the concepts of C++ for beginners to advanded software engineers.
C++ is a MUST for students and working professionals to become a great Software Engineer. I will list down some of the key advantages of learning C++:
C++ is very close to hardware, so you get a chance to work at a low level which gives you lot of control in terms of memory management, better performance and finally a robust software development.
C++ is very close to hardware, so you get a chance to work at a low level which gives you lot of control in terms of memory management, better performance and finally a robust software development.
C++ programming gives you a clear understanding about Object Oriented Programming. You will understand low level implementation of polymorphism when you will implement virtual tables and virtual table pointers, or dynamic type identification.
C++ programming gives you a clear understanding about Object Oriented Programming. You will understand low level implementation of polymorphism when you will implement virtual tables and virtual table pointers, or dynamic type identification.
C++ is one of the every green programming languages and loved by millions of software developers. If you are a great C++ programmer then you will never sit without work and more importantly you will get highly paid for your work.
C++ is one of the every green programming languages and loved by millions of software developers. If you are a great C++ programmer then you will never sit without work and more importantly you will get highly paid for your work.
C++ is the most widely used programming languages in application and system programming. So you can choose your area of interest of software development.
C++ is the most widely used programming languages in application and system programming. So you can choose your area of interest of software development.
C++ really teaches you the difference between compiler, linker and loader, different data types, storage classes, variable types their scopes etc.
C++ really teaches you the difference between compiler, linker and loader, different data types, storage classes, variable types their scopes etc.
There are 1000s of good reasons to learn C++ Programming. But one thing for sure, to learn any programming language, not only C++, you just need to code, and code and finally code until you become expert.
Just to give you a little excitement about C++ programming, I'm going to give you a small conventional C++ Hello World program, You can try it using Demo link
C++ is a super set of C programming with additional implementation of object-oriented concepts.
#include <iostream>
using namespace std;
// main() is where program execution begins.
int main() {
cout << "Hello World"; // prints Hello World
return 0;
}
There are many C++ compilers available which you can use to compile and run above mentioned program:
Apple C++. Xcode
Apple C++. Xcode
Bloodshed Dev-C++
Bloodshed Dev-C++
Clang C++
Clang C++
Cygwin (GNU C++)
Cygwin (GNU C++)
Mentor Graphics
Mentor Graphics
MINGW - "Minimalist GNU for Windows"
MINGW - "Minimalist GNU for Windows"
GNU CC source
GNU CC source
IBM C++
IBM C++
Intel C++
Intel C++
Microsoft Visual C++
Microsoft Visual C++
Oracle C++
Oracle C++
HP C++
HP C++
It is really impossible to give a complete list of all the available compilers. The C++ world is just too large and too much new is happening.
As mentioned before, C++ is one of the most widely used programming languages. It has it's presence in almost every area of software development. I'm going to list few of them here:
Application Software Development - C++ programming has been used in developing almost all the major Operating Systems like Windows, Mac OSX and Linux. Apart from the operating systems, the core part of many browsers like Mozilla Firefox and Chrome have been written using C++. C++ also has been used in developing the most popular database system called MySQL.
Application Software Development - C++ programming has been used in developing almost all the major Operating Systems like Windows, Mac OSX and Linux. Apart from the operating systems, the core part of many browsers like Mozilla Firefox and Chrome have been written using C++. C++ also has been used in developing the most popular database system called MySQL.
Programming Languages Development - C++ has been used extensively in developing new programming languages like C#, Java, JavaScript, Perl, UNIX’s C Shell, PHP and Python, and Verilog etc.
Programming Languages Development - C++ has been used extensively in developing new programming languages like C#, Java, JavaScript, Perl, UNIX’s C Shell, PHP and Python, and Verilog etc.
Computation Programming - C++ is the best friends of scientists because of fast speed and computational efficiencies.
Computation Programming - C++ is the best friends of scientists because of fast speed and computational efficiencies.
Games Development - C++ is extremely fast which allows programmers to do procedural programming for CPU intensive functions and provides greater control over hardware, because of which it has been widely used in development of gaming engines.
Games Development - C++ is extremely fast which allows programmers to do procedural programming for CPU intensive functions and provides greater control over hardware, because of which it has been widely used in development of gaming engines.
Embedded System - C++ is being heavily used in developing Medical and Engineering Applications like softwares for MRI machines, high-end CAD/CAM systems etc.
Embedded System - C++ is being heavily used in developing Medical and Engineering Applications like softwares for MRI machines, high-end CAD/CAM systems etc.
This list goes on, there are various areas where software developers are happily using C++ to provide great softwares. I highly recommend you to learn C++ and contribute great softwares to the community.
This C++ tutorial has been prepared for the beginners to help them understand the basic to advanced concepts related to C++.
Before you start practicing with various types of examples given in this C++ tutorial,we are making an assumption that you are already aware of the basics of computer program and computer programming language.
154 Lectures
11.5 hours
Arnab Chakraborty
14 Lectures
57 mins
Kaushik Roy Chowdhury
30 Lectures
12.5 hours
Frahaan Hussain
54 Lectures
3.5 hours
Frahaan Hussain
77 Lectures
5.5 hours
Frahaan Hussain
12 Lectures
3.5 hours
Frahaan Hussain
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2653,
"s": 2318,
"text": "C++ is a middle-level programming language developed by Bjarne Stroustrup starting in 1979 at Bell Labs. C++ runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX. This C++ tutorial adopts a simple and practical approach to describe the concepts of C++ for beginners to advanded software engineers."
},
{
"code": null,
"e": 2804,
"s": 2653,
"text": "C++ is a MUST for students and working professionals to become a great Software Engineer. I will list down some of the key advantages of learning C++:"
},
{
"code": null,
"e": 3002,
"s": 2804,
"text": "C++ is very close to hardware, so you get a chance to work at a low level which gives you lot of control in terms of memory management, better performance and finally a robust software development."
},
{
"code": null,
"e": 3200,
"s": 3002,
"text": "C++ is very close to hardware, so you get a chance to work at a low level which gives you lot of control in terms of memory management, better performance and finally a robust software development."
},
{
"code": null,
"e": 3443,
"s": 3200,
"text": "C++ programming gives you a clear understanding about Object Oriented Programming. You will understand low level implementation of polymorphism when you will implement virtual tables and virtual table pointers, or dynamic type identification."
},
{
"code": null,
"e": 3686,
"s": 3443,
"text": "C++ programming gives you a clear understanding about Object Oriented Programming. You will understand low level implementation of polymorphism when you will implement virtual tables and virtual table pointers, or dynamic type identification."
},
{
"code": null,
"e": 3917,
"s": 3686,
"text": "C++ is one of the every green programming languages and loved by millions of software developers. If you are a great C++ programmer then you will never sit without work and more importantly you will get highly paid for your work."
},
{
"code": null,
"e": 4148,
"s": 3917,
"text": "C++ is one of the every green programming languages and loved by millions of software developers. If you are a great C++ programmer then you will never sit without work and more importantly you will get highly paid for your work."
},
{
"code": null,
"e": 4302,
"s": 4148,
"text": "C++ is the most widely used programming languages in application and system programming. So you can choose your area of interest of software development."
},
{
"code": null,
"e": 4456,
"s": 4302,
"text": "C++ is the most widely used programming languages in application and system programming. So you can choose your area of interest of software development."
},
{
"code": null,
"e": 4603,
"s": 4456,
"text": "C++ really teaches you the difference between compiler, linker and loader, different data types, storage classes, variable types their scopes etc."
},
{
"code": null,
"e": 4750,
"s": 4603,
"text": "C++ really teaches you the difference between compiler, linker and loader, different data types, storage classes, variable types their scopes etc."
},
{
"code": null,
"e": 4955,
"s": 4750,
"text": "There are 1000s of good reasons to learn C++ Programming. But one thing for sure, to learn any programming language, not only C++, you just need to code, and code and finally code until you become expert."
},
{
"code": null,
"e": 5114,
"s": 4955,
"text": "Just to give you a little excitement about C++ programming, I'm going to give you a small conventional C++ Hello World program, You can try it using Demo link"
},
{
"code": null,
"e": 5210,
"s": 5114,
"text": "C++ is a super set of C programming with additional implementation of object-oriented concepts."
},
{
"code": null,
"e": 5373,
"s": 5210,
"text": "#include <iostream>\nusing namespace std;\n\n// main() is where program execution begins.\nint main() {\n cout << \"Hello World\"; // prints Hello World\n return 0;\n}"
},
{
"code": null,
"e": 5474,
"s": 5373,
"text": "There are many C++ compilers available which you can use to compile and run above mentioned program:"
},
{
"code": null,
"e": 5491,
"s": 5474,
"text": "Apple C++. Xcode"
},
{
"code": null,
"e": 5508,
"s": 5491,
"text": "Apple C++. Xcode"
},
{
"code": null,
"e": 5526,
"s": 5508,
"text": "Bloodshed Dev-C++"
},
{
"code": null,
"e": 5544,
"s": 5526,
"text": "Bloodshed Dev-C++"
},
{
"code": null,
"e": 5554,
"s": 5544,
"text": "Clang C++"
},
{
"code": null,
"e": 5564,
"s": 5554,
"text": "Clang C++"
},
{
"code": null,
"e": 5581,
"s": 5564,
"text": "Cygwin (GNU C++)"
},
{
"code": null,
"e": 5598,
"s": 5581,
"text": "Cygwin (GNU C++)"
},
{
"code": null,
"e": 5614,
"s": 5598,
"text": "Mentor Graphics"
},
{
"code": null,
"e": 5630,
"s": 5614,
"text": "Mentor Graphics"
},
{
"code": null,
"e": 5667,
"s": 5630,
"text": "MINGW - \"Minimalist GNU for Windows\""
},
{
"code": null,
"e": 5704,
"s": 5667,
"text": "MINGW - \"Minimalist GNU for Windows\""
},
{
"code": null,
"e": 5718,
"s": 5704,
"text": "GNU CC source"
},
{
"code": null,
"e": 5732,
"s": 5718,
"text": "GNU CC source"
},
{
"code": null,
"e": 5740,
"s": 5732,
"text": "IBM C++"
},
{
"code": null,
"e": 5748,
"s": 5740,
"text": "IBM C++"
},
{
"code": null,
"e": 5758,
"s": 5748,
"text": "Intel C++"
},
{
"code": null,
"e": 5768,
"s": 5758,
"text": "Intel C++"
},
{
"code": null,
"e": 5789,
"s": 5768,
"text": "Microsoft Visual C++"
},
{
"code": null,
"e": 5810,
"s": 5789,
"text": "Microsoft Visual C++"
},
{
"code": null,
"e": 5821,
"s": 5810,
"text": "Oracle C++"
},
{
"code": null,
"e": 5832,
"s": 5821,
"text": "Oracle C++"
},
{
"code": null,
"e": 5839,
"s": 5832,
"text": "HP C++"
},
{
"code": null,
"e": 5846,
"s": 5839,
"text": "HP C++"
},
{
"code": null,
"e": 5989,
"s": 5846,
"text": "It is really impossible to give a complete list of all the available compilers. The C++ world is just too large and too much new is happening."
},
{
"code": null,
"e": 6171,
"s": 5989,
"text": "As mentioned before, C++ is one of the most widely used programming languages. It has it's presence in almost every area of software development. I'm going to list few of them here:"
},
{
"code": null,
"e": 6533,
"s": 6171,
"text": "Application Software Development - C++ programming has been used in developing almost all the major Operating Systems like Windows, Mac OSX and Linux. Apart from the operating systems, the core part of many browsers like Mozilla Firefox and Chrome have been written using C++. C++ also has been used in developing the most popular database system called MySQL."
},
{
"code": null,
"e": 6895,
"s": 6533,
"text": "Application Software Development - C++ programming has been used in developing almost all the major Operating Systems like Windows, Mac OSX and Linux. Apart from the operating systems, the core part of many browsers like Mozilla Firefox and Chrome have been written using C++. C++ also has been used in developing the most popular database system called MySQL."
},
{
"code": null,
"e": 7083,
"s": 6895,
"text": "Programming Languages Development - C++ has been used extensively in developing new programming languages like C#, Java, JavaScript, Perl, UNIX’s C Shell, PHP and Python, and Verilog etc."
},
{
"code": null,
"e": 7271,
"s": 7083,
"text": "Programming Languages Development - C++ has been used extensively in developing new programming languages like C#, Java, JavaScript, Perl, UNIX’s C Shell, PHP and Python, and Verilog etc."
},
{
"code": null,
"e": 7389,
"s": 7271,
"text": "Computation Programming - C++ is the best friends of scientists because of fast speed and computational efficiencies."
},
{
"code": null,
"e": 7507,
"s": 7389,
"text": "Computation Programming - C++ is the best friends of scientists because of fast speed and computational efficiencies."
},
{
"code": null,
"e": 7750,
"s": 7507,
"text": "Games Development - C++ is extremely fast which allows programmers to do procedural programming for CPU intensive functions and provides greater control over hardware, because of which it has been widely used in development of gaming engines."
},
{
"code": null,
"e": 7993,
"s": 7750,
"text": "Games Development - C++ is extremely fast which allows programmers to do procedural programming for CPU intensive functions and provides greater control over hardware, because of which it has been widely used in development of gaming engines."
},
{
"code": null,
"e": 8152,
"s": 7993,
"text": "Embedded System - C++ is being heavily used in developing Medical and Engineering Applications like softwares for MRI machines, high-end CAD/CAM systems etc."
},
{
"code": null,
"e": 8311,
"s": 8152,
"text": "Embedded System - C++ is being heavily used in developing Medical and Engineering Applications like softwares for MRI machines, high-end CAD/CAM systems etc."
},
{
"code": null,
"e": 8515,
"s": 8311,
"text": "This list goes on, there are various areas where software developers are happily using C++ to provide great softwares. I highly recommend you to learn C++ and contribute great softwares to the community."
},
{
"code": null,
"e": 8640,
"s": 8515,
"text": "This C++ tutorial has been prepared for the beginners to help them understand the basic to advanced concepts related to C++."
},
{
"code": null,
"e": 8850,
"s": 8640,
"text": "Before you start practicing with various types of examples given in this C++ tutorial,we are making an assumption that you are already aware of the basics of computer program and computer programming language."
},
{
"code": null,
"e": 8887,
"s": 8850,
"text": "\n 154 Lectures \n 11.5 hours \n"
},
{
"code": null,
"e": 8906,
"s": 8887,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 8938,
"s": 8906,
"text": "\n 14 Lectures \n 57 mins\n"
},
{
"code": null,
"e": 8961,
"s": 8938,
"text": " Kaushik Roy Chowdhury"
},
{
"code": null,
"e": 8997,
"s": 8961,
"text": "\n 30 Lectures \n 12.5 hours \n"
},
{
"code": null,
"e": 9014,
"s": 8997,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 9049,
"s": 9014,
"text": "\n 54 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 9066,
"s": 9049,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 9101,
"s": 9066,
"text": "\n 77 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 9118,
"s": 9101,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 9153,
"s": 9118,
"text": "\n 12 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 9170,
"s": 9153,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 9177,
"s": 9170,
"text": " Print"
},
{
"code": null,
"e": 9188,
"s": 9177,
"text": " Add Notes"
}
] |
Spring Boot - Servlet Filter
|
A filter is an object used to intercept the HTTP requests and responses of your application. By using filter, we can perform two operations at two instances −
Before sending the request to the controller
Before sending a response to the client.
The following code shows the sample code for a Servlet Filter implementation class with @Component annotation.
@Component
public class SimpleFilter implements Filter {
@Override
public void destroy() {}
@Override
public void doFilter
(ServletRequest request, ServletResponse response, FilterChain filterchain)
throws IOException, ServletException {}
@Override
public void init(FilterConfig filterconfig) throws ServletException {}
}
The following example shows the code for reading the remote host and remote address from the ServletRequest object before sending the request to the controller.
In doFilter() method, we have added the System.out.println statements to print the remote host and remote address.
package com.tutorialspoint.demo;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.springframework.stereotype.Component;
@Component
public class SimpleFilter implements Filter {
@Override
public void destroy() {}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterchain)
throws IOException, ServletException {
System.out.println("Remote Host:"+request.getRemoteHost());
System.out.println("Remote Address:"+request.getRemoteAddr());
filterchain.doFilter(request, response);
}
@Override
public void init(FilterConfig filterconfig) throws ServletException {}
}
In the Spring Boot main application class file, we have added the simple REST endpoint that returns the “Hello World” string.
package com.tutorialspoint.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@RequestMapping(value = "/")
public String hello() {
return "Hello World";
}
}
The code for Maven build – pom.xml is given below −
<?xml version = "1.0" encoding = "UTF-8"?>
<project xmlns = "http://maven.apache.org/POM/4.0.0" xmlns:xsi = "
http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.tutorialspoint</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.8.RELEASE</version>
<relativePath/>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
The code for Gradle Build – build.gradle is given below −
buildscript {
ext {
springBootVersion = '1.5.8.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
group = 'com.tutorialspoint'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
compile('org.springframework.boot:spring-boot-starter-web')
testCompile('org.springframework.boot:spring-boot-starter-test')
}
You can create an executable JAR file, and run the Spring Boot application by using the Maven or Gradle commands shown below −
For Maven, use the command as shown below −
mvn clean install
After BUILD SUCCESS, you can find the JAR file under the target directory.
For Gradle, use the command as shown below −
gradle clean build
After BUILD SUCCESSFUL, you can find the JAR file under the build/libs directory.
Now, run the JAR file by using the following command
java –jar <JARFILE>
You can see the application has started on the Tomcat port 8080.
Now hit the URL http://localhost:8080/ and see the output Hello World. It should look as shown below −
Then, you can see the Remote host and Remote address on the console log as shown below −
102 Lectures
8 hours
Karthikeya T
39 Lectures
5 hours
Chaand Sheikh
73 Lectures
5.5 hours
Senol Atac
62 Lectures
4.5 hours
Senol Atac
67 Lectures
4.5 hours
Senol Atac
69 Lectures
5 hours
Senol Atac
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 3184,
"s": 3025,
"text": "A filter is an object used to intercept the HTTP requests and responses of your application. By using filter, we can perform two operations at two instances −"
},
{
"code": null,
"e": 3229,
"s": 3184,
"text": "Before sending the request to the controller"
},
{
"code": null,
"e": 3270,
"s": 3229,
"text": "Before sending a response to the client."
},
{
"code": null,
"e": 3381,
"s": 3270,
"text": "The following code shows the sample code for a Servlet Filter implementation class with @Component annotation."
},
{
"code": null,
"e": 3736,
"s": 3381,
"text": "@Component\npublic class SimpleFilter implements Filter {\n @Override\n public void destroy() {}\n\n @Override\n public void doFilter\n (ServletRequest request, ServletResponse response, FilterChain filterchain) \n throws IOException, ServletException {}\n\n @Override\n public void init(FilterConfig filterconfig) throws ServletException {}\n}"
},
{
"code": null,
"e": 3897,
"s": 3736,
"text": "The following example shows the code for reading the remote host and remote address from the ServletRequest object before sending the request to the controller."
},
{
"code": null,
"e": 4012,
"s": 3897,
"text": "In doFilter() method, we have added the System.out.println statements to print the remote host and remote address."
},
{
"code": null,
"e": 4879,
"s": 4012,
"text": "package com.tutorialspoint.demo;\n\nimport java.io.IOException;\n\nimport javax.servlet.Filter;\nimport javax.servlet.FilterChain;\nimport javax.servlet.FilterConfig;\nimport javax.servlet.ServletException;\nimport javax.servlet.ServletRequest;\nimport javax.servlet.ServletResponse;\n\nimport org.springframework.stereotype.Component;\n\n@Component\npublic class SimpleFilter implements Filter {\n @Override\n public void destroy() {}\n\n @Override\n public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterchain) \n throws IOException, ServletException {\n \n System.out.println(\"Remote Host:\"+request.getRemoteHost());\n System.out.println(\"Remote Address:\"+request.getRemoteAddr());\n filterchain.doFilter(request, response);\n }\n\n @Override\n public void init(FilterConfig filterconfig) throws ServletException {}\n}"
},
{
"code": null,
"e": 5005,
"s": 4879,
"text": "In the Spring Boot main application class file, we have added the simple REST endpoint that returns the “Hello World” string."
},
{
"code": null,
"e": 5557,
"s": 5005,
"text": "package com.tutorialspoint.demo;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RestController;\n\n@SpringBootApplication\n@RestController\npublic class DemoApplication {\n public static void main(String[] args) {\n SpringApplication.run(DemoApplication.class, args);\n }\n @RequestMapping(value = \"/\")\n public String hello() {\n return \"Hello World\";\n }\n}"
},
{
"code": null,
"e": 5609,
"s": 5557,
"text": "The code for Maven build – pom.xml is given below −"
},
{
"code": null,
"e": 7156,
"s": 5609,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<project xmlns = \"http://maven.apache.org/POM/4.0.0\" xmlns:xsi = \"\n http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://maven.apache.org/POM/4.0.0 \n http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n \n <modelVersion>4.0.0</modelVersion>\n <groupId>com.tutorialspoint</groupId>\n <artifactId>demo</artifactId>\n <version>0.0.1-SNAPSHOT</version>\n <packaging>jar</packaging>\n <name>demo</name>\n <description>Demo project for Spring Boot</description>\n\n <parent>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-parent</artifactId>\n <version>1.5.8.RELEASE</version>\n <relativePath/> \n </parent>\n\n <properties>\n <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>\n <java.version>1.8</java.version>\n </properties>\n\n <dependencies>\n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-web</artifactId>\n </dependency>\n\n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-test</artifactId>\n <scope>test</scope>\n </dependency>\n </dependencies>\n\n <build>\n <plugins>\n <plugin>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-maven-plugin</artifactId>\n </plugin>\n </plugins>\n </build>\n \n</project>"
},
{
"code": null,
"e": 7214,
"s": 7156,
"text": "The code for Gradle Build – build.gradle is given below −"
},
{
"code": null,
"e": 7798,
"s": 7214,
"text": "buildscript {\n ext {\n springBootVersion = '1.5.8.RELEASE'\n }\n repositories {\n mavenCentral()\n }\n dependencies {\n classpath(\"org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}\")\n }\n}\n\napply plugin: 'java'\napply plugin: 'eclipse'\napply plugin: 'org.springframework.boot'\n\ngroup = 'com.tutorialspoint'\nversion = '0.0.1-SNAPSHOT'\nsourceCompatibility = 1.8\n\nrepositories {\n mavenCentral()\n}\ndependencies {\n compile('org.springframework.boot:spring-boot-starter-web')\n testCompile('org.springframework.boot:spring-boot-starter-test')\n}"
},
{
"code": null,
"e": 7925,
"s": 7798,
"text": "You can create an executable JAR file, and run the Spring Boot application by using the Maven or Gradle commands shown below −"
},
{
"code": null,
"e": 7969,
"s": 7925,
"text": "For Maven, use the command as shown below −"
},
{
"code": null,
"e": 7988,
"s": 7969,
"text": "mvn clean install\n"
},
{
"code": null,
"e": 8063,
"s": 7988,
"text": "After BUILD SUCCESS, you can find the JAR file under the target directory."
},
{
"code": null,
"e": 8108,
"s": 8063,
"text": "For Gradle, use the command as shown below −"
},
{
"code": null,
"e": 8128,
"s": 8108,
"text": "gradle clean build\n"
},
{
"code": null,
"e": 8210,
"s": 8128,
"text": "After BUILD SUCCESSFUL, you can find the JAR file under the build/libs directory."
},
{
"code": null,
"e": 8263,
"s": 8210,
"text": "Now, run the JAR file by using the following command"
},
{
"code": null,
"e": 8285,
"s": 8263,
"text": "java –jar <JARFILE> \n"
},
{
"code": null,
"e": 8350,
"s": 8285,
"text": "You can see the application has started on the Tomcat port 8080."
},
{
"code": null,
"e": 8453,
"s": 8350,
"text": "Now hit the URL http://localhost:8080/ and see the output Hello World. It should look as shown below −"
},
{
"code": null,
"e": 8542,
"s": 8453,
"text": "Then, you can see the Remote host and Remote address on the console log as shown below −"
},
{
"code": null,
"e": 8576,
"s": 8542,
"text": "\n 102 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 8590,
"s": 8576,
"text": " Karthikeya T"
},
{
"code": null,
"e": 8623,
"s": 8590,
"text": "\n 39 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 8638,
"s": 8623,
"text": " Chaand Sheikh"
},
{
"code": null,
"e": 8673,
"s": 8638,
"text": "\n 73 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 8685,
"s": 8673,
"text": " Senol Atac"
},
{
"code": null,
"e": 8720,
"s": 8685,
"text": "\n 62 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 8732,
"s": 8720,
"text": " Senol Atac"
},
{
"code": null,
"e": 8767,
"s": 8732,
"text": "\n 67 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 8779,
"s": 8767,
"text": " Senol Atac"
},
{
"code": null,
"e": 8812,
"s": 8779,
"text": "\n 69 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 8824,
"s": 8812,
"text": " Senol Atac"
},
{
"code": null,
"e": 8831,
"s": 8824,
"text": " Print"
},
{
"code": null,
"e": 8842,
"s": 8831,
"text": " Add Notes"
}
] |
Convert a string to hexadecimal ASCII values in C++
|
In this tutorial, we will be discussing a program to convert a string to hexadecimal ASCII values.
For this we will be provided with a string of characters. Our task is to print that particular given string into its hexadecimal equivalent.
Live Demo
#include <stdio.h>
#include <string.h>
//converting string to hexadecimal
void convert_hexa(char* input, char* output){
int loop=0;
int i=0;
while(input[loop] != '\0'){
sprintf((char*)(output+i),"%02X", input[loop]);
loop+=1;
i+=2;
}
//marking the end of the string
output[i++] = '\0';
}
int main(){
char ascii_str[] = "tutorials point";
int len = strlen(ascii_str);
char hex_str[(len*2)+1];
//function call
convert_hexa(ascii_str, hex_str);
printf("ASCII: %s\n", ascii_str);
printf("Hexadecimal: %s\n", hex_str);
return 0;
}
ASCII: tutorials point
Hexadecimal: 7475746F7269616C7320706F696E74
|
[
{
"code": null,
"e": 1161,
"s": 1062,
"text": "In this tutorial, we will be discussing a program to convert a string to hexadecimal ASCII values."
},
{
"code": null,
"e": 1302,
"s": 1161,
"text": "For this we will be provided with a string of characters. Our task is to print that particular given string into its hexadecimal equivalent."
},
{
"code": null,
"e": 1313,
"s": 1302,
"text": " Live Demo"
},
{
"code": null,
"e": 1899,
"s": 1313,
"text": "#include <stdio.h>\n#include <string.h>\n//converting string to hexadecimal\nvoid convert_hexa(char* input, char* output){\n int loop=0;\n int i=0;\n while(input[loop] != '\\0'){\n sprintf((char*)(output+i),\"%02X\", input[loop]);\n loop+=1;\n i+=2;\n }\n //marking the end of the string\n output[i++] = '\\0';\n}\nint main(){\n char ascii_str[] = \"tutorials point\";\n int len = strlen(ascii_str);\n char hex_str[(len*2)+1];\n //function call\n convert_hexa(ascii_str, hex_str);\n printf(\"ASCII: %s\\n\", ascii_str);\n printf(\"Hexadecimal: %s\\n\", hex_str);\n return 0;\n}"
},
{
"code": null,
"e": 1966,
"s": 1899,
"text": "ASCII: tutorials point\nHexadecimal: 7475746F7269616C7320706F696E74"
}
] |
Minimize operations required to obtain N - GeeksforGeeks
|
01 Apr, 2021
Given an integer N, the task is to obtain N, starting from 1 using minimum number of operations. The operations that can be performed in one step are as follows:
Multiply the number by 2.
Multiply the number by 3.
Add 1 to the number.
Explanation:
Input: N = 5 Output: 3 Explanation: Starting value: x = 1
Multiply x by 2 : x = 2
Multiply x by 2 : x = 4
Add 1 to x : x = 5
Therefore, the minimum number of operations required = 3
Input: N = 15 Output: 4 Explanation: 3 operations required to obtain x = 5. Multiply x by 3 : x = 15. Therefore, the minimum number of operations required = 4
Approach: The idea is to use the concept of Dynamic Programming. Follow the steps below:
If minimum operations to obtain any number smaller than N is known, then minimum operations to obtain N can be calculated.
Create the following lookup table:
dp[i] = Minimum number of operations to obtain i from 1
So for any number x, minimum operations required to obtain x can be calculated as:
dp[x] = min(dp[x-1], dp[x/2], dp[x/3])
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
#include <bits/stdc++.h>using namespace std; // Function to find the minimum number// of operationsint minOperations(int n){ // Storing the minimum operations // to obtain all numbers up to N int dp[n + 1]; // Initilal state dp[1] = 0; // Iterate for the remaining numbers for (int i = 2; i <= n; i++) { dp[i] = INT_MAX; // If the number can be obtained // by multiplication by 2 if (i % 2 == 0) { int x = dp[i / 2]; if (x + 1 < dp[i]) { dp[i] = x + 1; } } // If the number can be obtained // by multiplication by 3 if (i % 3 == 0) { int x = dp[i / 3]; if (x + 1 < dp[i]) { dp[i] = x + 1; } } // Obtaining the number by adding 1 int x = dp[i - 1]; if (x + 1 < dp[i]) { dp[i] = x + 1; } } // Return the minm operations // to obtain n return dp[n];} // Driver Codeint main(){ int n = 15; cout << minOperations(n); return 0;}
class GFG{ // Function to find the minimum number// of operationsstatic int minOperations(int n){ // Storing the minimum operations // to obtain all numbers up to N int dp[] = new int[n + 1]; // Initilal state dp[1] = 0; // Iterate for the remaining numbers for(int i = 2; i <= n; i++) { dp[i] = Integer.MAX_VALUE; // If the number can be obtained // by multiplication by 2 if (i % 2 == 0) { int x = dp[i / 2]; if (x + 1 < dp[i]) { dp[i] = x + 1; } } // If the number can be obtained // by multiplication by 3 if (i % 3 == 0) { int x = dp[i / 3]; if (x + 1 < dp[i]) { dp[i] = x + 1; } } // Obtaining the number by adding 1 int x = dp[i - 1]; if (x + 1 < dp[i]) { dp[i] = x + 1; } } // Return the minm operations // to obtain n return dp[n];} // Driver Codepublic static void main (String []args){ int n = 15; System.out.print( minOperations(n));}} // This code is contributed by chitranayal
import sys # Function to find the minimum number# of operationsdef minOperations(n): # Storing the minimum operations # to obtain all numbers up to N dp = [sys.maxsize] * (n + 1) # Initial state dp[1] = 0 # Iterate for the remaining numbers for i in range(2, n + 1): # If the number can be obtained # by multiplication by 2 if i % 2 == 0: x = dp[i // 2] if x + 1 < dp[i]: dp[i] = x + 1 # If the number can be obtained # by multiplication by 3 if i % 3 == 0: x = dp[i // 3] if x + 1 < dp[i]: dp[i] = x + 1 # Obtaining the number by adding 1 x = dp[i - 1] if x + 1 < dp[i]: dp[i] = x + 1 # Return the minimum operations # to obtain n return dp[n] # Driver coden = 15 print(minOperations(n)) # This code is contributed by Stuti Pathak
using System;class GFG{ // Function to find the minimum number// of operationsstatic int minOperations(int n){ // Storing the minimum operations // to obtain all numbers up to N int []dp = new int[n + 1]; int x; // Initilal state dp[1] = 0; // Iterate for the remaining numbers for(int i = 2; i <= n; i++) { dp[i] = int.MaxValue; // If the number can be obtained // by multiplication by 2 if (i % 2 == 0) { x = dp[i / 2]; if (x + 1 < dp[i]) { dp[i] = x + 1; } } // If the number can be obtained // by multiplication by 3 if (i % 3 == 0) { x = dp[i / 3]; if (x + 1 < dp[i]) { dp[i] = x + 1; } } // Obtaining the number by adding 1 x = dp[i - 1]; if (x + 1 < dp[i]) { dp[i] = x + 1; } } // Return the minm operations // to obtain n return dp[n];} // Driver Codepublic static void Main (string []args){ int n = 15; Console.Write(minOperations(n));}} // This code is contributed by rock_cool
<script> // Function to find the minimum number// of operationsfunction minOperations(n){ // Storing the minimum operations // to obtain all numbers up to N let dp = new Array(n + 1); // Initilal state dp[1] = 0; // Iterate for the remaining numbers for(let i = 2; i <= n; i++) { dp[i] = Number.MAX_VALUE; // If the number can be obtained // by multiplication by 2 if (i % 2 == 0) { let x = dp[parseInt(i / 2, 10)]; if (x + 1 < dp[i]) { dp[i] = x + 1; } } // If the number can be obtained // by multiplication by 3 if (i % 3 == 0) { let x = dp[parseInt(i / 3, 10)]; if (x + 1 < dp[i]) { dp[i] = x + 1; } } // Obtaining the number by adding 1 let x = dp[i - 1]; if (x + 1 < dp[i]) { dp[i] = x + 1; } } // Return the minm operations // to obtain n return dp[n];} // Driver codelet n = 15; document.write(minOperations(n)); // This code is contributed by divyesh072019 </script>
4
Time Complexity: O(N) Auxiliary Space: O(N)
stutipathak31jan
ukasp
rock_cool
divyesh072019
divisibility
Dynamic Programming
Mathematical
Recursion
Dynamic Programming
Mathematical
Recursion
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Maximum Subarray Sum using Divide and Conquer algorithm
Optimal Substructure Property in Dynamic Programming | DP-2
Min Cost Path | DP-6
Weighted Job Scheduling
Maximum sum such that no two elements are adjacent
C++ Data Types
Write a program to print all permutations of a given string
Set in C++ Standard Template Library (STL)
Modulo Operator (%) in C/C++ with Examples
Program to find GCD or HCF of two numbers
|
[
{
"code": null,
"e": 24618,
"s": 24590,
"text": "\n01 Apr, 2021"
},
{
"code": null,
"e": 24780,
"s": 24618,
"text": "Given an integer N, the task is to obtain N, starting from 1 using minimum number of operations. The operations that can be performed in one step are as follows:"
},
{
"code": null,
"e": 24806,
"s": 24780,
"text": "Multiply the number by 2."
},
{
"code": null,
"e": 24832,
"s": 24806,
"text": "Multiply the number by 3."
},
{
"code": null,
"e": 24853,
"s": 24832,
"text": "Add 1 to the number."
},
{
"code": null,
"e": 24867,
"s": 24853,
"text": "Explanation: "
},
{
"code": null,
"e": 24925,
"s": 24867,
"text": "Input: N = 5 Output: 3 Explanation: Starting value: x = 1"
},
{
"code": null,
"e": 24949,
"s": 24925,
"text": "Multiply x by 2 : x = 2"
},
{
"code": null,
"e": 24973,
"s": 24949,
"text": "Multiply x by 2 : x = 4"
},
{
"code": null,
"e": 24992,
"s": 24973,
"text": "Add 1 to x : x = 5"
},
{
"code": null,
"e": 25049,
"s": 24992,
"text": "Therefore, the minimum number of operations required = 3"
},
{
"code": null,
"e": 25210,
"s": 25049,
"text": "Input: N = 15 Output: 4 Explanation: 3 operations required to obtain x = 5. Multiply x by 3 : x = 15. Therefore, the minimum number of operations required = 4 "
},
{
"code": null,
"e": 25299,
"s": 25210,
"text": "Approach: The idea is to use the concept of Dynamic Programming. Follow the steps below:"
},
{
"code": null,
"e": 25422,
"s": 25299,
"text": "If minimum operations to obtain any number smaller than N is known, then minimum operations to obtain N can be calculated."
},
{
"code": null,
"e": 25457,
"s": 25422,
"text": "Create the following lookup table:"
},
{
"code": null,
"e": 25515,
"s": 25457,
"text": " dp[i] = Minimum number of operations to obtain i from 1 "
},
{
"code": null,
"e": 25598,
"s": 25515,
"text": "So for any number x, minimum operations required to obtain x can be calculated as:"
},
{
"code": null,
"e": 25638,
"s": 25598,
"text": " dp[x] = min(dp[x-1], dp[x/2], dp[x/3])"
},
{
"code": null,
"e": 25689,
"s": 25638,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 25693,
"s": 25689,
"text": "C++"
},
{
"code": null,
"e": 25698,
"s": 25693,
"text": "Java"
},
{
"code": null,
"e": 25706,
"s": 25698,
"text": "Python3"
},
{
"code": null,
"e": 25709,
"s": 25706,
"text": "C#"
},
{
"code": null,
"e": 25720,
"s": 25709,
"text": "Javascript"
},
{
"code": "#include <bits/stdc++.h>using namespace std; // Function to find the minimum number// of operationsint minOperations(int n){ // Storing the minimum operations // to obtain all numbers up to N int dp[n + 1]; // Initilal state dp[1] = 0; // Iterate for the remaining numbers for (int i = 2; i <= n; i++) { dp[i] = INT_MAX; // If the number can be obtained // by multiplication by 2 if (i % 2 == 0) { int x = dp[i / 2]; if (x + 1 < dp[i]) { dp[i] = x + 1; } } // If the number can be obtained // by multiplication by 3 if (i % 3 == 0) { int x = dp[i / 3]; if (x + 1 < dp[i]) { dp[i] = x + 1; } } // Obtaining the number by adding 1 int x = dp[i - 1]; if (x + 1 < dp[i]) { dp[i] = x + 1; } } // Return the minm operations // to obtain n return dp[n];} // Driver Codeint main(){ int n = 15; cout << minOperations(n); return 0;}",
"e": 26789,
"s": 25720,
"text": null
},
{
"code": "class GFG{ // Function to find the minimum number// of operationsstatic int minOperations(int n){ // Storing the minimum operations // to obtain all numbers up to N int dp[] = new int[n + 1]; // Initilal state dp[1] = 0; // Iterate for the remaining numbers for(int i = 2; i <= n; i++) { dp[i] = Integer.MAX_VALUE; // If the number can be obtained // by multiplication by 2 if (i % 2 == 0) { int x = dp[i / 2]; if (x + 1 < dp[i]) { dp[i] = x + 1; } } // If the number can be obtained // by multiplication by 3 if (i % 3 == 0) { int x = dp[i / 3]; if (x + 1 < dp[i]) { dp[i] = x + 1; } } // Obtaining the number by adding 1 int x = dp[i - 1]; if (x + 1 < dp[i]) { dp[i] = x + 1; } } // Return the minm operations // to obtain n return dp[n];} // Driver Codepublic static void main (String []args){ int n = 15; System.out.print( minOperations(n));}} // This code is contributed by chitranayal",
"e": 27991,
"s": 26789,
"text": null
},
{
"code": "import sys # Function to find the minimum number# of operationsdef minOperations(n): # Storing the minimum operations # to obtain all numbers up to N dp = [sys.maxsize] * (n + 1) # Initial state dp[1] = 0 # Iterate for the remaining numbers for i in range(2, n + 1): # If the number can be obtained # by multiplication by 2 if i % 2 == 0: x = dp[i // 2] if x + 1 < dp[i]: dp[i] = x + 1 # If the number can be obtained # by multiplication by 3 if i % 3 == 0: x = dp[i // 3] if x + 1 < dp[i]: dp[i] = x + 1 # Obtaining the number by adding 1 x = dp[i - 1] if x + 1 < dp[i]: dp[i] = x + 1 # Return the minimum operations # to obtain n return dp[n] # Driver coden = 15 print(minOperations(n)) # This code is contributed by Stuti Pathak",
"e": 28972,
"s": 27991,
"text": null
},
{
"code": "using System;class GFG{ // Function to find the minimum number// of operationsstatic int minOperations(int n){ // Storing the minimum operations // to obtain all numbers up to N int []dp = new int[n + 1]; int x; // Initilal state dp[1] = 0; // Iterate for the remaining numbers for(int i = 2; i <= n; i++) { dp[i] = int.MaxValue; // If the number can be obtained // by multiplication by 2 if (i % 2 == 0) { x = dp[i / 2]; if (x + 1 < dp[i]) { dp[i] = x + 1; } } // If the number can be obtained // by multiplication by 3 if (i % 3 == 0) { x = dp[i / 3]; if (x + 1 < dp[i]) { dp[i] = x + 1; } } // Obtaining the number by adding 1 x = dp[i - 1]; if (x + 1 < dp[i]) { dp[i] = x + 1; } } // Return the minm operations // to obtain n return dp[n];} // Driver Codepublic static void Main (string []args){ int n = 15; Console.Write(minOperations(n));}} // This code is contributed by rock_cool",
"e": 30185,
"s": 28972,
"text": null
},
{
"code": "<script> // Function to find the minimum number// of operationsfunction minOperations(n){ // Storing the minimum operations // to obtain all numbers up to N let dp = new Array(n + 1); // Initilal state dp[1] = 0; // Iterate for the remaining numbers for(let i = 2; i <= n; i++) { dp[i] = Number.MAX_VALUE; // If the number can be obtained // by multiplication by 2 if (i % 2 == 0) { let x = dp[parseInt(i / 2, 10)]; if (x + 1 < dp[i]) { dp[i] = x + 1; } } // If the number can be obtained // by multiplication by 3 if (i % 3 == 0) { let x = dp[parseInt(i / 3, 10)]; if (x + 1 < dp[i]) { dp[i] = x + 1; } } // Obtaining the number by adding 1 let x = dp[i - 1]; if (x + 1 < dp[i]) { dp[i] = x + 1; } } // Return the minm operations // to obtain n return dp[n];} // Driver codelet n = 15; document.write(minOperations(n)); // This code is contributed by divyesh072019 </script>",
"e": 31379,
"s": 30185,
"text": null
},
{
"code": null,
"e": 31381,
"s": 31379,
"text": "4"
},
{
"code": null,
"e": 31428,
"s": 31383,
"text": "Time Complexity: O(N) Auxiliary Space: O(N) "
},
{
"code": null,
"e": 31445,
"s": 31428,
"text": "stutipathak31jan"
},
{
"code": null,
"e": 31451,
"s": 31445,
"text": "ukasp"
},
{
"code": null,
"e": 31461,
"s": 31451,
"text": "rock_cool"
},
{
"code": null,
"e": 31475,
"s": 31461,
"text": "divyesh072019"
},
{
"code": null,
"e": 31488,
"s": 31475,
"text": "divisibility"
},
{
"code": null,
"e": 31508,
"s": 31488,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 31521,
"s": 31508,
"text": "Mathematical"
},
{
"code": null,
"e": 31531,
"s": 31521,
"text": "Recursion"
},
{
"code": null,
"e": 31551,
"s": 31531,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 31564,
"s": 31551,
"text": "Mathematical"
},
{
"code": null,
"e": 31574,
"s": 31564,
"text": "Recursion"
},
{
"code": null,
"e": 31672,
"s": 31574,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31681,
"s": 31672,
"text": "Comments"
},
{
"code": null,
"e": 31694,
"s": 31681,
"text": "Old Comments"
},
{
"code": null,
"e": 31750,
"s": 31694,
"text": "Maximum Subarray Sum using Divide and Conquer algorithm"
},
{
"code": null,
"e": 31810,
"s": 31750,
"text": "Optimal Substructure Property in Dynamic Programming | DP-2"
},
{
"code": null,
"e": 31831,
"s": 31810,
"text": "Min Cost Path | DP-6"
},
{
"code": null,
"e": 31855,
"s": 31831,
"text": "Weighted Job Scheduling"
},
{
"code": null,
"e": 31906,
"s": 31855,
"text": "Maximum sum such that no two elements are adjacent"
},
{
"code": null,
"e": 31921,
"s": 31906,
"text": "C++ Data Types"
},
{
"code": null,
"e": 31981,
"s": 31921,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 32024,
"s": 31981,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 32067,
"s": 32024,
"text": "Modulo Operator (%) in C/C++ with Examples"
}
] |
Undefined Vs Null in JavaScript - GeeksforGeeks
|
05 Nov, 2020
There are several differences between null and undefined, which are sometimes understood as the same.
Definition:Null: It is the intentional absence of the value. It is one of the primitive values of JavaScript.Undefined: It means the value does not exist in the compiler. It is the global object.Type:Null: Object Undefined: undefinedYou can see refer to “==” vs “===” article.
null == undefined // true
null === undefined // false
It means null is equal to undefined but not identical.When we define a variable to undefined then we are trying to convey that the variable does not exist .When we define a variable to null then we are trying to convey that the variable is empty.Differentiating using isNaN():You can refer to NaN article for betterunderstanding.isNaN(2 + null) // false
isNaN(2 + undefined) // true
Examples:Null:null ? console.log("true") : console.log("false") // false
Null is also referred as false.Undefined:When variable is not assigned a valuevar temp;
if(temp === undefined)
console.log("true");
else
console.log("false");
Output: trueAccessing values which does not existvar temp=['a','b','c'];
if(temp[3] === undefined)
console.log("true");
else
console.log("false");
Output:true
Definition:Null: It is the intentional absence of the value. It is one of the primitive values of JavaScript.Undefined: It means the value does not exist in the compiler. It is the global object.
Definition:
Null: It is the intentional absence of the value. It is one of the primitive values of JavaScript.
Null: It is the intentional absence of the value. It is one of the primitive values of JavaScript.
Undefined: It means the value does not exist in the compiler. It is the global object.
Undefined: It means the value does not exist in the compiler. It is the global object.
Type:Null: Object Undefined: undefined
Type:
Null: Object
Undefined: undefined
You can see refer to “==” vs “===” article.
null == undefined // true
null === undefined // false
It means null is equal to undefined but not identical.
You can see refer to “==” vs “===” article.
null == undefined // true
null === undefined // false
It means null is equal to undefined but not identical.
When we define a variable to undefined then we are trying to convey that the variable does not exist .When we define a variable to null then we are trying to convey that the variable is empty.
When we define a variable to undefined then we are trying to convey that the variable does not exist .When we define a variable to null then we are trying to convey that the variable is empty.
Differentiating using isNaN():You can refer to NaN article for betterunderstanding.isNaN(2 + null) // false
isNaN(2 + undefined) // true
Differentiating using isNaN():You can refer to NaN article for betterunderstanding.
isNaN(2 + null) // false
isNaN(2 + undefined) // true
Examples:Null:null ? console.log("true") : console.log("false") // false
Null is also referred as false.Undefined:When variable is not assigned a valuevar temp;
if(temp === undefined)
console.log("true");
else
console.log("false");
Output: trueAccessing values which does not existvar temp=['a','b','c'];
if(temp[3] === undefined)
console.log("true");
else
console.log("false");
Output:true
Examples:
Null:null ? console.log("true") : console.log("false") // false
Null is also referred as false.
Null:
null ? console.log("true") : console.log("false") // false
Null is also referred as false.
Undefined:When variable is not assigned a valuevar temp;
if(temp === undefined)
console.log("true");
else
console.log("false");
Output: trueAccessing values which does not existvar temp=['a','b','c'];
if(temp[3] === undefined)
console.log("true");
else
console.log("false");
Output:true
Undefined:
When variable is not assigned a value
var temp;
if(temp === undefined)
console.log("true");
else
console.log("false");
Output:
true
Accessing values which does not exist
var temp=['a','b','c'];
if(temp[3] === undefined)
console.log("true");
else
console.log("false");
Output:
true
bunnyram19
javascript-basics
Difference Between
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference between Process and Thread
Difference Between Method Overloading and Method Overriding in Java
Difference between Clustered and Non-clustered index
Differences between IPv4 and IPv6
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
File uploading in React.js
|
[
{
"code": null,
"e": 24075,
"s": 24047,
"text": "\n05 Nov, 2020"
},
{
"code": null,
"e": 24177,
"s": 24075,
"text": "There are several differences between null and undefined, which are sometimes understood as the same."
},
{
"code": null,
"e": 25291,
"s": 24177,
"text": "Definition:Null: It is the intentional absence of the value. It is one of the primitive values of JavaScript.Undefined: It means the value does not exist in the compiler. It is the global object.Type:Null: Object Undefined: undefinedYou can see refer to “==” vs “===” article. \n null == undefined // true\n null === undefined // false\nIt means null is equal to undefined but not identical.When we define a variable to undefined then we are trying to convey that the variable does not exist .When we define a variable to null then we are trying to convey that the variable is empty.Differentiating using isNaN():You can refer to NaN article for betterunderstanding.isNaN(2 + null) // false\nisNaN(2 + undefined) // true\nExamples:Null:null ? console.log(\"true\") : console.log(\"false\") // false\nNull is also referred as false.Undefined:When variable is not assigned a valuevar temp;\nif(temp === undefined)\nconsole.log(\"true\");\nelse\nconsole.log(\"false\");\nOutput: trueAccessing values which does not existvar temp=['a','b','c'];\nif(temp[3] === undefined)\nconsole.log(\"true\");\nelse\nconsole.log(\"false\");\nOutput:true"
},
{
"code": null,
"e": 25487,
"s": 25291,
"text": "Definition:Null: It is the intentional absence of the value. It is one of the primitive values of JavaScript.Undefined: It means the value does not exist in the compiler. It is the global object."
},
{
"code": null,
"e": 25499,
"s": 25487,
"text": "Definition:"
},
{
"code": null,
"e": 25598,
"s": 25499,
"text": "Null: It is the intentional absence of the value. It is one of the primitive values of JavaScript."
},
{
"code": null,
"e": 25697,
"s": 25598,
"text": "Null: It is the intentional absence of the value. It is one of the primitive values of JavaScript."
},
{
"code": null,
"e": 25784,
"s": 25697,
"text": "Undefined: It means the value does not exist in the compiler. It is the global object."
},
{
"code": null,
"e": 25871,
"s": 25784,
"text": "Undefined: It means the value does not exist in the compiler. It is the global object."
},
{
"code": null,
"e": 25910,
"s": 25871,
"text": "Type:Null: Object Undefined: undefined"
},
{
"code": null,
"e": 25916,
"s": 25910,
"text": "Type:"
},
{
"code": null,
"e": 25930,
"s": 25916,
"text": "Null: Object "
},
{
"code": null,
"e": 25951,
"s": 25930,
"text": "Undefined: undefined"
},
{
"code": null,
"e": 26107,
"s": 25951,
"text": "You can see refer to “==” vs “===” article. \n null == undefined // true\n null === undefined // false\nIt means null is equal to undefined but not identical."
},
{
"code": null,
"e": 26151,
"s": 26107,
"text": "You can see refer to “==” vs “===” article."
},
{
"code": null,
"e": 26210,
"s": 26151,
"text": " \n null == undefined // true\n null === undefined // false\n"
},
{
"code": null,
"e": 26265,
"s": 26210,
"text": "It means null is equal to undefined but not identical."
},
{
"code": null,
"e": 26458,
"s": 26265,
"text": "When we define a variable to undefined then we are trying to convey that the variable does not exist .When we define a variable to null then we are trying to convey that the variable is empty."
},
{
"code": null,
"e": 26651,
"s": 26458,
"text": "When we define a variable to undefined then we are trying to convey that the variable does not exist .When we define a variable to null then we are trying to convey that the variable is empty."
},
{
"code": null,
"e": 26795,
"s": 26651,
"text": "Differentiating using isNaN():You can refer to NaN article for betterunderstanding.isNaN(2 + null) // false\nisNaN(2 + undefined) // true\n"
},
{
"code": null,
"e": 26879,
"s": 26795,
"text": "Differentiating using isNaN():You can refer to NaN article for betterunderstanding."
},
{
"code": null,
"e": 26940,
"s": 26879,
"text": "isNaN(2 + null) // false\nisNaN(2 + undefined) // true\n"
},
{
"code": null,
"e": 27331,
"s": 26940,
"text": "Examples:Null:null ? console.log(\"true\") : console.log(\"false\") // false\nNull is also referred as false.Undefined:When variable is not assigned a valuevar temp;\nif(temp === undefined)\nconsole.log(\"true\");\nelse\nconsole.log(\"false\");\nOutput: trueAccessing values which does not existvar temp=['a','b','c'];\nif(temp[3] === undefined)\nconsole.log(\"true\");\nelse\nconsole.log(\"false\");\nOutput:true"
},
{
"code": null,
"e": 27341,
"s": 27331,
"text": "Examples:"
},
{
"code": null,
"e": 27437,
"s": 27341,
"text": "Null:null ? console.log(\"true\") : console.log(\"false\") // false\nNull is also referred as false."
},
{
"code": null,
"e": 27443,
"s": 27437,
"text": "Null:"
},
{
"code": null,
"e": 27503,
"s": 27443,
"text": "null ? console.log(\"true\") : console.log(\"false\") // false\n"
},
{
"code": null,
"e": 27535,
"s": 27503,
"text": "Null is also referred as false."
},
{
"code": null,
"e": 27822,
"s": 27535,
"text": "Undefined:When variable is not assigned a valuevar temp;\nif(temp === undefined)\nconsole.log(\"true\");\nelse\nconsole.log(\"false\");\nOutput: trueAccessing values which does not existvar temp=['a','b','c'];\nif(temp[3] === undefined)\nconsole.log(\"true\");\nelse\nconsole.log(\"false\");\nOutput:true"
},
{
"code": null,
"e": 27833,
"s": 27822,
"text": "Undefined:"
},
{
"code": null,
"e": 27871,
"s": 27833,
"text": "When variable is not assigned a value"
},
{
"code": null,
"e": 27953,
"s": 27871,
"text": "var temp;\nif(temp === undefined)\nconsole.log(\"true\");\nelse\nconsole.log(\"false\");\n"
},
{
"code": null,
"e": 27961,
"s": 27953,
"text": "Output:"
},
{
"code": null,
"e": 27967,
"s": 27961,
"text": " true"
},
{
"code": null,
"e": 28005,
"s": 27967,
"text": "Accessing values which does not exist"
},
{
"code": null,
"e": 28104,
"s": 28005,
"text": "var temp=['a','b','c'];\nif(temp[3] === undefined)\nconsole.log(\"true\");\nelse\nconsole.log(\"false\");\n"
},
{
"code": null,
"e": 28112,
"s": 28104,
"text": "Output:"
},
{
"code": null,
"e": 28117,
"s": 28112,
"text": "true"
},
{
"code": null,
"e": 28128,
"s": 28117,
"text": "bunnyram19"
},
{
"code": null,
"e": 28146,
"s": 28128,
"text": "javascript-basics"
},
{
"code": null,
"e": 28165,
"s": 28146,
"text": "Difference Between"
},
{
"code": null,
"e": 28176,
"s": 28165,
"text": "JavaScript"
},
{
"code": null,
"e": 28193,
"s": 28176,
"text": "Web Technologies"
},
{
"code": null,
"e": 28291,
"s": 28193,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28300,
"s": 28291,
"text": "Comments"
},
{
"code": null,
"e": 28313,
"s": 28300,
"text": "Old Comments"
},
{
"code": null,
"e": 28374,
"s": 28313,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28412,
"s": 28374,
"text": "Difference between Process and Thread"
},
{
"code": null,
"e": 28480,
"s": 28412,
"text": "Difference Between Method Overloading and Method Overriding in Java"
},
{
"code": null,
"e": 28533,
"s": 28480,
"text": "Difference between Clustered and Non-clustered index"
},
{
"code": null,
"e": 28567,
"s": 28533,
"text": "Differences between IPv4 and IPv6"
},
{
"code": null,
"e": 28628,
"s": 28567,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28673,
"s": 28628,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28745,
"s": 28673,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 28814,
"s": 28745,
"text": "How to calculate the number of days between two dates in javascript?"
}
] |
How to use Constraint Layout with recyclerview?
|
This example demonstrate about How to use Constraint Layout with recyclerview
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version = "1.0" encoding = "utf-8"?>
<android.support.design.widget.CoordinatorLayout android:layout_width = "match_parent"
android:layout_height = "match_parent"
xmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:app = "http://schemas.android.com/apk/res-auto">
<android.support.design.widget.AppBarLayout
android:layout_width = "match_parent"
android:layout_height = "wrap_content">
<android.support.v7.widget.Toolbar
android:id = "@+id/appbarlayout_tool_bar"
android:background = "@color/colorPrimary"
android:layout_width = "match_parent"
android:layout_height = "?attr/actionBarSize"
app:layout_scrollFlags = "scroll|snap|enterAlways"
app:theme = "@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme = "@style/ThemeOverlay.AppCompat.Light" />
</android.support.design.widget.AppBarLayout>
<android.support.v7.widget.RecyclerView
android:id = "@+id/recycler_view"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
app:layout_behavior = "@string/appbar_scrolling_view_behavior"/>
</android.support.design.widget.CoordinatorLayout>
In the above code, we have taken app bar layout and recycler view.
Step 3 − Add the following code to src/MainActivity.java
<?xml version = "1.0" encoding = "utf-8"?>
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.content.pm.ShortcutInfoCompat;
import android.support.v4.content.pm.ShortcutManagerCompat;
import android.support.v4.graphics.drawable.IconCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import android.support.v7.widget.Toolbar;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private customAdapter mAdapter;
TextView text;
ArrayList<String> list = new ArrayList<>();
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (android.support.v7.widget.Toolbar)findViewById(R.id.appbarlayout_tool_bar);
toolbar.setTitle("This is toolbar.");
setSupportActionBar(toolbar);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
mAdapter = new customAdapter(this,list);
recyclerView.setAdapter(mAdapter);
recyclerView.addItemDecoration(new DividerItemDecoration(recyclerView.getContext(), DividerItemDecoration.VERTICAL));
list.add("sairamm");
list.add("Krishna");
list.add("prasad");
list.add("sairamm");
list.add("Krishna");
list.add("prasad");
list.add("sairamm");
list.add("Krishna");
list.add("prasad");
list.add("sairamm");
list.add("Krishna");
list.add("prasad");
list.add("Krishna");
list.add("prasad");
list.add("sairamm");
list.add("Krishna");
list.add("prasad");
list.add("sairamm");
list.add("Krishna");
list.add("prasad");
}
}
Step 4 − Add the following code to Manifest.xml
<?xml version = "1.0" encoding = "utf-8"?>
<manifest xmlns:android = "http://schemas.android.com/apk/res/android"
package = "com.example.myapplication">
<uses-permission android:name = "android.permission.INTERNET" />
<uses-permission android:name = "com.android.launcher.permission.INSTALL_SHORTCUT" />
<application
android:allowBackup = "true"
android:theme = "@style/AppTheme.NoActionBar"
android:icon = "@mipmap/ic_launcher"
android:label = "@string/app_name"
android:roundIcon = "@mipmap/ic_launcher_round"
android:supportsRtl = "true">
<activity
android:name = ".MainActivity"
android:configChanges = "keyboardHidden|orientation|screenSize">
<intent-filter>
<action android:name = "android.intent.action.MAIN" />
<action android:name = "android.intent.action.CREATE_SHORTCUT" />
<category android:name = "android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Step 5 − Add the following code to customAdapter.java
<?xml version = "1.0" encoding = "utf-8"?>
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
public class customAdapter extends RecyclerView.Adapter<customAdapter.MyViewHolder> {
Context context;
ArrayList<String> list;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView title;
public MyViewHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.title);
}
}
public customAdapter(Context context, ArrayList<String> list) {
this.context = context;
this.list = list;
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_row, viewGroup, false);
return new MyViewHolder(itemView);
}
@Override
public void onBindViewHolder(@NonNull MyViewHolder myViewHolder, int i) {
myViewHolder.title.setText(list.get(i));
}
@Override
public int getItemCount() {
return list.size();
}
}
Step 6 − Add the following code to list_row.xml
<?xml version = "1.0" encoding = "utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:app = "http://schemas.android.com/apk/res-auto"
xmlns:tools = "http://schemas.android.com/tools"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:background = "@color/colorAccent"
tools:context = ".MainActivity">
<ImageView
android:id = "@+id/imageView2"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:src = "@drawable/logo"
app:layout_constraintBottom_toBottomOf = "parent"
app:layout_constraintEnd_toEndOf = "parent"
app:layout_constraintStart_toStartOf = "parent"
app:layout_constraintTop_toTopOf = "parent"
app:layout_constraintVertical_bias = "0.209" />
<TextView
android:id = "@+id/title"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:layout_marginTop = "35dp"
android:gravity = "center"
android:textSize = "30sp"
app:layout_constraintTop_toBottomOf = "@+id/imageView2"
tools:layout_editor_absoluteX = "0dp" />
<TextView
android:id = "@+id/textview2"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:layout_marginTop = "16dp"
android:layout_marginBottom = "8dp"
android:gravity = "center"
android:text = "Sairamkrishan"
android:textSize = "30sp"
app:layout_constraintBottom_toBottomOf = "parent"
app:layout_constraintTop_toBottomOf = "@+id/title"
app:layout_constraintVertical_bias = "0.0"
tools:layout_editor_absoluteX = "0dp" />
</android.support.constraint.ConstraintLayout>
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": 1140,
"s": 1062,
"text": "This example demonstrate about How to use Constraint Layout with recyclerview"
},
{
"code": null,
"e": 1269,
"s": 1140,
"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": 1334,
"s": 1269,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2549,
"s": 1334,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<android.support.design.widget.CoordinatorLayout android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:app = \"http://schemas.android.com/apk/res-auto\">\n <android.support.design.widget.AppBarLayout\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\">\n <android.support.v7.widget.Toolbar\n android:id = \"@+id/appbarlayout_tool_bar\"\n android:background = \"@color/colorPrimary\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"?attr/actionBarSize\"\n app:layout_scrollFlags = \"scroll|snap|enterAlways\"\n app:theme = \"@style/ThemeOverlay.AppCompat.Dark.ActionBar\"\n app:popupTheme = \"@style/ThemeOverlay.AppCompat.Light\" />\n </android.support.design.widget.AppBarLayout>\n <android.support.v7.widget.RecyclerView\n android:id = \"@+id/recycler_view\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n app:layout_behavior = \"@string/appbar_scrolling_view_behavior\"/>\n</android.support.design.widget.CoordinatorLayout>"
},
{
"code": null,
"e": 2616,
"s": 2549,
"text": "In the above code, we have taken app bar layout and recycler view."
},
{
"code": null,
"e": 2673,
"s": 2616,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 5130,
"s": 2673,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\nimport android.annotation.TargetApi;\nimport android.app.Activity;\nimport android.content.Intent;\nimport android.content.SharedPreferences;\nimport android.net.Uri;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.support.v4.content.pm.ShortcutInfoCompat;\nimport android.support.v4.content.pm.ShortcutManagerCompat;\nimport android.support.v4.graphics.drawable.IconCompat;\nimport android.support.v7.app.AppCompatActivity;\nimport android.support.v7.widget.DefaultItemAnimator;\nimport android.support.v7.widget.DividerItemDecoration;\nimport android.support.v7.widget.LinearLayoutManager;\nimport android.support.v7.widget.RecyclerView;\nimport android.view.View;\nimport android.widget.TextView;\nimport android.widget.Toast;\nimport android.support.v7.widget.Toolbar;\nimport java.util.ArrayList;\n\npublic class MainActivity extends AppCompatActivity {\n private RecyclerView recyclerView;\n private customAdapter mAdapter;\n TextView text;\n ArrayList<String> list = new ArrayList<>();\n @TargetApi(Build.VERSION_CODES.LOLLIPOP)\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n Toolbar toolbar = (android.support.v7.widget.Toolbar)findViewById(R.id.appbarlayout_tool_bar);\n toolbar.setTitle(\"This is toolbar.\");\n setSupportActionBar(toolbar);\n recyclerView = (RecyclerView) findViewById(R.id.recycler_view);\n RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());\n recyclerView.setLayoutManager(mLayoutManager);\n recyclerView.setItemAnimator(new DefaultItemAnimator());\n mAdapter = new customAdapter(this,list);\n recyclerView.setAdapter(mAdapter);\n recyclerView.addItemDecoration(new DividerItemDecoration(recyclerView.getContext(), DividerItemDecoration.VERTICAL));\n list.add(\"sairamm\");\n list.add(\"Krishna\");\n list.add(\"prasad\");\n list.add(\"sairamm\");\n list.add(\"Krishna\");\n list.add(\"prasad\");\n list.add(\"sairamm\");\n list.add(\"Krishna\");\n list.add(\"prasad\");\n list.add(\"sairamm\");\n list.add(\"Krishna\");\n list.add(\"prasad\");\n list.add(\"Krishna\");\n list.add(\"prasad\");\n list.add(\"sairamm\");\n list.add(\"Krishna\");\n list.add(\"prasad\");\n list.add(\"sairamm\");\n list.add(\"Krishna\");\n list.add(\"prasad\");\n }\n}"
},
{
"code": null,
"e": 5178,
"s": 5130,
"text": "Step 4 − Add the following code to Manifest.xml"
},
{
"code": null,
"e": 6217,
"s": 5178,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<manifest xmlns:android = \"http://schemas.android.com/apk/res/android\"\n package = \"com.example.myapplication\">\n <uses-permission android:name = \"android.permission.INTERNET\" />\n <uses-permission android:name = \"com.android.launcher.permission.INSTALL_SHORTCUT\" />\n <application\n android:allowBackup = \"true\"\n android:theme = \"@style/AppTheme.NoActionBar\"\n android:icon = \"@mipmap/ic_launcher\"\n android:label = \"@string/app_name\"\n android:roundIcon = \"@mipmap/ic_launcher_round\"\n android:supportsRtl = \"true\">\n <activity\n android:name = \".MainActivity\"\n android:configChanges = \"keyboardHidden|orientation|screenSize\">\n <intent-filter>\n <action android:name = \"android.intent.action.MAIN\" />\n <action android:name = \"android.intent.action.CREATE_SHORTCUT\" />\n <category android:name = \"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 6271,
"s": 6217,
"text": "Step 5 − Add the following code to customAdapter.java"
},
{
"code": null,
"e": 7557,
"s": 6271,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\nimport android.content.Context;\nimport android.support.annotation.NonNull;\nimport android.support.v7.widget.RecyclerView;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.TextView;\nimport java.util.ArrayList;\n\npublic class customAdapter extends RecyclerView.Adapter<customAdapter.MyViewHolder> {\n Context context;\n ArrayList<String> list;\n public class MyViewHolder extends RecyclerView.ViewHolder {\n public TextView title;\n public MyViewHolder(View view) {\n super(view);\n title = (TextView) view.findViewById(R.id.title);\n }\n }\n public customAdapter(Context context, ArrayList<String> list) {\n this.context = context;\n this.list = list;\n }\n @NonNull\n @Override\n public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {\n View itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_row, viewGroup, false);\n return new MyViewHolder(itemView);\n }\n @Override\n public void onBindViewHolder(@NonNull MyViewHolder myViewHolder, int i) {\n myViewHolder.title.setText(list.get(i));\n }\n @Override\n public int getItemCount() {\n return list.size();\n }\n}"
},
{
"code": null,
"e": 7605,
"s": 7557,
"text": "Step 6 − Add the following code to list_row.xml"
},
{
"code": null,
"e": 9394,
"s": 7605,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<android.support.constraint.ConstraintLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:app = \"http://schemas.android.com/apk/res-auto\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n android:background = \"@color/colorAccent\"\n tools:context = \".MainActivity\">\n <ImageView\n android:id = \"@+id/imageView2\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\"\n android:src = \"@drawable/logo\"\n app:layout_constraintBottom_toBottomOf = \"parent\"\n app:layout_constraintEnd_toEndOf = \"parent\"\n app:layout_constraintStart_toStartOf = \"parent\"\n app:layout_constraintTop_toTopOf = \"parent\"\n app:layout_constraintVertical_bias = \"0.209\" />\n <TextView\n android:id = \"@+id/title\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n android:layout_marginTop = \"35dp\"\n android:gravity = \"center\"\n android:textSize = \"30sp\"\n app:layout_constraintTop_toBottomOf = \"@+id/imageView2\"\n tools:layout_editor_absoluteX = \"0dp\" />\n <TextView\n android:id = \"@+id/textview2\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n android:layout_marginTop = \"16dp\"\n android:layout_marginBottom = \"8dp\"\n android:gravity = \"center\"\n android:text = \"Sairamkrishan\"\n android:textSize = \"30sp\"\n app:layout_constraintBottom_toBottomOf = \"parent\"\n app:layout_constraintTop_toBottomOf = \"@+id/title\"\n app:layout_constraintVertical_bias = \"0.0\"\n tools:layout_editor_absoluteX = \"0dp\" />\n</android.support.constraint.ConstraintLayout>"
},
{
"code": null,
"e": 9741,
"s": 9394,
"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 –"
}
] |
Automated software testing with Python
|
In this tutorial, we are going to learn about automating testing in Python. After writing code, we have to test them by giving different types of input and check whether the code is working correctly or not.
We can do it manually or automatically. Doing manual testing is very hard. So, we are going to learn about automated testing in Python. Let's start.
We have a module called unittest, which is used to test the code automatically. We are going to work with this module in this tutorial. It's straightforward for a beginner to get started with the unittest module for testing. Let's start the coding with basics.
The method which you have to test must start with the test text.
# importing unittest module
import unittest
class SampleTest(unittest.TestCase):
# return True or False
def test(self):
self.assertTrue(True)
# running the test
unittest.main()
If you run the above program, you will get the following results.
Ran 1 test in 0.001s
OK
Now, we are going to test different string methods with sample test cases. Remember that the method name must start with a test.
# importing unittest module
import unittest
class TestingStringMethods(unittest.TestCase):
# string equal
def test_string_equality(self):
# if both arguments are then it's succes
self.assertEqual('ttp' * 5, 'ttpttpttpttpttp')
# comparing the two strings
def test_string_case(self):
# if both arguments are then it's succes
self.assertEqual('tutorialspoint'.upper(), 'TUTORIALSPOINT')
# checking whether a string is upper or not
def test_is_string_upper(self):
# used to check whether the statement is True or False
self.assertTrue('TUTORIALSPOINT'.isupper())
self.assertFalse('TUTORIALSpoint'.isupper())
# running the tests
unittest.main()
If you run the above program, you will get the following results.
Ran 3 tests in 0.001s
OK
You can use the testing in your programs to save a lot of time. If you have any doubts in the tutorial, mention them in the comment section.
|
[
{
"code": null,
"e": 1270,
"s": 1062,
"text": "In this tutorial, we are going to learn about automating testing in Python. After writing code, we have to test them by giving different types of input and check whether the code is working correctly or not."
},
{
"code": null,
"e": 1419,
"s": 1270,
"text": "We can do it manually or automatically. Doing manual testing is very hard. So, we are going to learn about automated testing in Python. Let's start."
},
{
"code": null,
"e": 1680,
"s": 1419,
"text": "We have a module called unittest, which is used to test the code automatically. We are going to work with this module in this tutorial. It's straightforward for a beginner to get started with the unittest module for testing. Let's start the coding with basics."
},
{
"code": null,
"e": 1745,
"s": 1680,
"text": "The method which you have to test must start with the test text."
},
{
"code": null,
"e": 1934,
"s": 1745,
"text": "# importing unittest module\nimport unittest\nclass SampleTest(unittest.TestCase):\n # return True or False\n def test(self):\n self.assertTrue(True)\n# running the test\nunittest.main()"
},
{
"code": null,
"e": 2000,
"s": 1934,
"text": "If you run the above program, you will get the following results."
},
{
"code": null,
"e": 2024,
"s": 2000,
"text": "Ran 1 test in 0.001s\nOK"
},
{
"code": null,
"e": 2153,
"s": 2024,
"text": "Now, we are going to test different string methods with sample test cases. Remember that the method name must start with a test."
},
{
"code": null,
"e": 2853,
"s": 2153,
"text": "# importing unittest module\nimport unittest\nclass TestingStringMethods(unittest.TestCase):\n # string equal\n def test_string_equality(self):\n # if both arguments are then it's succes\n self.assertEqual('ttp' * 5, 'ttpttpttpttpttp')\n # comparing the two strings\n def test_string_case(self):\n # if both arguments are then it's succes\n self.assertEqual('tutorialspoint'.upper(), 'TUTORIALSPOINT')\n # checking whether a string is upper or not\n def test_is_string_upper(self):\n # used to check whether the statement is True or False\n self.assertTrue('TUTORIALSPOINT'.isupper())\n self.assertFalse('TUTORIALSpoint'.isupper())\n# running the tests\nunittest.main()"
},
{
"code": null,
"e": 2919,
"s": 2853,
"text": "If you run the above program, you will get the following results."
},
{
"code": null,
"e": 2944,
"s": 2919,
"text": "Ran 3 tests in 0.001s\nOK"
},
{
"code": null,
"e": 3085,
"s": 2944,
"text": "You can use the testing in your programs to save a lot of time. If you have any doubts in the tutorial, mention them in the comment section."
}
] |
Order randomly in MySQL with a random value column?
|
Let us first create a table. After that we will create a new random value column and order the
record randomly:
mysql> create table DemoTable
(
StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
StudentName varchar(20)
);
Query OK, 0 rows affected (0.57 sec)
Following is the query to insert some records in the table using insert command:
mysql> insert into DemoTable(StudentName) values('Larry');
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable(StudentName) values('Sam');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable(StudentName) values('Mike');
Query OK, 1 row affected (0.34 sec)
mysql> insert into DemoTable(StudentName) values('Carol');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(StudentName) values('Robert');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable(StudentName) values('Chris');
Query OK, 1 row affected (0.14 sec)
Following is the query to display records from the table using select statement:
mysql> select *from DemoTable;
This will produce the following output
+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
| 1 | Larry |
| 2 | Sam |
| 3 | Mike |
| 4 | Carol |
| 5 | Robert |
| 6 | Chris |
+-----------+-------------+
6 rows in set (0.00 sec)
Here is the query to order by random fields. We have created a new random field here:
mysql> SELECT *
FROM (SELECT StudentName, RAND()+1 AS randomRecord
FROM DemoTable
) tbl
ORDER BY RandomRecord DESC;
This will produce the following output
+-------------+--------------------+
| StudentName | RandomRecord |
+-------------+--------------------+
| Carol | 1.8973721451101566 |
| Chris | 1.7821308670399065 |
| Mike | 1.4640037673190271 |
| Larry | 1.4134691557041081 |
| Sam | 1.1408822407395414 |
| Robert | 1.0948494543273461 |
+-------------+--------------------+
6 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1174,
"s": 1062,
"text": "Let us first create a table. After that we will create a new random value column and order the\nrecord randomly:"
},
{
"code": null,
"e": 1327,
"s": 1174,
"text": "mysql> create table DemoTable\n(\n StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n StudentName varchar(20)\n);\nQuery OK, 0 rows affected (0.57 sec)"
},
{
"code": null,
"e": 1408,
"s": 1327,
"text": "Following is the query to insert some records in the table using insert command:"
},
{
"code": null,
"e": 1976,
"s": 1408,
"text": "mysql> insert into DemoTable(StudentName) values('Larry');\nQuery OK, 1 row affected (0.20 sec)\nmysql> insert into DemoTable(StudentName) values('Sam');\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into DemoTable(StudentName) values('Mike');\nQuery OK, 1 row affected (0.34 sec)\nmysql> insert into DemoTable(StudentName) values('Carol');\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into DemoTable(StudentName) values('Robert');\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into DemoTable(StudentName) values('Chris');\nQuery OK, 1 row affected (0.14 sec)"
},
{
"code": null,
"e": 2057,
"s": 1976,
"text": "Following is the query to display records from the table using select statement:"
},
{
"code": null,
"e": 2088,
"s": 2057,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 2127,
"s": 2088,
"text": "This will produce the following output"
},
{
"code": null,
"e": 2435,
"s": 2127,
"text": "+-----------+-------------+\n| StudentId | StudentName |\n+-----------+-------------+\n| 1 | Larry |\n| 2 | Sam |\n| 3 | Mike |\n| 4 | Carol |\n| 5 | Robert |\n| 6 | Chris | \n+-----------+-------------+\n6 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2521,
"s": 2435,
"text": "Here is the query to order by random fields. We have created a new random field here:"
},
{
"code": null,
"e": 2637,
"s": 2521,
"text": "mysql> SELECT *\nFROM (SELECT StudentName, RAND()+1 AS randomRecord\nFROM DemoTable\n) tbl\nORDER BY RandomRecord DESC;"
},
{
"code": null,
"e": 2676,
"s": 2637,
"text": "This will produce the following output"
},
{
"code": null,
"e": 3071,
"s": 2676,
"text": "+-------------+--------------------+\n| StudentName | RandomRecord |\n+-------------+--------------------+\n| Carol | 1.8973721451101566 |\n| Chris | 1.7821308670399065 |\n| Mike | 1.4640037673190271 |\n| Larry | 1.4134691557041081 |\n| Sam | 1.1408822407395414 |\n| Robert | 1.0948494543273461 |\n+-------------+--------------------+\n6 rows in set (0.00 sec)"
}
] |
C++ Program to Implement the Hill Cypher
|
Based on linear algebra Hill cipher is a polygraphic substitution cipher in cryptography.
To encrypt message: The key string and message string are represented as matrix form. They are multiplied then, against modulo 26. The key matrix should have inverse to decrypt the message.
To decrypt message: The encrypted message is multiplied by inverse key matrix used for encryption against modulo 26 to get decrypt message.
1 0 1
2 4 0
3 5 6
Message string ‘ABC’ in matrix form −
0
1
2
After multiplying above two matrices we get,
2
4
17
Which will be the encrypted message ‘CER’
Inverse of key matrix is −
1.09091 0.227273 -0.181818
-0.545455 0.136364 0.0909091
-0.0909091 -0.227273 0.181818
Now after multiplying the inverse matrix of key matrix with encrypted message matrix is −
0
1
2
Which is the original message string is ‘ABC’.
Here, is a C++ program to implement above example.
Begin
Function getKeyMatrix()
For i = 0 to 2
For j = 0 to 3
Take the elements of matrix a[i][j] as input.
m[i][j] = a[i][j]
done
done
Take the message string as user input.
For i = 0 to 2
msg[i][0] = mes[i] - 65
done
End
Begin
Function encrypt()
For i = 0 to 2
For j = 0 to 0
For k = 0 to 2
en[i][j] = en[i][j] + a[i][k] * msg[k][j]
Take modulo 26 for each element of the matrix obtained by multiplication and print the encrypted message.
End
Begin
Function decrypt()
Call function inversematrix()
For i = 0 to 2
For j = 0 to 0
For k = 0 to 2
de[i][j] = de[i][j] + b[i][k] * en[k][j]
Take modulo 26 of the multiplication to get the original message.
#include<iostream>
#include<math.h>
using namespace std;
float en[3][1], de[3][1], a[3][3], b[3][3], msg[3][1], m[3][3];
void getKeyMatrix() { //get key and message from user
int i, j;
char mes[3];
cout<<"Enter 3x3 matrix for key (should have inverse):\n";
for(i = 0; i < 3; i++)
for(j = 0; j < 3; j++) {
cin>>a[i][j];
m[i][j] = a[i][j];
}
cout<<"\nEnter a string of 3 letter(use A through Z): ";
cin>>mes;
for(i = 0; i < 3; i++)
msg[i][0] = mes[i] - 65;
}
void encrypt() { //encrypts the message
int i, j, k;
for(i = 0; i < 3; i++)
for(j = 0; j < 1; j++)
for(k = 0; k < 3; k++)
en[i][j] = en[i][j] + a[i][k] * msg[k][j];
cout<<"\nEncrypted string is: ";
for(i = 0; i < 3; i++)
cout<<(char)(fmod(en[i][0], 26) + 65); //modulo 26 is taken for each element of the matrix obtained by multiplication
}
void inversematrix() { //find inverse of key matrix
int i, j, k;
float p, q;
for(i = 0; i < 3; i++)
for(j = 0; j < 3; j++) {
if(i == j)
b[i][j]=1;
else
b[i][j]=0;
}
for(k = 0; k < 3; k++) {
for(i = 0; i < 3; i++) {
p = m[i][k];
q = m[k][k];
for(j = 0; j < 3; j++) {
if(i != k) {
m[i][j] = m[i][j]*q - p*m[k][j];
b[i][j] = b[i][j]*q - p*b[k][j];
}
}
}
}
for(i = 0; i < 3; i++)
for(j = 0; j < 3; j++)
b[i][j] = b[i][j] / m[i][i];
cout<<"\n\nInverse Matrix is:\n";
for(i = 0; i < 3; i++) {
for(j = 0; j < 3; j++)
cout<<b[i][j]<<" ";
cout<<"\n";
}
}
void decrypt() { //decrypt the message
int i, j, k;
inversematrix();
for(i = 0; i < 3; i++)
for(j = 0; j < 1; j++)
for(k = 0; k < 3; k++)
de[i][j] = de[i][j] + b[i][k] * en[k][j];
cout<<"\nDecrypted string is: ";
for(i = 0; i < 3; i++)
cout<<(char)(fmod(de[i][0], 26) + 65); //modulo 26 is taken to get the original message
cout<<"\n";
}
int main() {
getKeyMatrix();
encrypt();
decrypt();
}
Enter 3x3 matrix for key (should have inverse):
1
0
1
2
4
0
3
5
6
Enter a string of 3 letter(use A through Z): ABC
Encrypted string is: CER
Inverse Matrix is:
1.09091 0.227273 -0.181818
-0.545455 0.136364 0.0909091
-0.0909091 -0.227273 0.181818
Decrypted string is: ABC
|
[
{
"code": null,
"e": 1152,
"s": 1062,
"text": "Based on linear algebra Hill cipher is a polygraphic substitution cipher in cryptography."
},
{
"code": null,
"e": 1342,
"s": 1152,
"text": "To encrypt message: The key string and message string are represented as matrix form. They are multiplied then, against modulo 26. The key matrix should have inverse to decrypt the message."
},
{
"code": null,
"e": 1482,
"s": 1342,
"text": "To decrypt message: The encrypted message is multiplied by inverse key matrix used for encryption against modulo 26 to get decrypt message."
},
{
"code": null,
"e": 1500,
"s": 1482,
"text": "1 0 1\n2 4 0\n3 5 6"
},
{
"code": null,
"e": 1538,
"s": 1500,
"text": "Message string ‘ABC’ in matrix form −"
},
{
"code": null,
"e": 1544,
"s": 1538,
"text": "0\n1\n2"
},
{
"code": null,
"e": 1589,
"s": 1544,
"text": "After multiplying above two matrices we get,"
},
{
"code": null,
"e": 1596,
"s": 1589,
"text": "2\n4\n17"
},
{
"code": null,
"e": 1638,
"s": 1596,
"text": "Which will be the encrypted message ‘CER’"
},
{
"code": null,
"e": 1665,
"s": 1638,
"text": "Inverse of key matrix is −"
},
{
"code": null,
"e": 1751,
"s": 1665,
"text": "1.09091 0.227273 -0.181818\n-0.545455 0.136364 0.0909091\n-0.0909091 -0.227273 0.181818"
},
{
"code": null,
"e": 1841,
"s": 1751,
"text": "Now after multiplying the inverse matrix of key matrix with encrypted message matrix is −"
},
{
"code": null,
"e": 1847,
"s": 1841,
"text": "0\n1\n2"
},
{
"code": null,
"e": 1894,
"s": 1847,
"text": "Which is the original message string is ‘ABC’."
},
{
"code": null,
"e": 1945,
"s": 1894,
"text": "Here, is a C++ program to implement above example."
},
{
"code": null,
"e": 2709,
"s": 1945,
"text": "Begin\nFunction getKeyMatrix()\n For i = 0 to 2\n For j = 0 to 3\n Take the elements of matrix a[i][j] as input.\n m[i][j] = a[i][j]\n done\n done\n Take the message string as user input.\n For i = 0 to 2\n msg[i][0] = mes[i] - 65\n done\nEnd\nBegin\nFunction encrypt()\n For i = 0 to 2\n For j = 0 to 0\n For k = 0 to 2\n en[i][j] = en[i][j] + a[i][k] * msg[k][j]\n Take modulo 26 for each element of the matrix obtained by multiplication and print the encrypted message.\nEnd\nBegin\nFunction decrypt()\n Call function inversematrix()\n For i = 0 to 2\n For j = 0 to 0\n For k = 0 to 2\n de[i][j] = de[i][j] + b[i][k] * en[k][j]\nTake modulo 26 of the multiplication to get the original message."
},
{
"code": null,
"e": 4738,
"s": 2709,
"text": "#include<iostream>\n#include<math.h>\nusing namespace std;\nfloat en[3][1], de[3][1], a[3][3], b[3][3], msg[3][1], m[3][3];\nvoid getKeyMatrix() { //get key and message from user\n int i, j;\n char mes[3];\n cout<<\"Enter 3x3 matrix for key (should have inverse):\\n\";\n for(i = 0; i < 3; i++)\n for(j = 0; j < 3; j++) {\n cin>>a[i][j];\n m[i][j] = a[i][j];\n }\n cout<<\"\\nEnter a string of 3 letter(use A through Z): \";\n cin>>mes;\n for(i = 0; i < 3; i++)\n msg[i][0] = mes[i] - 65;\n}\nvoid encrypt() { //encrypts the message\n int i, j, k;\n for(i = 0; i < 3; i++)\n for(j = 0; j < 1; j++)\n for(k = 0; k < 3; k++)\n en[i][j] = en[i][j] + a[i][k] * msg[k][j];\n cout<<\"\\nEncrypted string is: \";\n for(i = 0; i < 3; i++)\n cout<<(char)(fmod(en[i][0], 26) + 65); //modulo 26 is taken for each element of the matrix obtained by multiplication\n}\nvoid inversematrix() { //find inverse of key matrix\n int i, j, k;\n float p, q;\n for(i = 0; i < 3; i++)\n for(j = 0; j < 3; j++) {\n if(i == j)\n b[i][j]=1;\n else\n b[i][j]=0;\n }\n for(k = 0; k < 3; k++) {\n for(i = 0; i < 3; i++) {\n p = m[i][k];\n q = m[k][k];\n for(j = 0; j < 3; j++) {\n if(i != k) {\n m[i][j] = m[i][j]*q - p*m[k][j];\n b[i][j] = b[i][j]*q - p*b[k][j];\n }\n }\n }\n }\n for(i = 0; i < 3; i++)\n for(j = 0; j < 3; j++)\n b[i][j] = b[i][j] / m[i][i];\n cout<<\"\\n\\nInverse Matrix is:\\n\";\n for(i = 0; i < 3; i++) {\n for(j = 0; j < 3; j++)\n cout<<b[i][j]<<\" \";\n cout<<\"\\n\";\n }\n}\nvoid decrypt() { //decrypt the message\n int i, j, k;\n inversematrix();\n for(i = 0; i < 3; i++)\n for(j = 0; j < 1; j++)\n for(k = 0; k < 3; k++)\n de[i][j] = de[i][j] + b[i][k] * en[k][j];\n cout<<\"\\nDecrypted string is: \";\n for(i = 0; i < 3; i++)\n cout<<(char)(fmod(de[i][0], 26) + 65); //modulo 26 is taken to get the original message\n cout<<\"\\n\";\n}\nint main() {\n getKeyMatrix();\n encrypt();\n decrypt();\n}"
},
{
"code": null,
"e": 5012,
"s": 4738,
"text": "Enter 3x3 matrix for key (should have inverse):\n1\n0\n1\n2\n4\n0\n3\n5\n6\n\nEnter a string of 3 letter(use A through Z): ABC\n\nEncrypted string is: CER\n\nInverse Matrix is:\n1.09091 0.227273 -0.181818\n-0.545455 0.136364 0.0909091\n-0.0909091 -0.227273 0.181818\n\nDecrypted string is: ABC"
}
] |
Pull an element in sub of sub-array in MongoDB?
|
To pull an element, use $pull along with $(positional) operator. Let us create a collection with documents −
> db.demo679.insertOne(
... {
... id:1,
... "details": [
... {
... CountryName:"US",
... "information": [
...
... { "Name": "Chris", "FirstName": "Name=Chris" },
...
... {"Name": "Bob", "FirstName": "Name=Bob" }
... ]
... },
... {
... CountryName:"UK",
... "information": [
...
... { "Name": "Robert", "FirstName": "Name=Robert" },
...
... {"Name": "Sam", "FirstName": "Name=Sam" }
... ]
... }
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5ea442cf04263e90dac943fd")
}
Display all documents from a collection with the help of find() method −
> db.demo679.find();
This will produce the following output −
{ "_id" : ObjectId("5ea442cf04263e90dac943fd"), "id" : 1, "details" : [
{ "CountryName" : "US", "information" : [
{ "Name" : "Chris", "FirstName" : "Name=Chris" },
{ "Name" : "Bob", "FirstName" : "Name=Bob" }
] },
{ "CountryName" : "UK", "information" : [
{ "Name" : "Robert", "FirstName" : "Name=Robert" },
{ "Name" : "Sam", "FirstName" : "Name=Sam" }
] }
] }
Following is the query to pull an element in sub of sub-array in MongoDB −
> db.demo679.update(
... { "details.CountryName":"US" },
... { $pull: { 'details.$.information': { "Name" : "Bob", "FirstName" : "Name=Bob" } } }
... );
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo679.find().pretty();
This will produce the following output −
{
"_id" : ObjectId("5ea442cf04263e90dac943fd"),
"id" : 1,
"details" : [
{
"CountryName" : "US",
"information" : [
{
"Name" : "Chris",
"FirstName" : "Name=Chris"
}
]
},
{
"CountryName" : "UK",
"information" : [
{
"Name" : "Robert",
"FirstName" : "Name=Robert"
},
{
"Name" : "Sam",
"FirstName" : "Name=Sam"
}
]
}
]
}
|
[
{
"code": null,
"e": 1171,
"s": 1062,
"text": "To pull an element, use $pull along with $(positional) operator. Let us create a collection with documents −"
},
{
"code": null,
"e": 1861,
"s": 1171,
"text": "> db.demo679.insertOne(\n... {\n... id:1,\n... \"details\": [\n... {\n... CountryName:\"US\",\n... \"information\": [\n...\n... { \"Name\": \"Chris\", \"FirstName\": \"Name=Chris\" },\n...\n... {\"Name\": \"Bob\", \"FirstName\": \"Name=Bob\" }\n... ]\n... },\n... {\n... CountryName:\"UK\",\n... \"information\": [\n...\n... { \"Name\": \"Robert\", \"FirstName\": \"Name=Robert\" },\n...\n... {\"Name\": \"Sam\", \"FirstName\": \"Name=Sam\" }\n... ]\n... }\n... ]\n... }\n... );\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5ea442cf04263e90dac943fd\")\n}"
},
{
"code": null,
"e": 1934,
"s": 1861,
"text": "Display all documents from a collection with the help of find() method −"
},
{
"code": null,
"e": 1955,
"s": 1934,
"text": "> db.demo679.find();"
},
{
"code": null,
"e": 1996,
"s": 1955,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2395,
"s": 1996,
"text": "{ \"_id\" : ObjectId(\"5ea442cf04263e90dac943fd\"), \"id\" : 1, \"details\" : [\n { \"CountryName\" : \"US\", \"information\" : [\n { \"Name\" : \"Chris\", \"FirstName\" : \"Name=Chris\" },\n { \"Name\" : \"Bob\", \"FirstName\" : \"Name=Bob\" }\n ] },\n { \"CountryName\" : \"UK\", \"information\" : [\n { \"Name\" : \"Robert\", \"FirstName\" : \"Name=Robert\" },\n { \"Name\" : \"Sam\", \"FirstName\" : \"Name=Sam\" }\n ] } \n] }"
},
{
"code": null,
"e": 2470,
"s": 2395,
"text": "Following is the query to pull an element in sub of sub-array in MongoDB −"
},
{
"code": null,
"e": 2695,
"s": 2470,
"text": "> db.demo679.update(\n... { \"details.CountryName\":\"US\" },\n... { $pull: { 'details.$.information': { \"Name\" : \"Bob\", \"FirstName\" : \"Name=Bob\" } } }\n... );\nWriteResult({ \"nMatched\" : 1, \"nUpserted\" : 0, \"nModified\" : 1 })"
},
{
"code": null,
"e": 2768,
"s": 2695,
"text": "Display all documents from a collection with the help of find() method −"
},
{
"code": null,
"e": 2798,
"s": 2768,
"text": "> db.demo679.find().pretty();"
},
{
"code": null,
"e": 2839,
"s": 2798,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 3406,
"s": 2839,
"text": "{\n \"_id\" : ObjectId(\"5ea442cf04263e90dac943fd\"),\n \"id\" : 1,\n \"details\" : [\n {\n \"CountryName\" : \"US\",\n \"information\" : [\n {\n \"Name\" : \"Chris\",\n \"FirstName\" : \"Name=Chris\"\n }\n ]\n },\n {\n \"CountryName\" : \"UK\",\n \"information\" : [\n {\n \"Name\" : \"Robert\",\n \"FirstName\" : \"Name=Robert\"\n },\n {\n \"Name\" : \"Sam\",\n \"FirstName\" : \"Name=Sam\"\n }\n ]\n }\n ]\n}"
}
] |
How to add background music to your web page?
|
To add background music on a web page, use <embed>...</embed> element. Also, use the autoplay attribute. This will run music in the background whenever the page loads.
Set the width and height in a way the player hides on the web page. The loop attribute is added to specify whether the audio will start over again. Add the music file to the server and mention the link in src attribute.
You can try to run the following code to add background music to your web page:
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>HTML background music</title>
</head>
<body>
<p>The music is running in the background.</p>
<p>(Song: Kalimba which is provided as a Sample Music in Windows)</p>
<embed src="/html/Kalimba.mp3" loop="true" autostart="true" width="2" height="0">
</body>
</html>
|
[
{
"code": null,
"e": 1230,
"s": 1062,
"text": "To add background music on a web page, use <embed>...</embed> element. Also, use the autoplay attribute. This will run music in the background whenever the page loads."
},
{
"code": null,
"e": 1450,
"s": 1230,
"text": "Set the width and height in a way the player hides on the web page. The loop attribute is added to specify whether the audio will start over again. Add the music file to the server and mention the link in src attribute."
},
{
"code": null,
"e": 1530,
"s": 1450,
"text": "You can try to run the following code to add background music to your web page:"
},
{
"code": null,
"e": 1540,
"s": 1530,
"text": "Live Demo"
},
{
"code": null,
"e": 1873,
"s": 1540,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>HTML background music</title>\n </head>\n <body>\n <p>The music is running in the background.</p>\n <p>(Song: Kalimba which is provided as a Sample Music in Windows)</p>\n <embed src=\"/html/Kalimba.mp3\" loop=\"true\" autostart=\"true\" width=\"2\" height=\"0\">\n </body>\n</html>"
}
] |
Analytical Hashing Techniques. Spark SQL Functions to Simplify your... | by Scott Haines | Towards Data Science
|
Anyone working in the field of analytics and machine learning will eventually need to generate strong composite grouping keys, and idempotent identifiers, for the data they are working with. These cryptographically strong identifiers help to reduce the amount of effort required to do complex bucketing, deduplication, and a slew of other important tasks.
We will look at two ways of generating hashes:
Using Base64 Encoding and String ConcatenationUsing Murmur Hashing & Base64 Encoding
Using Base64 Encoding and String Concatenation
Using Murmur Hashing & Base64 Encoding
The core spark sql functions library is a prebuilt library with over 300 common SQL functions. However, looking at the functions index and simply listing things isn’t as memorable as running the code itself. If you have the spark-shell, then you can follow along and learn some analytical hashing techniques.
$SPARK_HOME/bin/spark-shell
With the spark-shell up and running, you can follow the next step just by running :paste in the shell to paste multiline. *(:paste, then paste the code, and then cmd+D to process the code)
import org.apache.spark.sql._import org.apache.spark.sql.functions._import org.apache.spark.sql.types._import spark.implicits._
val schema = new StructType() .add(StructField("name", StringType, true)) .add(StructField("emotion", StringType, true)) .add(StructField("uuid", IntegerType, true))val df = spark .createDataFrame( spark.sparkContext.parallelize( Seq( Row("happy","smile", 1),Row("angry", "frown", 2)) ), schema )
At this point you should have a very simple DataFrame that you can now apply the Spark SQL Functions to. The contents of which are shown using df.show().
scala> df.show()+-----+-------+----+| name|emotion|uuid|+-----+-------+----+|happy| smile| 1||angry| frown| 2|+-----+-------+----+
Now we have a simple data frame. Next we can add a base64 encoder column to the DataFrame simply by using the withColumn function and passing in the Spark SQL Functions we want to use.
Base64 Encoded String Values
val hashed = df.withColumn( "hash", base64( concat_ws("-", $"name", $"emotion") ))
The results of this transformation yield us a new column that is the result of base64 encoding the concatenated string values from the columns name and emotion. This is broken down as the following flow.
df.withColumn("concat", concat_ws("-",$"name",$"emotion")) .select("concat") .show+-----------+| concat|+-----------+|happy-smile||angry-frown|+-----------+
The end result of the full columnar expression is as follows.
scala> hashed.show()+-----+-------+----+----------------+| name|emotion|uuid| hash|+-----+-------+----+----------------+|happy| smile| 1|aGFwcHktc21pbGU=||angry| frown| 2|YW5ncnktZnJvd24=|+-----+-------+----+----------------+
Nice. Right.
Next. We can look at a stronger technique for hashing. This uses the Murmur3 Hashing algorithm, and explicit binary transformations before feeding into the base64 encoder.
There are many ways to generate a hash, and the application of hashing can be used from bucketing, to graph traversal. When you want to create strong hash codes you can rely on different hashing techniques from Cyclic Redundancy Checks (CRC), to the efficient Murmur Hash (v3). We will use what we can get for free in Spark which is the Murmur3.
hashed.withColumn("binhash", base64(bin(hash($"name",$"emotion")))).select("uuid", "hash", "binhash").show(false)
Which will return the following rows (comparing the two hashing methods) based on the same input data.
+----+----------------+--------------------------------------------+|uuid|hash |binhash |+----+----------------+--------------------------------------------+|1 |aGFwcHktc21pbGU=|MTAxMTEwMDAxMTAwMDAwMTAwMDAwMDEwMTExMDAxMA==||2 |YW5ncnktZnJvd24=|MTEwMTAwMDEwMTExMTExMDEwMDAwMDExMDAxMTAxMA==|+----+----------------+--------------------------------------------+
If you are curious to see how Spark works behind the scenes there is a great new feature of the explain function that will enable you to view the code that Spark generates (and optimizes) for your transformations. To view this, all you need to do is the following.
hashed.withColumn("binhash", base64(bin(hash($"name",$"emotion")))).select("binhash").explain("codegen")
This will output the java code and explain more about your computation.
This code is part of Spark’s Catalyst Optimizer and luckily there is a high probability you will never have to work at this lower level and can likely just go on with your life. But if you are writing custom data source readers and writers then this will likely be something you will want to deep dive into. If nothing else you can learn more about the underlying mechanics, in the example use case from above, the codegen details the use of the murmur hash library being used. This is a nice tool for debugging and for those who just want to learn in a 360 degree model.
You now have two more techniques that you can use in order to create strong composite keys or to use as a spring board for creating idempotent keys. I just thought it would be fun to share these techniques since they come in handy and reuse the core libraries that ship along side Spark. Happy Trails.
|
[
{
"code": null,
"e": 528,
"s": 172,
"text": "Anyone working in the field of analytics and machine learning will eventually need to generate strong composite grouping keys, and idempotent identifiers, for the data they are working with. These cryptographically strong identifiers help to reduce the amount of effort required to do complex bucketing, deduplication, and a slew of other important tasks."
},
{
"code": null,
"e": 575,
"s": 528,
"text": "We will look at two ways of generating hashes:"
},
{
"code": null,
"e": 660,
"s": 575,
"text": "Using Base64 Encoding and String ConcatenationUsing Murmur Hashing & Base64 Encoding"
},
{
"code": null,
"e": 707,
"s": 660,
"text": "Using Base64 Encoding and String Concatenation"
},
{
"code": null,
"e": 746,
"s": 707,
"text": "Using Murmur Hashing & Base64 Encoding"
},
{
"code": null,
"e": 1055,
"s": 746,
"text": "The core spark sql functions library is a prebuilt library with over 300 common SQL functions. However, looking at the functions index and simply listing things isn’t as memorable as running the code itself. If you have the spark-shell, then you can follow along and learn some analytical hashing techniques."
},
{
"code": null,
"e": 1083,
"s": 1055,
"text": "$SPARK_HOME/bin/spark-shell"
},
{
"code": null,
"e": 1272,
"s": 1083,
"text": "With the spark-shell up and running, you can follow the next step just by running :paste in the shell to paste multiline. *(:paste, then paste the code, and then cmd+D to process the code)"
},
{
"code": null,
"e": 1400,
"s": 1272,
"text": "import org.apache.spark.sql._import org.apache.spark.sql.functions._import org.apache.spark.sql.types._import spark.implicits._"
},
{
"code": null,
"e": 1729,
"s": 1400,
"text": "val schema = new StructType() .add(StructField(\"name\", StringType, true)) .add(StructField(\"emotion\", StringType, true)) .add(StructField(\"uuid\", IntegerType, true))val df = spark .createDataFrame( spark.sparkContext.parallelize( Seq( Row(\"happy\",\"smile\", 1),Row(\"angry\", \"frown\", 2)) ), schema )"
},
{
"code": null,
"e": 1883,
"s": 1729,
"text": "At this point you should have a very simple DataFrame that you can now apply the Spark SQL Functions to. The contents of which are shown using df.show()."
},
{
"code": null,
"e": 2020,
"s": 1883,
"text": "scala> df.show()+-----+-------+----+| name|emotion|uuid|+-----+-------+----+|happy| smile| 1||angry| frown| 2|+-----+-------+----+"
},
{
"code": null,
"e": 2205,
"s": 2020,
"text": "Now we have a simple data frame. Next we can add a base64 encoder column to the DataFrame simply by using the withColumn function and passing in the Spark SQL Functions we want to use."
},
{
"code": null,
"e": 2234,
"s": 2205,
"text": "Base64 Encoded String Values"
},
{
"code": null,
"e": 2322,
"s": 2234,
"text": "val hashed = df.withColumn( \"hash\", base64( concat_ws(\"-\", $\"name\", $\"emotion\") ))"
},
{
"code": null,
"e": 2526,
"s": 2322,
"text": "The results of this transformation yield us a new column that is the result of base64 encoding the concatenated string values from the columns name and emotion. This is broken down as the following flow."
},
{
"code": null,
"e": 2690,
"s": 2526,
"text": "df.withColumn(\"concat\", concat_ws(\"-\",$\"name\",$\"emotion\")) .select(\"concat\") .show+-----------+| concat|+-----------+|happy-smile||angry-frown|+-----------+"
},
{
"code": null,
"e": 2752,
"s": 2690,
"text": "The end result of the full columnar expression is as follows."
},
{
"code": null,
"e": 2995,
"s": 2752,
"text": "scala> hashed.show()+-----+-------+----+----------------+| name|emotion|uuid| hash|+-----+-------+----+----------------+|happy| smile| 1|aGFwcHktc21pbGU=||angry| frown| 2|YW5ncnktZnJvd24=|+-----+-------+----+----------------+"
},
{
"code": null,
"e": 3008,
"s": 2995,
"text": "Nice. Right."
},
{
"code": null,
"e": 3180,
"s": 3008,
"text": "Next. We can look at a stronger technique for hashing. This uses the Murmur3 Hashing algorithm, and explicit binary transformations before feeding into the base64 encoder."
},
{
"code": null,
"e": 3526,
"s": 3180,
"text": "There are many ways to generate a hash, and the application of hashing can be used from bucketing, to graph traversal. When you want to create strong hash codes you can rely on different hashing techniques from Cyclic Redundancy Checks (CRC), to the efficient Murmur Hash (v3). We will use what we can get for free in Spark which is the Murmur3."
},
{
"code": null,
"e": 3641,
"s": 3526,
"text": "hashed.withColumn(\"binhash\", base64(bin(hash($\"name\",$\"emotion\")))).select(\"uuid\", \"hash\", \"binhash\").show(false)"
},
{
"code": null,
"e": 3744,
"s": 3641,
"text": "Which will return the following rows (comparing the two hashing methods) based on the same input data."
},
{
"code": null,
"e": 4153,
"s": 3744,
"text": "+----+----------------+--------------------------------------------+|uuid|hash |binhash |+----+----------------+--------------------------------------------+|1 |aGFwcHktc21pbGU=|MTAxMTEwMDAxMTAwMDAwMTAwMDAwMDEwMTExMDAxMA==||2 |YW5ncnktZnJvd24=|MTEwMTAwMDEwMTExMTExMDEwMDAwMDExMDAxMTAxMA==|+----+----------------+--------------------------------------------+"
},
{
"code": null,
"e": 4418,
"s": 4153,
"text": "If you are curious to see how Spark works behind the scenes there is a great new feature of the explain function that will enable you to view the code that Spark generates (and optimizes) for your transformations. To view this, all you need to do is the following."
},
{
"code": null,
"e": 4524,
"s": 4418,
"text": "hashed.withColumn(\"binhash\", base64(bin(hash($\"name\",$\"emotion\")))).select(\"binhash\").explain(\"codegen\")"
},
{
"code": null,
"e": 4596,
"s": 4524,
"text": "This will output the java code and explain more about your computation."
},
{
"code": null,
"e": 5168,
"s": 4596,
"text": "This code is part of Spark’s Catalyst Optimizer and luckily there is a high probability you will never have to work at this lower level and can likely just go on with your life. But if you are writing custom data source readers and writers then this will likely be something you will want to deep dive into. If nothing else you can learn more about the underlying mechanics, in the example use case from above, the codegen details the use of the murmur hash library being used. This is a nice tool for debugging and for those who just want to learn in a 360 degree model."
}
] |
Interesting and Cool Tricks in Java - GeeksforGeeks
|
07 May, 2020
Java is one of the best object-oriented programming language developed by James Gosling from Sun Microsystems in the year 1991 and was publicly available in the year 1995. It is an interpreted programming language with platform independency making it one of the best programming language among all.
In this article, we’ll see some interesting and cool tricks in Java.
Executing Comments: Most of the developers think comments are never executed in a program and are used for ease in understanding the code. But, they are executed. For example:public class GFG { public static void main(String[] args) { // \u000d System.out.println("GeeksForGeeks"); }}Output:GeeksForGeeks
Explanation:This comment is executed because of Unicode character “\u000d” and java compiler parses this unicode character as a new line. Java allows using Unicode characters without encoding.Underscore in Numeric Literals: In Java SE 7 and above, underscores can be used in numeric literals without generating any warning or error in the output.Example:public class GFG { public static void main(String[] args) { int x = 123_34; System.out.println(x); }}Output:12334
Double Brace Initialization: In Java, collections such as sets, lists, maps, etc. does not have a simple and easy way to initialize the values during declaration. Developers either push values into the collection or creates a static block for the constant collection. Using double brace initialization, collections can be initialized during declaration with less efforts and time.Example:import java.util.HashSet;import java.util.Set; public class GFG { public static void main(String[] args) { Set<String> GFG = new HashSet<String>() {{ add("DS"); add("ALGORITHMS"); add("BLOCKCHAIN"); add("MACHINE LEARNING"); } }; System.out.println(GFG); }}Output:[MACHINE LEARNING, ALGORITHMS, DS, BLOCKCHAIN]
Finding a position to insert the numeric element in the array: There is a small cool trick to find the position where the requested element can be inserted in the sorted array.Example:import java.util.Arrays;public class GFG { public static void main(String[] args) { int[] arr = new int[] { 1, 3, 4, 5, 6 }; // 2 has to be inserted int pos = Arrays.binarySearch(arr, 2); System.out.print("Element has to be inserted at: " + ~pos); }}Output:Element has to be inserted at: 1
Wrapper class vs datatype: In the below example, the second print statement will not display true because reference of wrapper class objects are getting compared and not their values.import java.util.Arrays;public class GFG { public static void main(String[] args) { int num_1 = 10; int num_2 = 10; Integer wrapnum_1 = new Integer(10); Integer wrapnum_2 = new Integer(10); System.out.println(num_1 == num_2); // Compares reference System.out.println(wrapnum_1 == wrapnum_2); // Compares value of object System.out.println(wrapnum_1.equals(wrapnum_2)); }}Output:true
false
true
My Personal Notes
arrow_drop_upSave
Executing Comments: Most of the developers think comments are never executed in a program and are used for ease in understanding the code. But, they are executed. For example:public class GFG { public static void main(String[] args) { // \u000d System.out.println("GeeksForGeeks"); }}Output:GeeksForGeeks
Explanation:This comment is executed because of Unicode character “\u000d” and java compiler parses this unicode character as a new line. Java allows using Unicode characters without encoding.
public class GFG { public static void main(String[] args) { // \u000d System.out.println("GeeksForGeeks"); }}
GeeksForGeeks
Explanation:This comment is executed because of Unicode character “\u000d” and java compiler parses this unicode character as a new line. Java allows using Unicode characters without encoding.
Underscore in Numeric Literals: In Java SE 7 and above, underscores can be used in numeric literals without generating any warning or error in the output.Example:public class GFG { public static void main(String[] args) { int x = 123_34; System.out.println(x); }}Output:12334
Example:
public class GFG { public static void main(String[] args) { int x = 123_34; System.out.println(x); }}
12334
Double Brace Initialization: In Java, collections such as sets, lists, maps, etc. does not have a simple and easy way to initialize the values during declaration. Developers either push values into the collection or creates a static block for the constant collection. Using double brace initialization, collections can be initialized during declaration with less efforts and time.Example:import java.util.HashSet;import java.util.Set; public class GFG { public static void main(String[] args) { Set<String> GFG = new HashSet<String>() {{ add("DS"); add("ALGORITHMS"); add("BLOCKCHAIN"); add("MACHINE LEARNING"); } }; System.out.println(GFG); }}Output:[MACHINE LEARNING, ALGORITHMS, DS, BLOCKCHAIN]
Example:
import java.util.HashSet;import java.util.Set; public class GFG { public static void main(String[] args) { Set<String> GFG = new HashSet<String>() {{ add("DS"); add("ALGORITHMS"); add("BLOCKCHAIN"); add("MACHINE LEARNING"); } }; System.out.println(GFG); }}
[MACHINE LEARNING, ALGORITHMS, DS, BLOCKCHAIN]
Finding a position to insert the numeric element in the array: There is a small cool trick to find the position where the requested element can be inserted in the sorted array.Example:import java.util.Arrays;public class GFG { public static void main(String[] args) { int[] arr = new int[] { 1, 3, 4, 5, 6 }; // 2 has to be inserted int pos = Arrays.binarySearch(arr, 2); System.out.print("Element has to be inserted at: " + ~pos); }}Output:Element has to be inserted at: 1
Example:
import java.util.Arrays;public class GFG { public static void main(String[] args) { int[] arr = new int[] { 1, 3, 4, 5, 6 }; // 2 has to be inserted int pos = Arrays.binarySearch(arr, 2); System.out.print("Element has to be inserted at: " + ~pos); }}
Element has to be inserted at: 1
Wrapper class vs datatype: In the below example, the second print statement will not display true because reference of wrapper class objects are getting compared and not their values.import java.util.Arrays;public class GFG { public static void main(String[] args) { int num_1 = 10; int num_2 = 10; Integer wrapnum_1 = new Integer(10); Integer wrapnum_2 = new Integer(10); System.out.println(num_1 == num_2); // Compares reference System.out.println(wrapnum_1 == wrapnum_2); // Compares value of object System.out.println(wrapnum_1.equals(wrapnum_2)); }}Output:true
false
true
My Personal Notes
arrow_drop_upSave
import java.util.Arrays;public class GFG { public static void main(String[] args) { int num_1 = 10; int num_2 = 10; Integer wrapnum_1 = new Integer(10); Integer wrapnum_2 = new Integer(10); System.out.println(num_1 == num_2); // Compares reference System.out.println(wrapnum_1 == wrapnum_2); // Compares value of object System.out.println(wrapnum_1.equals(wrapnum_2)); }}
true
false
true
Articles
GBlog
GFacts
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Analysis of Algorithms | Set 1 (Asymptotic Analysis)
Mutex vs Semaphore
Time Complexity and Space Complexity
Understanding "extern" keyword in C
SQL | Views
Roadmap to Become a Web Developer in 2022
Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ...
Socket Programming in C/C++
DSA Sheet by Love Babbar
GET and POST requests using Python
|
[
{
"code": null,
"e": 24628,
"s": 24600,
"text": "\n07 May, 2020"
},
{
"code": null,
"e": 24927,
"s": 24628,
"text": "Java is one of the best object-oriented programming language developed by James Gosling from Sun Microsystems in the year 1991 and was publicly available in the year 1995. It is an interpreted programming language with platform independency making it one of the best programming language among all."
},
{
"code": null,
"e": 24996,
"s": 24927,
"text": "In this article, we’ll see some interesting and cool tricks in Java."
},
{
"code": null,
"e": 27840,
"s": 24996,
"text": "Executing Comments: Most of the developers think comments are never executed in a program and are used for ease in understanding the code. But, they are executed. For example:public class GFG { public static void main(String[] args) { // \\u000d System.out.println(\"GeeksForGeeks\"); }}Output:GeeksForGeeks\nExplanation:This comment is executed because of Unicode character “\\u000d” and java compiler parses this unicode character as a new line. Java allows using Unicode characters without encoding.Underscore in Numeric Literals: In Java SE 7 and above, underscores can be used in numeric literals without generating any warning or error in the output.Example:public class GFG { public static void main(String[] args) { int x = 123_34; System.out.println(x); }}Output:12334\nDouble Brace Initialization: In Java, collections such as sets, lists, maps, etc. does not have a simple and easy way to initialize the values during declaration. Developers either push values into the collection or creates a static block for the constant collection. Using double brace initialization, collections can be initialized during declaration with less efforts and time.Example:import java.util.HashSet;import java.util.Set; public class GFG { public static void main(String[] args) { Set<String> GFG = new HashSet<String>() {{ add(\"DS\"); add(\"ALGORITHMS\"); add(\"BLOCKCHAIN\"); add(\"MACHINE LEARNING\"); } }; System.out.println(GFG); }}Output:[MACHINE LEARNING, ALGORITHMS, DS, BLOCKCHAIN]\nFinding a position to insert the numeric element in the array: There is a small cool trick to find the position where the requested element can be inserted in the sorted array.Example:import java.util.Arrays;public class GFG { public static void main(String[] args) { int[] arr = new int[] { 1, 3, 4, 5, 6 }; // 2 has to be inserted int pos = Arrays.binarySearch(arr, 2); System.out.print(\"Element has to be inserted at: \" + ~pos); }}Output:Element has to be inserted at: 1\nWrapper class vs datatype: In the below example, the second print statement will not display true because reference of wrapper class objects are getting compared and not their values.import java.util.Arrays;public class GFG { public static void main(String[] args) { int num_1 = 10; int num_2 = 10; Integer wrapnum_1 = new Integer(10); Integer wrapnum_2 = new Integer(10); System.out.println(num_1 == num_2); // Compares reference System.out.println(wrapnum_1 == wrapnum_2); // Compares value of object System.out.println(wrapnum_1.equals(wrapnum_2)); }}Output:true\nfalse\ntrue\nMy Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 28354,
"s": 27840,
"text": "Executing Comments: Most of the developers think comments are never executed in a program and are used for ease in understanding the code. But, they are executed. For example:public class GFG { public static void main(String[] args) { // \\u000d System.out.println(\"GeeksForGeeks\"); }}Output:GeeksForGeeks\nExplanation:This comment is executed because of Unicode character “\\u000d” and java compiler parses this unicode character as a new line. Java allows using Unicode characters without encoding."
},
{
"code": "public class GFG { public static void main(String[] args) { // \\u000d System.out.println(\"GeeksForGeeks\"); }}",
"e": 28480,
"s": 28354,
"text": null
},
{
"code": null,
"e": 28495,
"s": 28480,
"text": "GeeksForGeeks\n"
},
{
"code": null,
"e": 28688,
"s": 28495,
"text": "Explanation:This comment is executed because of Unicode character “\\u000d” and java compiler parses this unicode character as a new line. Java allows using Unicode characters without encoding."
},
{
"code": null,
"e": 28988,
"s": 28688,
"text": "Underscore in Numeric Literals: In Java SE 7 and above, underscores can be used in numeric literals without generating any warning or error in the output.Example:public class GFG { public static void main(String[] args) { int x = 123_34; System.out.println(x); }}Output:12334\n"
},
{
"code": null,
"e": 28997,
"s": 28988,
"text": "Example:"
},
{
"code": "public class GFG { public static void main(String[] args) { int x = 123_34; System.out.println(x); }}",
"e": 29122,
"s": 28997,
"text": null
},
{
"code": null,
"e": 29129,
"s": 29122,
"text": "12334\n"
},
{
"code": null,
"e": 29903,
"s": 29129,
"text": "Double Brace Initialization: In Java, collections such as sets, lists, maps, etc. does not have a simple and easy way to initialize the values during declaration. Developers either push values into the collection or creates a static block for the constant collection. Using double brace initialization, collections can be initialized during declaration with less efforts and time.Example:import java.util.HashSet;import java.util.Set; public class GFG { public static void main(String[] args) { Set<String> GFG = new HashSet<String>() {{ add(\"DS\"); add(\"ALGORITHMS\"); add(\"BLOCKCHAIN\"); add(\"MACHINE LEARNING\"); } }; System.out.println(GFG); }}Output:[MACHINE LEARNING, ALGORITHMS, DS, BLOCKCHAIN]\n"
},
{
"code": null,
"e": 29912,
"s": 29903,
"text": "Example:"
},
{
"code": "import java.util.HashSet;import java.util.Set; public class GFG { public static void main(String[] args) { Set<String> GFG = new HashSet<String>() {{ add(\"DS\"); add(\"ALGORITHMS\"); add(\"BLOCKCHAIN\"); add(\"MACHINE LEARNING\"); } }; System.out.println(GFG); }}",
"e": 30244,
"s": 29912,
"text": null
},
{
"code": null,
"e": 30292,
"s": 30244,
"text": "[MACHINE LEARNING, ALGORITHMS, DS, BLOCKCHAIN]\n"
},
{
"code": null,
"e": 30855,
"s": 30292,
"text": "Finding a position to insert the numeric element in the array: There is a small cool trick to find the position where the requested element can be inserted in the sorted array.Example:import java.util.Arrays;public class GFG { public static void main(String[] args) { int[] arr = new int[] { 1, 3, 4, 5, 6 }; // 2 has to be inserted int pos = Arrays.binarySearch(arr, 2); System.out.print(\"Element has to be inserted at: \" + ~pos); }}Output:Element has to be inserted at: 1\n"
},
{
"code": null,
"e": 30864,
"s": 30855,
"text": "Example:"
},
{
"code": "import java.util.Arrays;public class GFG { public static void main(String[] args) { int[] arr = new int[] { 1, 3, 4, 5, 6 }; // 2 has to be inserted int pos = Arrays.binarySearch(arr, 2); System.out.print(\"Element has to be inserted at: \" + ~pos); }}",
"e": 31203,
"s": 30864,
"text": null
},
{
"code": null,
"e": 31237,
"s": 31203,
"text": "Element has to be inserted at: 1\n"
},
{
"code": null,
"e": 31934,
"s": 31237,
"text": "Wrapper class vs datatype: In the below example, the second print statement will not display true because reference of wrapper class objects are getting compared and not their values.import java.util.Arrays;public class GFG { public static void main(String[] args) { int num_1 = 10; int num_2 = 10; Integer wrapnum_1 = new Integer(10); Integer wrapnum_2 = new Integer(10); System.out.println(num_1 == num_2); // Compares reference System.out.println(wrapnum_1 == wrapnum_2); // Compares value of object System.out.println(wrapnum_1.equals(wrapnum_2)); }}Output:true\nfalse\ntrue\nMy Personal Notes\narrow_drop_upSave"
},
{
"code": "import java.util.Arrays;public class GFG { public static void main(String[] args) { int num_1 = 10; int num_2 = 10; Integer wrapnum_1 = new Integer(10); Integer wrapnum_2 = new Integer(10); System.out.println(num_1 == num_2); // Compares reference System.out.println(wrapnum_1 == wrapnum_2); // Compares value of object System.out.println(wrapnum_1.equals(wrapnum_2)); }}",
"e": 32390,
"s": 31934,
"text": null
},
{
"code": null,
"e": 32407,
"s": 32390,
"text": "true\nfalse\ntrue\n"
},
{
"code": null,
"e": 32416,
"s": 32407,
"text": "Articles"
},
{
"code": null,
"e": 32422,
"s": 32416,
"text": "GBlog"
},
{
"code": null,
"e": 32429,
"s": 32422,
"text": "GFacts"
},
{
"code": null,
"e": 32434,
"s": 32429,
"text": "Java"
},
{
"code": null,
"e": 32439,
"s": 32434,
"text": "Java"
},
{
"code": null,
"e": 32537,
"s": 32439,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32590,
"s": 32537,
"text": "Analysis of Algorithms | Set 1 (Asymptotic Analysis)"
},
{
"code": null,
"e": 32609,
"s": 32590,
"text": "Mutex vs Semaphore"
},
{
"code": null,
"e": 32646,
"s": 32609,
"text": "Time Complexity and Space Complexity"
},
{
"code": null,
"e": 32682,
"s": 32646,
"text": "Understanding \"extern\" keyword in C"
},
{
"code": null,
"e": 32694,
"s": 32682,
"text": "SQL | Views"
},
{
"code": null,
"e": 32736,
"s": 32694,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 32810,
"s": 32736,
"text": "Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ..."
},
{
"code": null,
"e": 32838,
"s": 32810,
"text": "Socket Programming in C/C++"
},
{
"code": null,
"e": 32863,
"s": 32838,
"text": "DSA Sheet by Love Babbar"
}
] |
Accenture On Campus 2020 Placement Drive - GeeksforGeeks
|
07 Oct, 2021
The recruitment of the Accenture process started with a Pre Placement Talk. Where the HR explained the hiring process of the company. There were two roles available for the Drive, ASE(Associate Software Engineer) and FSE (Full Stack Engineer).
Round 1: It was a Communication Assessment test. This Communication Assessment focuses on testing the communication skills of the candidate.
After registering for the Accenture Campus placement drive. I have got a link to attend the communication assessment. I gave the communication assessment from home in front of a camera. The communication assessment pattern was the same as discussed by faceprep.
Round 2: This round was on Cognitive and Technical assessment. The Online test was conducted by CoCubes. There were a total of 90 minutes to solve the test. The Online test consists of 4 sections.
Verbal: Paragraphs, Synonyms, Antonyms, Comprehension reading, Plural nouns, Odd one out, One-word substitution.
Logical Reasoning: Coding-Decoding, Statement, Cause and effect, Venn diagram-based questions, series
Quantitative Aptitude: Profit and Loss, Height and Distances, Work and Time, Trigonometry, Simple and Compound Interest, Percentages, Problem on ages.
Technical Questions: Pseudocode (mostly on recursion), Basics of MS Office, Shortcut keys.
There was no sectional time, but there was a sectional cutoff. Time management created a bit of a problem for me. As there were only 10 minutes remaining when I started attempting technical questions. Without wasting much time on solving the pseudocode firstly, I solved all the questions related to the basics of MS Office and shortcut keys. After that, I started attempting pseudocode, the pseudocode was lengthy. I am not able to solve all the pseudocode. In the last 1 min, I Fluked all the remaining technical questions. For that 1 min, I lost the hope of clearing this online exam, as I fluked more than 50% of the technical questions. Moreover, there was a sectional cut off.
After submitting the exam, my computer screen was looking different from the other student’s screen. I started wondering why my screen was looking different from other students. Then my friend sitting beside me told read whats written on the screen, that I have cleared the Online test and I have a choice to opt-in or opt-out for FSE role.
Seriously I was very much happy because the first time my Flukes came true for any online exam. After that, I made a choice to opt-in for the FSE(Full-stack engineer) role.
Round 3: Coding Assessment (Optional, Applicable only if you opt-in for FSE role).The Coding Assessment was of 30 mins with 2 questions. There were 5 languages C, C++, .Net, Java, Python. I was good in python, so I choose to solve the coding assessment in python. Both the questions were very simple.
Find the nth number from series if the x is even and mth number from series, if the x is, was odd.Series: 1^m + x or 1^n + x
Series: 1^m + x or 1^n + x
Given a list of the array, sort the array in descending order with the frequency of elements.Input : [2, 5, 6, 2, 3, 5, 5]
Output : [5, 5, 5, 2, 2, 6, 3]
Input : [2, 5, 6, 2, 3, 5, 5]
Output : [5, 5, 5, 2, 2, 6, 3]
I solved both the questions and passed all the visible test cases.
After finishing the Coding Assessment there was a lunch break for one hour. Post lunch there was a Group Interview.
Round 4: Group Interview, in the group interview, there were 5 candidates and two Interviewers. Along with me the were 4 other candidates, from every branch ME, Civil, E&TC, IT. The Interviewer questioned each of the candidates. I was the last candidate to be questioned.
Interviewer: What is Github?Me: Answered the same.
Interviewer: What are your favorite subjects?Me: DBMS, Data Structure, Machine Learning.
Interviewer: What are the different types of Normalization?Me: Normalization of Machine Learning or DBMS?
Interviewer: Normalization of DBMS.Me: There are three main types of Normalizations. 1NF, 2NF, 3NF
Interviewer: Are you sure?Me: Yes, sir
Interviewer: You are Wrong. you need to update your knowledge (Rudely)
I got very much nervous After hearing this.
The First Interviewer gave the opportunity to another interviewer to question me.
Interviewer: What was your project during the internship?Me: Explained the same
Interviewer: What is your final year project and why you selected the same?Me: Told the same
Interviewer: You may leave now.
I was the last candidate to be questioned and the first candidate to leave from the Interview. I made the assumption that I will not be selected, As I have given 1 Wrong answer, moreover the behavior of interviewers does not seem to be pleasant.
The result was declared on the next day, Surprisingly, I got selected for the role of ASE(Associate Software Engineer). I received a Letter of Intent from Accenture for ASE role. I was wondering why I did not get selected for the FSE role. The reason may be, the FSE role was evaluated at the zonal level and along with our college, there were 2 more colleges in the Drive. Accenture almost hired 80% of students who have cleared the Cognitive and Technical assessment from our college.
Accenture
Marketing
On-Campus
Interview Experiences
Accenture
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Microsoft Interview Experience for Internship (Via Engage)
Amazon Interview Experience for SDE-1 (On-Campus)
Infosys Interview Experience for DSE - System Engineer | On-Campus 2022
Amazon Interview Experience for SDE-1
Oracle Interview Experience | Set 69 (Application Engineer)
Amazon Interview Experience for SDE-1(Off-Campus)
Amazon Interview Experience for SDE1 (8 Months Experienced) 2022
Amazon Interview Experience (Off-Campus) 2022
Amazon Interview Experience for SDE-1
Infosys DSE Interview Experience 2021
|
[
{
"code": null,
"e": 24733,
"s": 24705,
"text": "\n07 Oct, 2021"
},
{
"code": null,
"e": 24977,
"s": 24733,
"text": "The recruitment of the Accenture process started with a Pre Placement Talk. Where the HR explained the hiring process of the company. There were two roles available for the Drive, ASE(Associate Software Engineer) and FSE (Full Stack Engineer)."
},
{
"code": null,
"e": 25118,
"s": 24977,
"text": "Round 1: It was a Communication Assessment test. This Communication Assessment focuses on testing the communication skills of the candidate."
},
{
"code": null,
"e": 25380,
"s": 25118,
"text": "After registering for the Accenture Campus placement drive. I have got a link to attend the communication assessment. I gave the communication assessment from home in front of a camera. The communication assessment pattern was the same as discussed by faceprep."
},
{
"code": null,
"e": 25577,
"s": 25380,
"text": "Round 2: This round was on Cognitive and Technical assessment. The Online test was conducted by CoCubes. There were a total of 90 minutes to solve the test. The Online test consists of 4 sections."
},
{
"code": null,
"e": 25690,
"s": 25577,
"text": "Verbal: Paragraphs, Synonyms, Antonyms, Comprehension reading, Plural nouns, Odd one out, One-word substitution."
},
{
"code": null,
"e": 25792,
"s": 25690,
"text": "Logical Reasoning: Coding-Decoding, Statement, Cause and effect, Venn diagram-based questions, series"
},
{
"code": null,
"e": 25943,
"s": 25792,
"text": "Quantitative Aptitude: Profit and Loss, Height and Distances, Work and Time, Trigonometry, Simple and Compound Interest, Percentages, Problem on ages."
},
{
"code": null,
"e": 26034,
"s": 25943,
"text": "Technical Questions: Pseudocode (mostly on recursion), Basics of MS Office, Shortcut keys."
},
{
"code": null,
"e": 26717,
"s": 26034,
"text": "There was no sectional time, but there was a sectional cutoff. Time management created a bit of a problem for me. As there were only 10 minutes remaining when I started attempting technical questions. Without wasting much time on solving the pseudocode firstly, I solved all the questions related to the basics of MS Office and shortcut keys. After that, I started attempting pseudocode, the pseudocode was lengthy. I am not able to solve all the pseudocode. In the last 1 min, I Fluked all the remaining technical questions. For that 1 min, I lost the hope of clearing this online exam, as I fluked more than 50% of the technical questions. Moreover, there was a sectional cut off."
},
{
"code": null,
"e": 27058,
"s": 26717,
"text": "After submitting the exam, my computer screen was looking different from the other student’s screen. I started wondering why my screen was looking different from other students. Then my friend sitting beside me told read whats written on the screen, that I have cleared the Online test and I have a choice to opt-in or opt-out for FSE role."
},
{
"code": null,
"e": 27231,
"s": 27058,
"text": "Seriously I was very much happy because the first time my Flukes came true for any online exam. After that, I made a choice to opt-in for the FSE(Full-stack engineer) role."
},
{
"code": null,
"e": 27532,
"s": 27231,
"text": "Round 3: Coding Assessment (Optional, Applicable only if you opt-in for FSE role).The Coding Assessment was of 30 mins with 2 questions. There were 5 languages C, C++, .Net, Java, Python. I was good in python, so I choose to solve the coding assessment in python. Both the questions were very simple."
},
{
"code": null,
"e": 27657,
"s": 27532,
"text": "Find the nth number from series if the x is even and mth number from series, if the x is, was odd.Series: 1^m + x or 1^n + x"
},
{
"code": null,
"e": 27684,
"s": 27657,
"text": "Series: 1^m + x or 1^n + x"
},
{
"code": null,
"e": 27865,
"s": 27684,
"text": "Given a list of the array, sort the array in descending order with the frequency of elements.Input : [2, 5, 6, 2, 3, 5, 5] \nOutput : [5, 5, 5, 2, 2, 6, 3]"
},
{
"code": null,
"e": 27953,
"s": 27865,
"text": "Input : [2, 5, 6, 2, 3, 5, 5] \nOutput : [5, 5, 5, 2, 2, 6, 3]"
},
{
"code": null,
"e": 28020,
"s": 27953,
"text": "I solved both the questions and passed all the visible test cases."
},
{
"code": null,
"e": 28136,
"s": 28020,
"text": "After finishing the Coding Assessment there was a lunch break for one hour. Post lunch there was a Group Interview."
},
{
"code": null,
"e": 28408,
"s": 28136,
"text": "Round 4: Group Interview, in the group interview, there were 5 candidates and two Interviewers. Along with me the were 4 other candidates, from every branch ME, Civil, E&TC, IT. The Interviewer questioned each of the candidates. I was the last candidate to be questioned."
},
{
"code": null,
"e": 28459,
"s": 28408,
"text": "Interviewer: What is Github?Me: Answered the same."
},
{
"code": null,
"e": 28548,
"s": 28459,
"text": "Interviewer: What are your favorite subjects?Me: DBMS, Data Structure, Machine Learning."
},
{
"code": null,
"e": 28654,
"s": 28548,
"text": "Interviewer: What are the different types of Normalization?Me: Normalization of Machine Learning or DBMS?"
},
{
"code": null,
"e": 28753,
"s": 28654,
"text": "Interviewer: Normalization of DBMS.Me: There are three main types of Normalizations. 1NF, 2NF, 3NF"
},
{
"code": null,
"e": 28792,
"s": 28753,
"text": "Interviewer: Are you sure?Me: Yes, sir"
},
{
"code": null,
"e": 28863,
"s": 28792,
"text": "Interviewer: You are Wrong. you need to update your knowledge (Rudely)"
},
{
"code": null,
"e": 28907,
"s": 28863,
"text": "I got very much nervous After hearing this."
},
{
"code": null,
"e": 28989,
"s": 28907,
"text": "The First Interviewer gave the opportunity to another interviewer to question me."
},
{
"code": null,
"e": 29069,
"s": 28989,
"text": "Interviewer: What was your project during the internship?Me: Explained the same"
},
{
"code": null,
"e": 29162,
"s": 29069,
"text": "Interviewer: What is your final year project and why you selected the same?Me: Told the same"
},
{
"code": null,
"e": 29194,
"s": 29162,
"text": "Interviewer: You may leave now."
},
{
"code": null,
"e": 29440,
"s": 29194,
"text": "I was the last candidate to be questioned and the first candidate to leave from the Interview. I made the assumption that I will not be selected, As I have given 1 Wrong answer, moreover the behavior of interviewers does not seem to be pleasant."
},
{
"code": null,
"e": 29927,
"s": 29440,
"text": "The result was declared on the next day, Surprisingly, I got selected for the role of ASE(Associate Software Engineer). I received a Letter of Intent from Accenture for ASE role. I was wondering why I did not get selected for the FSE role. The reason may be, the FSE role was evaluated at the zonal level and along with our college, there were 2 more colleges in the Drive. Accenture almost hired 80% of students who have cleared the Cognitive and Technical assessment from our college."
},
{
"code": null,
"e": 29937,
"s": 29927,
"text": "Accenture"
},
{
"code": null,
"e": 29947,
"s": 29937,
"text": "Marketing"
},
{
"code": null,
"e": 29957,
"s": 29947,
"text": "On-Campus"
},
{
"code": null,
"e": 29979,
"s": 29957,
"text": "Interview Experiences"
},
{
"code": null,
"e": 29989,
"s": 29979,
"text": "Accenture"
},
{
"code": null,
"e": 30087,
"s": 29989,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30096,
"s": 30087,
"text": "Comments"
},
{
"code": null,
"e": 30109,
"s": 30096,
"text": "Old Comments"
},
{
"code": null,
"e": 30168,
"s": 30109,
"text": "Microsoft Interview Experience for Internship (Via Engage)"
},
{
"code": null,
"e": 30218,
"s": 30168,
"text": "Amazon Interview Experience for SDE-1 (On-Campus)"
},
{
"code": null,
"e": 30290,
"s": 30218,
"text": "Infosys Interview Experience for DSE - System Engineer | On-Campus 2022"
},
{
"code": null,
"e": 30328,
"s": 30290,
"text": "Amazon Interview Experience for SDE-1"
},
{
"code": null,
"e": 30388,
"s": 30328,
"text": "Oracle Interview Experience | Set 69 (Application Engineer)"
},
{
"code": null,
"e": 30438,
"s": 30388,
"text": "Amazon Interview Experience for SDE-1(Off-Campus)"
},
{
"code": null,
"e": 30503,
"s": 30438,
"text": "Amazon Interview Experience for SDE1 (8 Months Experienced) 2022"
},
{
"code": null,
"e": 30549,
"s": 30503,
"text": "Amazon Interview Experience (Off-Campus) 2022"
},
{
"code": null,
"e": 30587,
"s": 30549,
"text": "Amazon Interview Experience for SDE-1"
}
] |
Kotlin - Sealed Class
|
In this chapter, we will learn about another class type called “Sealed” class. This type of class is used to represent a restricted class hierarchy. Sealed allows the developers to maintain a data type of a predefined type. To make a sealed class, we need to use the keyword “sealed” as a modifier of that class. A sealed class can have its own subclass but all those subclasses need to be declared inside the same Kotlin file along with the sealed class. In the following example, we will see how to use a sealed class.
sealed class MyExample {
class OP1 : MyExample() // MyExmaple class can be of two types only
class OP2 : MyExample()
}
fun main(args: Array<String>) {
val obj: MyExample = MyExample.OP2()
val output = when (obj) { // defining the object of the class depending on the inuputs
is MyExample.OP1 -> "Option One has been chosen"
is MyExample.OP2 -> "option Two has been chosen"
}
println(output)
}
In the above example, we have one sealed class named “MyExample”, which can be of two types only - one is “OP1” and another one is “OP2”. In the main class, we are creating an object in our class and assigning its type at runtime. Now, as this “MyExample” class is sealed, we can apply the “when ” clause at runtime to implement the final output.
In sealed class, we need not use any unnecessary “else” statement to complex out the code. The above piece of code will yield the following output in the browser.
option Two has been chosen
68 Lectures
4.5 hours
Arnab Chakraborty
71 Lectures
5.5 hours
Frahaan Hussain
18 Lectures
1.5 hours
Mahmoud Ramadan
49 Lectures
6 hours
Catalin Stefan
49 Lectures
2.5 hours
Skillbakerystudios
22 Lectures
1 hours
CLEMENT OCHIENG
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2946,
"s": 2425,
"text": "In this chapter, we will learn about another class type called “Sealed” class. This type of class is used to represent a restricted class hierarchy. Sealed allows the developers to maintain a data type of a predefined type. To make a sealed class, we need to use the keyword “sealed” as a modifier of that class. A sealed class can have its own subclass but all those subclasses need to be declared inside the same Kotlin file along with the sealed class. In the following example, we will see how to use a sealed class."
},
{
"code": null,
"e": 3379,
"s": 2946,
"text": "sealed class MyExample {\n class OP1 : MyExample() // MyExmaple class can be of two types only\n class OP2 : MyExample()\n}\nfun main(args: Array<String>) {\n val obj: MyExample = MyExample.OP2() \n \n val output = when (obj) { // defining the object of the class depending on the inuputs \n is MyExample.OP1 -> \"Option One has been chosen\"\n is MyExample.OP2 -> \"option Two has been chosen\"\n }\n \n println(output)\n}"
},
{
"code": null,
"e": 3726,
"s": 3379,
"text": "In the above example, we have one sealed class named “MyExample”, which can be of two types only - one is “OP1” and another one is “OP2”. In the main class, we are creating an object in our class and assigning its type at runtime. Now, as this “MyExample” class is sealed, we can apply the “when ” clause at runtime to implement the final output."
},
{
"code": null,
"e": 3889,
"s": 3726,
"text": "In sealed class, we need not use any unnecessary “else” statement to complex out the code. The above piece of code will yield the following output in the browser."
},
{
"code": null,
"e": 3917,
"s": 3889,
"text": "option Two has been chosen\n"
},
{
"code": null,
"e": 3952,
"s": 3917,
"text": "\n 68 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3971,
"s": 3952,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 4006,
"s": 3971,
"text": "\n 71 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 4023,
"s": 4006,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4058,
"s": 4023,
"text": "\n 18 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4075,
"s": 4058,
"text": " Mahmoud Ramadan"
},
{
"code": null,
"e": 4108,
"s": 4075,
"text": "\n 49 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 4124,
"s": 4108,
"text": " Catalin Stefan"
},
{
"code": null,
"e": 4159,
"s": 4124,
"text": "\n 49 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4179,
"s": 4159,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 4212,
"s": 4179,
"text": "\n 22 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 4229,
"s": 4212,
"text": " CLEMENT OCHIENG"
},
{
"code": null,
"e": 4236,
"s": 4229,
"text": " Print"
},
{
"code": null,
"e": 4247,
"s": 4236,
"text": " Add Notes"
}
] |
What are the components of ER diagrams in DBMS?
|
ER model stands for the Entity Relationship Model in the database management system (DBMS). It is the first step of designing to give the flow for a concept. It is the DFD (Data Flow Diagram) requirement of a company.
It is the basic building block for relational models. Not that much training is required to design the database project .It is very easy to convert the E-R model into a relational table or to a normalized table.
It is a high-level data model diagram that defines the conceptual view of the database. It acts as a blueprint to implement a database in future.
The components of ER diagram are as follows −
Entity
Entity
Attributes
Attributes
Relationship
Relationship
Weak entity
Weak entity
Strong entity
Strong entity
Simple attribute
Simple attribute
Key attribute
Key attribute
Composite attribute
Composite attribute
Derived attribute
Derived attribute
Multivalued attribute
Multivalued attribute
The components of the ER diagram are pictorially represented as follows −
It may be an object, person, place or event that stores data in a database. In a relationship diagram an entity is represented in rectangle form. For example, students, employees, managers, etc.
The entity is pictorially depicted as follows −
It is a collection of entities of the same type which share similar properties. For example, a group of students in a college and students are an entity set.
Entity is characterised into two types as follows −
Strong entity set
Strong entity set
Weak entity set
Weak entity set
The entity types which consist of key attributes or if there are enough attributes for forming a primary key attribute are called a strong entity set. It is represented by a single rectangle.
For Example,
Roll no of student
EmpID of employee
An entity does not have a primary key attribute and depends on another strong entity via foreign key attribute. It is represented by a double rectangle.
It is the name, thing etc. These are the data characteristics of entities or data elements and data fields.
The types of attributes in the Entity Relationship (ER) model are as follows −
Single value attribute − These attributes contain a single value. For example, age, salary etc.
Single value attribute − These attributes contain a single value. For example, age, salary etc.
Multivalued attribute − They contain more than one value of a single entity. For example, phone numbers.
Multivalued attribute − They contain more than one value of a single entity. For example, phone numbers.
Composite attribute − The attributes which can be further divided. For example, Name-> First name, Middle name, last name
Composite attribute − The attributes which can be further divided. For example, Name-> First name, Middle name, last name
Derived attribute − The attribute that can be derived from others. For example, Date of Birth.
Derived attribute − The attribute that can be derived from others. For example, Date of Birth.
It is used to describe the relation between two or more entities. It is represented by a diamond shape.
For Example, students study in college and employees work in a department.
The relationship is pictorially represented as follows −
Here works for is a relation between two entities.
A relationship where a number of different entities set participate is called a degree of a relationship.
It is categorised into the following −
Unary Relationship
Unary Relationship
Binary Relationship
Binary Relationship
Ternary Relationship
Ternary Relationship
n-ary Relationship
n-ary Relationship
|
[
{
"code": null,
"e": 1280,
"s": 1062,
"text": "ER model stands for the Entity Relationship Model in the database management system (DBMS). It is the first step of designing to give the flow for a concept. It is the DFD (Data Flow Diagram) requirement of a company."
},
{
"code": null,
"e": 1492,
"s": 1280,
"text": "It is the basic building block for relational models. Not that much training is required to design the database project .It is very easy to convert the E-R model into a relational table or to a normalized table."
},
{
"code": null,
"e": 1638,
"s": 1492,
"text": "It is a high-level data model diagram that defines the conceptual view of the database. It acts as a blueprint to implement a database in future."
},
{
"code": null,
"e": 1684,
"s": 1638,
"text": "The components of ER diagram are as follows −"
},
{
"code": null,
"e": 1691,
"s": 1684,
"text": "Entity"
},
{
"code": null,
"e": 1698,
"s": 1691,
"text": "Entity"
},
{
"code": null,
"e": 1709,
"s": 1698,
"text": "Attributes"
},
{
"code": null,
"e": 1720,
"s": 1709,
"text": "Attributes"
},
{
"code": null,
"e": 1733,
"s": 1720,
"text": "Relationship"
},
{
"code": null,
"e": 1746,
"s": 1733,
"text": "Relationship"
},
{
"code": null,
"e": 1758,
"s": 1746,
"text": "Weak entity"
},
{
"code": null,
"e": 1770,
"s": 1758,
"text": "Weak entity"
},
{
"code": null,
"e": 1784,
"s": 1770,
"text": "Strong entity"
},
{
"code": null,
"e": 1798,
"s": 1784,
"text": "Strong entity"
},
{
"code": null,
"e": 1815,
"s": 1798,
"text": "Simple attribute"
},
{
"code": null,
"e": 1832,
"s": 1815,
"text": "Simple attribute"
},
{
"code": null,
"e": 1846,
"s": 1832,
"text": "Key attribute"
},
{
"code": null,
"e": 1860,
"s": 1846,
"text": "Key attribute"
},
{
"code": null,
"e": 1880,
"s": 1860,
"text": "Composite attribute"
},
{
"code": null,
"e": 1900,
"s": 1880,
"text": "Composite attribute"
},
{
"code": null,
"e": 1918,
"s": 1900,
"text": "Derived attribute"
},
{
"code": null,
"e": 1936,
"s": 1918,
"text": "Derived attribute"
},
{
"code": null,
"e": 1958,
"s": 1936,
"text": "Multivalued attribute"
},
{
"code": null,
"e": 1980,
"s": 1958,
"text": "Multivalued attribute"
},
{
"code": null,
"e": 2054,
"s": 1980,
"text": "The components of the ER diagram are pictorially represented as follows −"
},
{
"code": null,
"e": 2249,
"s": 2054,
"text": "It may be an object, person, place or event that stores data in a database. In a relationship diagram an entity is represented in rectangle form. For example, students, employees, managers, etc."
},
{
"code": null,
"e": 2297,
"s": 2249,
"text": "The entity is pictorially depicted as follows −"
},
{
"code": null,
"e": 2455,
"s": 2297,
"text": "It is a collection of entities of the same type which share similar properties. For example, a group of students in a college and students are an entity set."
},
{
"code": null,
"e": 2507,
"s": 2455,
"text": "Entity is characterised into two types as follows −"
},
{
"code": null,
"e": 2525,
"s": 2507,
"text": "Strong entity set"
},
{
"code": null,
"e": 2543,
"s": 2525,
"text": "Strong entity set"
},
{
"code": null,
"e": 2559,
"s": 2543,
"text": "Weak entity set"
},
{
"code": null,
"e": 2575,
"s": 2559,
"text": "Weak entity set"
},
{
"code": null,
"e": 2767,
"s": 2575,
"text": "The entity types which consist of key attributes or if there are enough attributes for forming a primary key attribute are called a strong entity set. It is represented by a single rectangle."
},
{
"code": null,
"e": 2780,
"s": 2767,
"text": "For Example,"
},
{
"code": null,
"e": 2817,
"s": 2780,
"text": "Roll no of student\nEmpID of employee"
},
{
"code": null,
"e": 2970,
"s": 2817,
"text": "An entity does not have a primary key attribute and depends on another strong entity via foreign key attribute. It is represented by a double rectangle."
},
{
"code": null,
"e": 3078,
"s": 2970,
"text": "It is the name, thing etc. These are the data characteristics of entities or data elements and data fields."
},
{
"code": null,
"e": 3157,
"s": 3078,
"text": "The types of attributes in the Entity Relationship (ER) model are as follows −"
},
{
"code": null,
"e": 3253,
"s": 3157,
"text": "Single value attribute − These attributes contain a single value. For example, age, salary etc."
},
{
"code": null,
"e": 3349,
"s": 3253,
"text": "Single value attribute − These attributes contain a single value. For example, age, salary etc."
},
{
"code": null,
"e": 3454,
"s": 3349,
"text": "Multivalued attribute − They contain more than one value of a single entity. For example, phone numbers."
},
{
"code": null,
"e": 3559,
"s": 3454,
"text": "Multivalued attribute − They contain more than one value of a single entity. For example, phone numbers."
},
{
"code": null,
"e": 3681,
"s": 3559,
"text": "Composite attribute − The attributes which can be further divided. For example, Name-> First name, Middle name, last name"
},
{
"code": null,
"e": 3803,
"s": 3681,
"text": "Composite attribute − The attributes which can be further divided. For example, Name-> First name, Middle name, last name"
},
{
"code": null,
"e": 3898,
"s": 3803,
"text": "Derived attribute − The attribute that can be derived from others. For example, Date of Birth."
},
{
"code": null,
"e": 3993,
"s": 3898,
"text": "Derived attribute − The attribute that can be derived from others. For example, Date of Birth."
},
{
"code": null,
"e": 4097,
"s": 3993,
"text": "It is used to describe the relation between two or more entities. It is represented by a diamond shape."
},
{
"code": null,
"e": 4172,
"s": 4097,
"text": "For Example, students study in college and employees work in a department."
},
{
"code": null,
"e": 4229,
"s": 4172,
"text": "The relationship is pictorially represented as follows −"
},
{
"code": null,
"e": 4280,
"s": 4229,
"text": "Here works for is a relation between two entities."
},
{
"code": null,
"e": 4386,
"s": 4280,
"text": "A relationship where a number of different entities set participate is called a degree of a relationship."
},
{
"code": null,
"e": 4425,
"s": 4386,
"text": "It is categorised into the following −"
},
{
"code": null,
"e": 4444,
"s": 4425,
"text": "Unary Relationship"
},
{
"code": null,
"e": 4463,
"s": 4444,
"text": "Unary Relationship"
},
{
"code": null,
"e": 4483,
"s": 4463,
"text": "Binary Relationship"
},
{
"code": null,
"e": 4503,
"s": 4483,
"text": "Binary Relationship"
},
{
"code": null,
"e": 4524,
"s": 4503,
"text": "Ternary Relationship"
},
{
"code": null,
"e": 4545,
"s": 4524,
"text": "Ternary Relationship"
},
{
"code": null,
"e": 4564,
"s": 4545,
"text": "n-ary Relationship"
},
{
"code": null,
"e": 4583,
"s": 4564,
"text": "n-ary Relationship"
}
] |
Python MySQL - Create Table
|
The CREATE TABLE statement is used to create tables in MYSQL database. Here, you need to specify the name of the table and, definition (name and datatype) of each column.
Following is the syntax to create a table in MySQL −
CREATE TABLE table_name(
column1 datatype,
column2 datatype,
column3 datatype,
.....
columnN datatype,
);
Following query creates a table named EMPLOYEE in MySQL with five columns namely, FIRST_NAME, LAST_NAME, AGE, SEX and, INCOME.
mysql> CREATE TABLE EMPLOYEE(
FIRST_NAME CHAR(20) NOT NULL,
LAST_NAME CHAR(20),
AGE INT,
SEX CHAR(1),
INCOME FLOAT
);
Query OK, 0 rows affected (0.42 sec)
The DESC statement gives you the description of the specified table. Using this you can verify if the table has been created or not as shown below −
mysql> Desc Employee;
+------------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------+----------+------+-----+---------+-------+
| FIRST_NAME | char(20) | NO | | NULL | |
| LAST_NAME | char(20) | YES | | NULL | |
| AGE | int(11) | YES | | NULL | |
| SEX | char(1) | YES | | NULL | |
| INCOME | float | YES | | NULL | |
+------------+----------+------+-----+---------+-------+
5 rows in set (0.07 sec)
The method named execute() (invoked on the cursor object) accepts two variables −
A String value representing the query to be executed.
A String value representing the query to be executed.
An optional args parameter which can be a tuple or, list or, dictionary, representing the parameters of the query (values of the place holders).
An optional args parameter which can be a tuple or, list or, dictionary, representing the parameters of the query (values of the place holders).
It returns an integer value representing the number of rows effected by the query.
Once a database connection is established, you can create tables by passing the CREATE TABLE query to the execute() method.
In short, to create a table using python 7minus;
Import mysql.connector package.
Import mysql.connector package.
Create a connection object using the mysql.connector.connect() method, by passing the user name, password, host (optional default: localhost) and, database (optional) as parameters to it.
Create a connection object using the mysql.connector.connect() method, by passing the user name, password, host (optional default: localhost) and, database (optional) as parameters to it.
Create a cursor object by invoking the cursor() method on the connection object created above.
Create a cursor object by invoking the cursor() method on the connection object created above.
Then, execute the CREATE TABLE statement by passing it as a parameter to the execute() method.
Then, execute the CREATE TABLE statement by passing it as a parameter to the execute() method.
Following example creates a table named Employee in the database mydb.
import mysql.connector
#establishing the connection
conn = mysql.connector.connect(
user='root', password='password', host='127.0.0.1', database='mydb'
)
#Creating a cursor object using the cursor() method
cursor = conn.cursor()
#Dropping EMPLOYEE table if already exists.
cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")
#Creating table as per requirement
sql ='''CREATE TABLE EMPLOYEE(
FIRST_NAME CHAR(20) NOT NULL,
LAST_NAME CHAR(20),
AGE INT,
SEX CHAR(1),
INCOME FLOAT
)'''
cursor.execute(sql)
#Closing the connection
conn.close()
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": 3376,
"s": 3205,
"text": "The CREATE TABLE statement is used to create tables in MYSQL database. Here, you need to specify the name of the table and, definition (name and datatype) of each column."
},
{
"code": null,
"e": 3429,
"s": 3376,
"text": "Following is the syntax to create a table in MySQL −"
},
{
"code": null,
"e": 3550,
"s": 3429,
"text": "CREATE TABLE table_name(\n column1 datatype,\n column2 datatype,\n column3 datatype,\n .....\n columnN datatype,\n);"
},
{
"code": null,
"e": 3677,
"s": 3550,
"text": "Following query creates a table named EMPLOYEE in MySQL with five columns namely, FIRST_NAME, LAST_NAME, AGE, SEX and, INCOME."
},
{
"code": null,
"e": 3847,
"s": 3677,
"text": "mysql> CREATE TABLE EMPLOYEE(\n FIRST_NAME CHAR(20) NOT NULL,\n LAST_NAME CHAR(20),\n AGE INT,\n SEX CHAR(1),\n INCOME FLOAT\n);\nQuery OK, 0 rows affected (0.42 sec)"
},
{
"code": null,
"e": 3996,
"s": 3847,
"text": "The DESC statement gives you the description of the specified table. Using this you can verify if the table has been created or not as shown below −"
},
{
"code": null,
"e": 4557,
"s": 3996,
"text": "mysql> Desc Employee;\n+------------+----------+------+-----+---------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+------------+----------+------+-----+---------+-------+\n| FIRST_NAME | char(20) | NO | | NULL | |\n| LAST_NAME | char(20) | YES | | NULL | |\n| AGE | int(11) | YES | | NULL | |\n| SEX | char(1) | YES | | NULL | |\n| INCOME | float | YES | | NULL | |\n+------------+----------+------+-----+---------+-------+\n5 rows in set (0.07 sec)\n"
},
{
"code": null,
"e": 4639,
"s": 4557,
"text": "The method named execute() (invoked on the cursor object) accepts two variables −"
},
{
"code": null,
"e": 4693,
"s": 4639,
"text": "A String value representing the query to be executed."
},
{
"code": null,
"e": 4747,
"s": 4693,
"text": "A String value representing the query to be executed."
},
{
"code": null,
"e": 4892,
"s": 4747,
"text": "An optional args parameter which can be a tuple or, list or, dictionary, representing the parameters of the query (values of the place holders)."
},
{
"code": null,
"e": 5037,
"s": 4892,
"text": "An optional args parameter which can be a tuple or, list or, dictionary, representing the parameters of the query (values of the place holders)."
},
{
"code": null,
"e": 5120,
"s": 5037,
"text": "It returns an integer value representing the number of rows effected by the query."
},
{
"code": null,
"e": 5244,
"s": 5120,
"text": "Once a database connection is established, you can create tables by passing the CREATE TABLE query to the execute() method."
},
{
"code": null,
"e": 5293,
"s": 5244,
"text": "In short, to create a table using python 7minus;"
},
{
"code": null,
"e": 5325,
"s": 5293,
"text": "Import mysql.connector package."
},
{
"code": null,
"e": 5357,
"s": 5325,
"text": "Import mysql.connector package."
},
{
"code": null,
"e": 5545,
"s": 5357,
"text": "Create a connection object using the mysql.connector.connect() method, by passing the user name, password, host (optional default: localhost) and, database (optional) as parameters to it."
},
{
"code": null,
"e": 5733,
"s": 5545,
"text": "Create a connection object using the mysql.connector.connect() method, by passing the user name, password, host (optional default: localhost) and, database (optional) as parameters to it."
},
{
"code": null,
"e": 5828,
"s": 5733,
"text": "Create a cursor object by invoking the cursor() method on the connection object created above."
},
{
"code": null,
"e": 5923,
"s": 5828,
"text": "Create a cursor object by invoking the cursor() method on the connection object created above."
},
{
"code": null,
"e": 6018,
"s": 5923,
"text": "Then, execute the CREATE TABLE statement by passing it as a parameter to the execute() method."
},
{
"code": null,
"e": 6113,
"s": 6018,
"text": "Then, execute the CREATE TABLE statement by passing it as a parameter to the execute() method."
},
{
"code": null,
"e": 6184,
"s": 6113,
"text": "Following example creates a table named Employee in the database mydb."
},
{
"code": null,
"e": 6741,
"s": 6184,
"text": "import mysql.connector\n\n#establishing the connection\nconn = mysql.connector.connect(\n user='root', password='password', host='127.0.0.1', database='mydb'\n)\n\n#Creating a cursor object using the cursor() method\ncursor = conn.cursor()\n\n#Dropping EMPLOYEE table if already exists.\ncursor.execute(\"DROP TABLE IF EXISTS EMPLOYEE\")\n\n#Creating table as per requirement\nsql ='''CREATE TABLE EMPLOYEE(\n FIRST_NAME CHAR(20) NOT NULL,\n LAST_NAME CHAR(20),\n AGE INT,\n SEX CHAR(1),\n INCOME FLOAT\n)'''\ncursor.execute(sql)\n\n#Closing the connection\nconn.close()"
},
{
"code": null,
"e": 6778,
"s": 6741,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 6794,
"s": 6778,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 6827,
"s": 6794,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 6846,
"s": 6827,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 6881,
"s": 6846,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 6903,
"s": 6881,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 6937,
"s": 6903,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 6965,
"s": 6937,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 7000,
"s": 6965,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 7014,
"s": 7000,
"text": " Lets Kode It"
},
{
"code": null,
"e": 7047,
"s": 7014,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 7064,
"s": 7047,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 7071,
"s": 7064,
"text": " Print"
},
{
"code": null,
"e": 7082,
"s": 7071,
"text": " Add Notes"
}
] |
Const keyword in C++ - GeeksforGeeks
|
03 Feb, 2022
In this article, the various functions of the const keyword which is found in C++ are discussed. Whenever const keyword is attached with any method(), variable, pointer variable, and with the object of a class it prevents that specific object/method()/variable to modify its data items value.
There are a certain set of rules for the declaration and initialization of the constant variables:
The const variable cannot be left un-initialized at the time of the assignment.
It cannot be assigned value anywhere in the program.
Explicit value needed to be provided to the constant variable at the time of declaration of the constant variable.
Below is the C++ program to demonstrate the above concept:
C++
// C++ program to demonstrate the// the above concept#include <iostream>using namespace std; // Driver Codeint main(){ // const int x; CTE error // x = 9; CTE error const int y = 10; cout << y; return 0;}
10
The error faced for faulty declaration: If you try to initialize the const variable without assigning an explicit value then a compile-time error (CTE) is generated.
Pointers can be declared with a const keyword. So, there are three possible ways to use a const keyword with a pointer, which are as follows:
When the pointer variable point to a const value:
Syntax:
const data_type* var_name;
Below is the C++ program to implement the above concept:
C++
// C++ program to demonstrate the// above concept#include <iostream>using namespace std; // Driver Codeint main(){ int x{ 10 }; char y{ 'M' }; const int* i = &x; const char* j = &y; // Value of x and y can be altered, // they are not constant variables x = 9; y = 'A'; // Change of constant values because, // i and j are pointing to const-int // & const-char type value // *i = 6; // *j = 7; cout << *i << " " << *j;}
9 A
Explanation: Here in the above case, i and j are two pointer variables that are pointing to a memory location const int-type and char-type, but the value stored at these corresponding locations can be changed as we have done above.
Otherwise, the following error will appear: If we try to modify the value of the const variable.
When the const pointer variable point to the value:
Syntax:
data_type* const var_name;
Below is the example to demonstrate the above concept:
C++
// C++ program to demonstrate the// above concept#include <iostream>using namespace std; // Driver Codeint main(){ // x and z non-const var int x = 5; int z = 6; // y and p non-const var char y = 'A'; char p = 'C'; // const pointer(i) pointing // to the var x's location int* const i = &x; // const pointer(j) pointing // to the var y's location char* const j = &y; // The values that is stored at the memory location can modified // even if we modify it through the pointer itself // No CTE error *i = 10; *j = 'D'; // CTE because pointer variable // is const type so the address // pointed by the pointer variables // can't be changed // *i = &z; // *j = &p; cout << *i << " and " << *j << endl; cout << i << " and " << j; return 0;}
Output:
10 and D
0x7ffe7b2392a0 and DC
Explanation: The values that are stored in the corresponding pointer variable i and j are modifiable, but the locations that are pointed out by const-pointer variables where the corresponding values of x and y are stored aren’t modifiable.
Otherwise, the following error will appear: The pointer variables are const and pointing to the locations where the x and y are stored if we try to change the address location then we’ll face the error.
When const pointer pointing to a const variable:
Syntax:
const data_type* const var_name;
Below is the C++ program to demonstrate the above concept:
C++
// C++ program to demonstrate// the above concept#include <iostream>using namespace std; // Driver codeint main(){ int x{ 9 }; const int* const i = &x; // *i=10; // The above statement will give CTE // Once Ptr(*i) value is // assigned, later it can't // be modified(Error) char y{ 'A' }; const char* const j = &y; // *j='B'; // The above statement will give CTE // Once Ptr(*j) value is // assigned, later it can't // be modified(Error) cout << *i << " and " << *j; return 0;}
9 and A
Explanation: Here, the const pointer variable points to the const variable. So, you are neither allowed to change the const pointer variable(*P) nor the value stored at the location pointed by that pointer variable(*P).
Otherwise, the following error will appear: Here both pointer variable and the locations pointed by the pointer variable are const so if any of them is modified, the following error will appear:
Pass const-argument value to a non-const parameter of a function cause error: Passing const argument value to a non-const parameter of a function isn’t valid it gives you a compile-time error.
Below is the C++ program to demonstrate the above concept:
C++
// C++ program to demonstrate// the above concept#include <iostream>using namespace std; int foo(int* y){ return *y;} // Driver codeint main(){ int z = 8; const int* x = &z; cout << foo(x); return 0;}
Output: The compile-time error that will appear as if const value is passed to any non-const argument of the function then the following compile-time error will appear:
In nutshell, the above discussion can be concluded as follows:
1. int value = 5; // non-const value
2. const int *ptr_1 = &value; // ptr_1 points to a “const int” value, so this is a pointer to a const value.
3. int *const ptr_2 = &value; // ptr_2 points to an “int”, so this is a const pointer to a non-const value.
4. const int *const ptr_3 = &value; // ptr_3 points to a “const int” value, so this is a const pointer to a const value.
Like member functions and member function arguments, the objects of a class can also be declared as const. An object declared as const cannot be modified and hence, can invoke only const member functions as these functions ensure not to modify the object.
Syntax:
const Class_Name Object_name;
When a function is declared as const, it can be called on any type of object, const object as well as non-const objects.
Whenever an object is declared as const, it needs to be initialized at the time of declaration. However, the object initialization while declaring is possible only with the help of constructors.
There are two ways of a constant function declaration:
Ordinary const-function Declaration:
const void foo()
{
//void foo() const Not valid
}
int main()
{
foo(x);
}
A const member function of the class:
class
{
void foo() const
{
//.....
}
}
Below is the example of a constant function:
C++
// C++ program to demonstrate the// constant function#include <iostream>using namespace std; // Class Testclass Test { int value; public: // Constructor Test(int v = 0) { value = v; } // We get compiler error if we // add a line like "value = 100;" // in this function. int getValue() const { return value; } // a nonconst function trying to modify value void setValue(int val) { value = val; }}; // Driver Codeint main(){ // Object of the class T Test t(20); // non-const object invoking const function, no error cout << t.getValue() << endl; // const object const Test t_const(10); // const object invoking const function, no error cout << t_const.getValue() << endl; // const object invoking non-const function, CTE // t_const.setValue(15); // non-const object invoking non-const function, no error t.setValue(12); cout << t.getValue() << endl; return 0;}
20
The Following error will if you try call the non-const function from a const object
A function() parameters and return type of function() can be declared as constant. Constant values cannot be changed as any such attempt will generate a compile-time error.
Below is the C++ program to implement the above approach:
C++
// C++ program to demonstrate the// above approach#include <iostream>using namespace std; // Function foo() with variable// const intvoid foo(const int y){ // y = 6; const value // can't be change cout << y;} // Function foo() with variable intvoid foo1(int y){ // Non-const value can be change y = 5; cout << '\n' << y;} // Driver Codeint main(){ int x = 9; const int z = 10; foo(z); foo1(x); return 0;}
10
5
Explanation: The following error will be displayed:
// y = 6; a const value can’t be changed or modified.
For const return type: The return type of the function() is const and so it returns a const integer value to us. Below is the C++ program to implement the above approach:
C++
// C++ program for the above approach#include <iostream>using namespace std; const int foo(int y){ y--; return y;} int main(){ int x = 9; const int z = 10; cout << foo(x) << '\n' << foo(z); return 0;}
8
9
There is no substantial issue to pass const or non-const variable to the function because the value that will be returned by the function will be constant automatically. As the argument of the function is non-const.
For const return type and const parameter: Here, both return type and parameter of the function are of const types. Below is the C++ program to implement the above approach:
C++
// C++ program for the above approach#include <iostream>using namespace std; const int foo(const int y){ // y = 9; it'll give CTE error as // y is const var its value can't // be change return y;} // Driver codeint main(){ int x = 9; const int z = 10; cout << foo(x) << '\n' << foo(z); return 0;}
9
10
Explanation: Here, both const and non-const values can be passed as the const parameter to the function, but we are not allowed to then change the value of a passed variable because the parameter is const. Otherwise, we’ll face the error as below:
// y=9; it’ll give the compile-time error as y is const var its value can’t be changed.
surendrapandey
CoderSaty
snaze01
C++-const keyword
const keyword
Articles
C++
C++ Programs
Technical Scripter
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Amazon’s most frequently asked interview questions | Set 2
Lamport's logical clock
Advantages and Disadvantages of Linked List
Compiler vs Interpreter
Escape Sequences in Java
Vector in C++ STL
Arrays in C/C++
Inheritance in C++
Initialize a vector in C++ (6 different ways)
Map in C++ Standard Template Library (STL)
|
[
{
"code": null,
"e": 24426,
"s": 24398,
"text": "\n03 Feb, 2022"
},
{
"code": null,
"e": 24719,
"s": 24426,
"text": "In this article, the various functions of the const keyword which is found in C++ are discussed. Whenever const keyword is attached with any method(), variable, pointer variable, and with the object of a class it prevents that specific object/method()/variable to modify its data items value."
},
{
"code": null,
"e": 24818,
"s": 24719,
"text": "There are a certain set of rules for the declaration and initialization of the constant variables:"
},
{
"code": null,
"e": 24898,
"s": 24818,
"text": "The const variable cannot be left un-initialized at the time of the assignment."
},
{
"code": null,
"e": 24951,
"s": 24898,
"text": "It cannot be assigned value anywhere in the program."
},
{
"code": null,
"e": 25066,
"s": 24951,
"text": "Explicit value needed to be provided to the constant variable at the time of declaration of the constant variable."
},
{
"code": null,
"e": 25125,
"s": 25066,
"text": "Below is the C++ program to demonstrate the above concept:"
},
{
"code": null,
"e": 25129,
"s": 25125,
"text": "C++"
},
{
"code": "// C++ program to demonstrate the// the above concept#include <iostream>using namespace std; // Driver Codeint main(){ // const int x; CTE error // x = 9; CTE error const int y = 10; cout << y; return 0;}",
"e": 25354,
"s": 25129,
"text": null
},
{
"code": null,
"e": 25357,
"s": 25354,
"text": "10"
},
{
"code": null,
"e": 25526,
"s": 25359,
"text": "The error faced for faulty declaration: If you try to initialize the const variable without assigning an explicit value then a compile-time error (CTE) is generated. "
},
{
"code": null,
"e": 25669,
"s": 25526,
"text": " Pointers can be declared with a const keyword. So, there are three possible ways to use a const keyword with a pointer, which are as follows:"
},
{
"code": null,
"e": 25719,
"s": 25669,
"text": "When the pointer variable point to a const value:"
},
{
"code": null,
"e": 25728,
"s": 25719,
"text": "Syntax: "
},
{
"code": null,
"e": 25755,
"s": 25728,
"text": "const data_type* var_name;"
},
{
"code": null,
"e": 25813,
"s": 25755,
"text": "Below is the C++ program to implement the above concept: "
},
{
"code": null,
"e": 25817,
"s": 25813,
"text": "C++"
},
{
"code": "// C++ program to demonstrate the// above concept#include <iostream>using namespace std; // Driver Codeint main(){ int x{ 10 }; char y{ 'M' }; const int* i = &x; const char* j = &y; // Value of x and y can be altered, // they are not constant variables x = 9; y = 'A'; // Change of constant values because, // i and j are pointing to const-int // & const-char type value // *i = 6; // *j = 7; cout << *i << \" \" << *j;}",
"e": 26282,
"s": 25817,
"text": null
},
{
"code": null,
"e": 26286,
"s": 26282,
"text": "9 A"
},
{
"code": null,
"e": 26521,
"s": 26288,
"text": "Explanation: Here in the above case, i and j are two pointer variables that are pointing to a memory location const int-type and char-type, but the value stored at these corresponding locations can be changed as we have done above. "
},
{
"code": null,
"e": 26618,
"s": 26521,
"text": "Otherwise, the following error will appear: If we try to modify the value of the const variable."
},
{
"code": null,
"e": 26670,
"s": 26618,
"text": "When the const pointer variable point to the value:"
},
{
"code": null,
"e": 26678,
"s": 26670,
"text": "Syntax:"
},
{
"code": null,
"e": 26705,
"s": 26678,
"text": "data_type* const var_name;"
},
{
"code": null,
"e": 26760,
"s": 26705,
"text": "Below is the example to demonstrate the above concept:"
},
{
"code": null,
"e": 26764,
"s": 26760,
"text": "C++"
},
{
"code": "// C++ program to demonstrate the// above concept#include <iostream>using namespace std; // Driver Codeint main(){ // x and z non-const var int x = 5; int z = 6; // y and p non-const var char y = 'A'; char p = 'C'; // const pointer(i) pointing // to the var x's location int* const i = &x; // const pointer(j) pointing // to the var y's location char* const j = &y; // The values that is stored at the memory location can modified // even if we modify it through the pointer itself // No CTE error *i = 10; *j = 'D'; // CTE because pointer variable // is const type so the address // pointed by the pointer variables // can't be changed // *i = &z; // *j = &p; cout << *i << \" and \" << *j << endl; cout << i << \" and \" << j; return 0;}",
"e": 27593,
"s": 26764,
"text": null
},
{
"code": null,
"e": 27632,
"s": 27593,
"text": "Output:\n10 and D\n0x7ffe7b2392a0 and DC"
},
{
"code": null,
"e": 27873,
"s": 27632,
"text": "Explanation: The values that are stored in the corresponding pointer variable i and j are modifiable, but the locations that are pointed out by const-pointer variables where the corresponding values of x and y are stored aren’t modifiable. "
},
{
"code": null,
"e": 28076,
"s": 27873,
"text": "Otherwise, the following error will appear: The pointer variables are const and pointing to the locations where the x and y are stored if we try to change the address location then we’ll face the error."
},
{
"code": null,
"e": 28125,
"s": 28076,
"text": "When const pointer pointing to a const variable:"
},
{
"code": null,
"e": 28133,
"s": 28125,
"text": "Syntax:"
},
{
"code": null,
"e": 28166,
"s": 28133,
"text": "const data_type* const var_name;"
},
{
"code": null,
"e": 28225,
"s": 28166,
"text": "Below is the C++ program to demonstrate the above concept:"
},
{
"code": null,
"e": 28229,
"s": 28225,
"text": "C++"
},
{
"code": "// C++ program to demonstrate// the above concept#include <iostream>using namespace std; // Driver codeint main(){ int x{ 9 }; const int* const i = &x; // *i=10; // The above statement will give CTE // Once Ptr(*i) value is // assigned, later it can't // be modified(Error) char y{ 'A' }; const char* const j = &y; // *j='B'; // The above statement will give CTE // Once Ptr(*j) value is // assigned, later it can't // be modified(Error) cout << *i << \" and \" << *j; return 0;}",
"e": 28768,
"s": 28229,
"text": null
},
{
"code": null,
"e": 28776,
"s": 28768,
"text": "9 and A"
},
{
"code": null,
"e": 28998,
"s": 28778,
"text": "Explanation: Here, the const pointer variable points to the const variable. So, you are neither allowed to change the const pointer variable(*P) nor the value stored at the location pointed by that pointer variable(*P)."
},
{
"code": null,
"e": 29193,
"s": 28998,
"text": "Otherwise, the following error will appear: Here both pointer variable and the locations pointed by the pointer variable are const so if any of them is modified, the following error will appear:"
},
{
"code": null,
"e": 29386,
"s": 29193,
"text": "Pass const-argument value to a non-const parameter of a function cause error: Passing const argument value to a non-const parameter of a function isn’t valid it gives you a compile-time error."
},
{
"code": null,
"e": 29445,
"s": 29386,
"text": "Below is the C++ program to demonstrate the above concept:"
},
{
"code": null,
"e": 29449,
"s": 29445,
"text": "C++"
},
{
"code": "// C++ program to demonstrate// the above concept#include <iostream>using namespace std; int foo(int* y){ return *y;} // Driver codeint main(){ int z = 8; const int* x = &z; cout << foo(x); return 0;}",
"e": 29665,
"s": 29449,
"text": null
},
{
"code": null,
"e": 29834,
"s": 29665,
"text": "Output: The compile-time error that will appear as if const value is passed to any non-const argument of the function then the following compile-time error will appear:"
},
{
"code": null,
"e": 29897,
"s": 29834,
"text": "In nutshell, the above discussion can be concluded as follows:"
},
{
"code": null,
"e": 29942,
"s": 29897,
"text": "1. int value = 5; // non-const value"
},
{
"code": null,
"e": 30056,
"s": 29942,
"text": "2. const int *ptr_1 = &value; // ptr_1 points to a “const int” value, so this is a pointer to a const value."
},
{
"code": null,
"e": 30171,
"s": 30056,
"text": "3. int *const ptr_2 = &value; // ptr_2 points to an “int”, so this is a const pointer to a non-const value."
},
{
"code": null,
"e": 30294,
"s": 30171,
"text": "4. const int *const ptr_3 = &value; // ptr_3 points to a “const int” value, so this is a const pointer to a const value."
},
{
"code": null,
"e": 30550,
"s": 30294,
"text": "Like member functions and member function arguments, the objects of a class can also be declared as const. An object declared as const cannot be modified and hence, can invoke only const member functions as these functions ensure not to modify the object."
},
{
"code": null,
"e": 30558,
"s": 30550,
"text": "Syntax:"
},
{
"code": null,
"e": 30588,
"s": 30558,
"text": "const Class_Name Object_name;"
},
{
"code": null,
"e": 30709,
"s": 30588,
"text": "When a function is declared as const, it can be called on any type of object, const object as well as non-const objects."
},
{
"code": null,
"e": 30904,
"s": 30709,
"text": "Whenever an object is declared as const, it needs to be initialized at the time of declaration. However, the object initialization while declaring is possible only with the help of constructors."
},
{
"code": null,
"e": 30959,
"s": 30904,
"text": "There are two ways of a constant function declaration:"
},
{
"code": null,
"e": 30996,
"s": 30959,
"text": "Ordinary const-function Declaration:"
},
{
"code": null,
"e": 31095,
"s": 30996,
"text": "const void foo()\n{\n //void foo() const Not valid\n} \nint main()\n{\n foo(x);\n} "
},
{
"code": null,
"e": 31133,
"s": 31095,
"text": "A const member function of the class:"
},
{
"code": null,
"e": 31188,
"s": 31133,
"text": "class\n{\n void foo() const\n {\n //.....\n }\n}"
},
{
"code": null,
"e": 31233,
"s": 31188,
"text": "Below is the example of a constant function:"
},
{
"code": null,
"e": 31237,
"s": 31233,
"text": "C++"
},
{
"code": "// C++ program to demonstrate the// constant function#include <iostream>using namespace std; // Class Testclass Test { int value; public: // Constructor Test(int v = 0) { value = v; } // We get compiler error if we // add a line like \"value = 100;\" // in this function. int getValue() const { return value; } // a nonconst function trying to modify value void setValue(int val) { value = val; }}; // Driver Codeint main(){ // Object of the class T Test t(20); // non-const object invoking const function, no error cout << t.getValue() << endl; // const object const Test t_const(10); // const object invoking const function, no error cout << t_const.getValue() << endl; // const object invoking non-const function, CTE // t_const.setValue(15); // non-const object invoking non-const function, no error t.setValue(12); cout << t.getValue() << endl; return 0;}",
"e": 32232,
"s": 31237,
"text": null
},
{
"code": null,
"e": 32235,
"s": 32232,
"text": "20"
},
{
"code": null,
"e": 32321,
"s": 32237,
"text": "The Following error will if you try call the non-const function from a const object"
},
{
"code": null,
"e": 32494,
"s": 32321,
"text": "A function() parameters and return type of function() can be declared as constant. Constant values cannot be changed as any such attempt will generate a compile-time error."
},
{
"code": null,
"e": 32553,
"s": 32494,
"text": "Below is the C++ program to implement the above approach: "
},
{
"code": null,
"e": 32557,
"s": 32553,
"text": "C++"
},
{
"code": "// C++ program to demonstrate the// above approach#include <iostream>using namespace std; // Function foo() with variable// const intvoid foo(const int y){ // y = 6; const value // can't be change cout << y;} // Function foo() with variable intvoid foo1(int y){ // Non-const value can be change y = 5; cout << '\\n' << y;} // Driver Codeint main(){ int x = 9; const int z = 10; foo(z); foo1(x); return 0;}",
"e": 33007,
"s": 32557,
"text": null
},
{
"code": null,
"e": 33012,
"s": 33007,
"text": "10\n5"
},
{
"code": null,
"e": 33068,
"s": 33014,
"text": " Explanation: The following error will be displayed: "
},
{
"code": null,
"e": 33122,
"s": 33068,
"text": "// y = 6; a const value can’t be changed or modified."
},
{
"code": null,
"e": 33294,
"s": 33122,
"text": "For const return type: The return type of the function() is const and so it returns a const integer value to us. Below is the C++ program to implement the above approach: "
},
{
"code": null,
"e": 33298,
"s": 33294,
"text": "C++"
},
{
"code": "// C++ program for the above approach#include <iostream>using namespace std; const int foo(int y){ y--; return y;} int main(){ int x = 9; const int z = 10; cout << foo(x) << '\\n' << foo(z); return 0;}",
"e": 33526,
"s": 33298,
"text": null
},
{
"code": null,
"e": 33530,
"s": 33526,
"text": "8\n9"
},
{
"code": null,
"e": 33748,
"s": 33532,
"text": "There is no substantial issue to pass const or non-const variable to the function because the value that will be returned by the function will be constant automatically. As the argument of the function is non-const."
},
{
"code": null,
"e": 33922,
"s": 33748,
"text": "For const return type and const parameter: Here, both return type and parameter of the function are of const types. Below is the C++ program to implement the above approach:"
},
{
"code": null,
"e": 33926,
"s": 33922,
"text": "C++"
},
{
"code": "// C++ program for the above approach#include <iostream>using namespace std; const int foo(const int y){ // y = 9; it'll give CTE error as // y is const var its value can't // be change return y;} // Driver codeint main(){ int x = 9; const int z = 10; cout << foo(x) << '\\n' << foo(z); return 0;}",
"e": 34256,
"s": 33926,
"text": null
},
{
"code": null,
"e": 34261,
"s": 34256,
"text": "9\n10"
},
{
"code": null,
"e": 34512,
"s": 34263,
"text": "Explanation: Here, both const and non-const values can be passed as the const parameter to the function, but we are not allowed to then change the value of a passed variable because the parameter is const. Otherwise, we’ll face the error as below: "
},
{
"code": null,
"e": 34600,
"s": 34512,
"text": "// y=9; it’ll give the compile-time error as y is const var its value can’t be changed."
},
{
"code": null,
"e": 34615,
"s": 34600,
"text": "surendrapandey"
},
{
"code": null,
"e": 34625,
"s": 34615,
"text": "CoderSaty"
},
{
"code": null,
"e": 34633,
"s": 34625,
"text": "snaze01"
},
{
"code": null,
"e": 34651,
"s": 34633,
"text": "C++-const keyword"
},
{
"code": null,
"e": 34665,
"s": 34651,
"text": "const keyword"
},
{
"code": null,
"e": 34674,
"s": 34665,
"text": "Articles"
},
{
"code": null,
"e": 34678,
"s": 34674,
"text": "C++"
},
{
"code": null,
"e": 34691,
"s": 34678,
"text": "C++ Programs"
},
{
"code": null,
"e": 34710,
"s": 34691,
"text": "Technical Scripter"
},
{
"code": null,
"e": 34714,
"s": 34710,
"text": "CPP"
},
{
"code": null,
"e": 34812,
"s": 34714,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34871,
"s": 34812,
"text": "Amazon’s most frequently asked interview questions | Set 2"
},
{
"code": null,
"e": 34895,
"s": 34871,
"text": "Lamport's logical clock"
},
{
"code": null,
"e": 34939,
"s": 34895,
"text": "Advantages and Disadvantages of Linked List"
},
{
"code": null,
"e": 34963,
"s": 34939,
"text": "Compiler vs Interpreter"
},
{
"code": null,
"e": 34988,
"s": 34963,
"text": "Escape Sequences in Java"
},
{
"code": null,
"e": 35006,
"s": 34988,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 35022,
"s": 35006,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 35041,
"s": 35022,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 35087,
"s": 35041,
"text": "Initialize a vector in C++ (6 different ways)"
}
] |
Python - Case Insensitive string counter - GeeksforGeeks
|
02 Sep, 2020
Given a List of Strings, find frequency of strings case insensitive.
Input : test_list = [“Gfg”, “Best”, “GFG”, “is”, “IS”, “BEST”]Output : {‘gfg’: 2, ‘best’: 2, ‘is’: 2}Explanation : All occur twice.
Input : test_list = [“Gfg”, “gfg”, “GFG”]Output : {‘gfg’: 3}Explanation : Only “gfg” 3 occurrences.
Method : Using defaultdict() + lower()
In this, we perform lower() to all the strings, before mapping in defaultdict. This ensures case insensitivity while mapping and cumulating frequency.
Python3
# Python3 code to demonstrate working of # Strings Frequency (Case Insensitive)# Using defaultdict() + lower()from collections import defaultdict # initializing listtest_list = ["Gfg", "Best", "best", "gfg", "GFG", "is", "IS", "BEST"] # printing original listprint("The original list is : " + str(test_list)) res = defaultdict(int)for ele in test_list: # lowercasing to cater for Case Insensitivity res[ele.lower()] += 1 # printing result print("Strings Frequency : " + str(dict(res)))
The original list is : ['Gfg', 'Best', 'best', 'gfg', 'GFG', 'is', 'IS', 'BEST']
Strings Frequency : {'gfg': 3, 'best': 3, 'is': 2}
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
Box Plot in Python using Matplotlib
Bar Plot in Matplotlib
Python | Get dictionary keys as a list
Python | Convert set into a list
Ways to filter Pandas DataFrame by column values
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Binary Search (Recursive and Iterative)
Python | Split string into list of characters
|
[
{
"code": null,
"e": 23901,
"s": 23873,
"text": "\n02 Sep, 2020"
},
{
"code": null,
"e": 23970,
"s": 23901,
"text": "Given a List of Strings, find frequency of strings case insensitive."
},
{
"code": null,
"e": 24102,
"s": 23970,
"text": "Input : test_list = [“Gfg”, “Best”, “GFG”, “is”, “IS”, “BEST”]Output : {‘gfg’: 2, ‘best’: 2, ‘is’: 2}Explanation : All occur twice."
},
{
"code": null,
"e": 24202,
"s": 24102,
"text": "Input : test_list = [“Gfg”, “gfg”, “GFG”]Output : {‘gfg’: 3}Explanation : Only “gfg” 3 occurrences."
},
{
"code": null,
"e": 24241,
"s": 24202,
"text": "Method : Using defaultdict() + lower()"
},
{
"code": null,
"e": 24392,
"s": 24241,
"text": "In this, we perform lower() to all the strings, before mapping in defaultdict. This ensures case insensitivity while mapping and cumulating frequency."
},
{
"code": null,
"e": 24400,
"s": 24392,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of # Strings Frequency (Case Insensitive)# Using defaultdict() + lower()from collections import defaultdict # initializing listtest_list = [\"Gfg\", \"Best\", \"best\", \"gfg\", \"GFG\", \"is\", \"IS\", \"BEST\"] # printing original listprint(\"The original list is : \" + str(test_list)) res = defaultdict(int)for ele in test_list: # lowercasing to cater for Case Insensitivity res[ele.lower()] += 1 # printing result print(\"Strings Frequency : \" + str(dict(res)))",
"e": 24902,
"s": 24400,
"text": null
},
{
"code": null,
"e": 25035,
"s": 24902,
"text": "The original list is : ['Gfg', 'Best', 'best', 'gfg', 'GFG', 'is', 'IS', 'BEST']\nStrings Frequency : {'gfg': 3, 'best': 3, 'is': 2}\n"
},
{
"code": null,
"e": 25058,
"s": 25035,
"text": "Python string-programs"
},
{
"code": null,
"e": 25065,
"s": 25058,
"text": "Python"
},
{
"code": null,
"e": 25081,
"s": 25065,
"text": "Python Programs"
},
{
"code": null,
"e": 25179,
"s": 25081,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25188,
"s": 25179,
"text": "Comments"
},
{
"code": null,
"e": 25201,
"s": 25188,
"text": "Old Comments"
},
{
"code": null,
"e": 25237,
"s": 25201,
"text": "Box Plot in Python using Matplotlib"
},
{
"code": null,
"e": 25260,
"s": 25237,
"text": "Bar Plot in Matplotlib"
},
{
"code": null,
"e": 25299,
"s": 25260,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 25332,
"s": 25299,
"text": "Python | Convert set into a list"
},
{
"code": null,
"e": 25381,
"s": 25332,
"text": "Ways to filter Pandas DataFrame by column values"
},
{
"code": null,
"e": 25403,
"s": 25381,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 25442,
"s": 25403,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 25480,
"s": 25442,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 25539,
"s": 25480,
"text": "Python Program for Binary Search (Recursive and Iterative)"
}
] |
Objective-C Extensions
|
A class extension bears some similarity to a category, but it can only be added to a class for which you have the source code at compile time (the class is compiled at the same time as the class extension).
The methods declared by a class extension are implemented in the implementation block for the original class, so you can't, for example, declare a class extension on a framework class, such as a Cocoa or Cocoa Touch class like NSString.
Extensions are actually categories without the category name. It's often referred as anonymous categories.
The syntax to declare a extension uses the @interface keyword, just like a standard Objective-C class description, but does not indicate any inheritance from a subclass. Instead, it just adds parentheses, as shown below −
@interface ClassName ()
@end
An extension cannot be declared for any class, only for the classes that we have original implementation of source code.
An extension cannot be declared for any class, only for the classes that we have original implementation of source code.
An extension is adding private methods and private variables that are only specific to the class.
An extension is adding private methods and private variables that are only specific to the class.
Any method or variable declared inside the extensions is not accessible even to the inherited classes.
Any method or variable declared inside the extensions is not accessible even to the inherited classes.
Let's create a class SampleClass that has an extension. In the extension, let's have a private variable internalID.
Then, let's have a method getExternalID that returns the externalID after processing the internalID.
The example is shown below and this wont work on online compiler.
#import <Foundation/Foundation.h>
@interface SampleClass : NSObject {
NSString *name;
}
- (void)setInternalID;
- (NSString *)getExternalID;
@end
@interface SampleClass() {
NSString *internalID;
}
@end
@implementation SampleClass
- (void)setInternalID {
internalID = [NSString stringWithFormat:
@"UNIQUEINTERNALKEY%dUNIQUEINTERNALKEY",arc4random()%100];
}
- (NSString *)getExternalID {
return [internalID stringByReplacingOccurrencesOfString:
@"UNIQUEINTERNALKEY" withString:@""];
}
@end
int main(int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
SampleClass *sampleClass = [[SampleClass alloc]init];
[sampleClass setInternalID];
NSLog(@"ExternalID: %@",[sampleClass getExternalID]);
[pool drain];
return 0;
}
Now when we compile and run the program, we will get the following result.
2013-09-22 21:18:31.754 Extensions[331:303] ExternalID: 51
In the above example, we can see that the internalID is not returned directly. We here remove the UNIQUEINTERNALKEY and only make the remaining value available to the method getExternalID.
The above example just uses a string operation, but it can have many features like encryption/decryption and so on.
18 Lectures
1 hours
PARTHA MAJUMDAR
6 Lectures
25 mins
Ken Burke
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2767,
"s": 2560,
"text": "A class extension bears some similarity to a category, but it can only be added to a class for which you have the source code at compile time (the class is compiled at the same time as the class extension)."
},
{
"code": null,
"e": 3004,
"s": 2767,
"text": "The methods declared by a class extension are implemented in the implementation block for the original class, so you can't, for example, declare a class extension on a framework class, such as a Cocoa or Cocoa Touch class like NSString."
},
{
"code": null,
"e": 3111,
"s": 3004,
"text": "Extensions are actually categories without the category name. It's often referred as anonymous categories."
},
{
"code": null,
"e": 3333,
"s": 3111,
"text": "The syntax to declare a extension uses the @interface keyword, just like a standard Objective-C class description, but does not indicate any inheritance from a subclass. Instead, it just adds parentheses, as shown below −"
},
{
"code": null,
"e": 3363,
"s": 3333,
"text": "@interface ClassName ()\n\n@end"
},
{
"code": null,
"e": 3484,
"s": 3363,
"text": "An extension cannot be declared for any class, only for the classes that we have original implementation of source code."
},
{
"code": null,
"e": 3605,
"s": 3484,
"text": "An extension cannot be declared for any class, only for the classes that we have original implementation of source code."
},
{
"code": null,
"e": 3703,
"s": 3605,
"text": "An extension is adding private methods and private variables that are only specific to the class."
},
{
"code": null,
"e": 3801,
"s": 3703,
"text": "An extension is adding private methods and private variables that are only specific to the class."
},
{
"code": null,
"e": 3904,
"s": 3801,
"text": "Any method or variable declared inside the extensions is not accessible even to the inherited classes."
},
{
"code": null,
"e": 4007,
"s": 3904,
"text": "Any method or variable declared inside the extensions is not accessible even to the inherited classes."
},
{
"code": null,
"e": 4123,
"s": 4007,
"text": "Let's create a class SampleClass that has an extension. In the extension, let's have a private variable internalID."
},
{
"code": null,
"e": 4224,
"s": 4123,
"text": "Then, let's have a method getExternalID that returns the externalID after processing the internalID."
},
{
"code": null,
"e": 4290,
"s": 4224,
"text": "The example is shown below and this wont work on online compiler."
},
{
"code": null,
"e": 5099,
"s": 4290,
"text": "#import <Foundation/Foundation.h>\n\n@interface SampleClass : NSObject {\n NSString *name;\n}\n\n- (void)setInternalID;\n- (NSString *)getExternalID;\n\n@end\n\n@interface SampleClass() {\n NSString *internalID;\n}\n\n@end\n\n@implementation SampleClass\n\n- (void)setInternalID {\n internalID = [NSString stringWithFormat: \n @\"UNIQUEINTERNALKEY%dUNIQUEINTERNALKEY\",arc4random()%100];\n}\n\n- (NSString *)getExternalID {\n return [internalID stringByReplacingOccurrencesOfString: \n @\"UNIQUEINTERNALKEY\" withString:@\"\"];\n}\n\n@end\n\nint main(int argc, const char * argv[]) {\n NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];\n SampleClass *sampleClass = [[SampleClass alloc]init];\n [sampleClass setInternalID];\n NSLog(@\"ExternalID: %@\",[sampleClass getExternalID]); \n [pool drain];\n return 0;\n}"
},
{
"code": null,
"e": 5174,
"s": 5099,
"text": "Now when we compile and run the program, we will get the following result."
},
{
"code": null,
"e": 5234,
"s": 5174,
"text": "2013-09-22 21:18:31.754 Extensions[331:303] ExternalID: 51\n"
},
{
"code": null,
"e": 5423,
"s": 5234,
"text": "In the above example, we can see that the internalID is not returned directly. We here remove the UNIQUEINTERNALKEY and only make the remaining value available to the method getExternalID."
},
{
"code": null,
"e": 5539,
"s": 5423,
"text": "The above example just uses a string operation, but it can have many features like encryption/decryption and so on."
},
{
"code": null,
"e": 5572,
"s": 5539,
"text": "\n 18 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5589,
"s": 5572,
"text": " PARTHA MAJUMDAR"
},
{
"code": null,
"e": 5620,
"s": 5589,
"text": "\n 6 Lectures \n 25 mins\n"
},
{
"code": null,
"e": 5631,
"s": 5620,
"text": " Ken Burke"
},
{
"code": null,
"e": 5638,
"s": 5631,
"text": " Print"
},
{
"code": null,
"e": 5649,
"s": 5638,
"text": " Add Notes"
}
] |
Artificial Eyeliner on LIVE Feed using Python, OpenCV and Dlib | by Kaushil Kundalia | Towards Data Science
|
Computer vision is one of the most exciting fields with a broad spectrum of applications ranging from medical imaging to creating funniest face filters. In this article, I have tried to create an artificial eyeliner to mimic Snapchat or Instagram filters. Hope you enjoy reading.
This article is meant for beginners in computer vision, who want to build something exciting. I’ll keep the explanation as simple as I can. I’d advice on going through the code on GitHub along with reading the article to have a better understanding.
It is important to set up a new virtual environment and install all the required dependencies before you begin. You can visit my GitHub repo for the instructions.
We’ll be using OpenCV, NumPy, imutils, SciPy and Dlib for this project. Below is a brief description of the use of these libraries in our project — feel free to skip this section if you’re already familiar.
OpenCV : It is one of the most popular modules used for image manipulation. We’ll be using OpenCV to read, write and draw on an image.
NumPy: NumPy is frequently used when working with OpenCV projects. An image is essentially an array of pixels and OpenCV uses these arrays stored in the form of NumPy arrays for performing operation on images.
Imutils: Imutils comes loaded with continence functions to make your life working with computer vision easier. Here, we’ll use it for converting dlib objects to numpy arrays that are very flexible and widely acceptable.
Scipy: As the name says, SciPy is used for scientific computing on python. We’ll use it to create interpolations (it’s okay if it doesn’t make sense right now).
Dlib: Dlib originally came as a C++ library that contains various ML algorithms. We’ll be using dlib to extract facial landmark points.
Briefly explaining — the program first extracts 68 landmark points from each face. Of those 68 points, points 37–42 belong to the left eye and points 43–48 belong to the right eye — see picture below.
Because our goal is to apply eyeliner, we are only interested in points 37–48 and we extract these points. We’ll interpolate these extracted points. Interpolation means that we try to insert points between two given points. We can either make this interpolation linear or smooth — see figure below for details.
The flow chart of the eyeliner algorithm is shown below.
Next, we describe the algorithm in further detail. If you are just interested in running the code, skip to the next section.
We’ll first extract the coordinates of the bounding box surrounding the face.
OpenCV converts an image to a NumPy array. This numpy.array (that is a matrix representation of an image) is stored in the variable named frame. We use a function called face_detector() that returns the coordinates of bounding boxes surrounding all the faces found in a frame. These bounding box coordinates are stored in a variable named bounding_boxes.We iterate a loop over bounding_boxes to apply eyeliner over each face detected in a frame. face_landmark_points stores the 68 landmark points. eye_landmark_points is an array of eye landmark points received from getEyeLandmarkPts() .
The getEyeLandmarkPts() takes 68 landmark points as input and returns an array of 4 elements having coordinates of left upper eyelid (L_eye_top) , left lower eyelid (L_eye_bottom) and same for right eye (R_eye_top & R_eye_bottom). This is done by simple NumPy indexing. We’re shifting the extreme points (pt no. 37,40,43 and 46. See the 68 landmark points figure) to further outside by 5 px. This is done in line no. 6–9. This is to give a more realistic look.
NOTE: In an array, indexing starts from 0. So we change pt no. 36, 39, 42 and 45 in our code.
Now we need to interpolate through these points to get a smooth curve from which we can make eyeliner. We need to treat each curve differently. (i.e. L_eye_top , L_eye_bottom, R_eye_top, R_eye_bottom). Hence we use a separate variable name for each curve. interpolateCoordinates() is used to generate interpolations over each of these curves.The functioninterp1d() from the scipy module is used to generate the interpolation. The kind='quadratic' means to generate a curvature of those points.
interpolateCoordinates() is called by getEyelinerPoints() repetitively to generate interpolated coordinates for each curve. It returns an array of interpolated points for each curve.
drawEyeLiner() takes the generated interpolated points as an argument and draws a line between two consecutive points. This is done for each curve in two loops, one for left and other for right eye. These drawn lines make our eyeliner. It returns a new frame op which has the eyeliner. And BOOM ! We’re done :D.
The usage of this project is very simple. Just clone the github repo from here.
git clone https://github.com/kaushil24/Artificial-Eyeliner/
Next, open the command prompt and type the following code to run a sample test
python3 eyeliner.py -v "Media/Sample Video.mp4"
You can use your own video by placing your video path inside the argument. The complete CLI commands are as follows:
python eyeliner.py [-i image] [-v video] [-d dat] [-t thickness] [-c color] [-s save]
-i : Path of the image you want to apply eyeliner on
-v : Path of the video you want to apply eyeliner on.
-v : Live eyeliner of webcam video if webcam is given. Eg: python3 -v webcam -s "Webcam output"
-t : Whole numbers (int) to set thickness of eyeliner. Default = 2. Recommended number value between 1-5
-d: Path to your shape_predictor_68_face_landmarks.dat file. Default path is in the root. Unless you have the shape_predictor_68_face_landmarks.dat file stored at some other location you need not use this argument.
-c : Change the color of eyeliner. Syntax -c 255 255 255. Default = 0 0 0. Where each number represents its R G B value.
-s : Location and file name you want to save the output on. NOTE The program automatically adds extension while saving the file. If a file with same name already exists, it will overwrite that file.
Play around with the code and if you add something useful, do make a pull request. Let’s make it a collaborative project.
GitHub repo: https://github.com/kaushil24/Artificial-Eyeliner/
Well this brings us to the end.
Hey this is my first post. Please comment your doubts and feedback, and I shall be happy to solve them. Hope you enjoyed reading this article! Have an amazing day.
|
[
{
"code": null,
"e": 451,
"s": 171,
"text": "Computer vision is one of the most exciting fields with a broad spectrum of applications ranging from medical imaging to creating funniest face filters. In this article, I have tried to create an artificial eyeliner to mimic Snapchat or Instagram filters. Hope you enjoy reading."
},
{
"code": null,
"e": 701,
"s": 451,
"text": "This article is meant for beginners in computer vision, who want to build something exciting. I’ll keep the explanation as simple as I can. I’d advice on going through the code on GitHub along with reading the article to have a better understanding."
},
{
"code": null,
"e": 864,
"s": 701,
"text": "It is important to set up a new virtual environment and install all the required dependencies before you begin. You can visit my GitHub repo for the instructions."
},
{
"code": null,
"e": 1071,
"s": 864,
"text": "We’ll be using OpenCV, NumPy, imutils, SciPy and Dlib for this project. Below is a brief description of the use of these libraries in our project — feel free to skip this section if you’re already familiar."
},
{
"code": null,
"e": 1206,
"s": 1071,
"text": "OpenCV : It is one of the most popular modules used for image manipulation. We’ll be using OpenCV to read, write and draw on an image."
},
{
"code": null,
"e": 1416,
"s": 1206,
"text": "NumPy: NumPy is frequently used when working with OpenCV projects. An image is essentially an array of pixels and OpenCV uses these arrays stored in the form of NumPy arrays for performing operation on images."
},
{
"code": null,
"e": 1636,
"s": 1416,
"text": "Imutils: Imutils comes loaded with continence functions to make your life working with computer vision easier. Here, we’ll use it for converting dlib objects to numpy arrays that are very flexible and widely acceptable."
},
{
"code": null,
"e": 1797,
"s": 1636,
"text": "Scipy: As the name says, SciPy is used for scientific computing on python. We’ll use it to create interpolations (it’s okay if it doesn’t make sense right now)."
},
{
"code": null,
"e": 1933,
"s": 1797,
"text": "Dlib: Dlib originally came as a C++ library that contains various ML algorithms. We’ll be using dlib to extract facial landmark points."
},
{
"code": null,
"e": 2134,
"s": 1933,
"text": "Briefly explaining — the program first extracts 68 landmark points from each face. Of those 68 points, points 37–42 belong to the left eye and points 43–48 belong to the right eye — see picture below."
},
{
"code": null,
"e": 2445,
"s": 2134,
"text": "Because our goal is to apply eyeliner, we are only interested in points 37–48 and we extract these points. We’ll interpolate these extracted points. Interpolation means that we try to insert points between two given points. We can either make this interpolation linear or smooth — see figure below for details."
},
{
"code": null,
"e": 2502,
"s": 2445,
"text": "The flow chart of the eyeliner algorithm is shown below."
},
{
"code": null,
"e": 2627,
"s": 2502,
"text": "Next, we describe the algorithm in further detail. If you are just interested in running the code, skip to the next section."
},
{
"code": null,
"e": 2705,
"s": 2627,
"text": "We’ll first extract the coordinates of the bounding box surrounding the face."
},
{
"code": null,
"e": 3294,
"s": 2705,
"text": "OpenCV converts an image to a NumPy array. This numpy.array (that is a matrix representation of an image) is stored in the variable named frame. We use a function called face_detector() that returns the coordinates of bounding boxes surrounding all the faces found in a frame. These bounding box coordinates are stored in a variable named bounding_boxes.We iterate a loop over bounding_boxes to apply eyeliner over each face detected in a frame. face_landmark_points stores the 68 landmark points. eye_landmark_points is an array of eye landmark points received from getEyeLandmarkPts() ."
},
{
"code": null,
"e": 3755,
"s": 3294,
"text": "The getEyeLandmarkPts() takes 68 landmark points as input and returns an array of 4 elements having coordinates of left upper eyelid (L_eye_top) , left lower eyelid (L_eye_bottom) and same for right eye (R_eye_top & R_eye_bottom). This is done by simple NumPy indexing. We’re shifting the extreme points (pt no. 37,40,43 and 46. See the 68 landmark points figure) to further outside by 5 px. This is done in line no. 6–9. This is to give a more realistic look."
},
{
"code": null,
"e": 3849,
"s": 3755,
"text": "NOTE: In an array, indexing starts from 0. So we change pt no. 36, 39, 42 and 45 in our code."
},
{
"code": null,
"e": 4343,
"s": 3849,
"text": "Now we need to interpolate through these points to get a smooth curve from which we can make eyeliner. We need to treat each curve differently. (i.e. L_eye_top , L_eye_bottom, R_eye_top, R_eye_bottom). Hence we use a separate variable name for each curve. interpolateCoordinates() is used to generate interpolations over each of these curves.The functioninterp1d() from the scipy module is used to generate the interpolation. The kind='quadratic' means to generate a curvature of those points."
},
{
"code": null,
"e": 4526,
"s": 4343,
"text": "interpolateCoordinates() is called by getEyelinerPoints() repetitively to generate interpolated coordinates for each curve. It returns an array of interpolated points for each curve."
},
{
"code": null,
"e": 4838,
"s": 4526,
"text": "drawEyeLiner() takes the generated interpolated points as an argument and draws a line between two consecutive points. This is done for each curve in two loops, one for left and other for right eye. These drawn lines make our eyeliner. It returns a new frame op which has the eyeliner. And BOOM ! We’re done :D."
},
{
"code": null,
"e": 4918,
"s": 4838,
"text": "The usage of this project is very simple. Just clone the github repo from here."
},
{
"code": null,
"e": 4978,
"s": 4918,
"text": "git clone https://github.com/kaushil24/Artificial-Eyeliner/"
},
{
"code": null,
"e": 5057,
"s": 4978,
"text": "Next, open the command prompt and type the following code to run a sample test"
},
{
"code": null,
"e": 5105,
"s": 5057,
"text": "python3 eyeliner.py -v \"Media/Sample Video.mp4\""
},
{
"code": null,
"e": 5222,
"s": 5105,
"text": "You can use your own video by placing your video path inside the argument. The complete CLI commands are as follows:"
},
{
"code": null,
"e": 5308,
"s": 5222,
"text": "python eyeliner.py [-i image] [-v video] [-d dat] [-t thickness] [-c color] [-s save]"
},
{
"code": null,
"e": 5361,
"s": 5308,
"text": "-i : Path of the image you want to apply eyeliner on"
},
{
"code": null,
"e": 5415,
"s": 5361,
"text": "-v : Path of the video you want to apply eyeliner on."
},
{
"code": null,
"e": 5511,
"s": 5415,
"text": "-v : Live eyeliner of webcam video if webcam is given. Eg: python3 -v webcam -s \"Webcam output\""
},
{
"code": null,
"e": 5616,
"s": 5511,
"text": "-t : Whole numbers (int) to set thickness of eyeliner. Default = 2. Recommended number value between 1-5"
},
{
"code": null,
"e": 5831,
"s": 5616,
"text": "-d: Path to your shape_predictor_68_face_landmarks.dat file. Default path is in the root. Unless you have the shape_predictor_68_face_landmarks.dat file stored at some other location you need not use this argument."
},
{
"code": null,
"e": 5952,
"s": 5831,
"text": "-c : Change the color of eyeliner. Syntax -c 255 255 255. Default = 0 0 0. Where each number represents its R G B value."
},
{
"code": null,
"e": 6151,
"s": 5952,
"text": "-s : Location and file name you want to save the output on. NOTE The program automatically adds extension while saving the file. If a file with same name already exists, it will overwrite that file."
},
{
"code": null,
"e": 6273,
"s": 6151,
"text": "Play around with the code and if you add something useful, do make a pull request. Let’s make it a collaborative project."
},
{
"code": null,
"e": 6336,
"s": 6273,
"text": "GitHub repo: https://github.com/kaushil24/Artificial-Eyeliner/"
},
{
"code": null,
"e": 6368,
"s": 6336,
"text": "Well this brings us to the end."
}
] |
Using Static Variables in Java - GeeksforGeeks
|
22 Sep, 2021
Here we will discuss the static variables in java. Java actually doesn’t have the concept of Global variable. To define a Global variable in java, the keyword static is used. The advantage of the static variable is discussed below. Now geeks you must be wondering out what are the advantages of static variable, why to incorporate in our program. Now we are taking a real-time example as an illustration here in order to perceive why we are using it.
Illustration: Employee directory
Suppose there are 25 students in the Production Engineering department of NIT Agartala. All students have its unique enrollment number, registration number, and name. So instance data member is good in such a case. Now all instance data members will get memory each time when the object is created. Here, “department” refers to the common property of all the objects. If we make it static, this field will get the memory only once.
Thus static variables can be used to refer to the common property of all objects (which is not unique for each object), for example, college name of students, company name of employees, CEO of a company, etc. It makes the program memory efficient (i.e., it saves memory).
Example
Java
// Java Program to show the Advantages of Static Variable // Class 1class emp { // Attributes of employees int id; String name; int salary; // Here we are declaring CEO as a static variable static String ceo; // Constructors of this class emp(int id, String name, int salary, String ceo) { // This keyword refers to current instance itself this.id = id; this.name = name; this.salary = salary; this.ceo = ceo; } // Method of this class void display() { // Print all associated attributes System.out.println("ID: " + id + ", " + "Name:: " + name + ", " + "Salary: $" + salary + " & " + "CEO:: " + ceo); }} // Class 2// Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating object of class 1 // Object 1 emp Monodwip = new emp(1, "Monodwip", 30000, "Rinkel"); // Object 2 emp Mukta = new emp(2, "Mukta", 50000, "Rinkel"); // We have changed the CEO for Subham, As CEO is // declared static, sowill change for all the // objects // Object 3 emp Subham = new emp(3, "Subham", 40000, "Arnab"); // Calling display() method over all objects Monodwip.display(); Mukta.display(); Subham.display(); }}
ID: 1, Name:: Monodwip, Salary: $30000 & CEO:: Arnab
ID: 2, Name:: Mukta, Salary: $50000 & CEO:: Arnab
ID: 3, Name:: Subham, Salary: $40000 & CEO:: Arnab
Output explanation:
From the above output, we can perceive that Rinkel got replaced by Arnab for all the objects, hence justifying the usage of static variable.
Blogathon-2021
java-basics
Blogathon
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install Numpy on MacOS?
Dart - Null Aware Operators
How to Create a Table With Multiple Foreign Keys in SQL?
How to Install Tkinter in Windows?
Format Dates in Flutter
Arrays in Java
Split() String method in Java with examples
Arrays.sort() in Java with examples
For-each loop in Java
Initialize an ArrayList in Java
|
[
{
"code": null,
"e": 24421,
"s": 24393,
"text": "\n22 Sep, 2021"
},
{
"code": null,
"e": 24872,
"s": 24421,
"text": "Here we will discuss the static variables in java. Java actually doesn’t have the concept of Global variable. To define a Global variable in java, the keyword static is used. The advantage of the static variable is discussed below. Now geeks you must be wondering out what are the advantages of static variable, why to incorporate in our program. Now we are taking a real-time example as an illustration here in order to perceive why we are using it."
},
{
"code": null,
"e": 24905,
"s": 24872,
"text": "Illustration: Employee directory"
},
{
"code": null,
"e": 25337,
"s": 24905,
"text": "Suppose there are 25 students in the Production Engineering department of NIT Agartala. All students have its unique enrollment number, registration number, and name. So instance data member is good in such a case. Now all instance data members will get memory each time when the object is created. Here, “department” refers to the common property of all the objects. If we make it static, this field will get the memory only once."
},
{
"code": null,
"e": 25609,
"s": 25337,
"text": "Thus static variables can be used to refer to the common property of all objects (which is not unique for each object), for example, college name of students, company name of employees, CEO of a company, etc. It makes the program memory efficient (i.e., it saves memory)."
},
{
"code": null,
"e": 25617,
"s": 25609,
"text": "Example"
},
{
"code": null,
"e": 25622,
"s": 25617,
"text": "Java"
},
{
"code": "// Java Program to show the Advantages of Static Variable // Class 1class emp { // Attributes of employees int id; String name; int salary; // Here we are declaring CEO as a static variable static String ceo; // Constructors of this class emp(int id, String name, int salary, String ceo) { // This keyword refers to current instance itself this.id = id; this.name = name; this.salary = salary; this.ceo = ceo; } // Method of this class void display() { // Print all associated attributes System.out.println(\"ID: \" + id + \", \" + \"Name:: \" + name + \", \" + \"Salary: $\" + salary + \" & \" + \"CEO:: \" + ceo); }} // Class 2// Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating object of class 1 // Object 1 emp Monodwip = new emp(1, \"Monodwip\", 30000, \"Rinkel\"); // Object 2 emp Mukta = new emp(2, \"Mukta\", 50000, \"Rinkel\"); // We have changed the CEO for Subham, As CEO is // declared static, sowill change for all the // objects // Object 3 emp Subham = new emp(3, \"Subham\", 40000, \"Arnab\"); // Calling display() method over all objects Monodwip.display(); Mukta.display(); Subham.display(); }}",
"e": 27066,
"s": 25622,
"text": null
},
{
"code": null,
"e": 27221,
"s": 27066,
"text": "ID: 1, Name:: Monodwip, Salary: $30000 & CEO:: Arnab\nID: 2, Name:: Mukta, Salary: $50000 & CEO:: Arnab\nID: 3, Name:: Subham, Salary: $40000 & CEO:: Arnab\n"
},
{
"code": null,
"e": 27241,
"s": 27221,
"text": "Output explanation:"
},
{
"code": null,
"e": 27382,
"s": 27241,
"text": "From the above output, we can perceive that Rinkel got replaced by Arnab for all the objects, hence justifying the usage of static variable."
},
{
"code": null,
"e": 27397,
"s": 27382,
"text": "Blogathon-2021"
},
{
"code": null,
"e": 27409,
"s": 27397,
"text": "java-basics"
},
{
"code": null,
"e": 27419,
"s": 27409,
"text": "Blogathon"
},
{
"code": null,
"e": 27424,
"s": 27419,
"text": "Java"
},
{
"code": null,
"e": 27429,
"s": 27424,
"text": "Java"
},
{
"code": null,
"e": 27527,
"s": 27429,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27536,
"s": 27527,
"text": "Comments"
},
{
"code": null,
"e": 27549,
"s": 27536,
"text": "Old Comments"
},
{
"code": null,
"e": 27580,
"s": 27549,
"text": "How to Install Numpy on MacOS?"
},
{
"code": null,
"e": 27608,
"s": 27580,
"text": "Dart - Null Aware Operators"
},
{
"code": null,
"e": 27665,
"s": 27608,
"text": "How to Create a Table With Multiple Foreign Keys in SQL?"
},
{
"code": null,
"e": 27700,
"s": 27665,
"text": "How to Install Tkinter in Windows?"
},
{
"code": null,
"e": 27724,
"s": 27700,
"text": "Format Dates in Flutter"
},
{
"code": null,
"e": 27739,
"s": 27724,
"text": "Arrays in Java"
},
{
"code": null,
"e": 27783,
"s": 27739,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 27819,
"s": 27783,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 27841,
"s": 27819,
"text": "For-each loop in Java"
}
] |
Design Patterns - State Pattern
|
In State pattern a class behavior changes based on its state. This type of design pattern comes under behavior pattern.
In State pattern, we create objects which represent various states and a context object whose behavior varies as its state object changes.
We are going to create a State interface defining an action and concrete state classes implementing the State interface. Context is a class which carries a State.
StatePatternDemo, our demo class, will use Context and state objects to demonstrate change in Context behavior based on type of state it is in.
Create an interface.
State.java
public interface State {
public void doAction(Context context);
}
Create concrete classes implementing the same interface.
StartState.java
public class StartState implements State {
public void doAction(Context context) {
System.out.println("Player is in start state");
context.setState(this);
}
public String toString(){
return "Start State";
}
}
StopState.java
public class StopState implements State {
public void doAction(Context context) {
System.out.println("Player is in stop state");
context.setState(this);
}
public String toString(){
return "Stop State";
}
}
Create Context Class.
Context.java
public class Context {
private State state;
public Context(){
state = null;
}
public void setState(State state){
this.state = state;
}
public State getState(){
return state;
}
}
Use the Context to see change in behaviour when State changes.
StatePatternDemo.java
public class StatePatternDemo {
public static void main(String[] args) {
Context context = new Context();
StartState startState = new StartState();
startState.doAction(context);
System.out.println(context.getState().toString());
StopState stopState = new StopState();
stopState.doAction(context);
System.out.println(context.getState().toString());
}
}
Verify the output.
Player is in start state
Start State
Player is in stop state
Stop State
102 Lectures
10 hours
Arnab Chakraborty
30 Lectures
3 hours
Arnab Chakraborty
31 Lectures
4 hours
Arnab Chakraborty
43 Lectures
1.5 hours
Manoj Kumar
7 Lectures
1 hours
Zach Miller
54 Lectures
4 hours
Sasha Miller
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2871,
"s": 2751,
"text": "In State pattern a class behavior changes based on its state. This type of design pattern comes under behavior pattern."
},
{
"code": null,
"e": 3010,
"s": 2871,
"text": "In State pattern, we create objects which represent various states and a context object whose behavior varies as its state object changes."
},
{
"code": null,
"e": 3173,
"s": 3010,
"text": "We are going to create a State interface defining an action and concrete state classes implementing the State interface. Context is a class which carries a State."
},
{
"code": null,
"e": 3318,
"s": 3173,
"text": "StatePatternDemo, our demo class, will use Context and state objects to demonstrate change in Context behavior based on type of state it is in."
},
{
"code": null,
"e": 3339,
"s": 3318,
"text": "Create an interface."
},
{
"code": null,
"e": 3350,
"s": 3339,
"text": "State.java"
},
{
"code": null,
"e": 3419,
"s": 3350,
"text": "public interface State {\n public void doAction(Context context);\n}"
},
{
"code": null,
"e": 3476,
"s": 3419,
"text": "Create concrete classes implementing the same interface."
},
{
"code": null,
"e": 3492,
"s": 3476,
"text": "StartState.java"
},
{
"code": null,
"e": 3734,
"s": 3492,
"text": "public class StartState implements State {\n\n public void doAction(Context context) {\n System.out.println(\"Player is in start state\");\n context.setState(this);\t\n }\n\n public String toString(){\n return \"Start State\";\n }\n}"
},
{
"code": null,
"e": 3749,
"s": 3734,
"text": "StopState.java"
},
{
"code": null,
"e": 3988,
"s": 3749,
"text": "public class StopState implements State {\n\n public void doAction(Context context) {\n System.out.println(\"Player is in stop state\");\n context.setState(this);\t\n }\n\n public String toString(){\n return \"Stop State\";\n }\n}"
},
{
"code": null,
"e": 4010,
"s": 3988,
"text": "Create Context Class."
},
{
"code": null,
"e": 4023,
"s": 4010,
"text": "Context.java"
},
{
"code": null,
"e": 4245,
"s": 4023,
"text": "public class Context {\n private State state;\n\n public Context(){\n state = null;\n }\n\n public void setState(State state){\n this.state = state;\t\t\n }\n\n public State getState(){\n return state;\n }\n}"
},
{
"code": null,
"e": 4308,
"s": 4245,
"text": "Use the Context to see change in behaviour when State changes."
},
{
"code": null,
"e": 4330,
"s": 4308,
"text": "StatePatternDemo.java"
},
{
"code": null,
"e": 4734,
"s": 4330,
"text": "public class StatePatternDemo {\n public static void main(String[] args) {\n Context context = new Context();\n\n StartState startState = new StartState();\n startState.doAction(context);\n\n System.out.println(context.getState().toString());\n\n StopState stopState = new StopState();\n stopState.doAction(context);\n\n System.out.println(context.getState().toString());\n }\n}"
},
{
"code": null,
"e": 4753,
"s": 4734,
"text": "Verify the output."
},
{
"code": null,
"e": 4826,
"s": 4753,
"text": "Player is in start state\nStart State\nPlayer is in stop state\nStop State\n"
},
{
"code": null,
"e": 4861,
"s": 4826,
"text": "\n 102 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 4880,
"s": 4861,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 4913,
"s": 4880,
"text": "\n 30 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 4932,
"s": 4913,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 4965,
"s": 4932,
"text": "\n 31 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4984,
"s": 4965,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 5019,
"s": 4984,
"text": "\n 43 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5032,
"s": 5019,
"text": " Manoj Kumar"
},
{
"code": null,
"e": 5064,
"s": 5032,
"text": "\n 7 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5077,
"s": 5064,
"text": " Zach Miller"
},
{
"code": null,
"e": 5110,
"s": 5077,
"text": "\n 54 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 5124,
"s": 5110,
"text": " Sasha Miller"
},
{
"code": null,
"e": 5131,
"s": 5124,
"text": " Print"
},
{
"code": null,
"e": 5142,
"s": 5131,
"text": " Add Notes"
}
] |
Improving sentence embeddings with BERT and Representation Learning | by Denis Antyukhov | Towards Data Science
|
In this experiment, we fine-tune a BERT model to improve its capability for encoding short texts. This yields more useful sentence embeddings for downstream NLP tasks.
While a vanilla BERT can be used for encoding sentences, the embeddings generated with it are not robust. As we can see below, the samples deemed similar by the model are often more lexically than semantically related. Small perturbations in input samples result in large changes of predicted similarity.
To improve, we use the Stanford Natural Language Inference dataset which contains sentence pairs manually labeled with entailment, contradiction, and neutral tags. For these sentences we will be learning such a representation, that the similarity between the entailing pairs is greater than the similarity between the contradicting ones.
To evaluate the quality of learned embeddings we measure Spearman rank correlation on STS and SICK-R datasets.
The plan for this experiment is:
preparing the SNLI and MNLI datasetsimplementing the data generatordefining the lossbuilding the modelpreparing the evaluation pipelinetraining the model
preparing the SNLI and MNLI datasets
implementing the data generator
defining the loss
building the model
preparing the evaluation pipeline
training the model
This guide contains code for building and training a sentence encoder on labeled data.
For a familiar reader, it should take around 90 minutes to finish this guide and train the sentence encoder. The code was tested with tensorflow==1.15.
The code for this experiment is available here. This time, most of the code from the previous experiment is reused. I recommend checking it out first.
The standalone version can be found in the repository.
We begin with downloading the SNLI, MNLI, STS and SICK datasets and the pre-trained English BERT model.
Define a loader function for SNLI jsonl format.
To handle the dataset more conveniently, we re-arrange it a little bit. For each unique anchor we create an ID and an entry containing the anchor, entailment and contradiction samples. The anchors lacking at least one sample of each class are filtered out.
A single entry looks as follows
{ 'anchor': ["No, don't answer."], 'contradiction': ['Please respond.'], 'entailment': ["Don't respond. ", "Don't say a word. "]}
Finally, load the SNLI and MNLI datasets.
For training the model we will sample triplets, consisting of an anchor, a positive sample and a negative sample. To handle complex batch generation logic we use the following code:
The high-level logic is contained in the generate_batch method.
Batch anchor IDs are selected randomly from all available IDs.Anchor samples are retrieved from anchor samples of their IDs.Positive samples are retrieved from entailment samples of their IDs.Negative samples are retrieved from contradiction samples of their IDs.These may be considered hard negative samples, because they are often semantically similar to their anchors. To reduce overfitting we mix them with random negative samples retrieved from other, random ID.
Batch anchor IDs are selected randomly from all available IDs.
Anchor samples are retrieved from anchor samples of their IDs.
Positive samples are retrieved from entailment samples of their IDs.
Negative samples are retrieved from contradiction samples of their IDs.These may be considered hard negative samples, because they are often semantically similar to their anchors. To reduce overfitting we mix them with random negative samples retrieved from other, random ID.
We can frame the problem of learning a measure of sentence similarity as a ranking problem. Suppose we have a corpus of k paraphrased sentence pairs x and y and want to learn a function that estimates if y is a paraphrase of x or not. For some x we have a single positive sample y and k-1 negative samples y_k. This probability distribution can be written as:
The joint probability of P(x, y) is estimated using a scoring function, S:
During training it is infeasible to sum over all k-1 negative samples in the dataset. Instead, we approximate P(x) by sampling K responses from our corpus for each batch and using them as negative samples. We get:
We will be minimizing the negative log probability of our data. So, for a batch of K triplets for the loss we can write down:
Note: the expression above is known as Softmax-Loss.
Inner product is used as a similarity function S in this experiment. The code for computing the expression in the last brackets is below
First, we import the fine-tuning code from the previous experiment and build the BERT module.
The model has three inputs for the anchor, positive and negative samples. A BERT layer with a mean pooling operation is used as a shared text encoder. Text preprocessing is handled by the encoder layer. Softmax loss is computed on the encoded sentences.
For convenience, 3 models are created: enc_model for encoding sentences, sim_model for computing similarity between sentence pairs and trn_model for training. All models use shared weights.
Natural Language Encoders are usually evaluated by embedding labeled sentence pairs, measuring some kind of similarity between them, then computing the correlation of that similarity with human judgement.
We use STS 2012–2016 and SICK 2014 datasets for evaluating our model. For all sentence pairs in the test set we compute cosine similarity. We report Pearson rank correlation with human-annotated labels.
The Callback below handles the evaluation procedure and saves the provided savemodel to savepath, every time a new best result is achieved.
We train the model for 10 epochs, with 256 batches each. Each batch consists of 256 triplets. We perform an evaluation at the beginning of each epoch.
trn_model.fit_generator(tr_gen._generator, validation_data=ts_gen._generator, steps_per_epoch=256, validation_steps=32, epochs=5, callbacks=callbacks)*** New best: STS_spearman_r = 0.5426*** New best: STS_pearson_r = 0.5481*** New best: SICK_spearman_r = 0.5799*** New best: SICK_pearson_r = 0.6069Epoch 1/10255/256 [============================>.] - ETA: 1s - loss: 0.6858256/256 [==============================] - 535s 2s/step - loss: 0.6844 - val_loss: 0.4366*** New best: STS_spearman_r = 0.7186*** New best: STS_pearson_r = 0.7367*** New best: SICK_spearman_r = 0.7258*** New best: SICK_pearson_r = 0.8098Epoch 2/10255/256 [============================>.] - ETA: 1s - loss: 0.3950256/256 [==============================] - 524s 2s/step - loss: 0.3950 - val_loss: 0.3700*** New best: STS_spearman_r = 0.7337*** New best: STS_pearson_r = 0.7495*** New best: SICK_spearman_r = 0.7444*** New best: SICK_pearson_r = 0.8216...Epoch 9/10255/256 [============================>.] - ETA: 1s - loss: 0.2481256/256 [==============================] - 524s 2s/step - loss: 0.2481 - val_loss: 0.2631*** New best: STS_spearman_r = 0.7536*** New best: STS_pearson_r = 0.7638*** New best: SICK_spearman_r = 0.7623*** New best: SICK_pearson_r = 0.8316Epoch 10/10255/256 [============================>.] - ETA: 1s - loss: 0.2381256/256 [==============================] - 525s 2s/step - loss: 0.2383 - val_loss: 0.2492*** New best: STS_spearman_r = 0.7547*** New best: STS_pearson_r = 0.7648*** New best: SICK_spearman_r = 0.7628*** New best: SICK_pearson_r = 0.8325
For reference we can check the evaluation results from Sentence-BERT paper where the authors evaluated several pre-trained sentence embedding systems on STS and SICK tasks.
Our results with a vanilla mean-pooled BERT model are consistent with the published metrics, scoring 57.99 Spearman rank correlation score on SICK-R.After 10 epochs, the best Colab model achieved 76.94, which is on par with the best result of Universal Sentence Encoder with 76.69.
Since negative examples are shared between all samples in a batch, fine-tuning with larger batch_size tends to improve metrics up to a certain point. Unfreezing more encoder layers also helps, if your GPU can handle it.
Once the training is complete, we can compare the base and trained models by encoding test triplets and examining the predicted similarities side-by-side. Some examples:
Above we have proposed a method to improving sentence embeddings using labeled sentence pairs.
By explicitly training the model to encode the sentence pairs with respect to their semantic relations, we were able to learn more efficient and robust sentence representations.
Both automatic and manual evaluation demonstrate substantial improvement over the baseline sentence representation model.
Pre-training BERT from scratch with cloud TPUBuilding a Search Engine with BERT and TensorflowFine-tuning BERT with Keras and tf.ModuleImproving sentence embeddings with BERT and Representation Learning[you are here]
Pre-training BERT from scratch with cloud TPU
Building a Search Engine with BERT and Tensorflow
Fine-tuning BERT with Keras and tf.Module
Improving sentence embeddings with BERT and Representation Learning[you are here]
|
[
{
"code": null,
"e": 215,
"s": 47,
"text": "In this experiment, we fine-tune a BERT model to improve its capability for encoding short texts. This yields more useful sentence embeddings for downstream NLP tasks."
},
{
"code": null,
"e": 520,
"s": 215,
"text": "While a vanilla BERT can be used for encoding sentences, the embeddings generated with it are not robust. As we can see below, the samples deemed similar by the model are often more lexically than semantically related. Small perturbations in input samples result in large changes of predicted similarity."
},
{
"code": null,
"e": 858,
"s": 520,
"text": "To improve, we use the Stanford Natural Language Inference dataset which contains sentence pairs manually labeled with entailment, contradiction, and neutral tags. For these sentences we will be learning such a representation, that the similarity between the entailing pairs is greater than the similarity between the contradicting ones."
},
{
"code": null,
"e": 969,
"s": 858,
"text": "To evaluate the quality of learned embeddings we measure Spearman rank correlation on STS and SICK-R datasets."
},
{
"code": null,
"e": 1002,
"s": 969,
"text": "The plan for this experiment is:"
},
{
"code": null,
"e": 1156,
"s": 1002,
"text": "preparing the SNLI and MNLI datasetsimplementing the data generatordefining the lossbuilding the modelpreparing the evaluation pipelinetraining the model"
},
{
"code": null,
"e": 1193,
"s": 1156,
"text": "preparing the SNLI and MNLI datasets"
},
{
"code": null,
"e": 1225,
"s": 1193,
"text": "implementing the data generator"
},
{
"code": null,
"e": 1243,
"s": 1225,
"text": "defining the loss"
},
{
"code": null,
"e": 1262,
"s": 1243,
"text": "building the model"
},
{
"code": null,
"e": 1296,
"s": 1262,
"text": "preparing the evaluation pipeline"
},
{
"code": null,
"e": 1315,
"s": 1296,
"text": "training the model"
},
{
"code": null,
"e": 1402,
"s": 1315,
"text": "This guide contains code for building and training a sentence encoder on labeled data."
},
{
"code": null,
"e": 1554,
"s": 1402,
"text": "For a familiar reader, it should take around 90 minutes to finish this guide and train the sentence encoder. The code was tested with tensorflow==1.15."
},
{
"code": null,
"e": 1705,
"s": 1554,
"text": "The code for this experiment is available here. This time, most of the code from the previous experiment is reused. I recommend checking it out first."
},
{
"code": null,
"e": 1760,
"s": 1705,
"text": "The standalone version can be found in the repository."
},
{
"code": null,
"e": 1864,
"s": 1760,
"text": "We begin with downloading the SNLI, MNLI, STS and SICK datasets and the pre-trained English BERT model."
},
{
"code": null,
"e": 1912,
"s": 1864,
"text": "Define a loader function for SNLI jsonl format."
},
{
"code": null,
"e": 2169,
"s": 1912,
"text": "To handle the dataset more conveniently, we re-arrange it a little bit. For each unique anchor we create an ID and an entry containing the anchor, entailment and contradiction samples. The anchors lacking at least one sample of each class are filtered out."
},
{
"code": null,
"e": 2201,
"s": 2169,
"text": "A single entry looks as follows"
},
{
"code": null,
"e": 2338,
"s": 2201,
"text": "{ 'anchor': [\"No, don't answer.\"], 'contradiction': ['Please respond.'], 'entailment': [\"Don't respond. \", \"Don't say a word. \"]}"
},
{
"code": null,
"e": 2380,
"s": 2338,
"text": "Finally, load the SNLI and MNLI datasets."
},
{
"code": null,
"e": 2562,
"s": 2380,
"text": "For training the model we will sample triplets, consisting of an anchor, a positive sample and a negative sample. To handle complex batch generation logic we use the following code:"
},
{
"code": null,
"e": 2626,
"s": 2562,
"text": "The high-level logic is contained in the generate_batch method."
},
{
"code": null,
"e": 3094,
"s": 2626,
"text": "Batch anchor IDs are selected randomly from all available IDs.Anchor samples are retrieved from anchor samples of their IDs.Positive samples are retrieved from entailment samples of their IDs.Negative samples are retrieved from contradiction samples of their IDs.These may be considered hard negative samples, because they are often semantically similar to their anchors. To reduce overfitting we mix them with random negative samples retrieved from other, random ID."
},
{
"code": null,
"e": 3157,
"s": 3094,
"text": "Batch anchor IDs are selected randomly from all available IDs."
},
{
"code": null,
"e": 3220,
"s": 3157,
"text": "Anchor samples are retrieved from anchor samples of their IDs."
},
{
"code": null,
"e": 3289,
"s": 3220,
"text": "Positive samples are retrieved from entailment samples of their IDs."
},
{
"code": null,
"e": 3565,
"s": 3289,
"text": "Negative samples are retrieved from contradiction samples of their IDs.These may be considered hard negative samples, because they are often semantically similar to their anchors. To reduce overfitting we mix them with random negative samples retrieved from other, random ID."
},
{
"code": null,
"e": 3925,
"s": 3565,
"text": "We can frame the problem of learning a measure of sentence similarity as a ranking problem. Suppose we have a corpus of k paraphrased sentence pairs x and y and want to learn a function that estimates if y is a paraphrase of x or not. For some x we have a single positive sample y and k-1 negative samples y_k. This probability distribution can be written as:"
},
{
"code": null,
"e": 4000,
"s": 3925,
"text": "The joint probability of P(x, y) is estimated using a scoring function, S:"
},
{
"code": null,
"e": 4214,
"s": 4000,
"text": "During training it is infeasible to sum over all k-1 negative samples in the dataset. Instead, we approximate P(x) by sampling K responses from our corpus for each batch and using them as negative samples. We get:"
},
{
"code": null,
"e": 4340,
"s": 4214,
"text": "We will be minimizing the negative log probability of our data. So, for a batch of K triplets for the loss we can write down:"
},
{
"code": null,
"e": 4393,
"s": 4340,
"text": "Note: the expression above is known as Softmax-Loss."
},
{
"code": null,
"e": 4530,
"s": 4393,
"text": "Inner product is used as a similarity function S in this experiment. The code for computing the expression in the last brackets is below"
},
{
"code": null,
"e": 4624,
"s": 4530,
"text": "First, we import the fine-tuning code from the previous experiment and build the BERT module."
},
{
"code": null,
"e": 4878,
"s": 4624,
"text": "The model has three inputs for the anchor, positive and negative samples. A BERT layer with a mean pooling operation is used as a shared text encoder. Text preprocessing is handled by the encoder layer. Softmax loss is computed on the encoded sentences."
},
{
"code": null,
"e": 5068,
"s": 4878,
"text": "For convenience, 3 models are created: enc_model for encoding sentences, sim_model for computing similarity between sentence pairs and trn_model for training. All models use shared weights."
},
{
"code": null,
"e": 5273,
"s": 5068,
"text": "Natural Language Encoders are usually evaluated by embedding labeled sentence pairs, measuring some kind of similarity between them, then computing the correlation of that similarity with human judgement."
},
{
"code": null,
"e": 5476,
"s": 5273,
"text": "We use STS 2012–2016 and SICK 2014 datasets for evaluating our model. For all sentence pairs in the test set we compute cosine similarity. We report Pearson rank correlation with human-annotated labels."
},
{
"code": null,
"e": 5616,
"s": 5476,
"text": "The Callback below handles the evaluation procedure and saves the provided savemodel to savepath, every time a new best result is achieved."
},
{
"code": null,
"e": 5767,
"s": 5616,
"text": "We train the model for 10 epochs, with 256 batches each. Each batch consists of 256 triplets. We perform an evaluation at the beginning of each epoch."
},
{
"code": null,
"e": 7318,
"s": 5767,
"text": "trn_model.fit_generator(tr_gen._generator, validation_data=ts_gen._generator, steps_per_epoch=256, validation_steps=32, epochs=5, callbacks=callbacks)*** New best: STS_spearman_r = 0.5426*** New best: STS_pearson_r = 0.5481*** New best: SICK_spearman_r = 0.5799*** New best: SICK_pearson_r = 0.6069Epoch 1/10255/256 [============================>.] - ETA: 1s - loss: 0.6858256/256 [==============================] - 535s 2s/step - loss: 0.6844 - val_loss: 0.4366*** New best: STS_spearman_r = 0.7186*** New best: STS_pearson_r = 0.7367*** New best: SICK_spearman_r = 0.7258*** New best: SICK_pearson_r = 0.8098Epoch 2/10255/256 [============================>.] - ETA: 1s - loss: 0.3950256/256 [==============================] - 524s 2s/step - loss: 0.3950 - val_loss: 0.3700*** New best: STS_spearman_r = 0.7337*** New best: STS_pearson_r = 0.7495*** New best: SICK_spearman_r = 0.7444*** New best: SICK_pearson_r = 0.8216...Epoch 9/10255/256 [============================>.] - ETA: 1s - loss: 0.2481256/256 [==============================] - 524s 2s/step - loss: 0.2481 - val_loss: 0.2631*** New best: STS_spearman_r = 0.7536*** New best: STS_pearson_r = 0.7638*** New best: SICK_spearman_r = 0.7623*** New best: SICK_pearson_r = 0.8316Epoch 10/10255/256 [============================>.] - ETA: 1s - loss: 0.2381256/256 [==============================] - 525s 2s/step - loss: 0.2383 - val_loss: 0.2492*** New best: STS_spearman_r = 0.7547*** New best: STS_pearson_r = 0.7648*** New best: SICK_spearman_r = 0.7628*** New best: SICK_pearson_r = 0.8325"
},
{
"code": null,
"e": 7491,
"s": 7318,
"text": "For reference we can check the evaluation results from Sentence-BERT paper where the authors evaluated several pre-trained sentence embedding systems on STS and SICK tasks."
},
{
"code": null,
"e": 7773,
"s": 7491,
"text": "Our results with a vanilla mean-pooled BERT model are consistent with the published metrics, scoring 57.99 Spearman rank correlation score on SICK-R.After 10 epochs, the best Colab model achieved 76.94, which is on par with the best result of Universal Sentence Encoder with 76.69."
},
{
"code": null,
"e": 7993,
"s": 7773,
"text": "Since negative examples are shared between all samples in a batch, fine-tuning with larger batch_size tends to improve metrics up to a certain point. Unfreezing more encoder layers also helps, if your GPU can handle it."
},
{
"code": null,
"e": 8163,
"s": 7993,
"text": "Once the training is complete, we can compare the base and trained models by encoding test triplets and examining the predicted similarities side-by-side. Some examples:"
},
{
"code": null,
"e": 8258,
"s": 8163,
"text": "Above we have proposed a method to improving sentence embeddings using labeled sentence pairs."
},
{
"code": null,
"e": 8436,
"s": 8258,
"text": "By explicitly training the model to encode the sentence pairs with respect to their semantic relations, we were able to learn more efficient and robust sentence representations."
},
{
"code": null,
"e": 8558,
"s": 8436,
"text": "Both automatic and manual evaluation demonstrate substantial improvement over the baseline sentence representation model."
},
{
"code": null,
"e": 8775,
"s": 8558,
"text": "Pre-training BERT from scratch with cloud TPUBuilding a Search Engine with BERT and TensorflowFine-tuning BERT with Keras and tf.ModuleImproving sentence embeddings with BERT and Representation Learning[you are here]"
},
{
"code": null,
"e": 8821,
"s": 8775,
"text": "Pre-training BERT from scratch with cloud TPU"
},
{
"code": null,
"e": 8871,
"s": 8821,
"text": "Building a Search Engine with BERT and Tensorflow"
},
{
"code": null,
"e": 8913,
"s": 8871,
"text": "Fine-tuning BERT with Keras and tf.Module"
}
] |
Compute nCr % p | Set 1 (Introduction and Dynamic Programming Solution) - GeeksforGeeks
|
14 Mar, 2022
Given three numbers n, r and p, compute value of nCr mod p. Example:
Input: n = 10, r = 2, p = 13
Output: 6
Explanation: 10C2 is 45 and 45 % 13 is 6.
A Simple Solution is to first compute nCr, then compute nCr % p. This solution works fine when the value of nCr is small. What if the value of nCr is large? The value of nCr%p is generally needed for large values of n when nCr cannot fit in a variable, and causes overflow. So computing nCr and then using modular operator is not a good idea as there will be overflow even for slightly larger values of n and r. For example the methods discussed here and here cause overflow for n = 50 and r = 40.The idea is to compute nCr using below formula
C(n, r) = C(n-1, r-1) + C(n-1, r)
C(n, 0) = C(n, n) = 1
Working of Above formula and Pascal Triangle: Let us see how above formula works for C(4, 3)1==========>> n = 0, C(0, 0) = 1 1–1========>> n = 1, C(1, 0) = 1, C(1, 1) = 1 1–2–1======>> n = 2, C(2, 0) = 1, C(2, 1) = 2, C(2, 2) = 1 1–3–3–1====>> n = 3, C(3, 0) = 1, C(3, 1) = 3, C(3, 2) = 3, C(3, 3)=1 1–4–6–4–1==>> n = 4, C(4, 0) = 1, C(4, 1) = 4, C(4, 2) = 6, C(4, 3)=4, C(4, 4)=1 So here every loop on i, builds i’th row of pascal triangle, using (i-1)th rowExtension of above formula for modular arithmetic: We can use distributive property of modular operator to find nCr % p using above formula.
C(n, r)%p = [ C(n-1, r-1)%p + C(n-1, r)%p ] % p
C(n, 0) = C(n, n) = 1
The above formula can implemented using Dynamic Programming using a 2D array.The 2D array based dynamic programming solution can be further optimized by constructing one row at a time. See Space optimized version in below post for details.Binomial Coefficient using Dynamic ProgrammingBelow is implementation based on the space optimized version discussed in above post.
C++
JAVA
Python3
C#
PHP
Javascript
// A Dynamic Programming based solution to compute nCr % p#include <bits/stdc++.h>using namespace std; // Returns nCr % pint nCrModp(int n, int r, int p){ // Optimization for the cases when r is large if (r > n - r) r = n - r; // The array C is going to store last row of // pascal triangle at the end. And last entry // of last row is nCr int C[r + 1]; memset(C, 0, sizeof(C)); C[0] = 1; // Top row of Pascal Triangle // One by constructs remaining rows of Pascal // Triangle from top to bottom for (int i = 1; i <= n; i++) { // Fill entries of current row using previous // row values for (int j = min(i, r); j > 0; j--) // nCj = (n-1)Cj + (n-1)C(j-1); C[j] = (C[j] + C[j - 1]) % p; } return C[r];} // Driver programint main(){ int n = 10, r = 2, p = 13; cout << "Value of nCr % p is " << nCrModp(n, r, p); return 0;}
// A Dynamic Programming based// solution to compute nCr % pimport java.io.*;import java.util.*;import java.math.*; class GFG { // Returns nCr % p static int nCrModp(int n, int r, int p) { if (r > n - r) r = n - r; // The array C is going to store last // row of pascal triangle at the end. // And last entry of last row is nCr int C[] = new int[r + 1]; C[0] = 1; // Top row of Pascal Triangle // One by constructs remaining rows of Pascal // Triangle from top to bottom for (int i = 1; i <= n; i++) { // Fill entries of current row using previous // row values for (int j = Math.min(i, r); j > 0; j--) // nCj = (n-1)Cj + (n-1)C(j-1); C[j] = (C[j] + C[j - 1]) % p; } return C[r]; } // Driver program public static void main(String args[]) { int n = 10, r = 2, p = 13; System.out.println("Value of nCr % p is " + nCrModp(n, r, p)); }} // This code is contributed by Nikita Tiwari.
# A Dynamic Programming based solution to compute nCr % p # Returns nCr % pdef nCrModp(n, r, p): # Optimization for the cases when r is large # compared to n-r if (r > n- r): r = n - r # The array C is going to store last row of # pascal triangle at the end. And last entry # of last row is nCr. C = [0 for i in range(r + 1)] C[0] = 1 # Top row of Pascal Triangle # One by constructs remaining rows of Pascal # Triangle from top to bottom for i in range(1, n + 1): # Fill entries of current row # using previous row values for j in range(min(i, r), 0, -1): # nCj = (n - 1)Cj + (n - 1)C(j - 1) C[j] = (C[j] + C[j-1]) % p return C[r] # Driver Programn = 10r = 2p = 13print('Value of nCr % p is', nCrModp(n, r, p)) # This code is contributed by Soumen Ghosh
// A Dynamic Programming based// solution to compute nCr % pusing System; class GFG { // Returns nCr % p static int nCrModp(int n, int r, int p) { // Optimization for the cases when r is large if (r > n - r) r = n - r; // The array C is going to store last // row of pascal triangle at the end. // And last entry of last row is nCr int[] C = new int[r + 1]; for (int i = 0; i < r + 1; i++) C[i] = 0; C[0] = 1; // Top row of Pascal Triangle // One by constructs remaining rows // of Pascal Triangle from top to bottom for (int i = 1; i <= n; i++) { // Fill entries of current row using // previous row values for (int j = Math.Min(i, r); j > 0; j--) // nCj = (n-1)Cj + (n-1)C(j-1); C[j] = (C[j] + C[j - 1]) % p; } return C[r]; } // Driver program public static void Main() { int n = 10, r = 2, p = 13; Console.Write("Value of nCr % p is " + nCrModp(n, r, p)); }} // This code is contributed by nitin mittal.
<?php// A Dynamic Programming based// solution to compute nCr % p // Returns nCr % pfunction nCrModp($n, $r, $p){ // Optimization for the cases when r is largeif ($r > $n - $r) $r = $n - $r; // The array C is going// to store last row of// pascal triangle at// the end. And last entry// of last row is nCr$C = array(); for( $i = 0; $i < $r + 1; $i++) $C[$i] = 0; // Top row of Pascal// Triangle$C[0] = 1; // One by constructs remaining// rows of Pascal Triangle from// top to bottomfor ($i = 1; $i <= $n; $i++){ // Fill entries of current // row using previous row values for ($j = Min($i, $r); $j > 0; $j--) // nCj = (n-1)Cj + (n-1)C(j-1); $C[$j] = ($C[$j] + $C[$j - 1]) % $p;} return $C[$r];} // Driver Code$n = 10; $r = 2;$p = 13; echo "Value of nCr % p is ", nCrModp($n, $r, $p); // This code is contributed// by anuj_67.?>
<script>// A Dynamic Programming based// solution to compute nCr % p // Returns nCr % pfunction nCrModp(n,r,p){ if (r > n - r) r = n - r; // The array C is going to store last // row of pascal triangle at the end. // And last entry of last row is nCr let C = new Array(r + 1); for(let i = 0; i < r + 1; i++) C[i] = 0; C[0] = 1; // Top row of Pascal Triangle // One by constructs remaining rows of Pascal // Triangle from top to bottom for (let i = 1; i <= n; i++) { // Fill entries of current row using previous // row values for (let j = Math.min(i, r); j > 0; j--) // nCj = (n-1)Cj + (n-1)C(j-1); C[j] = (C[j] + C[j - 1]) % p; } return C[r];} // Driver programlet n = 10, r = 2, p = 13;document.write("Value of nCr % p is " + nCrModp(n, r, p)); // This code is contributed by avanitrachhadiya2155</script>
Value of nCr % p is 6
Time complexity of above solution is O(n*r) and it requires O(r) space. There are more and better solutions to above problem. Compute nCr % p | Set 2 (Lucas Theorem)Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Another approach lies in utilizing the concept of the Pascal Triangle. Instead of calculating the nCr value for every n starting from n=0 till n=n, the approach aims at using the nth row itself for the calculation. The method proceeds by finding out a general relationship between nCr and nCr-1.
FORMULA: C(n,r)=C(n,r-1)* (n-r+1)/r
Example:
For instance, take n=5 and r=3.
Input: n = 5, r = 3, p = 1000000007
Output: 6
Explanation: 5C3 is 10 and 10 % 100000007 is 10.
As per the formula,
C(5,3)=5!/(3!)*(2!)
C(5,3)=10
Also,
C(5,2)=5!/(2!)*(3!)
C(5,2)=10
Let's try applying the above formula.
C(n,r)=C(n,r-1)* (n-r+1)/r
C(5,3)=C(5,2)*(5-3+1)/3
C(5,3)=C(5,2)*1
C(5,3)=10*1
The above example shows that C(n,r) can be easily calculated by calculating C(n,r-1) and multiplying the result with the term (n-r+1)/r. But this multiplication may cause integer overflow for large values of n. To tackle this situation, use modulo multiplication, and modulo division concepts in order to achieve optimizations in terms of integer overflow.
Let’s find out how to build Pascal Triangle for the same.
1D array declaration can be further optimized by just the declaration of a single variable to perform calculations. However, integer overflow demands other functions too for the final implementation.
The post below mentions the space and time-optimized implementation for the binary coefficient calculation.
C++
// C++ program to find the nCr%p// based on optimal Dynamic// Programming implementation and// Pascal Triangle concepts#include <bits/stdc++.h>using namespace std; // Returns (a * b) % modlong long moduloMultiplication(long long a, long long b, long long mod){ // Initialize result long long res = 0; // Update a if it is more than // or equal to mod a %= mod; while (b) { // If b is odd, add a with result if (b & 1) res = (res + a) % mod; // Here we assume that doing 2*a // doesn't cause overflow a = (2 * a) % mod; b >>= 1; // b = b / 2 } return res;} // C++ function for extended Euclidean Algorithmlong long int gcdExtended(long long int a, long long int b, long long int* x, long long int* y); // Function to find modulo inverse of b. It returns// -1 when inverse doesn't existslong long int modInverse(long long int b, long long int m){ long long int x, y; // used in extended GCD algorithm long long int g = gcdExtended(b, m, &x, &y); // Return -1 if b and m are not co-prime if (g != 1) return -1; // m is added to handle negative x return (x % m + m) % m;} // C function for extended Euclidean Algorithm (used to// find modular inverse.long long int gcdExtended(long long int a, long long int b, long long int* x, long long int* y){ // Base Case if (a == 0) { *x = 0, *y = 1; return b; } // To store results of recursive call long long int x1, y1; long long int gcd = gcdExtended(b % a, a, &x1, &y1); // Update x and y using results of recursive // call *x = y1 - (b / a) * x1; *y = x1; return gcd;} // Function to compute a/b under modulo mlong long int modDivide(long long int a, long long int b, long long int m){ a = a % m; long long int inv = modInverse(b, m); if (inv == -1) // cout << "Division not defined"; return 0; else return (inv * a) % m;} // Function to calculate nCr % pint nCr(int n, int r, int p){ // Edge Case which is not possible if (r > n) return 0; // Optimization for the cases when r is large if (r > n - r) r = n - r; // x stores the current result at long long int x = 1; // each iteration // Initialized to 1 as nC0 is always 1. for (int i = 1; i <= r; i++) { // Formula derived for calculating result is // C(n,r-1)*(n-r+1)/r // Function calculates x*(n-i+1) % p. x = moduloMultiplication(x, (n + 1 - i), p); // Function calculates x/i % p. x = modDivide(x, i, p); } return x;} // Driver Codeint main(){ long long int n = 5, r = 3, p = 1000000007; cout << "Value of nCr % p is " << nCr(n, r, p); return 0;}
Value of nCr % p is 10
The above code needs an extra of O(1) space for the calculations.
The time involved in the calculation of nCr % p is of the order O(n).
This article is improved by Aryan Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
nitin mittal
vt_m
abhishek gupta 47
aryangupta18
avanitrachhadiya2155
rkbhola5
varshagumber28
binomial coefficient
large-numbers
Modular Arithmetic
Dynamic Programming
Mathematical
Dynamic Programming
Mathematical
Modular Arithmetic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bellman–Ford Algorithm | DP-23
Floyd Warshall Algorithm | DP-16
Matrix Chain Multiplication | DP-8
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Subset Sum Problem | DP-25
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Program to find GCD or HCF of two numbers
Merge two sorted arrays
|
[
{
"code": null,
"e": 24666,
"s": 24638,
"text": "\n14 Mar, 2022"
},
{
"code": null,
"e": 24736,
"s": 24666,
"text": "Given three numbers n, r and p, compute value of nCr mod p. Example: "
},
{
"code": null,
"e": 24818,
"s": 24736,
"text": "Input: n = 10, r = 2, p = 13\nOutput: 6\nExplanation: 10C2 is 45 and 45 % 13 is 6."
},
{
"code": null,
"e": 25364,
"s": 24818,
"text": "A Simple Solution is to first compute nCr, then compute nCr % p. This solution works fine when the value of nCr is small. What if the value of nCr is large? The value of nCr%p is generally needed for large values of n when nCr cannot fit in a variable, and causes overflow. So computing nCr and then using modular operator is not a good idea as there will be overflow even for slightly larger values of n and r. For example the methods discussed here and here cause overflow for n = 50 and r = 40.The idea is to compute nCr using below formula "
},
{
"code": null,
"e": 25426,
"s": 25364,
"text": " C(n, r) = C(n-1, r-1) + C(n-1, r)\n C(n, 0) = C(n, n) = 1"
},
{
"code": null,
"e": 26026,
"s": 25426,
"text": "Working of Above formula and Pascal Triangle: Let us see how above formula works for C(4, 3)1==========>> n = 0, C(0, 0) = 1 1–1========>> n = 1, C(1, 0) = 1, C(1, 1) = 1 1–2–1======>> n = 2, C(2, 0) = 1, C(2, 1) = 2, C(2, 2) = 1 1–3–3–1====>> n = 3, C(3, 0) = 1, C(3, 1) = 3, C(3, 2) = 3, C(3, 3)=1 1–4–6–4–1==>> n = 4, C(4, 0) = 1, C(4, 1) = 4, C(4, 2) = 6, C(4, 3)=4, C(4, 4)=1 So here every loop on i, builds i’th row of pascal triangle, using (i-1)th rowExtension of above formula for modular arithmetic: We can use distributive property of modular operator to find nCr % p using above formula."
},
{
"code": null,
"e": 26102,
"s": 26026,
"text": " C(n, r)%p = [ C(n-1, r-1)%p + C(n-1, r)%p ] % p\n C(n, 0) = C(n, n) = 1"
},
{
"code": null,
"e": 26475,
"s": 26102,
"text": "The above formula can implemented using Dynamic Programming using a 2D array.The 2D array based dynamic programming solution can be further optimized by constructing one row at a time. See Space optimized version in below post for details.Binomial Coefficient using Dynamic ProgrammingBelow is implementation based on the space optimized version discussed in above post. "
},
{
"code": null,
"e": 26479,
"s": 26475,
"text": "C++"
},
{
"code": null,
"e": 26484,
"s": 26479,
"text": "JAVA"
},
{
"code": null,
"e": 26492,
"s": 26484,
"text": "Python3"
},
{
"code": null,
"e": 26495,
"s": 26492,
"text": "C#"
},
{
"code": null,
"e": 26499,
"s": 26495,
"text": "PHP"
},
{
"code": null,
"e": 26510,
"s": 26499,
"text": "Javascript"
},
{
"code": "// A Dynamic Programming based solution to compute nCr % p#include <bits/stdc++.h>using namespace std; // Returns nCr % pint nCrModp(int n, int r, int p){ // Optimization for the cases when r is large if (r > n - r) r = n - r; // The array C is going to store last row of // pascal triangle at the end. And last entry // of last row is nCr int C[r + 1]; memset(C, 0, sizeof(C)); C[0] = 1; // Top row of Pascal Triangle // One by constructs remaining rows of Pascal // Triangle from top to bottom for (int i = 1; i <= n; i++) { // Fill entries of current row using previous // row values for (int j = min(i, r); j > 0; j--) // nCj = (n-1)Cj + (n-1)C(j-1); C[j] = (C[j] + C[j - 1]) % p; } return C[r];} // Driver programint main(){ int n = 10, r = 2, p = 13; cout << \"Value of nCr % p is \" << nCrModp(n, r, p); return 0;}",
"e": 27433,
"s": 26510,
"text": null
},
{
"code": "// A Dynamic Programming based// solution to compute nCr % pimport java.io.*;import java.util.*;import java.math.*; class GFG { // Returns nCr % p static int nCrModp(int n, int r, int p) { if (r > n - r) r = n - r; // The array C is going to store last // row of pascal triangle at the end. // And last entry of last row is nCr int C[] = new int[r + 1]; C[0] = 1; // Top row of Pascal Triangle // One by constructs remaining rows of Pascal // Triangle from top to bottom for (int i = 1; i <= n; i++) { // Fill entries of current row using previous // row values for (int j = Math.min(i, r); j > 0; j--) // nCj = (n-1)Cj + (n-1)C(j-1); C[j] = (C[j] + C[j - 1]) % p; } return C[r]; } // Driver program public static void main(String args[]) { int n = 10, r = 2, p = 13; System.out.println(\"Value of nCr % p is \" + nCrModp(n, r, p)); }} // This code is contributed by Nikita Tiwari.",
"e": 28535,
"s": 27433,
"text": null
},
{
"code": "# A Dynamic Programming based solution to compute nCr % p # Returns nCr % pdef nCrModp(n, r, p): # Optimization for the cases when r is large # compared to n-r if (r > n- r): r = n - r # The array C is going to store last row of # pascal triangle at the end. And last entry # of last row is nCr. C = [0 for i in range(r + 1)] C[0] = 1 # Top row of Pascal Triangle # One by constructs remaining rows of Pascal # Triangle from top to bottom for i in range(1, n + 1): # Fill entries of current row # using previous row values for j in range(min(i, r), 0, -1): # nCj = (n - 1)Cj + (n - 1)C(j - 1) C[j] = (C[j] + C[j-1]) % p return C[r] # Driver Programn = 10r = 2p = 13print('Value of nCr % p is', nCrModp(n, r, p)) # This code is contributed by Soumen Ghosh",
"e": 29384,
"s": 28535,
"text": null
},
{
"code": "// A Dynamic Programming based// solution to compute nCr % pusing System; class GFG { // Returns nCr % p static int nCrModp(int n, int r, int p) { // Optimization for the cases when r is large if (r > n - r) r = n - r; // The array C is going to store last // row of pascal triangle at the end. // And last entry of last row is nCr int[] C = new int[r + 1]; for (int i = 0; i < r + 1; i++) C[i] = 0; C[0] = 1; // Top row of Pascal Triangle // One by constructs remaining rows // of Pascal Triangle from top to bottom for (int i = 1; i <= n; i++) { // Fill entries of current row using // previous row values for (int j = Math.Min(i, r); j > 0; j--) // nCj = (n-1)Cj + (n-1)C(j-1); C[j] = (C[j] + C[j - 1]) % p; } return C[r]; } // Driver program public static void Main() { int n = 10, r = 2, p = 13; Console.Write(\"Value of nCr % p is \" + nCrModp(n, r, p)); }} // This code is contributed by nitin mittal.",
"e": 30537,
"s": 29384,
"text": null
},
{
"code": "<?php// A Dynamic Programming based// solution to compute nCr % p // Returns nCr % pfunction nCrModp($n, $r, $p){ // Optimization for the cases when r is largeif ($r > $n - $r) $r = $n - $r; // The array C is going// to store last row of// pascal triangle at// the end. And last entry// of last row is nCr$C = array(); for( $i = 0; $i < $r + 1; $i++) $C[$i] = 0; // Top row of Pascal// Triangle$C[0] = 1; // One by constructs remaining// rows of Pascal Triangle from// top to bottomfor ($i = 1; $i <= $n; $i++){ // Fill entries of current // row using previous row values for ($j = Min($i, $r); $j > 0; $j--) // nCj = (n-1)Cj + (n-1)C(j-1); $C[$j] = ($C[$j] + $C[$j - 1]) % $p;} return $C[$r];} // Driver Code$n = 10; $r = 2;$p = 13; echo \"Value of nCr % p is \", nCrModp($n, $r, $p); // This code is contributed// by anuj_67.?>",
"e": 31429,
"s": 30537,
"text": null
},
{
"code": "<script>// A Dynamic Programming based// solution to compute nCr % p // Returns nCr % pfunction nCrModp(n,r,p){ if (r > n - r) r = n - r; // The array C is going to store last // row of pascal triangle at the end. // And last entry of last row is nCr let C = new Array(r + 1); for(let i = 0; i < r + 1; i++) C[i] = 0; C[0] = 1; // Top row of Pascal Triangle // One by constructs remaining rows of Pascal // Triangle from top to bottom for (let i = 1; i <= n; i++) { // Fill entries of current row using previous // row values for (let j = Math.min(i, r); j > 0; j--) // nCj = (n-1)Cj + (n-1)C(j-1); C[j] = (C[j] + C[j - 1]) % p; } return C[r];} // Driver programlet n = 10, r = 2, p = 13;document.write(\"Value of nCr % p is \" + nCrModp(n, r, p)); // This code is contributed by avanitrachhadiya2155</script>",
"e": 32429,
"s": 31429,
"text": null
},
{
"code": null,
"e": 32451,
"s": 32429,
"text": "Value of nCr % p is 6"
},
{
"code": null,
"e": 32741,
"s": 32451,
"text": "Time complexity of above solution is O(n*r) and it requires O(r) space. There are more and better solutions to above problem. Compute nCr % p | Set 2 (Lucas Theorem)Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 33037,
"s": 32741,
"text": "Another approach lies in utilizing the concept of the Pascal Triangle. Instead of calculating the nCr value for every n starting from n=0 till n=n, the approach aims at using the nth row itself for the calculation. The method proceeds by finding out a general relationship between nCr and nCr-1."
},
{
"code": null,
"e": 33422,
"s": 33037,
"text": "FORMULA: C(n,r)=C(n,r-1)* (n-r+1)/r\n\nExample:\n\nFor instance, take n=5 and r=3.\n\nInput: n = 5, r = 3, p = 1000000007\nOutput: 6\nExplanation: 5C3 is 10 and 10 % 100000007 is 10.\n\n\nAs per the formula,\nC(5,3)=5!/(3!)*(2!)\nC(5,3)=10\n\nAlso,\nC(5,2)=5!/(2!)*(3!)\nC(5,2)=10\n\n\nLet's try applying the above formula.\n\nC(n,r)=C(n,r-1)* (n-r+1)/r\nC(5,3)=C(5,2)*(5-3+1)/3\nC(5,3)=C(5,2)*1\nC(5,3)=10*1"
},
{
"code": null,
"e": 33779,
"s": 33422,
"text": "The above example shows that C(n,r) can be easily calculated by calculating C(n,r-1) and multiplying the result with the term (n-r+1)/r. But this multiplication may cause integer overflow for large values of n. To tackle this situation, use modulo multiplication, and modulo division concepts in order to achieve optimizations in terms of integer overflow."
},
{
"code": null,
"e": 33837,
"s": 33779,
"text": "Let’s find out how to build Pascal Triangle for the same."
},
{
"code": null,
"e": 34037,
"s": 33837,
"text": "1D array declaration can be further optimized by just the declaration of a single variable to perform calculations. However, integer overflow demands other functions too for the final implementation."
},
{
"code": null,
"e": 34145,
"s": 34037,
"text": "The post below mentions the space and time-optimized implementation for the binary coefficient calculation."
},
{
"code": null,
"e": 34149,
"s": 34145,
"text": "C++"
},
{
"code": "// C++ program to find the nCr%p// based on optimal Dynamic// Programming implementation and// Pascal Triangle concepts#include <bits/stdc++.h>using namespace std; // Returns (a * b) % modlong long moduloMultiplication(long long a, long long b, long long mod){ // Initialize result long long res = 0; // Update a if it is more than // or equal to mod a %= mod; while (b) { // If b is odd, add a with result if (b & 1) res = (res + a) % mod; // Here we assume that doing 2*a // doesn't cause overflow a = (2 * a) % mod; b >>= 1; // b = b / 2 } return res;} // C++ function for extended Euclidean Algorithmlong long int gcdExtended(long long int a, long long int b, long long int* x, long long int* y); // Function to find modulo inverse of b. It returns// -1 when inverse doesn't existslong long int modInverse(long long int b, long long int m){ long long int x, y; // used in extended GCD algorithm long long int g = gcdExtended(b, m, &x, &y); // Return -1 if b and m are not co-prime if (g != 1) return -1; // m is added to handle negative x return (x % m + m) % m;} // C function for extended Euclidean Algorithm (used to// find modular inverse.long long int gcdExtended(long long int a, long long int b, long long int* x, long long int* y){ // Base Case if (a == 0) { *x = 0, *y = 1; return b; } // To store results of recursive call long long int x1, y1; long long int gcd = gcdExtended(b % a, a, &x1, &y1); // Update x and y using results of recursive // call *x = y1 - (b / a) * x1; *y = x1; return gcd;} // Function to compute a/b under modulo mlong long int modDivide(long long int a, long long int b, long long int m){ a = a % m; long long int inv = modInverse(b, m); if (inv == -1) // cout << \"Division not defined\"; return 0; else return (inv * a) % m;} // Function to calculate nCr % pint nCr(int n, int r, int p){ // Edge Case which is not possible if (r > n) return 0; // Optimization for the cases when r is large if (r > n - r) r = n - r; // x stores the current result at long long int x = 1; // each iteration // Initialized to 1 as nC0 is always 1. for (int i = 1; i <= r; i++) { // Formula derived for calculating result is // C(n,r-1)*(n-r+1)/r // Function calculates x*(n-i+1) % p. x = moduloMultiplication(x, (n + 1 - i), p); // Function calculates x/i % p. x = modDivide(x, i, p); } return x;} // Driver Codeint main(){ long long int n = 5, r = 3, p = 1000000007; cout << \"Value of nCr % p is \" << nCr(n, r, p); return 0;}",
"e": 37057,
"s": 34149,
"text": null
},
{
"code": null,
"e": 37080,
"s": 37057,
"text": "Value of nCr % p is 10"
},
{
"code": null,
"e": 37146,
"s": 37080,
"text": "The above code needs an extra of O(1) space for the calculations."
},
{
"code": null,
"e": 37216,
"s": 37146,
"text": "The time involved in the calculation of nCr % p is of the order O(n)."
},
{
"code": null,
"e": 37384,
"s": 37216,
"text": "This article is improved by Aryan Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 37397,
"s": 37384,
"text": "nitin mittal"
},
{
"code": null,
"e": 37402,
"s": 37397,
"text": "vt_m"
},
{
"code": null,
"e": 37420,
"s": 37402,
"text": "abhishek gupta 47"
},
{
"code": null,
"e": 37433,
"s": 37420,
"text": "aryangupta18"
},
{
"code": null,
"e": 37454,
"s": 37433,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 37463,
"s": 37454,
"text": "rkbhola5"
},
{
"code": null,
"e": 37478,
"s": 37463,
"text": "varshagumber28"
},
{
"code": null,
"e": 37499,
"s": 37478,
"text": "binomial coefficient"
},
{
"code": null,
"e": 37513,
"s": 37499,
"text": "large-numbers"
},
{
"code": null,
"e": 37532,
"s": 37513,
"text": "Modular Arithmetic"
},
{
"code": null,
"e": 37552,
"s": 37532,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 37565,
"s": 37552,
"text": "Mathematical"
},
{
"code": null,
"e": 37585,
"s": 37565,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 37598,
"s": 37585,
"text": "Mathematical"
},
{
"code": null,
"e": 37617,
"s": 37598,
"text": "Modular Arithmetic"
},
{
"code": null,
"e": 37715,
"s": 37617,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37746,
"s": 37715,
"text": "Bellman–Ford Algorithm | DP-23"
},
{
"code": null,
"e": 37779,
"s": 37746,
"text": "Floyd Warshall Algorithm | DP-16"
},
{
"code": null,
"e": 37814,
"s": 37779,
"text": "Matrix Chain Multiplication | DP-8"
},
{
"code": null,
"e": 37882,
"s": 37814,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
},
{
"code": null,
"e": 37909,
"s": 37882,
"text": "Subset Sum Problem | DP-25"
},
{
"code": null,
"e": 37969,
"s": 37909,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 37984,
"s": 37969,
"text": "C++ Data Types"
},
{
"code": null,
"e": 38027,
"s": 37984,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 38069,
"s": 38027,
"text": "Program to find GCD or HCF of two numbers"
}
] |
Matcher replaceAll(Function) method in Java with Examples - GeeksforGeeks
|
07 Sep, 2021
The replaceAll(Function) method of Matcher Class behaves as a append-and-replace method. This method replaces all instances of the pattern matched in the matcher with the function passed in the parameter.Syntax:
public String replaceAll(
Function replacerFunction)
Parameters: This method takes a parameter replacerFunction which is the function that defines the replacement of the matcher.Return Value: This method returns a String with the target String constructed by replacing the String.Exceptions: This method throws following exceptions:
NullPointerException: if the replacer function is null
ConcurrentModificationException: if it is detected that the replacer function modified this matcher’s state
Below examples illustrate the Matcher.replaceAll() method:Example 1:
Java
// Java code to illustrate replaceAll() method import java.util.regex.*; public class GFG { public static void main(String[] args) { // Get the regex to be checked String regex = "(Geeks)"; // Create a pattern from regex Pattern pattern = Pattern.compile(regex); // Get the String to be matched String stringToBeMatched = "GeeksForGeeks Geeks for For Geeks Geek"; // Create a matcher for the input String Matcher matcher = pattern.matcher(stringToBeMatched); System.out.println("Before Replacement: " + stringToBeMatched); // Get the String to be replaced String stringToBeReplaced = "Geeks"; StringBuilder builder = new StringBuilder(); // Replace every matched pattern // with the target String // using replaceAll() method System.out.println("After Replacement: " + matcher .replaceAll( x -> x.group().toUpperCase())); }}
Output:
Before Replacement: GeeksForGeeks Geeks for For Geeks Geek
After Replacement: GEEKSForGEEKS GEEKS for For GEEKS Geek
Example 2:
Java
// Java code to illustrate replaceAll() method import java.util.regex.*; public class GFG { public static void main(String[] args) { // Get the regex to be checked String regex = "(FGF)"; // Create a pattern from regex Pattern pattern = Pattern.compile(regex); // Get the String to be matched String stringToBeMatched = "GFGFGFGFGFGFGFGFGFG FGF GFG GFG FGF"; // Create a matcher for the input String Matcher matcher = pattern.matcher(stringToBeMatched); System.out.println("Before Replacement: " + stringToBeMatched); // Get the String to be replaced String stringToBeReplaced = "(GFG)"; StringBuilder builder = new StringBuilder(); // Replace every matched pattern // with the target String // using replaceAll() method System.out.println("After Replacement: " + matcher .replaceAll( x -> x.group().toLowerCase())); }}
Output:
Before Replacement: GFGFGFGFGFGFGFGFGFG FGF GFG GFG FGF
After Replacement: GfgfGfgfGfgfGfgfGFG fgf GFG GFG fgf
Reference: https://docs.oracle.com/javase/9/docs/api/java/util/regex/Matcher.html#replaceAll-java.util.function.Function-
kk9826225
Java - util package
Java-Functions
Java-Matcher
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Comparator Interface in Java with Examples
PriorityQueue in Java
How to remove an element from ArrayList in Java?
|
[
{
"code": null,
"e": 25347,
"s": 25319,
"text": "\n07 Sep, 2021"
},
{
"code": null,
"e": 25561,
"s": 25347,
"text": "The replaceAll(Function) method of Matcher Class behaves as a append-and-replace method. This method replaces all instances of the pattern matched in the matcher with the function passed in the parameter.Syntax: "
},
{
"code": null,
"e": 25622,
"s": 25561,
"text": "public String replaceAll(\n Function replacerFunction)"
},
{
"code": null,
"e": 25904,
"s": 25622,
"text": "Parameters: This method takes a parameter replacerFunction which is the function that defines the replacement of the matcher.Return Value: This method returns a String with the target String constructed by replacing the String.Exceptions: This method throws following exceptions: "
},
{
"code": null,
"e": 25959,
"s": 25904,
"text": "NullPointerException: if the replacer function is null"
},
{
"code": null,
"e": 26067,
"s": 25959,
"text": "ConcurrentModificationException: if it is detected that the replacer function modified this matcher’s state"
},
{
"code": null,
"e": 26137,
"s": 26067,
"text": "Below examples illustrate the Matcher.replaceAll() method:Example 1: "
},
{
"code": null,
"e": 26142,
"s": 26137,
"text": "Java"
},
{
"code": "// Java code to illustrate replaceAll() method import java.util.regex.*; public class GFG { public static void main(String[] args) { // Get the regex to be checked String regex = \"(Geeks)\"; // Create a pattern from regex Pattern pattern = Pattern.compile(regex); // Get the String to be matched String stringToBeMatched = \"GeeksForGeeks Geeks for For Geeks Geek\"; // Create a matcher for the input String Matcher matcher = pattern.matcher(stringToBeMatched); System.out.println(\"Before Replacement: \" + stringToBeMatched); // Get the String to be replaced String stringToBeReplaced = \"Geeks\"; StringBuilder builder = new StringBuilder(); // Replace every matched pattern // with the target String // using replaceAll() method System.out.println(\"After Replacement: \" + matcher .replaceAll( x -> x.group().toUpperCase())); }}",
"e": 27259,
"s": 26142,
"text": null
},
{
"code": null,
"e": 27269,
"s": 27259,
"text": "Output: "
},
{
"code": null,
"e": 27386,
"s": 27269,
"text": "Before Replacement: GeeksForGeeks Geeks for For Geeks Geek\nAfter Replacement: GEEKSForGEEKS GEEKS for For GEEKS Geek"
},
{
"code": null,
"e": 27398,
"s": 27386,
"text": "Example 2: "
},
{
"code": null,
"e": 27403,
"s": 27398,
"text": "Java"
},
{
"code": "// Java code to illustrate replaceAll() method import java.util.regex.*; public class GFG { public static void main(String[] args) { // Get the regex to be checked String regex = \"(FGF)\"; // Create a pattern from regex Pattern pattern = Pattern.compile(regex); // Get the String to be matched String stringToBeMatched = \"GFGFGFGFGFGFGFGFGFG FGF GFG GFG FGF\"; // Create a matcher for the input String Matcher matcher = pattern.matcher(stringToBeMatched); System.out.println(\"Before Replacement: \" + stringToBeMatched); // Get the String to be replaced String stringToBeReplaced = \"(GFG)\"; StringBuilder builder = new StringBuilder(); // Replace every matched pattern // with the target String // using replaceAll() method System.out.println(\"After Replacement: \" + matcher .replaceAll( x -> x.group().toLowerCase())); }}",
"e": 28515,
"s": 27403,
"text": null
},
{
"code": null,
"e": 28525,
"s": 28515,
"text": "Output: "
},
{
"code": null,
"e": 28636,
"s": 28525,
"text": "Before Replacement: GFGFGFGFGFGFGFGFGFG FGF GFG GFG FGF\nAfter Replacement: GfgfGfgfGfgfGfgfGFG fgf GFG GFG fgf"
},
{
"code": null,
"e": 28759,
"s": 28636,
"text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/util/regex/Matcher.html#replaceAll-java.util.function.Function- "
},
{
"code": null,
"e": 28769,
"s": 28759,
"text": "kk9826225"
},
{
"code": null,
"e": 28789,
"s": 28769,
"text": "Java - util package"
},
{
"code": null,
"e": 28804,
"s": 28789,
"text": "Java-Functions"
},
{
"code": null,
"e": 28817,
"s": 28804,
"text": "Java-Matcher"
},
{
"code": null,
"e": 28822,
"s": 28817,
"text": "Java"
},
{
"code": null,
"e": 28827,
"s": 28822,
"text": "Java"
},
{
"code": null,
"e": 28925,
"s": 28827,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28940,
"s": 28925,
"text": "Stream In Java"
},
{
"code": null,
"e": 28961,
"s": 28940,
"text": "Constructors in Java"
},
{
"code": null,
"e": 28980,
"s": 28961,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 29010,
"s": 28980,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 29056,
"s": 29010,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 29073,
"s": 29056,
"text": "Generics in Java"
},
{
"code": null,
"e": 29094,
"s": 29073,
"text": "Introduction to Java"
},
{
"code": null,
"e": 29137,
"s": 29094,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 29159,
"s": 29137,
"text": "PriorityQueue in Java"
}
] |
Python – Incremental List Extension
|
27 Dec, 2019
Sometimes, while working with Python list, we can have a problem in which we need to extend a list in a very customized way. We may have to repeat contents of list and while doing that, each time new list must add a number to original list. This incremental expansion has applications in many domains. Let’s discuss a way in which this task can be performed.
Method : Using list comprehensionThis task can be performed in a brute manner, but having a shorter implementation using list comprehension always is better. In this, we perform task in 2 steps, first we make a helper list to form a addition factor list and then cumulate the result using original list.
# Python3 code to demonstrate working of# Incremental List Extension# Using list comprehension # initializing listtest_list = [7, 8, 9] # printing original listprint("The original list is : " + str(test_list)) # Extension factorN = 4 # Addition factor M = 3 # Incremental List Extension# Using list comprehensiontemp = [1 * M**i for i in range(N)]temp[0] = 0res = list([ele + tele for tele in temp for ele in test_list]) # printing result print("List after extension and addition : " + str(res))
The original list is : [7, 8, 9]
List after extension and addition : [7, 8, 9, 10, 11, 12, 16, 17, 18, 34, 35, 36]
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Dec, 2019"
},
{
"code": null,
"e": 387,
"s": 28,
"text": "Sometimes, while working with Python list, we can have a problem in which we need to extend a list in a very customized way. We may have to repeat contents of list and while doing that, each time new list must add a number to original list. This incremental expansion has applications in many domains. Let’s discuss a way in which this task can be performed."
},
{
"code": null,
"e": 691,
"s": 387,
"text": "Method : Using list comprehensionThis task can be performed in a brute manner, but having a shorter implementation using list comprehension always is better. In this, we perform task in 2 steps, first we make a helper list to form a addition factor list and then cumulate the result using original list."
},
{
"code": "# Python3 code to demonstrate working of# Incremental List Extension# Using list comprehension # initializing listtest_list = [7, 8, 9] # printing original listprint(\"The original list is : \" + str(test_list)) # Extension factorN = 4 # Addition factor M = 3 # Incremental List Extension# Using list comprehensiontemp = [1 * M**i for i in range(N)]temp[0] = 0res = list([ele + tele for tele in temp for ele in test_list]) # printing result print(\"List after extension and addition : \" + str(res))",
"e": 1193,
"s": 691,
"text": null
},
{
"code": null,
"e": 1309,
"s": 1193,
"text": "The original list is : [7, 8, 9]\nList after extension and addition : [7, 8, 9, 10, 11, 12, 16, 17, 18, 34, 35, 36]\n"
},
{
"code": null,
"e": 1330,
"s": 1309,
"text": "Python list-programs"
},
{
"code": null,
"e": 1337,
"s": 1330,
"text": "Python"
},
{
"code": null,
"e": 1353,
"s": 1337,
"text": "Python Programs"
},
{
"code": null,
"e": 1451,
"s": 1353,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1483,
"s": 1451,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1510,
"s": 1483,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1541,
"s": 1510,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 1564,
"s": 1541,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1585,
"s": 1564,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1607,
"s": 1585,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 1646,
"s": 1607,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 1684,
"s": 1646,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 1733,
"s": 1684,
"text": "Python | Convert string dictionary to dictionary"
}
] |
Find same contacts in a list of contacts
|
28 Jun, 2022
Given a list of contacts containing the username, email and phone number in any order. Identify the same contacts (i.e., the same person having many contacts) and output the same contacts together.
Notes:
A contact can store its three fields in any order, i.e., a phone number can appear before username or username can appear before the phone number.Two contacts are the same if they have either the same username or email or phone number.
A contact can store its three fields in any order, i.e., a phone number can appear before username or username can appear before the phone number.
Two contacts are the same if they have either the same username or email or phone number.
Example:
Input: contact[] =
{ {"Gaurav", "[email protected]", "[email protected]"},
{ "Lucky", "[email protected]", "+1234567"},
{ "gaurav123", "+5412312", "[email protected]"}.
{ "gaurav1993", "+5412312", "[email protected]"}
}
Output:
0 2 3
1
contact[2] is same as contact[3] because they both have same
contact number.
contact[0] is same as contact[3] because they both have same
e-mail address.
Therefore, contact[0] and contact[2] are also same.
We strongly recommend you to minimize your browser and try this yourself first. Input is basically an array of structures. A structure contains three fields such that any field can represent any detail about a contact.
The idea is to first create a graph of contacts using given array. In the graph, there is an edge between vertex i to vertex j if they both have either same username or same email or same phone number. Once the graph is constructed, the task reduces to finding connected components in an undirected graph. We can find connected components either by doing DFS or BFS starting from every unvisited vertex. In below code, DFS is used.
Below is implementation of this idea.
C++
Python3
// A C++ program to find same contacts in a list of contacts#include<bits/stdc++.h>using namespace std; // Structure for storing contact details.struct contact{ string field1, field2, field3;}; // A utility function to fill entries in adjacency matrix// representation of graphvoid buildGraph(contact arr[], int n, int *mat[]){ // Initialize the adjacency matrix for (int i=0; i<n; i++) for (int j=0; j<n; j++) mat[i][j] = 0; // Traverse through all contacts for (int i = 0; i < n; i++) { // Add mat from i to j and vice versa, if possible. // Since length of each contact field is at max some // constant. (say 30) so body execution of this for // loop takes constant time. for (int j = i+1; j < n; j++) if (arr[i].field1 == arr[j].field1 || arr[i].field1 == arr[j].field2 || arr[i].field1 == arr[j].field3 || arr[i].field2 == arr[j].field1 || arr[i].field2 == arr[j].field2 || arr[i].field2 == arr[j].field3 || arr[i].field3 == arr[j].field1 || arr[i].field3 == arr[j].field2 || arr[i].field3 == arr[j].field3) { mat[i][j] = 1; mat[j][i] = 1; break; } }} // A recursive function to perform DFS with vertex i as sourcevoid DFSvisit(int i, int *mat[], bool visited[], vector<int>& sol, int n){ visited[i] = true; sol.push_back(i); for (int j = 0; j < n; j++) if (mat[i][j] && !visited[j]) DFSvisit(j, mat, visited, sol, n);} // Finds similar contacts in an array of contactsvoid findSameContacts(contact arr[], int n){ // vector for storing the solution vector<int> sol; // Declare 2D adjacency matrix for mats int **mat = new int*[n]; for (int i = 0; i < n; i++) mat[i] = new int[n]; // visited array to keep track of visited nodes bool visited[n]; memset(visited, 0, sizeof(visited)); // Fill adjacency matrix buildGraph(arr, n, mat); // Since, we made a graph with contacts as nodes with fields as links. // two nodes are linked if they represent the same person. // so, total number of connected components and nodes in each component // will be our answer. for (int i = 0; i < n; i++) { if (!visited[i]) { DFSvisit(i, mat, visited, sol, n); // Add delimiter to separate nodes of one component from other. sol.push_back(-1); } } // Print the solution for (int i = 0; i < sol.size(); i++) if (sol[i] == -1) cout << endl; else cout << sol[i] << " ";} // Drive Codeint main(){ contact arr[] = {{"Gaurav", "[email protected]", "[email protected]"}, {"Lucky", "[email protected]", "+1234567"}, {"gaurav123", "+5412312", "[email protected]"}, {"gaurav1993", "+5412312", "[email protected]"}, {"raja", "+2231210", "[email protected]"}, {"bahubali", "+878312", "raja"} }; int n = sizeof arr / sizeof arr[0]; findSameContacts(arr, n); return 0;}
# A Python3 program to find same contacts# in a list of contacts # Structure for storing contact details.class contact: def __init__(self, field1, field2, field3): self.field1 = field1 self.field2 = field2 self.field3 = field3 # A utility function to fill entries in# adjacency matrix representation of graphdef buildGraph(arr, n, mat): # Initialize the adjacency matrix for i in range(n): for j in range(n): mat[i][j] = 0 # Traverse through all contacts for i in range(n): # Add mat from i to j and vice versa, # if possible. Since length of each # contact field is at max some constant. # (say 30) so body execution of this for # loop takes constant time. for j in range(i + 1, n): if (arr[i].field1 == arr[j].field1 or arr[i].field1 == arr[j].field2 or arr[i].field1 == arr[j].field3 or arr[i].field2 == arr[j].field1 or arr[i].field2 == arr[j].field2 or arr[i].field2 == arr[j].field3 or arr[i].field3 == arr[j].field1 or arr[i].field3 == arr[j].field2 or arr[i].field3 == arr[j].field3): mat[i][j] = 1 mat[j][i] = 1 break # A recursive function to perform DFS# with vertex i as sourcedef DFSvisit(i, mat, visited, sol, n): visited[i] = True sol.append(i) for j in range(n): if (mat[i][j] and not visited[j]): DFSvisit(j, mat, visited, sol, n) # Finds similar contacts in an# array of contactsdef findSameContacts(arr, n): # vector for storing the solution sol = [] # Declare 2D adjacency matrix for mats mat = [[None] * n for i in range(n)] # visited array to keep track # of visited nodes visited = [0] * n # Fill adjacency matrix buildGraph(arr, n, mat) # Since, we made a graph with contacts # as nodes with fields as links. Two # nodes are linked if they represent # the same person. So, total number of # connected components and nodes in each # component will be our answer. for i in range(n): if (not visited[i]): DFSvisit(i, mat, visited, sol, n) # Add delimiter to separate nodes # of one component from other. sol.append(-1) # Print the solution for i in range(len(sol)): if (sol[i] == -1): print() else: print(sol[i], end = " ") # Driver Codeif __name__ == '__main__': arr = [contact("Gaurav", "[email protected]", "[email protected]"), contact("Lucky", "[email protected]", "+1234567"), contact("gaurav123", "+5412312", "[email protected]"), contact("gaurav1993", "+5412312", "[email protected]"), contact("raja", "+2231210", "[email protected]"), contact("bahubali", "+878312", "raja")] n = len(arr) findSameContacts(arr, n) # This code is contributed by PranchalK
0 3 2
1
4 5
Time complexity: O(n2) where n is number of contacts.
Another Approach: (Using Union Find)
The problem can be solved with Union Find as well. Here, we unify all the people who have at least one common contact. We need to isolate all the indices which have common contacts. To achieve this, we can maintain an array of the map of indices for each contact and unify all the indices corresponding to them. After the Union Find, we get Disjoint Sets which are distinct people.
C++14
// CPP14 program to find common contacts.#include <bits/stdc++.h>using namespace std; // The class DSU will implement the Union Findclass DSU { vector<int> parent, size; public: // In the constructor, we assign the each index as its // own parent and size as the number of contacts // available for that index DSU(vector<vector<string> >& contacts) { for (int i = 0; i < contacts.size(); i++) { parent.push_back(i); size.push_back(contacts[i].size()); } } // Finds the set in which the element belongs. Path // compression is used to optimise time complexity int findSet(int v) { if (v == parent[v]) return v; return parent[v] = findSet(parent[v]); } // Unifies the sets a and b where, the element belonging // to the smaller set is merged to the one belonging to // the smaller set void unionSet(int a, int b, vector<string>& person1, vector<string>& person2) { if (size[a] > size[b]) { parent[b] = a; size[a] += size[b]; for (auto contact : person2) person1.push_back(contact); } else { parent[a] = b; size[b] += size[a]; for (auto contact : person1) person2.push_back(contact); } }}; // Driver Codeint main(){ vector<vector<string> > contacts = { { "Gaurav", "[email protected]", "[email protected]" }, { "Lucky", "[email protected]", "+1234567" }, { "gaurav123", "+5412312", "[email protected]" }, { "gaurav1993", "+5412312", "[email protected]" }, { "raja", "+2231210", "[email protected]" }, { "bahubali", "+878312", "raja" } }; // Initializing the object of DSU class DSU dsu(contacts); // Will contain the mapping of a contact to all the // indices it is present within unordered_map<string, vector<int> > contactToIndex; for (int index = 0; index < contacts.size(); index++) { for (auto contact : contacts[index]) contactToIndex[contact].push_back(index); } // Unifies the sets of each contact if they are not // present in the same set for (auto contact : contactToIndex) { vector<int> indices = contact.second; for (int i = 0; i < indices.size() - 1; i++) { int set1 = dsu.findSet(indices[i]), set2 = dsu.findSet(indices[i + 1]); if (set1 != set2) dsu.unionSet(set1, set2, contacts[set1], contacts[set2]); } } // Contains a map of all the distinct sets available // after union find has been completed unordered_map<int, vector<int> > unifiedSet; // All parents are mapped to the elements in the set for (int i = 0; i < contacts.size(); i++) { unifiedSet[dsu.findSet(i)].push_back(i); } // Printing out elements from distinct sets for (auto eachSet : unifiedSet) { for (auto element : eachSet.second) cout << element << " "; cout << endl; } return 0;}
4 5
0 2 3
1
Time Complexity: O(N * α(N)) where N is the number of contacts and α is the Inverse Ackermann FunctionSpace Complexity: O(N)
PranchalKatiyar
nidhi_biet
veedee
simmytarika5
anikakapoor
sagartomar9927
anikaseth98
saurabh1990aror
surindertarika1234
hardikkoriintern
BFS
DFS
Graph
DFS
Graph
BFS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Find if there is a path between two vertices in a directed graph
Introduction to Data Structures
Find if there is a path between two vertices in an undirected graph
What is Data Structure: Types, Classifications and Applications
Top 50 Graph Coding Problems for Interviews
K Centers Problem | Set 1 (Greedy Approximate Algorithm)
Bridges in a graph
Real-time application of Data Structures
Longest Path in a Directed Acyclic Graph
Water Jug problem using BFS
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n28 Jun, 2022"
},
{
"code": null,
"e": 253,
"s": 54,
"text": "Given a list of contacts containing the username, email and phone number in any order. Identify the same contacts (i.e., the same person having many contacts) and output the same contacts together. "
},
{
"code": null,
"e": 261,
"s": 253,
"text": "Notes: "
},
{
"code": null,
"e": 498,
"s": 261,
"text": "A contact can store its three fields in any order, i.e., a phone number can appear before username or username can appear before the phone number.Two contacts are the same if they have either the same username or email or phone number. "
},
{
"code": null,
"e": 645,
"s": 498,
"text": "A contact can store its three fields in any order, i.e., a phone number can appear before username or username can appear before the phone number."
},
{
"code": null,
"e": 736,
"s": 645,
"text": "Two contacts are the same if they have either the same username or email or phone number. "
},
{
"code": null,
"e": 746,
"s": 736,
"text": "Example: "
},
{
"code": null,
"e": 1224,
"s": 746,
"text": "Input: contact[] = \n { {\"Gaurav\", \"[email protected]\", \"[email protected]\"},\n { \"Lucky\", \"[email protected]\", \"+1234567\"},\n { \"gaurav123\", \"+5412312\", \"[email protected]\"}.\n { \"gaurav1993\", \"+5412312\", \"[email protected]\"}\n }\nOutput:\n 0 2 3\n 1 \ncontact[2] is same as contact[3] because they both have same\ncontact number.\ncontact[0] is same as contact[3] because they both have same\ne-mail address.\nTherefore, contact[0] and contact[2] are also same."
},
{
"code": null,
"e": 1443,
"s": 1224,
"text": "We strongly recommend you to minimize your browser and try this yourself first. Input is basically an array of structures. A structure contains three fields such that any field can represent any detail about a contact."
},
{
"code": null,
"e": 1875,
"s": 1443,
"text": "The idea is to first create a graph of contacts using given array. In the graph, there is an edge between vertex i to vertex j if they both have either same username or same email or same phone number. Once the graph is constructed, the task reduces to finding connected components in an undirected graph. We can find connected components either by doing DFS or BFS starting from every unvisited vertex. In below code, DFS is used."
},
{
"code": null,
"e": 1915,
"s": 1875,
"text": "Below is implementation of this idea. "
},
{
"code": null,
"e": 1919,
"s": 1915,
"text": "C++"
},
{
"code": null,
"e": 1927,
"s": 1919,
"text": "Python3"
},
{
"code": "// A C++ program to find same contacts in a list of contacts#include<bits/stdc++.h>using namespace std; // Structure for storing contact details.struct contact{ string field1, field2, field3;}; // A utility function to fill entries in adjacency matrix// representation of graphvoid buildGraph(contact arr[], int n, int *mat[]){ // Initialize the adjacency matrix for (int i=0; i<n; i++) for (int j=0; j<n; j++) mat[i][j] = 0; // Traverse through all contacts for (int i = 0; i < n; i++) { // Add mat from i to j and vice versa, if possible. // Since length of each contact field is at max some // constant. (say 30) so body execution of this for // loop takes constant time. for (int j = i+1; j < n; j++) if (arr[i].field1 == arr[j].field1 || arr[i].field1 == arr[j].field2 || arr[i].field1 == arr[j].field3 || arr[i].field2 == arr[j].field1 || arr[i].field2 == arr[j].field2 || arr[i].field2 == arr[j].field3 || arr[i].field3 == arr[j].field1 || arr[i].field3 == arr[j].field2 || arr[i].field3 == arr[j].field3) { mat[i][j] = 1; mat[j][i] = 1; break; } }} // A recursive function to perform DFS with vertex i as sourcevoid DFSvisit(int i, int *mat[], bool visited[], vector<int>& sol, int n){ visited[i] = true; sol.push_back(i); for (int j = 0; j < n; j++) if (mat[i][j] && !visited[j]) DFSvisit(j, mat, visited, sol, n);} // Finds similar contacts in an array of contactsvoid findSameContacts(contact arr[], int n){ // vector for storing the solution vector<int> sol; // Declare 2D adjacency matrix for mats int **mat = new int*[n]; for (int i = 0; i < n; i++) mat[i] = new int[n]; // visited array to keep track of visited nodes bool visited[n]; memset(visited, 0, sizeof(visited)); // Fill adjacency matrix buildGraph(arr, n, mat); // Since, we made a graph with contacts as nodes with fields as links. // two nodes are linked if they represent the same person. // so, total number of connected components and nodes in each component // will be our answer. for (int i = 0; i < n; i++) { if (!visited[i]) { DFSvisit(i, mat, visited, sol, n); // Add delimiter to separate nodes of one component from other. sol.push_back(-1); } } // Print the solution for (int i = 0; i < sol.size(); i++) if (sol[i] == -1) cout << endl; else cout << sol[i] << \" \";} // Drive Codeint main(){ contact arr[] = {{\"Gaurav\", \"[email protected]\", \"[email protected]\"}, {\"Lucky\", \"[email protected]\", \"+1234567\"}, {\"gaurav123\", \"+5412312\", \"[email protected]\"}, {\"gaurav1993\", \"+5412312\", \"[email protected]\"}, {\"raja\", \"+2231210\", \"[email protected]\"}, {\"bahubali\", \"+878312\", \"raja\"} }; int n = sizeof arr / sizeof arr[0]; findSameContacts(arr, n); return 0;}",
"e": 5128,
"s": 1927,
"text": null
},
{
"code": "# A Python3 program to find same contacts# in a list of contacts # Structure for storing contact details.class contact: def __init__(self, field1, field2, field3): self.field1 = field1 self.field2 = field2 self.field3 = field3 # A utility function to fill entries in# adjacency matrix representation of graphdef buildGraph(arr, n, mat): # Initialize the adjacency matrix for i in range(n): for j in range(n): mat[i][j] = 0 # Traverse through all contacts for i in range(n): # Add mat from i to j and vice versa, # if possible. Since length of each # contact field is at max some constant. # (say 30) so body execution of this for # loop takes constant time. for j in range(i + 1, n): if (arr[i].field1 == arr[j].field1 or arr[i].field1 == arr[j].field2 or arr[i].field1 == arr[j].field3 or arr[i].field2 == arr[j].field1 or arr[i].field2 == arr[j].field2 or arr[i].field2 == arr[j].field3 or arr[i].field3 == arr[j].field1 or arr[i].field3 == arr[j].field2 or arr[i].field3 == arr[j].field3): mat[i][j] = 1 mat[j][i] = 1 break # A recursive function to perform DFS# with vertex i as sourcedef DFSvisit(i, mat, visited, sol, n): visited[i] = True sol.append(i) for j in range(n): if (mat[i][j] and not visited[j]): DFSvisit(j, mat, visited, sol, n) # Finds similar contacts in an# array of contactsdef findSameContacts(arr, n): # vector for storing the solution sol = [] # Declare 2D adjacency matrix for mats mat = [[None] * n for i in range(n)] # visited array to keep track # of visited nodes visited = [0] * n # Fill adjacency matrix buildGraph(arr, n, mat) # Since, we made a graph with contacts # as nodes with fields as links. Two # nodes are linked if they represent # the same person. So, total number of # connected components and nodes in each # component will be our answer. for i in range(n): if (not visited[i]): DFSvisit(i, mat, visited, sol, n) # Add delimiter to separate nodes # of one component from other. sol.append(-1) # Print the solution for i in range(len(sol)): if (sol[i] == -1): print() else: print(sol[i], end = \" \") # Driver Codeif __name__ == '__main__': arr = [contact(\"Gaurav\", \"[email protected]\", \"[email protected]\"), contact(\"Lucky\", \"[email protected]\", \"+1234567\"), contact(\"gaurav123\", \"+5412312\", \"[email protected]\"), contact(\"gaurav1993\", \"+5412312\", \"[email protected]\"), contact(\"raja\", \"+2231210\", \"[email protected]\"), contact(\"bahubali\", \"+878312\", \"raja\")] n = len(arr) findSameContacts(arr, n) # This code is contributed by PranchalK",
"e": 8145,
"s": 5128,
"text": null
},
{
"code": null,
"e": 8161,
"s": 8145,
"text": "0 3 2 \n1 \n4 5 \n"
},
{
"code": null,
"e": 8215,
"s": 8161,
"text": "Time complexity: O(n2) where n is number of contacts."
},
{
"code": null,
"e": 8253,
"s": 8215,
"text": "Another Approach: (Using Union Find) "
},
{
"code": null,
"e": 8635,
"s": 8253,
"text": "The problem can be solved with Union Find as well. Here, we unify all the people who have at least one common contact. We need to isolate all the indices which have common contacts. To achieve this, we can maintain an array of the map of indices for each contact and unify all the indices corresponding to them. After the Union Find, we get Disjoint Sets which are distinct people."
},
{
"code": null,
"e": 8641,
"s": 8635,
"text": "C++14"
},
{
"code": "// CPP14 program to find common contacts.#include <bits/stdc++.h>using namespace std; // The class DSU will implement the Union Findclass DSU { vector<int> parent, size; public: // In the constructor, we assign the each index as its // own parent and size as the number of contacts // available for that index DSU(vector<vector<string> >& contacts) { for (int i = 0; i < contacts.size(); i++) { parent.push_back(i); size.push_back(contacts[i].size()); } } // Finds the set in which the element belongs. Path // compression is used to optimise time complexity int findSet(int v) { if (v == parent[v]) return v; return parent[v] = findSet(parent[v]); } // Unifies the sets a and b where, the element belonging // to the smaller set is merged to the one belonging to // the smaller set void unionSet(int a, int b, vector<string>& person1, vector<string>& person2) { if (size[a] > size[b]) { parent[b] = a; size[a] += size[b]; for (auto contact : person2) person1.push_back(contact); } else { parent[a] = b; size[b] += size[a]; for (auto contact : person1) person2.push_back(contact); } }}; // Driver Codeint main(){ vector<vector<string> > contacts = { { \"Gaurav\", \"[email protected]\", \"[email protected]\" }, { \"Lucky\", \"[email protected]\", \"+1234567\" }, { \"gaurav123\", \"+5412312\", \"[email protected]\" }, { \"gaurav1993\", \"+5412312\", \"[email protected]\" }, { \"raja\", \"+2231210\", \"[email protected]\" }, { \"bahubali\", \"+878312\", \"raja\" } }; // Initializing the object of DSU class DSU dsu(contacts); // Will contain the mapping of a contact to all the // indices it is present within unordered_map<string, vector<int> > contactToIndex; for (int index = 0; index < contacts.size(); index++) { for (auto contact : contacts[index]) contactToIndex[contact].push_back(index); } // Unifies the sets of each contact if they are not // present in the same set for (auto contact : contactToIndex) { vector<int> indices = contact.second; for (int i = 0; i < indices.size() - 1; i++) { int set1 = dsu.findSet(indices[i]), set2 = dsu.findSet(indices[i + 1]); if (set1 != set2) dsu.unionSet(set1, set2, contacts[set1], contacts[set2]); } } // Contains a map of all the distinct sets available // after union find has been completed unordered_map<int, vector<int> > unifiedSet; // All parents are mapped to the elements in the set for (int i = 0; i < contacts.size(); i++) { unifiedSet[dsu.findSet(i)].push_back(i); } // Printing out elements from distinct sets for (auto eachSet : unifiedSet) { for (auto element : eachSet.second) cout << element << \" \"; cout << endl; } return 0;}",
"e": 11749,
"s": 8641,
"text": null
},
{
"code": null,
"e": 11765,
"s": 11749,
"text": "4 5 \n0 2 3 \n1 \n"
},
{
"code": null,
"e": 11890,
"s": 11765,
"text": "Time Complexity: O(N * α(N)) where N is the number of contacts and α is the Inverse Ackermann FunctionSpace Complexity: O(N)"
},
{
"code": null,
"e": 11906,
"s": 11890,
"text": "PranchalKatiyar"
},
{
"code": null,
"e": 11917,
"s": 11906,
"text": "nidhi_biet"
},
{
"code": null,
"e": 11924,
"s": 11917,
"text": "veedee"
},
{
"code": null,
"e": 11937,
"s": 11924,
"text": "simmytarika5"
},
{
"code": null,
"e": 11949,
"s": 11937,
"text": "anikakapoor"
},
{
"code": null,
"e": 11964,
"s": 11949,
"text": "sagartomar9927"
},
{
"code": null,
"e": 11976,
"s": 11964,
"text": "anikaseth98"
},
{
"code": null,
"e": 11992,
"s": 11976,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 12011,
"s": 11992,
"text": "surindertarika1234"
},
{
"code": null,
"e": 12028,
"s": 12011,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 12032,
"s": 12028,
"text": "BFS"
},
{
"code": null,
"e": 12036,
"s": 12032,
"text": "DFS"
},
{
"code": null,
"e": 12042,
"s": 12036,
"text": "Graph"
},
{
"code": null,
"e": 12046,
"s": 12042,
"text": "DFS"
},
{
"code": null,
"e": 12052,
"s": 12046,
"text": "Graph"
},
{
"code": null,
"e": 12056,
"s": 12052,
"text": "BFS"
},
{
"code": null,
"e": 12154,
"s": 12056,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 12219,
"s": 12154,
"text": "Find if there is a path between two vertices in a directed graph"
},
{
"code": null,
"e": 12251,
"s": 12219,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 12319,
"s": 12251,
"text": "Find if there is a path between two vertices in an undirected graph"
},
{
"code": null,
"e": 12383,
"s": 12319,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 12427,
"s": 12383,
"text": "Top 50 Graph Coding Problems for Interviews"
},
{
"code": null,
"e": 12484,
"s": 12427,
"text": "K Centers Problem | Set 1 (Greedy Approximate Algorithm)"
},
{
"code": null,
"e": 12503,
"s": 12484,
"text": "Bridges in a graph"
},
{
"code": null,
"e": 12544,
"s": 12503,
"text": "Real-time application of Data Structures"
},
{
"code": null,
"e": 12585,
"s": 12544,
"text": "Longest Path in a Directed Acyclic Graph"
}
] |
How to create Popup box in ReactJS ?
|
08 Nov, 2021
In this article, we are going to learn how we can create Popup in ReactJs. A pop-up is a graphical user interface display area, usually a small window, that suddenly appears in the foreground of the visual interface.
React is a free and open-source front-end JavaScript library for building user interfaces or UI components. It is maintained by Facebook and a community of individual developers and companies.
Approach: To create our Popup we are going to use the reactjs-popup package because it is powerful, lightweight, and fully customizable. After that, we will add our popup on our homepage with a button to trigger the popup using the installed package.
Create ReactJs Application: You can create a new ReactJs project using the below command:
npx create-react-app gfg
Install the required package: Now we will install the reactjs-popup package using the below command:
npm i reactjs-popup
Project Structure: It will look like this.
Adding Popup: In this example, we are going to add the popup on the homepage of our app using the package that we installed. For this, add the below content in the App.js file.
Javascript
import React from 'react';import Popup from 'reactjs-popup';import 'reactjs-popup/dist/index.css'; export default function PopupGfg(){ return( <div> <h4>Popup - GeeksforGeeks</h4> <Popup trigger={<button> Click to open popup </button>} position="right center"> <div>GeeksforGeeks</div> <button>Click here</button> </Popup> </div> )};
Explanation: In the above example first, we are importing the Popup component from the react-popup package. After that, we are using our Popup component to add a popup with a button to trigger the popup.
Steps to run the application: Run the below command in the terminal to run the app.
npm start
Output:
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Axios in React: A Guide for Beginners
ReactJS useNavigate() Hook
How to install bootstrap in React.js ?
How to create a multi-page website using React.js ?
How to do crud operations in ReactJS ?
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?
Differences between Functional Components and Class Components in React
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Nov, 2021"
},
{
"code": null,
"e": 245,
"s": 28,
"text": "In this article, we are going to learn how we can create Popup in ReactJs. A pop-up is a graphical user interface display area, usually a small window, that suddenly appears in the foreground of the visual interface."
},
{
"code": null,
"e": 438,
"s": 245,
"text": "React is a free and open-source front-end JavaScript library for building user interfaces or UI components. It is maintained by Facebook and a community of individual developers and companies."
},
{
"code": null,
"e": 689,
"s": 438,
"text": "Approach: To create our Popup we are going to use the reactjs-popup package because it is powerful, lightweight, and fully customizable. After that, we will add our popup on our homepage with a button to trigger the popup using the installed package."
},
{
"code": null,
"e": 779,
"s": 689,
"text": "Create ReactJs Application: You can create a new ReactJs project using the below command:"
},
{
"code": null,
"e": 804,
"s": 779,
"text": "npx create-react-app gfg"
},
{
"code": null,
"e": 905,
"s": 804,
"text": "Install the required package: Now we will install the reactjs-popup package using the below command:"
},
{
"code": null,
"e": 925,
"s": 905,
"text": "npm i reactjs-popup"
},
{
"code": null,
"e": 968,
"s": 925,
"text": "Project Structure: It will look like this."
},
{
"code": null,
"e": 1145,
"s": 968,
"text": "Adding Popup: In this example, we are going to add the popup on the homepage of our app using the package that we installed. For this, add the below content in the App.js file."
},
{
"code": null,
"e": 1156,
"s": 1145,
"text": "Javascript"
},
{
"code": "import React from 'react';import Popup from 'reactjs-popup';import 'reactjs-popup/dist/index.css'; export default function PopupGfg(){ return( <div> <h4>Popup - GeeksforGeeks</h4> <Popup trigger={<button> Click to open popup </button>} position=\"right center\"> <div>GeeksforGeeks</div> <button>Click here</button> </Popup> </div> )};",
"e": 1519,
"s": 1156,
"text": null
},
{
"code": null,
"e": 1723,
"s": 1519,
"text": "Explanation: In the above example first, we are importing the Popup component from the react-popup package. After that, we are using our Popup component to add a popup with a button to trigger the popup."
},
{
"code": null,
"e": 1807,
"s": 1723,
"text": "Steps to run the application: Run the below command in the terminal to run the app."
},
{
"code": null,
"e": 1817,
"s": 1807,
"text": "npm start"
},
{
"code": null,
"e": 1825,
"s": 1817,
"text": "Output:"
},
{
"code": null,
"e": 1841,
"s": 1825,
"text": "React-Questions"
},
{
"code": null,
"e": 1849,
"s": 1841,
"text": "ReactJS"
},
{
"code": null,
"e": 1866,
"s": 1849,
"text": "Web Technologies"
},
{
"code": null,
"e": 1964,
"s": 1866,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2002,
"s": 1964,
"text": "Axios in React: A Guide for Beginners"
},
{
"code": null,
"e": 2029,
"s": 2002,
"text": "ReactJS useNavigate() Hook"
},
{
"code": null,
"e": 2068,
"s": 2029,
"text": "How to install bootstrap in React.js ?"
},
{
"code": null,
"e": 2120,
"s": 2068,
"text": "How to create a multi-page website using React.js ?"
},
{
"code": null,
"e": 2159,
"s": 2120,
"text": "How to do crud operations in ReactJS ?"
},
{
"code": null,
"e": 2192,
"s": 2159,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2254,
"s": 2192,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2315,
"s": 2254,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2365,
"s": 2315,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
HTTP headers | Last-Modified
|
06 Nov, 2019
The last modified response header is a header sent by the server specifying the date of the last modification of the requested source. This is the formal definition of Last-Modified of HTTP headers, let’s break it down.
Suppose you have created a website and set the last-modified header. When a user browses your website, the user’s browser temporarily stores (caches) some information like HTML, images, style-sheets and even some infrequently changing dynamic content. All browsers always cache the resources by default, so no special header response is required.Now the user likes your website and visits it again! This time you are even better than before. The server will check whether you have updated the website since the user’s last visit. If there is no change, the server sends a “304 not modified” reply to the browser, and the information loads from the local cache.
The last-modified header is a response header used with a request header called “If modified” header. The If-modified header sends a request to the server to know when the resource was last modified. The last-modified header tells the browser when the resource was last modified, and whether it should use the cached copy or download the newer version of the website. These are cache-control headers.
Syntax:
Last-Modified: <day-name>, <day> <month> <year> <hour>:<minute>:<second> GMT
Note: The Last-modified header looks like this: Last-Modified: Tue, 15 Oct 2019 12:45:26 GMT
Directives:
<day-name>: It contains the days name like “Mon”, “Tue” etc. (case-sensitive).
<day>: It contains the date in 2 digit number, like “04” or “23” for days.
<month>: It contains the name of the month, in 3 letter month names like “Jan”, “Feb” etc.(case-sensitive).
<year>: In contains the 4 digit year like “2009”
<hour>: It contains the hour in 2 digit hour like “07” or “12”.
<minute>: Same as hour minutes 2 digit minute like “09” or “55”
<second>: Containing the seconds in 2 digit second like “08” or “50”.
GMT: All the dates in HTTP will show in Greenwich Mean Time format not in local time format.
Example:
Last-Modified: Tue, 15 Oct 2019 12:45:26 GMT
Advantages:
This reduces bandwidth usage and improves the speed of your website.
Reduces load on the server.
To check the Last-Modified in action go to Inspect Element -> Network check the request header for Last-Modified like below, Last-Modified is highlighted.
Supported Browsers: The browsers supported by HTTP headers Last-Modified are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
HTTP-headers
Picked
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
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 ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
REST API (Introduction)
Node.js fs.readFileSync() Method
How to set the default value for an HTML <select> element ?
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n06 Nov, 2019"
},
{
"code": null,
"e": 273,
"s": 53,
"text": "The last modified response header is a header sent by the server specifying the date of the last modification of the requested source. This is the formal definition of Last-Modified of HTTP headers, let’s break it down."
},
{
"code": null,
"e": 934,
"s": 273,
"text": "Suppose you have created a website and set the last-modified header. When a user browses your website, the user’s browser temporarily stores (caches) some information like HTML, images, style-sheets and even some infrequently changing dynamic content. All browsers always cache the resources by default, so no special header response is required.Now the user likes your website and visits it again! This time you are even better than before. The server will check whether you have updated the website since the user’s last visit. If there is no change, the server sends a “304 not modified” reply to the browser, and the information loads from the local cache."
},
{
"code": null,
"e": 1335,
"s": 934,
"text": "The last-modified header is a response header used with a request header called “If modified” header. The If-modified header sends a request to the server to know when the resource was last modified. The last-modified header tells the browser when the resource was last modified, and whether it should use the cached copy or download the newer version of the website. These are cache-control headers."
},
{
"code": null,
"e": 1343,
"s": 1335,
"text": "Syntax:"
},
{
"code": null,
"e": 1420,
"s": 1343,
"text": "Last-Modified: <day-name>, <day> <month> <year> <hour>:<minute>:<second> GMT"
},
{
"code": null,
"e": 1513,
"s": 1420,
"text": "Note: The Last-modified header looks like this: Last-Modified: Tue, 15 Oct 2019 12:45:26 GMT"
},
{
"code": null,
"e": 1525,
"s": 1513,
"text": "Directives:"
},
{
"code": null,
"e": 1604,
"s": 1525,
"text": "<day-name>: It contains the days name like “Mon”, “Tue” etc. (case-sensitive)."
},
{
"code": null,
"e": 1679,
"s": 1604,
"text": "<day>: It contains the date in 2 digit number, like “04” or “23” for days."
},
{
"code": null,
"e": 1787,
"s": 1679,
"text": "<month>: It contains the name of the month, in 3 letter month names like “Jan”, “Feb” etc.(case-sensitive)."
},
{
"code": null,
"e": 1836,
"s": 1787,
"text": "<year>: In contains the 4 digit year like “2009”"
},
{
"code": null,
"e": 1900,
"s": 1836,
"text": "<hour>: It contains the hour in 2 digit hour like “07” or “12”."
},
{
"code": null,
"e": 1964,
"s": 1900,
"text": "<minute>: Same as hour minutes 2 digit minute like “09” or “55”"
},
{
"code": null,
"e": 2034,
"s": 1964,
"text": "<second>: Containing the seconds in 2 digit second like “08” or “50”."
},
{
"code": null,
"e": 2127,
"s": 2034,
"text": "GMT: All the dates in HTTP will show in Greenwich Mean Time format not in local time format."
},
{
"code": null,
"e": 2136,
"s": 2127,
"text": "Example:"
},
{
"code": null,
"e": 2181,
"s": 2136,
"text": "Last-Modified: Tue, 15 Oct 2019 12:45:26 GMT"
},
{
"code": null,
"e": 2193,
"s": 2181,
"text": "Advantages:"
},
{
"code": null,
"e": 2262,
"s": 2193,
"text": "This reduces bandwidth usage and improves the speed of your website."
},
{
"code": null,
"e": 2290,
"s": 2262,
"text": "Reduces load on the server."
},
{
"code": null,
"e": 2445,
"s": 2290,
"text": "To check the Last-Modified in action go to Inspect Element -> Network check the request header for Last-Modified like below, Last-Modified is highlighted."
},
{
"code": null,
"e": 2536,
"s": 2445,
"text": "Supported Browsers: The browsers supported by HTTP headers Last-Modified are listed below:"
},
{
"code": null,
"e": 2550,
"s": 2536,
"text": "Google Chrome"
},
{
"code": null,
"e": 2568,
"s": 2550,
"text": "Internet Explorer"
},
{
"code": null,
"e": 2576,
"s": 2568,
"text": "Firefox"
},
{
"code": null,
"e": 2583,
"s": 2576,
"text": "Safari"
},
{
"code": null,
"e": 2589,
"s": 2583,
"text": "Opera"
},
{
"code": null,
"e": 2602,
"s": 2589,
"text": "HTTP-headers"
},
{
"code": null,
"e": 2609,
"s": 2602,
"text": "Picked"
},
{
"code": null,
"e": 2628,
"s": 2609,
"text": "Technical Scripter"
},
{
"code": null,
"e": 2645,
"s": 2628,
"text": "Web Technologies"
},
{
"code": null,
"e": 2743,
"s": 2645,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2776,
"s": 2743,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2838,
"s": 2776,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2899,
"s": 2838,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2949,
"s": 2899,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 2992,
"s": 2949,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 3064,
"s": 2992,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 3104,
"s": 3064,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 3128,
"s": 3104,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 3161,
"s": 3128,
"text": "Node.js fs.readFileSync() Method"
}
] |
Python Mongodb – Delete_one()
|
04 Jul, 2022
Mongodb is a very popular cross-platform document-oriented, NoSQL(stands for “not only SQL”) database program, written in C++. It stores data in JSON format(as key-value pairs), which makes it easy to use. MongoDB can run over multiple servers, balancing the load to keep the system up and run in case of hardware failure.
Step 1 – Establishing Connection: Port number Default: 27017
conn = MongoClient(‘localhost’, port-number)
If using default port-number i.e. 27017. Alternate connection method:
conn = MongoClient()
Step 2 – Create Database or Switch to Existing Database:
db = conn.dabasename
Create a collection or Switch to an existing collection:
collection = db.collection_name
In MongoDB, a single document can be deleted by the method delete_one(). The first parameter of the method would be a query object which defines the document to be deleted. If there are multiple documents matching the filter query, only the first appeared document would be deleted.
Note: Deleting a document is the same as deleting a record in the case of SQL.
Consider the sample database:
Examples:
Python
# Python program to demonstrate# delete_one import pymongo # creating Mongoclient object to# create database with the specified# connection URLstudents = pymongo.MongoClient('localhost', 27017) # connecting to a database with# name GFGDb = students["GFG"] # connecting to a collection with# name Geekscoll = Db["Geeks"] # creating query objectmyQuery ={'Class':'2'}coll.delete_one(myQuery) # print collection after deletion:for x in coll.find(): print(x)
Output :
'_id': 2.0, 'Name': 'Golu', 'Class': '3'}
{'_id': 3.0, 'Name': 'Raja', 'Class': '4'}
{'_id': 4.0, 'Name': 'Moni', 'Class': '5'}
MongoDB Shell:
surinderdawra388
gabaa406
khushb99
Python-mongoDB
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n04 Jul, 2022"
},
{
"code": null,
"e": 351,
"s": 28,
"text": "Mongodb is a very popular cross-platform document-oriented, NoSQL(stands for “not only SQL”) database program, written in C++. It stores data in JSON format(as key-value pairs), which makes it easy to use. MongoDB can run over multiple servers, balancing the load to keep the system up and run in case of hardware failure."
},
{
"code": null,
"e": 414,
"s": 351,
"text": "Step 1 – Establishing Connection: Port number Default: 27017 "
},
{
"code": null,
"e": 459,
"s": 414,
"text": "conn = MongoClient(‘localhost’, port-number)"
},
{
"code": null,
"e": 530,
"s": 459,
"text": "If using default port-number i.e. 27017. Alternate connection method: "
},
{
"code": null,
"e": 551,
"s": 530,
"text": "conn = MongoClient()"
},
{
"code": null,
"e": 610,
"s": 551,
"text": "Step 2 – Create Database or Switch to Existing Database: "
},
{
"code": null,
"e": 631,
"s": 610,
"text": "db = conn.dabasename"
},
{
"code": null,
"e": 689,
"s": 631,
"text": "Create a collection or Switch to an existing collection: "
},
{
"code": null,
"e": 721,
"s": 689,
"text": "collection = db.collection_name"
},
{
"code": null,
"e": 1005,
"s": 721,
"text": "In MongoDB, a single document can be deleted by the method delete_one(). The first parameter of the method would be a query object which defines the document to be deleted. If there are multiple documents matching the filter query, only the first appeared document would be deleted. "
},
{
"code": null,
"e": 1084,
"s": 1005,
"text": "Note: Deleting a document is the same as deleting a record in the case of SQL."
},
{
"code": null,
"e": 1115,
"s": 1084,
"text": "Consider the sample database: "
},
{
"code": null,
"e": 1127,
"s": 1115,
"text": "Examples: "
},
{
"code": null,
"e": 1134,
"s": 1127,
"text": "Python"
},
{
"code": "# Python program to demonstrate# delete_one import pymongo # creating Mongoclient object to# create database with the specified# connection URLstudents = pymongo.MongoClient('localhost', 27017) # connecting to a database with# name GFGDb = students[\"GFG\"] # connecting to a collection with# name Geekscoll = Db[\"Geeks\"] # creating query objectmyQuery ={'Class':'2'}coll.delete_one(myQuery) # print collection after deletion:for x in coll.find(): print(x)",
"e": 1594,
"s": 1134,
"text": null
},
{
"code": null,
"e": 1604,
"s": 1594,
"text": "Output : "
},
{
"code": null,
"e": 1732,
"s": 1604,
"text": "'_id': 2.0, 'Name': 'Golu', 'Class': '3'}\n{'_id': 3.0, 'Name': 'Raja', 'Class': '4'}\n{'_id': 4.0, 'Name': 'Moni', 'Class': '5'}"
},
{
"code": null,
"e": 1748,
"s": 1732,
"text": "MongoDB Shell: "
},
{
"code": null,
"e": 1767,
"s": 1750,
"text": "surinderdawra388"
},
{
"code": null,
"e": 1776,
"s": 1767,
"text": "gabaa406"
},
{
"code": null,
"e": 1785,
"s": 1776,
"text": "khushb99"
},
{
"code": null,
"e": 1800,
"s": 1785,
"text": "Python-mongoDB"
},
{
"code": null,
"e": 1807,
"s": 1800,
"text": "Python"
}
] |
How to turn off a particular bit in a number?
|
23 Jun, 2022
Given a number n and a value k, turn off the k’th bit in n. Please note that k = 1 means the rightmost bit.
Examples:
Input: n = 15, k = 1
Output: 14
Input: n = 14, k = 1
Output: 14
The rightmost bit was already off, so no change.
Input: n = 15, k = 2
Output: 13
Input: n = 15, k = 3
Output: 11
Input: n = 15, k = 4
Output: 7
Input: n = 15, k >= 5
Output: 15
The idea is to use bitwise <<, & and ~ operators. Using expression “~(1 << (k – 1))“, we get a number which has all bits set, except the k’th bit. If we do bitwise & of this expression with n, we get a number which has all bits same as n except the k’th bit which is 0.
Below is the implementation of above idea.
C++
Java
Python3
C#
PHP
Javascript
#include <iostream>using namespace std; // Returns a number that has all bits same as n// except the k'th bit which is made 0int turnOffK(int n, int k){ // k must be greater than 0 if (k <= 0) return n; // Do & of n with a number with all set bits except // the k'th bit return (n & ~(1 << (k - 1)));} // Driver program to test above functionint main(){ int n = 15; int k = 4; cout << turnOffK(n, k); return 0;}
// Java program to turn off a particular bit in a numberimport java.io.*; class TurnOff{ // Function to returns a number that has all bits same as n // except the k'th bit which is made 0 static int turnOffK(int n, int k) { // k must be greater than 0 if (k <= 0) return n; // Do & of n with a number with all set bits except // the k'th bit return (n & ~(1 << (k - 1))); } // Driver program public static void main (String[] args) { int n = 15; int k = 4; System.out.println(turnOffK(n, k)); }}// Contributed by Pramod Kumar
# Returns a number that# has all bits same as n# except the k'th bit# which is made 0 def turnOffK(n,k): # k must be greater than 0 if (k <= 0): return n # Do & of n with a number # with all set bits except # the k'th bit return (n & ~(1 << (k - 1))) # Driver coden = 15k = 4print(turnOffK(n, k)) # This code is contributed# by Anant Agarwal.
// C# program to turn off a// particular bit in a numberusing System; class GFG{ // Function to returns a number // that has all bits same as n // except the k'th bit which is // made 0 static int turnOffK(int n, int k) { // k must be greater than 0 if (k <= 0) return n; // Do & of n with a number // with all set bits except // the k'th bit return (n & ~ (1 << (k - 1))); } // Driver Code public static void Main () { int n = 15; int k = 4; Console.Write(turnOffK(n, k)); }} // This code is contributed by Nitin Mittal.
<?php// PHP program to turn off a// particular bit in a number // Returns a number that has// all bits same as n except// the k'th bit which is made 0function turnOffK($n, $k){ // k must be greater than 0 if ($k <= 0) return $n; // Do & of n with a number // with all set bits except // the k'th bit return ($n & ~(1 << ($k - 1)));} // Driver Code$n = 15;$k = 4;echo turnOffK($n, $k); // This code is contributed by nitin mittal?>
<script>// Returns a number that has all bits same as n// except the k'th bit which is made 0function turnOffK( n, k){ // k must be greater than 0 if (k <= 0) return n; // Do & of n with a number with all set bits except // the k'th bit return (n & ~(1 << (k - 1)));} // Driver program to test above functionlet n = 15;let k = 4;document.write(turnOffK(n, k)); // This code is contributed by rohitsingh07052.</script>
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
default, selected
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
7
Time Complexity: O(1)Auxiliary Space: O(1)
How to turn off a particular bit in a number? | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersHow to turn off a particular bit in a number? | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:57•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=tGpBOeBtr7w" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Exercise: Write a function turnOnK() that turns the k’th bit on.This article is contributed by Rahul Jain. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
nitin mittal
rohitsingh07052
ranjanrohit840
hardikkoriintern
Microsoft
Bit Magic
Strings
Microsoft
Strings
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Little and Big Endian Mystery
Program to find whether a given number is power of 2
Binary representation of a given number
Josephus problem | Set 1 (A O(n) Solution)
Divide two integers without using multiplication, division and mod operator
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": 52,
"s": 24,
"text": "\n23 Jun, 2022"
},
{
"code": null,
"e": 160,
"s": 52,
"text": "Given a number n and a value k, turn off the k’th bit in n. Please note that k = 1 means the rightmost bit."
},
{
"code": null,
"e": 171,
"s": 160,
"text": "Examples: "
},
{
"code": null,
"e": 424,
"s": 171,
"text": "Input: n = 15, k = 1\nOutput: 14\n\nInput: n = 14, k = 1\nOutput: 14\nThe rightmost bit was already off, so no change.\n\nInput: n = 15, k = 2\nOutput: 13\n\nInput: n = 15, k = 3\nOutput: 11\n\nInput: n = 15, k = 4\nOutput: 7\n\nInput: n = 15, k >= 5\nOutput: 15 "
},
{
"code": null,
"e": 695,
"s": 424,
"text": "The idea is to use bitwise <<, & and ~ operators. Using expression “~(1 << (k – 1))“, we get a number which has all bits set, except the k’th bit. If we do bitwise & of this expression with n, we get a number which has all bits same as n except the k’th bit which is 0. "
},
{
"code": null,
"e": 739,
"s": 695,
"text": "Below is the implementation of above idea. "
},
{
"code": null,
"e": 743,
"s": 739,
"text": "C++"
},
{
"code": null,
"e": 748,
"s": 743,
"text": "Java"
},
{
"code": null,
"e": 756,
"s": 748,
"text": "Python3"
},
{
"code": null,
"e": 759,
"s": 756,
"text": "C#"
},
{
"code": null,
"e": 763,
"s": 759,
"text": "PHP"
},
{
"code": null,
"e": 774,
"s": 763,
"text": "Javascript"
},
{
"code": "#include <iostream>using namespace std; // Returns a number that has all bits same as n// except the k'th bit which is made 0int turnOffK(int n, int k){ // k must be greater than 0 if (k <= 0) return n; // Do & of n with a number with all set bits except // the k'th bit return (n & ~(1 << (k - 1)));} // Driver program to test above functionint main(){ int n = 15; int k = 4; cout << turnOffK(n, k); return 0;}",
"e": 1214,
"s": 774,
"text": null
},
{
"code": "// Java program to turn off a particular bit in a numberimport java.io.*; class TurnOff{ // Function to returns a number that has all bits same as n // except the k'th bit which is made 0 static int turnOffK(int n, int k) { // k must be greater than 0 if (k <= 0) return n; // Do & of n with a number with all set bits except // the k'th bit return (n & ~(1 << (k - 1))); } // Driver program public static void main (String[] args) { int n = 15; int k = 4; System.out.println(turnOffK(n, k)); }}// Contributed by Pramod Kumar",
"e": 1841,
"s": 1214,
"text": null
},
{
"code": "# Returns a number that# has all bits same as n# except the k'th bit# which is made 0 def turnOffK(n,k): # k must be greater than 0 if (k <= 0): return n # Do & of n with a number # with all set bits except # the k'th bit return (n & ~(1 << (k - 1))) # Driver coden = 15k = 4print(turnOffK(n, k)) # This code is contributed# by Anant Agarwal.",
"e": 2214,
"s": 1841,
"text": null
},
{
"code": "// C# program to turn off a// particular bit in a numberusing System; class GFG{ // Function to returns a number // that has all bits same as n // except the k'th bit which is // made 0 static int turnOffK(int n, int k) { // k must be greater than 0 if (k <= 0) return n; // Do & of n with a number // with all set bits except // the k'th bit return (n & ~ (1 << (k - 1))); } // Driver Code public static void Main () { int n = 15; int k = 4; Console.Write(turnOffK(n, k)); }} // This code is contributed by Nitin Mittal.",
"e": 2854,
"s": 2214,
"text": null
},
{
"code": "<?php// PHP program to turn off a// particular bit in a number // Returns a number that has// all bits same as n except// the k'th bit which is made 0function turnOffK($n, $k){ // k must be greater than 0 if ($k <= 0) return $n; // Do & of n with a number // with all set bits except // the k'th bit return ($n & ~(1 << ($k - 1)));} // Driver Code$n = 15;$k = 4;echo turnOffK($n, $k); // This code is contributed by nitin mittal?>",
"e": 3316,
"s": 2854,
"text": null
},
{
"code": "<script>// Returns a number that has all bits same as n// except the k'th bit which is made 0function turnOffK( n, k){ // k must be greater than 0 if (k <= 0) return n; // Do & of n with a number with all set bits except // the k'th bit return (n & ~(1 << (k - 1)));} // Driver program to test above functionlet n = 15;let k = 4;document.write(turnOffK(n, k)); // This code is contributed by rohitsingh07052.</script>",
"e": 3750,
"s": 3316,
"text": null
},
{
"code": null,
"e": 3759,
"s": 3750,
"text": "Chapters"
},
{
"code": null,
"e": 3786,
"s": 3759,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 3836,
"s": 3786,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 3859,
"s": 3836,
"text": "captions off, selected"
},
{
"code": null,
"e": 3867,
"s": 3859,
"text": "English"
},
{
"code": null,
"e": 3885,
"s": 3867,
"text": "default, selected"
},
{
"code": null,
"e": 3909,
"s": 3885,
"text": "This is a modal window."
},
{
"code": null,
"e": 3978,
"s": 3909,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 4000,
"s": 3978,
"text": "End of dialog window."
},
{
"code": null,
"e": 4002,
"s": 4000,
"text": "7"
},
{
"code": null,
"e": 4047,
"s": 4002,
"text": "Time Complexity: O(1)Auxiliary Space: O(1) "
},
{
"code": null,
"e": 4955,
"s": 4047,
"text": "How to turn off a particular bit in a number? | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersHow to turn off a particular bit in a number? | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:57•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=tGpBOeBtr7w\" 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": 5187,
"s": 4955,
"text": "Exercise: Write a function turnOnK() that turns the k’th bit on.This article is contributed by Rahul Jain. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 5200,
"s": 5187,
"text": "nitin mittal"
},
{
"code": null,
"e": 5216,
"s": 5200,
"text": "rohitsingh07052"
},
{
"code": null,
"e": 5231,
"s": 5216,
"text": "ranjanrohit840"
},
{
"code": null,
"e": 5248,
"s": 5231,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 5258,
"s": 5248,
"text": "Microsoft"
},
{
"code": null,
"e": 5268,
"s": 5258,
"text": "Bit Magic"
},
{
"code": null,
"e": 5276,
"s": 5268,
"text": "Strings"
},
{
"code": null,
"e": 5286,
"s": 5276,
"text": "Microsoft"
},
{
"code": null,
"e": 5294,
"s": 5286,
"text": "Strings"
},
{
"code": null,
"e": 5304,
"s": 5294,
"text": "Bit Magic"
},
{
"code": null,
"e": 5402,
"s": 5304,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5432,
"s": 5402,
"text": "Little and Big Endian Mystery"
},
{
"code": null,
"e": 5485,
"s": 5432,
"text": "Program to find whether a given number is power of 2"
},
{
"code": null,
"e": 5525,
"s": 5485,
"text": "Binary representation of a given number"
},
{
"code": null,
"e": 5568,
"s": 5525,
"text": "Josephus problem | Set 1 (A O(n) Solution)"
},
{
"code": null,
"e": 5644,
"s": 5568,
"text": "Divide two integers without using multiplication, division and mod operator"
},
{
"code": null,
"e": 5690,
"s": 5644,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 5715,
"s": 5690,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 5775,
"s": 5715,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 5790,
"s": 5775,
"text": "C++ Data Types"
}
] |
Maximum number of unique values in the array after performing given operations
|
18 Apr, 2022
Given an array arr[] of size N and every element in the array arr[] is in the range [1, N] and the array may contain duplicates. The task is to find the maximum number of unique values that can be obtained such that the value at any index i can either be:
Increased by 1.
Decreased by 1.
Left as it is.
Note: The operation can be performed only once with each index and have to be performed for all the indices in the array arr[].Examples:
Input: arr[] = {1, 2, 4, 4} Output: 4 Explanation: One way is to perform the following operations for the index: 1: Leave the value at the first index(1) as it is. 2: Leave the value at the second index(2) as it is. 3: Leave the value at the third index(4) as it is. 4: Increment the value at the fourth index(4) by 1. Then the array becomes {1, 2, 4, 5} and there are 4 unique values.Input: arr[]={3, 3, 3, 3} Output: 3 Explanation: One way is to perform the following operations for the index: 1: Leave the value at the first index(3) as it is. 2: Decrement the value at the second index(3) by 1. 3: Leave the value at the third index(3) as it is. 4: Increment the value at the fourth index(3) by 1. Then the array becomes {3, 2, 3, 4} and there are 3 unique values.
Approach:
For some arbitrary element X present in the array at index i, we decide what operation to perform on it by taking the following things into consideration: We decrement the value X by 1 if the value (X – 1) is not present in the array and there are one or more other X’s present in the array at different indices.We don’t change the value X if the value X is present only once on the array.We increment the value X by 1 if the value (X + 1) is not present in the array and there are one or more other X’s present in the array at different indices.
We decrement the value X by 1 if the value (X – 1) is not present in the array and there are one or more other X’s present in the array at different indices.We don’t change the value X if the value X is present only once on the array.We increment the value X by 1 if the value (X + 1) is not present in the array and there are one or more other X’s present in the array at different indices.
We decrement the value X by 1 if the value (X – 1) is not present in the array and there are one or more other X’s present in the array at different indices.
We don’t change the value X if the value X is present only once on the array.
We increment the value X by 1 if the value (X + 1) is not present in the array and there are one or more other X’s present in the array at different indices.
By taking the above decisions for every element, we can be sure that the final count of unique elements which we get is the maximum.
However, to perform the above steps for every index and count the occurrences of the element X and continuously update the array arr[], the time taken would be quadratic which is not feasible for large-sized arrays.
One alternative to reduce the time complexity is to initially sort the array. By sorting, all the elements in the array are grouped and all the repeated values come together.
After sorting the array, since the range of the numbers is already given and it is fixed, a hash map can be used where the keys of the hash are the numbers in the range [1, N] and the value for each key is boolean which is used to determine if the key is present in the array or not.
In this problem, since the indices themselves are the keys of the hash, an array freq[] of size (N + 2) is used to implement the hash.
Below is the implementation of the above approach:
C++
C
Java
Python3
C#
Javascript
// C++ program to find the maximum number of// unique values in the array #include <bits/stdc++.h>using namespace std; // Function to find the maximum number of// unique values in the vectorint uniqueNumbers(vector<int> arr, int n){ // Sorting the given vector sort(arr.begin(),arr.end()); // This array will store the frequency // of each number in the array // after performing the given operation // initialise the array with 0 vector<int> freq(n+2,0) ; // Loop to apply operation on // each element of the array for (int x = 0; x < n; x++) { // Incrementing the value at index x // if the value arr[x] - 1 is // not present in the array if (freq[arr[x] - 1] == 0) { freq[arr[x] - 1]++; } // If arr[x] itself is not present, then it // is left as it is else if (freq[arr[x]] == 0) { freq[arr[x]]++; } // If both arr[x] - 1 and arr[x] are present // then the value is incremented by 1 else { freq[arr[x] + 1]++; } } // Variable to store the number of unique values int unique = 0; // Finding the unique values for (int x = 0; x <= n + 1; x++) { if (freq[x]) { unique++; } } // Returning the number of unique values return unique;} // Driver Codeint main(){ vector<int> arr= { 3, 3, 3, 3 }; // Size of the vector int n = arr.size(); int ans = uniqueNumbers(arr, n); cout << ans; return 0;}
// C program to find the maximum number of// unique values in the array#include <stdio.h>#include <stdlib.h> // comparison function for qsortint cmpfunc (const void * a, const void * b) { return ( *(int*)a - *(int*)b );} // Function to find the maximum number of// unique values in the arrayint uniqueNumbers(int* arr, int n){ // Sorting the given array qsort(arr, n, sizeof(int), cmpfunc); // This array will store the frequency // of each number in the array // after performing the given operation int freq[n+2]; // initialise the array with 0 for(int i = 0 ; i < n + 2 ; i++) freq[i] = 0; // Loop to apply operation on // each element of the array for (int x = 0; x < n; x++) { // Incrementing the value at index x // if the value arr[x] - 1 is // not present in the array if (freq[arr[x] - 1] == 0) { freq[arr[x] - 1]++; } // If arr[x] itself is not present, then it // is left as it is else if (freq[arr[x]] == 0) { freq[arr[x]]++; } // If both arr[x] - 1 and arr[x] are present // then the value is incremented by 1 else { freq[arr[x] + 1]++; } } // Variable to store the number of unique values int unique = 0; // Finding the unique values for (int x = 0; x <= n + 1; x++) { if (freq[x]) { unique++; } } // Returning the number of unique values return unique;} // Driver Codeint main(){ int arr[] = { 3, 3, 3, 3 }; // Size of the array int n = sizeof(arr)/sizeof(arr[0]); int ans = uniqueNumbers(arr, n); printf("%d", ans); return 0;} // This code is contributed by phalashi.
// Java program to find the maximum number of// unique values in the arrayimport java.util.*; class GFG { // Function to find the maximum number of // unique values in the array static int uniqueNumbers(int arr[], int n) { // Sorting the given array Arrays.sort(arr); // This array will store the frequency // of each number in the array // after performing the given operation int freq[] = new int[n + 2]; // Initialising the array with all zeroes for(int i = 0; i < n + 2; i++) freq[i] = 0; // Loop to apply operation on // each element of the array for (int x = 0; x < n; x++) { // Incrementing the value at index x // if the value arr[x] - 1 is // not present in the array if (freq[arr[x] - 1] == 0) { freq[arr[x] - 1]++; } // If arr[x] itself is not present, then it // is left as it is else if (freq[arr[x]] == 0) { freq[arr[x]]++; } // If both arr[x] - 1 and arr[x] are present // then the value is incremented by 1 else { freq[arr[x] + 1]++; } } // Variable to store the number of unique values int unique = 0; // Finding the unique values for (int x = 0; x <= n + 1; x++) { if (freq[x] != 0) { unique++; } } // Returning the number of unique values return unique; } // Driver Code public static void main (String[] args) { int []arr = { 3, 3, 3, 3 }; // Size of the array int n = 4; int ans = uniqueNumbers(arr, n); System.out.println(ans); }} // This code is contributed by Yash_R
# Python program to find the maximum number of# unique values in the array # Function to find the maximum number of# unique values in the arraydef uniqueNumbers(arr, n): # Sorting the given array arr.sort() # This array will store the frequency # of each number in the array # after performing the given operation freq =[0]*(n + 2) # Loop to apply the operation on # each element of the array for val in arr: # Incrementing the value at index x # if the value arr[x] - 1 is # not present in the array if(freq[val-1]== 0): freq[val-1]+= 1 # If arr[x] itself is not present, then it # is left as it is elif(freq[val]== 0): freq[val]+= 1 # If both arr[x] - 1 and arr[x] are present # then the value is incremented by 1 else: freq[val + 1]+= 1 # Variable to store the # number of unique values unique = 0 # Finding the number of unique values for val in freq: if(val>0): unique+= 1 return unique # Driver codeif __name__ == "__main__": arr =[3, 3, 3, 3] n = 4 print(uniqueNumbers(arr, n))
// C# program to find the maximum number of// unique values in the arrayusing System; class GFG { // Function to find the maximum number of // unique values in the array static int uniqueNumbers(int []arr, int n) { // Sorting the given array Array.Sort(arr); // This array will store the frequency // of each number in the array // after performing the given operation int []freq = new int[n + 2]; // Initialising the array with all zeroes for(int i = 0; i < n + 2; i++) freq[i] = 0; // Loop to apply operation on // each element of the array for (int x = 0; x < n; x++) { // Incrementing the value at index x // if the value arr[x] - 1 is // not present in the array if (freq[arr[x] - 1] == 0) { freq[arr[x] - 1]++; } // If arr[x] itself is not present, then it // is left as it is else if (freq[arr[x]] == 0) { freq[arr[x]]++; } // If both arr[x] - 1 and arr[x] are present // then the value is incremented by 1 else { freq[arr[x] + 1]++; } } // Variable to store the number of unique values int unique = 0; // Finding the unique values for (int x = 0; x <= n + 1; x++) { if (freq[x] != 0) { unique++; } } // Returning the number of unique values return unique; } // Driver Code public static void Main (string[] args) { int []arr = { 3, 3, 3, 3 }; // Size of the array int n = 4; int ans = uniqueNumbers(arr, n); Console.WriteLine(ans); }} // This code is contributed by Yash_R
<script>// javascript program to find the maximum number of// unique values in the array // Function to find the maximum number of // unique values in the array function uniqueNumbers(arr , n) { // Sorting the given array arr.sort((a,b)=>a-b); // This array will store the frequency // of each number in the array // after performing the given operation var freq = Array(n + 2).fill(0); // Initialising the array with all zeroes for (i = 0; i < n + 2; i++) freq[i] = 0; // Loop to apply operation on // each element of the array for (x = 0; x < n; x++) { // Incrementing the value at index x // if the value arr[x] - 1 is // not present in the array if (freq[arr[x] - 1] == 0) { freq[arr[x] - 1]++; } // If arr[x] itself is not present, then it // is left as it is else if (freq[arr[x]] == 0) { freq[arr[x]]++; } // If both arr[x] - 1 and arr[x] are present // then the value is incremented by 1 else { freq[arr[x] + 1]++; } } // Variable to store the number of unique values var unique = 0; // Finding the unique values for (x = 0; x <= n + 1; x++) { if (freq[x] != 0) { unique++; } } // Returning the number of unique values return unique; } // Driver Code var arr = [ 3, 3, 3, 3 ]; // Size of the array var n = 4; var ans = uniqueNumbers(arr, n); document.write(ans); // This code contributed by Rajput-Ji</script>
3
Time Complexity Analysis:
The time taken to sort the given array is O(N * log(N)) where N is the size of the array.
The time taken to run a loop over the sorted array to perform the operations is O(N).
The time taken to run a loop over the hash to count the unique values is O(N).
Therefore, the overall time complexity is O(N * log(N)) + O(N) + O(N). Since N * log(N) is greater, the final time complexity of the above approach is O(N * log(N)).
Auxiliary Space: O(N)
The extra space taken by the freq array is O(N). Therefore the auxiliary space is O(N).
Yash_R
Rajput-Ji
pankajsharmagfg
ashutoshsinghgeeksforgeeks
phasing17
sweetyty
frequency-counting
Algorithms
Arrays
Mathematical
Sorting
Arrays
Mathematical
Sorting
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
SDE SHEET - A Complete Guide for SDE Preparation
What is Hashing | A Complete Tutorial
Understanding Time Complexity with Simple Examples
CPU Scheduling in Operating Systems
Arrays in Java
Write a program to reverse an array or string
Maximum and minimum of an array using minimum number of comparisons
Largest Sum Contiguous Subarray
Arrays in C/C++
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n18 Apr, 2022"
},
{
"code": null,
"e": 312,
"s": 54,
"text": "Given an array arr[] of size N and every element in the array arr[] is in the range [1, N] and the array may contain duplicates. The task is to find the maximum number of unique values that can be obtained such that the value at any index i can either be: "
},
{
"code": null,
"e": 328,
"s": 312,
"text": "Increased by 1."
},
{
"code": null,
"e": 344,
"s": 328,
"text": "Decreased by 1."
},
{
"code": null,
"e": 359,
"s": 344,
"text": "Left as it is."
},
{
"code": null,
"e": 498,
"s": 359,
"text": "Note: The operation can be performed only once with each index and have to be performed for all the indices in the array arr[].Examples: "
},
{
"code": null,
"e": 1269,
"s": 498,
"text": "Input: arr[] = {1, 2, 4, 4} Output: 4 Explanation: One way is to perform the following operations for the index: 1: Leave the value at the first index(1) as it is. 2: Leave the value at the second index(2) as it is. 3: Leave the value at the third index(4) as it is. 4: Increment the value at the fourth index(4) by 1. Then the array becomes {1, 2, 4, 5} and there are 4 unique values.Input: arr[]={3, 3, 3, 3} Output: 3 Explanation: One way is to perform the following operations for the index: 1: Leave the value at the first index(3) as it is. 2: Decrement the value at the second index(3) by 1. 3: Leave the value at the third index(3) as it is. 4: Increment the value at the fourth index(3) by 1. Then the array becomes {3, 2, 3, 4} and there are 3 unique values. "
},
{
"code": null,
"e": 1283,
"s": 1271,
"text": "Approach: "
},
{
"code": null,
"e": 1830,
"s": 1283,
"text": "For some arbitrary element X present in the array at index i, we decide what operation to perform on it by taking the following things into consideration: We decrement the value X by 1 if the value (X – 1) is not present in the array and there are one or more other X’s present in the array at different indices.We don’t change the value X if the value X is present only once on the array.We increment the value X by 1 if the value (X + 1) is not present in the array and there are one or more other X’s present in the array at different indices."
},
{
"code": null,
"e": 2222,
"s": 1830,
"text": "We decrement the value X by 1 if the value (X – 1) is not present in the array and there are one or more other X’s present in the array at different indices.We don’t change the value X if the value X is present only once on the array.We increment the value X by 1 if the value (X + 1) is not present in the array and there are one or more other X’s present in the array at different indices."
},
{
"code": null,
"e": 2380,
"s": 2222,
"text": "We decrement the value X by 1 if the value (X – 1) is not present in the array and there are one or more other X’s present in the array at different indices."
},
{
"code": null,
"e": 2458,
"s": 2380,
"text": "We don’t change the value X if the value X is present only once on the array."
},
{
"code": null,
"e": 2616,
"s": 2458,
"text": "We increment the value X by 1 if the value (X + 1) is not present in the array and there are one or more other X’s present in the array at different indices."
},
{
"code": null,
"e": 2749,
"s": 2616,
"text": "By taking the above decisions for every element, we can be sure that the final count of unique elements which we get is the maximum."
},
{
"code": null,
"e": 2965,
"s": 2749,
"text": "However, to perform the above steps for every index and count the occurrences of the element X and continuously update the array arr[], the time taken would be quadratic which is not feasible for large-sized arrays."
},
{
"code": null,
"e": 3140,
"s": 2965,
"text": "One alternative to reduce the time complexity is to initially sort the array. By sorting, all the elements in the array are grouped and all the repeated values come together."
},
{
"code": null,
"e": 3424,
"s": 3140,
"text": "After sorting the array, since the range of the numbers is already given and it is fixed, a hash map can be used where the keys of the hash are the numbers in the range [1, N] and the value for each key is boolean which is used to determine if the key is present in the array or not."
},
{
"code": null,
"e": 3559,
"s": 3424,
"text": "In this problem, since the indices themselves are the keys of the hash, an array freq[] of size (N + 2) is used to implement the hash."
},
{
"code": null,
"e": 3612,
"s": 3559,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 3616,
"s": 3612,
"text": "C++"
},
{
"code": null,
"e": 3618,
"s": 3616,
"text": "C"
},
{
"code": null,
"e": 3623,
"s": 3618,
"text": "Java"
},
{
"code": null,
"e": 3631,
"s": 3623,
"text": "Python3"
},
{
"code": null,
"e": 3634,
"s": 3631,
"text": "C#"
},
{
"code": null,
"e": 3645,
"s": 3634,
"text": "Javascript"
},
{
"code": "// C++ program to find the maximum number of// unique values in the array #include <bits/stdc++.h>using namespace std; // Function to find the maximum number of// unique values in the vectorint uniqueNumbers(vector<int> arr, int n){ // Sorting the given vector sort(arr.begin(),arr.end()); // This array will store the frequency // of each number in the array // after performing the given operation // initialise the array with 0 vector<int> freq(n+2,0) ; // Loop to apply operation on // each element of the array for (int x = 0; x < n; x++) { // Incrementing the value at index x // if the value arr[x] - 1 is // not present in the array if (freq[arr[x] - 1] == 0) { freq[arr[x] - 1]++; } // If arr[x] itself is not present, then it // is left as it is else if (freq[arr[x]] == 0) { freq[arr[x]]++; } // If both arr[x] - 1 and arr[x] are present // then the value is incremented by 1 else { freq[arr[x] + 1]++; } } // Variable to store the number of unique values int unique = 0; // Finding the unique values for (int x = 0; x <= n + 1; x++) { if (freq[x]) { unique++; } } // Returning the number of unique values return unique;} // Driver Codeint main(){ vector<int> arr= { 3, 3, 3, 3 }; // Size of the vector int n = arr.size(); int ans = uniqueNumbers(arr, n); cout << ans; return 0;}",
"e": 5170,
"s": 3645,
"text": null
},
{
"code": "// C program to find the maximum number of// unique values in the array#include <stdio.h>#include <stdlib.h> // comparison function for qsortint cmpfunc (const void * a, const void * b) { return ( *(int*)a - *(int*)b );} // Function to find the maximum number of// unique values in the arrayint uniqueNumbers(int* arr, int n){ // Sorting the given array qsort(arr, n, sizeof(int), cmpfunc); // This array will store the frequency // of each number in the array // after performing the given operation int freq[n+2]; // initialise the array with 0 for(int i = 0 ; i < n + 2 ; i++) freq[i] = 0; // Loop to apply operation on // each element of the array for (int x = 0; x < n; x++) { // Incrementing the value at index x // if the value arr[x] - 1 is // not present in the array if (freq[arr[x] - 1] == 0) { freq[arr[x] - 1]++; } // If arr[x] itself is not present, then it // is left as it is else if (freq[arr[x]] == 0) { freq[arr[x]]++; } // If both arr[x] - 1 and arr[x] are present // then the value is incremented by 1 else { freq[arr[x] + 1]++; } } // Variable to store the number of unique values int unique = 0; // Finding the unique values for (int x = 0; x <= n + 1; x++) { if (freq[x]) { unique++; } } // Returning the number of unique values return unique;} // Driver Codeint main(){ int arr[] = { 3, 3, 3, 3 }; // Size of the array int n = sizeof(arr)/sizeof(arr[0]); int ans = uniqueNumbers(arr, n); printf(\"%d\", ans); return 0;} // This code is contributed by phalashi.",
"e": 6903,
"s": 5170,
"text": null
},
{
"code": "// Java program to find the maximum number of// unique values in the arrayimport java.util.*; class GFG { // Function to find the maximum number of // unique values in the array static int uniqueNumbers(int arr[], int n) { // Sorting the given array Arrays.sort(arr); // This array will store the frequency // of each number in the array // after performing the given operation int freq[] = new int[n + 2]; // Initialising the array with all zeroes for(int i = 0; i < n + 2; i++) freq[i] = 0; // Loop to apply operation on // each element of the array for (int x = 0; x < n; x++) { // Incrementing the value at index x // if the value arr[x] - 1 is // not present in the array if (freq[arr[x] - 1] == 0) { freq[arr[x] - 1]++; } // If arr[x] itself is not present, then it // is left as it is else if (freq[arr[x]] == 0) { freq[arr[x]]++; } // If both arr[x] - 1 and arr[x] are present // then the value is incremented by 1 else { freq[arr[x] + 1]++; } } // Variable to store the number of unique values int unique = 0; // Finding the unique values for (int x = 0; x <= n + 1; x++) { if (freq[x] != 0) { unique++; } } // Returning the number of unique values return unique; } // Driver Code public static void main (String[] args) { int []arr = { 3, 3, 3, 3 }; // Size of the array int n = 4; int ans = uniqueNumbers(arr, n); System.out.println(ans); }} // This code is contributed by Yash_R",
"e": 8786,
"s": 6903,
"text": null
},
{
"code": "# Python program to find the maximum number of# unique values in the array # Function to find the maximum number of# unique values in the arraydef uniqueNumbers(arr, n): # Sorting the given array arr.sort() # This array will store the frequency # of each number in the array # after performing the given operation freq =[0]*(n + 2) # Loop to apply the operation on # each element of the array for val in arr: # Incrementing the value at index x # if the value arr[x] - 1 is # not present in the array if(freq[val-1]== 0): freq[val-1]+= 1 # If arr[x] itself is not present, then it # is left as it is elif(freq[val]== 0): freq[val]+= 1 # If both arr[x] - 1 and arr[x] are present # then the value is incremented by 1 else: freq[val + 1]+= 1 # Variable to store the # number of unique values unique = 0 # Finding the number of unique values for val in freq: if(val>0): unique+= 1 return unique # Driver codeif __name__ == \"__main__\": arr =[3, 3, 3, 3] n = 4 print(uniqueNumbers(arr, n))",
"e": 9964,
"s": 8786,
"text": null
},
{
"code": "// C# program to find the maximum number of// unique values in the arrayusing System; class GFG { // Function to find the maximum number of // unique values in the array static int uniqueNumbers(int []arr, int n) { // Sorting the given array Array.Sort(arr); // This array will store the frequency // of each number in the array // after performing the given operation int []freq = new int[n + 2]; // Initialising the array with all zeroes for(int i = 0; i < n + 2; i++) freq[i] = 0; // Loop to apply operation on // each element of the array for (int x = 0; x < n; x++) { // Incrementing the value at index x // if the value arr[x] - 1 is // not present in the array if (freq[arr[x] - 1] == 0) { freq[arr[x] - 1]++; } // If arr[x] itself is not present, then it // is left as it is else if (freq[arr[x]] == 0) { freq[arr[x]]++; } // If both arr[x] - 1 and arr[x] are present // then the value is incremented by 1 else { freq[arr[x] + 1]++; } } // Variable to store the number of unique values int unique = 0; // Finding the unique values for (int x = 0; x <= n + 1; x++) { if (freq[x] != 0) { unique++; } } // Returning the number of unique values return unique; } // Driver Code public static void Main (string[] args) { int []arr = { 3, 3, 3, 3 }; // Size of the array int n = 4; int ans = uniqueNumbers(arr, n); Console.WriteLine(ans); }} // This code is contributed by Yash_R",
"e": 11837,
"s": 9964,
"text": null
},
{
"code": "<script>// javascript program to find the maximum number of// unique values in the array // Function to find the maximum number of // unique values in the array function uniqueNumbers(arr , n) { // Sorting the given array arr.sort((a,b)=>a-b); // This array will store the frequency // of each number in the array // after performing the given operation var freq = Array(n + 2).fill(0); // Initialising the array with all zeroes for (i = 0; i < n + 2; i++) freq[i] = 0; // Loop to apply operation on // each element of the array for (x = 0; x < n; x++) { // Incrementing the value at index x // if the value arr[x] - 1 is // not present in the array if (freq[arr[x] - 1] == 0) { freq[arr[x] - 1]++; } // If arr[x] itself is not present, then it // is left as it is else if (freq[arr[x]] == 0) { freq[arr[x]]++; } // If both arr[x] - 1 and arr[x] are present // then the value is incremented by 1 else { freq[arr[x] + 1]++; } } // Variable to store the number of unique values var unique = 0; // Finding the unique values for (x = 0; x <= n + 1; x++) { if (freq[x] != 0) { unique++; } } // Returning the number of unique values return unique; } // Driver Code var arr = [ 3, 3, 3, 3 ]; // Size of the array var n = 4; var ans = uniqueNumbers(arr, n); document.write(ans); // This code contributed by Rajput-Ji</script>",
"e": 13592,
"s": 11837,
"text": null
},
{
"code": null,
"e": 13594,
"s": 13592,
"text": "3"
},
{
"code": null,
"e": 13622,
"s": 13596,
"text": "Time Complexity Analysis:"
},
{
"code": null,
"e": 13712,
"s": 13622,
"text": "The time taken to sort the given array is O(N * log(N)) where N is the size of the array."
},
{
"code": null,
"e": 13798,
"s": 13712,
"text": "The time taken to run a loop over the sorted array to perform the operations is O(N)."
},
{
"code": null,
"e": 13877,
"s": 13798,
"text": "The time taken to run a loop over the hash to count the unique values is O(N)."
},
{
"code": null,
"e": 14043,
"s": 13877,
"text": "Therefore, the overall time complexity is O(N * log(N)) + O(N) + O(N). Since N * log(N) is greater, the final time complexity of the above approach is O(N * log(N))."
},
{
"code": null,
"e": 14065,
"s": 14043,
"text": "Auxiliary Space: O(N)"
},
{
"code": null,
"e": 14153,
"s": 14065,
"text": "The extra space taken by the freq array is O(N). Therefore the auxiliary space is O(N)."
},
{
"code": null,
"e": 14160,
"s": 14153,
"text": "Yash_R"
},
{
"code": null,
"e": 14170,
"s": 14160,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 14186,
"s": 14170,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 14213,
"s": 14186,
"text": "ashutoshsinghgeeksforgeeks"
},
{
"code": null,
"e": 14223,
"s": 14213,
"text": "phasing17"
},
{
"code": null,
"e": 14232,
"s": 14223,
"text": "sweetyty"
},
{
"code": null,
"e": 14251,
"s": 14232,
"text": "frequency-counting"
},
{
"code": null,
"e": 14262,
"s": 14251,
"text": "Algorithms"
},
{
"code": null,
"e": 14269,
"s": 14262,
"text": "Arrays"
},
{
"code": null,
"e": 14282,
"s": 14269,
"text": "Mathematical"
},
{
"code": null,
"e": 14290,
"s": 14282,
"text": "Sorting"
},
{
"code": null,
"e": 14297,
"s": 14290,
"text": "Arrays"
},
{
"code": null,
"e": 14310,
"s": 14297,
"text": "Mathematical"
},
{
"code": null,
"e": 14318,
"s": 14310,
"text": "Sorting"
},
{
"code": null,
"e": 14329,
"s": 14318,
"text": "Algorithms"
},
{
"code": null,
"e": 14427,
"s": 14329,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 14452,
"s": 14427,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 14501,
"s": 14452,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 14539,
"s": 14501,
"text": "What is Hashing | A Complete Tutorial"
},
{
"code": null,
"e": 14590,
"s": 14539,
"text": "Understanding Time Complexity with Simple Examples"
},
{
"code": null,
"e": 14626,
"s": 14590,
"text": "CPU Scheduling in Operating Systems"
},
{
"code": null,
"e": 14641,
"s": 14626,
"text": "Arrays in Java"
},
{
"code": null,
"e": 14687,
"s": 14641,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 14755,
"s": 14687,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 14787,
"s": 14755,
"text": "Largest Sum Contiguous Subarray"
}
] |
SQL Concepts and Queries
|
19 May, 2021
In this article, we will discuss the overview of SQL and will mainly focus on Concepts and Queries and will understand each with the help of examples. Let’s discuss it one by one.
Overview :SQL is a computer language that is used for storing, manipulating, and retrieving data in a structured format. This language was invented by IBM. Here SQL stands for Structured Query Language. Interacting databases with SQL queries, we can handle a large amount of data. There are several SQL-supported database servers such as MySQL, PostgreSQL, sqlite3 and so on. Data can be stored in a secured and structured format through these database servers. SQL queries are often used for data manipulation and business insights better.
SQL Database :Here, we will discuss the queries and will understand with the help of examples.
Query-1 :Show existing databases –Let’s consider the existing database like nformation_schema, mysql, performance_schema, sakila, student, sys, and world. And if you want to show the exiting database then we will use the show database query as follows.
SHOW DATABASES;
Output :
Query-2 :Drop a database –Suppose we want to drop the database namely student.
DROP DATABASE student;
SHOW DATABASES;
Query-3 :Create a database –Suppose we want to create a database namely a bank.
CREATE DATABASE bank;
SHOW DATABASES;
Query-4 :Using a database –
USE bank;
Query-5 :Create a Table –Here data type may be varchar, integer, date, etc.
CREATE TABLE table_name (
column1 datatype,
column2 datatype,
....
);
Example –
CREATE TABLE IF NOT EXISTS Employee (
EmployeeID int,
FirstName varchar(55),
LastName varchar(55),
Email varchar(150),
DOB date
);
Query-6 :Show tables in the same database –
SHOW TABLES;
Query-7 :Dropping a Table –
DROP TABLE table_name;
Query-8 :Inserting values into an existing table –
INSERT INTO Employee
VALUES(1111,'Dipak','Bera','[email protected]','1994-11-22');
Query-9 :Fetching values in a table –
SELECT * FROM Employee;
Query-10 :Not Null –We can specify which column does not accept the null value when we insert a value(row) in a table. It will be done at the time of table creation.
CREATE TABLE table_name (
column1 datatype NOT NULL,
column2 datatype,
....
);
Query-11 :Unique –We can also specify that entries in a particular column should be unique.
CREATE TABLE table_name (
column1 datatype UNIQUE,
column2 datatype,
....
);
Example –
CREATE TABLE demo_table
(
EmployeeID int NOT NULL UNIQUE,
FirstName varchar(55),
LastName varchar(55)
);
KEY CONCEPTS in SQL :Here, we will discuss some important concepts like keys, join operations, having clauses, order by, etc. Let’s discuss it one by one.
PRIMARY KEY –The constraint PRIMARY KEY suggests that entries should be neither null nor duplicate corresponding to the specified column.
CREATE TABLE IF NOT EXISTS Customer(
CustID int NOT NULL,
FName varchar(55),
LName varchar(55),
Email varchar(100),
DOB date,
CONSTRAINT customer_custid_pk PRIMARY KEY(CustID)
);
FOREIGN KEY –The FOREIGN KEY is used to build a connection between the current table and the previous table containing the primary key.
CREATE TABLE Account(
AccNo int NOT NULL,
AType varchar(20),
OBal int,
OD date,
CurBal int,
CONSTRAINT customer_AccNo_fk FOREIGN KEY(AccNo) REFERENCES Customer(CustID)
);
Here, AccNo column in the Account table is referred to by CustID column in the Customer table. Here Account table is a child table and the Customer table is the parent table.
ORDER BY :The ORDER BY keyword is used to show the result in ascending or descending order. By default, it is in ascending order.
Syntax –
SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;
Scenario-1 : Suppose we have the Account Table as follows.
Now, we will use the Order By command as follows.
SELECT * FROM Account ORDER BY CurBal;
Output : (By default it will be in increasing order)
Scenario-2 : For descending order :
SELECT * FROM Account ORDER BY CurBal DESC;
Output :
GROUP BY :This keyword is used for grouping the results.
Example –
SELECT COUNT(AType) FROM Account GROUP BY AType;
Output :
JOIN CONCEPTS :Here, we will discuss the join concept as follows.
LEFT JOIN :The LEFT JOIN keyword returns all records from the left table (table1) along with the matching records from the right table (table2). Syntax –
SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name;
LEFT JOIN
RIGHT JOIN :The RIGHT JOIN keyword returns all records from the right table (table2) along with the matching records from the left table (table1).
Syntax –
SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name = table2.column_name;
RIGHT JOIN
INNER JOIN : The INNER JOIN keyword returns all matching records from both the table.
Syntax –
SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;
INNER JOIN
FULL JOIN :The FULL JOIN or FULL OUTER JOIN keyword returns all records from both the table.
Syntax –
SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name = table2.column_name;
FULL JOIN
Note – This keyword is not used in MySQL’s latest version. Instead, the keyword UNION is used. Here the syntax is as follows.
SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;
SELF JOIN :This is a regular join between aliases of the same table.
Syntax –
SELECT column_name(s)
FROM table1 T1, table1 T2
WHERE condition;
WHERE CLAUSE :This clause is used for filtering our data.
Syntax –
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Example –
SELECT AccNo,CurBal FROM Account WHERE CurBal>=1000;
Output :
HAVING CLAUSE :This is required as the WHERE clause does not support aggregate functions such as count, min, max, avg, sum, and so on.
SELECT column1, column2, ...
FROM table_name
HAVING condition;
Example –
SELECT AccNo,CurBal FROM Account HAVING CurBal=MAX(CurBal);
Output :
mysql
DBMS
GATE CS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n19 May, 2021"
},
{
"code": null,
"e": 233,
"s": 53,
"text": "In this article, we will discuss the overview of SQL and will mainly focus on Concepts and Queries and will understand each with the help of examples. Let’s discuss it one by one."
},
{
"code": null,
"e": 774,
"s": 233,
"text": "Overview :SQL is a computer language that is used for storing, manipulating, and retrieving data in a structured format. This language was invented by IBM. Here SQL stands for Structured Query Language. Interacting databases with SQL queries, we can handle a large amount of data. There are several SQL-supported database servers such as MySQL, PostgreSQL, sqlite3 and so on. Data can be stored in a secured and structured format through these database servers. SQL queries are often used for data manipulation and business insights better."
},
{
"code": null,
"e": 870,
"s": 774,
"text": "SQL Database :Here, we will discuss the queries and will understand with the help of examples. "
},
{
"code": null,
"e": 1124,
"s": 870,
"text": "Query-1 :Show existing databases –Let’s consider the existing database like nformation_schema, mysql, performance_schema, sakila, student, sys, and world. And if you want to show the exiting database then we will use the show database query as follows. "
},
{
"code": null,
"e": 1142,
"s": 1124,
"text": "SHOW DATABASES; "
},
{
"code": null,
"e": 1152,
"s": 1142,
"text": " Output :"
},
{
"code": null,
"e": 1231,
"s": 1152,
"text": "Query-2 :Drop a database –Suppose we want to drop the database namely student."
},
{
"code": null,
"e": 1272,
"s": 1231,
"text": "DROP DATABASE student;\nSHOW DATABASES; "
},
{
"code": null,
"e": 1352,
"s": 1272,
"text": "Query-3 :Create a database –Suppose we want to create a database namely a bank."
},
{
"code": null,
"e": 1390,
"s": 1352,
"text": "CREATE DATABASE bank;\nSHOW DATABASES;"
},
{
"code": null,
"e": 1418,
"s": 1390,
"text": "Query-4 :Using a database –"
},
{
"code": null,
"e": 1428,
"s": 1418,
"text": "USE bank;"
},
{
"code": null,
"e": 1504,
"s": 1428,
"text": "Query-5 :Create a Table –Here data type may be varchar, integer, date, etc."
},
{
"code": null,
"e": 1582,
"s": 1504,
"text": "CREATE TABLE table_name (\n column1 datatype,\n column2 datatype,\n ....\n);"
},
{
"code": null,
"e": 1592,
"s": 1582,
"text": "Example –"
},
{
"code": null,
"e": 1738,
"s": 1592,
"text": "CREATE TABLE IF NOT EXISTS Employee (\n EmployeeID int,\n FirstName varchar(55),\n LastName varchar(55),\n Email varchar(150),\n DOB date\n);"
},
{
"code": null,
"e": 1782,
"s": 1738,
"text": "Query-6 :Show tables in the same database –"
},
{
"code": null,
"e": 1795,
"s": 1782,
"text": "SHOW TABLES;"
},
{
"code": null,
"e": 1823,
"s": 1795,
"text": "Query-7 :Dropping a Table –"
},
{
"code": null,
"e": 1846,
"s": 1823,
"text": "DROP TABLE table_name;"
},
{
"code": null,
"e": 1897,
"s": 1846,
"text": "Query-8 :Inserting values into an existing table –"
},
{
"code": null,
"e": 1983,
"s": 1897,
"text": "INSERT INTO Employee \nVALUES(1111,'Dipak','Bera','[email protected]','1994-11-22');"
},
{
"code": null,
"e": 2021,
"s": 1983,
"text": "Query-9 :Fetching values in a table –"
},
{
"code": null,
"e": 2045,
"s": 2021,
"text": "SELECT * FROM Employee;"
},
{
"code": null,
"e": 2211,
"s": 2045,
"text": "Query-10 :Not Null –We can specify which column does not accept the null value when we insert a value(row) in a table. It will be done at the time of table creation."
},
{
"code": null,
"e": 2295,
"s": 2211,
"text": "CREATE TABLE table_name (\n column1 datatype NOT NULL,\n column2 datatype,\n ....\n);"
},
{
"code": null,
"e": 2387,
"s": 2295,
"text": "Query-11 :Unique –We can also specify that entries in a particular column should be unique."
},
{
"code": null,
"e": 2466,
"s": 2387,
"text": "CREATE TABLE table_name (\n column1 datatype UNIQUE,\n column2 datatype,\n....\n);"
},
{
"code": null,
"e": 2476,
"s": 2466,
"text": "Example –"
},
{
"code": null,
"e": 2583,
"s": 2476,
"text": "CREATE TABLE demo_table\n(\nEmployeeID int NOT NULL UNIQUE, \nFirstName varchar(55), \nLastName varchar(55)\n);"
},
{
"code": null,
"e": 2739,
"s": 2583,
"text": "KEY CONCEPTS in SQL :Here, we will discuss some important concepts like keys, join operations, having clauses, order by, etc. Let’s discuss it one by one. "
},
{
"code": null,
"e": 2877,
"s": 2739,
"text": "PRIMARY KEY –The constraint PRIMARY KEY suggests that entries should be neither null nor duplicate corresponding to the specified column."
},
{
"code": null,
"e": 3057,
"s": 2877,
"text": "CREATE TABLE IF NOT EXISTS Customer(\nCustID int NOT NULL,\nFName varchar(55),\nLName varchar(55),\nEmail varchar(100),\nDOB date,\nCONSTRAINT customer_custid_pk PRIMARY KEY(CustID)\n);"
},
{
"code": null,
"e": 3193,
"s": 3057,
"text": "FOREIGN KEY –The FOREIGN KEY is used to build a connection between the current table and the previous table containing the primary key."
},
{
"code": null,
"e": 3365,
"s": 3193,
"text": "CREATE TABLE Account(\nAccNo int NOT NULL,\nAType varchar(20),\nOBal int,\nOD date,\nCurBal int,\nCONSTRAINT customer_AccNo_fk FOREIGN KEY(AccNo) REFERENCES Customer(CustID)\n);"
},
{
"code": null,
"e": 3540,
"s": 3365,
"text": "Here, AccNo column in the Account table is referred to by CustID column in the Customer table. Here Account table is a child table and the Customer table is the parent table."
},
{
"code": null,
"e": 3670,
"s": 3540,
"text": "ORDER BY :The ORDER BY keyword is used to show the result in ascending or descending order. By default, it is in ascending order."
},
{
"code": null,
"e": 3679,
"s": 3670,
"text": "Syntax –"
},
{
"code": null,
"e": 3765,
"s": 3679,
"text": "SELECT column1, column2, ...\nFROM table_name\nORDER BY column1, column2, ... ASC|DESC;"
},
{
"code": null,
"e": 3824,
"s": 3765,
"text": "Scenario-1 : Suppose we have the Account Table as follows."
},
{
"code": null,
"e": 3874,
"s": 3824,
"text": "Now, we will use the Order By command as follows."
},
{
"code": null,
"e": 3919,
"s": 3874,
"text": "SELECT * FROM Account ORDER BY CurBal; "
},
{
"code": null,
"e": 3972,
"s": 3919,
"text": "Output : (By default it will be in increasing order)"
},
{
"code": null,
"e": 4008,
"s": 3972,
"text": "Scenario-2 : For descending order :"
},
{
"code": null,
"e": 4052,
"s": 4008,
"text": "SELECT * FROM Account ORDER BY CurBal DESC;"
},
{
"code": null,
"e": 4064,
"s": 4052,
"text": "Output : "
},
{
"code": null,
"e": 4121,
"s": 4064,
"text": "GROUP BY :This keyword is used for grouping the results."
},
{
"code": null,
"e": 4131,
"s": 4121,
"text": "Example –"
},
{
"code": null,
"e": 4180,
"s": 4131,
"text": "SELECT COUNT(AType) FROM Account GROUP BY AType;"
},
{
"code": null,
"e": 4191,
"s": 4180,
"text": "Output : "
},
{
"code": null,
"e": 4284,
"s": 4218,
"text": "JOIN CONCEPTS :Here, we will discuss the join concept as follows."
},
{
"code": null,
"e": 4457,
"s": 4284,
"text": "LEFT JOIN :The LEFT JOIN keyword returns all records from the left table (table1) along with the matching records from the right table (table2). Syntax – "
},
{
"code": null,
"e": 4552,
"s": 4457,
"text": "SELECT column_name(s)\nFROM table1\nLEFT JOIN table2\nON table1.column_name = table2.column_name;"
},
{
"code": null,
"e": 4563,
"s": 4552,
"text": " LEFT JOIN"
},
{
"code": null,
"e": 4710,
"s": 4563,
"text": "RIGHT JOIN :The RIGHT JOIN keyword returns all records from the right table (table2) along with the matching records from the left table (table1)."
},
{
"code": null,
"e": 4719,
"s": 4710,
"text": "Syntax –"
},
{
"code": null,
"e": 4815,
"s": 4719,
"text": "SELECT column_name(s)\nFROM table1\nRIGHT JOIN table2\nON table1.column_name = table2.column_name;"
},
{
"code": null,
"e": 4826,
"s": 4815,
"text": "RIGHT JOIN"
},
{
"code": null,
"e": 4918,
"s": 4826,
"text": "INNER JOIN : The INNER JOIN keyword returns all matching records from both the table."
},
{
"code": null,
"e": 4929,
"s": 4918,
"text": " Syntax – "
},
{
"code": null,
"e": 5025,
"s": 4929,
"text": "SELECT column_name(s)\nFROM table1\nINNER JOIN table2\nON table1.column_name = table2.column_name;"
},
{
"code": null,
"e": 5036,
"s": 5025,
"text": "INNER JOIN"
},
{
"code": null,
"e": 5129,
"s": 5036,
"text": "FULL JOIN :The FULL JOIN or FULL OUTER JOIN keyword returns all records from both the table."
},
{
"code": null,
"e": 5138,
"s": 5129,
"text": "Syntax –"
},
{
"code": null,
"e": 5239,
"s": 5138,
"text": "SELECT column_name(s)\nFROM table1\nFULL OUTER JOIN table2\nON table1.column_name = table2.column_name;"
},
{
"code": null,
"e": 5249,
"s": 5239,
"text": "FULL JOIN"
},
{
"code": null,
"e": 5387,
"s": 5249,
"text": " Note – This keyword is not used in MySQL’s latest version. Instead, the keyword UNION is used. Here the syntax is as follows."
},
{
"code": null,
"e": 5462,
"s": 5387,
"text": "SELECT column_name(s) FROM table1\nUNION\nSELECT column_name(s) FROM table2;"
},
{
"code": null,
"e": 5531,
"s": 5462,
"text": "SELF JOIN :This is a regular join between aliases of the same table."
},
{
"code": null,
"e": 5540,
"s": 5531,
"text": "Syntax –"
},
{
"code": null,
"e": 5605,
"s": 5540,
"text": "SELECT column_name(s)\nFROM table1 T1, table1 T2\nWHERE condition;"
},
{
"code": null,
"e": 5663,
"s": 5605,
"text": "WHERE CLAUSE :This clause is used for filtering our data."
},
{
"code": null,
"e": 5672,
"s": 5663,
"text": "Syntax –"
},
{
"code": null,
"e": 5734,
"s": 5672,
"text": "SELECT column1, column2, ...\nFROM table_name\nWHERE condition;"
},
{
"code": null,
"e": 5744,
"s": 5734,
"text": "Example –"
},
{
"code": null,
"e": 5798,
"s": 5744,
"text": "SELECT AccNo,CurBal FROM Account WHERE CurBal>=1000;"
},
{
"code": null,
"e": 5807,
"s": 5798,
"text": "Output :"
},
{
"code": null,
"e": 5942,
"s": 5807,
"text": "HAVING CLAUSE :This is required as the WHERE clause does not support aggregate functions such as count, min, max, avg, sum, and so on."
},
{
"code": null,
"e": 6005,
"s": 5942,
"text": "SELECT column1, column2, ...\nFROM table_name\nHAVING condition;"
},
{
"code": null,
"e": 6015,
"s": 6005,
"text": "Example –"
},
{
"code": null,
"e": 6076,
"s": 6015,
"text": "SELECT AccNo,CurBal FROM Account HAVING CurBal=MAX(CurBal);"
},
{
"code": null,
"e": 6085,
"s": 6076,
"text": "Output :"
},
{
"code": null,
"e": 6091,
"s": 6085,
"text": "mysql"
},
{
"code": null,
"e": 6096,
"s": 6091,
"text": "DBMS"
},
{
"code": null,
"e": 6104,
"s": 6096,
"text": "GATE CS"
},
{
"code": null,
"e": 6108,
"s": 6104,
"text": "SQL"
},
{
"code": null,
"e": 6113,
"s": 6108,
"text": "DBMS"
},
{
"code": null,
"e": 6117,
"s": 6113,
"text": "SQL"
}
] |
ReactJS UI Ant Design Card Component
|
02 Jun, 2021
Ant Design Library has this component pre-built, and it is very easy to integrate as well. Card Component is used as a simple rectangular container, and it is used when the user wants to display content related to a single subject. We can use the following approach in ReactJS to use the Ant Design Card Component.
Card Props:
actions: It is used to denote the action list.
activeTabKey: It is used to denote the current TabPane’s key.
bodyStyle: It is used to denote the inline style to apply to the card content.
bordered: It is used to toggle the rendering of the border around the card.
cover: It is used to denote the Card cover.
defaultActiveTabKey: It is used to denote the Initial active TabPane’s key.
extra: It is used for the Content to render in the top-right corner of the card.
headStyle: It is used to denote the Inline style to apply to the card head.
hoverable: It is used to Lift up when hovering the card grid.
loading: It is used to show a loading indicator while the contents of the card are being fetched.
size: It is used to denote the size of the card.
tabBarExtraContent: It is used to denote the Extra content in the tab bar.
tabList: It is used to denote the List of TabPane’s head.
tabProps: It is used to denote the Tab props.
title: It is used to denote the Card title.
type: It is used to denote the Card style type.
onTabChange: It is a callback function that is triggered when the tab is switched.
Card.Grid Props:
className: It is used to denote the className of the container.
hoverable: It is used to Lift up when hovering the card grid.
style: It is used to pass the style object of the container.
Card.Meta Props:
avatar: It is used to denote the Avatar or icon.
className: It is used to denote the className of the container.
description: It is used to denote the description content.
style: It is used to pass the style object of the container.
title: It is used to denote the title content.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:npx create-react-app foldername
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Step 3: After creating the ReactJS application, Install the required module using the following command:npm install antd
Step 3: After creating the ReactJS application, Install the required module using the following command:
npm install antd
Project Structure: It will look like the following.
Project Structure
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
App.js
import React from 'react'import "antd/dist/antd.css";import { Card } from 'antd'; export default function App() { return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>ReactJS Ant-Design Card Component</h4> <> <Card title="Card title" bordered style={{ width: 500, border: '2px solid black' }}> <p>Sample Card Content 1</p> <p>Sample Card Content 2</p> <p>Sample Card Content 3</p> </Card> </> </div> );}
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Reference: https://ant.design/components/card/
ReactJS-Ant Design
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to fetch data from an API in ReactJS ?
How to redirect to another page in ReactJS ?
Axios in React: A Guide for Beginners
ReactJS Functional Components
ReactJS setState()
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
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": "\n02 Jun, 2021"
},
{
"code": null,
"e": 343,
"s": 28,
"text": "Ant Design Library has this component pre-built, and it is very easy to integrate as well. Card Component is used as a simple rectangular container, and it is used when the user wants to display content related to a single subject. We can use the following approach in ReactJS to use the Ant Design Card Component."
},
{
"code": null,
"e": 355,
"s": 343,
"text": "Card Props:"
},
{
"code": null,
"e": 402,
"s": 355,
"text": "actions: It is used to denote the action list."
},
{
"code": null,
"e": 464,
"s": 402,
"text": "activeTabKey: It is used to denote the current TabPane’s key."
},
{
"code": null,
"e": 543,
"s": 464,
"text": "bodyStyle: It is used to denote the inline style to apply to the card content."
},
{
"code": null,
"e": 619,
"s": 543,
"text": "bordered: It is used to toggle the rendering of the border around the card."
},
{
"code": null,
"e": 663,
"s": 619,
"text": "cover: It is used to denote the Card cover."
},
{
"code": null,
"e": 739,
"s": 663,
"text": "defaultActiveTabKey: It is used to denote the Initial active TabPane’s key."
},
{
"code": null,
"e": 820,
"s": 739,
"text": "extra: It is used for the Content to render in the top-right corner of the card."
},
{
"code": null,
"e": 896,
"s": 820,
"text": "headStyle: It is used to denote the Inline style to apply to the card head."
},
{
"code": null,
"e": 958,
"s": 896,
"text": "hoverable: It is used to Lift up when hovering the card grid."
},
{
"code": null,
"e": 1056,
"s": 958,
"text": "loading: It is used to show a loading indicator while the contents of the card are being fetched."
},
{
"code": null,
"e": 1105,
"s": 1056,
"text": "size: It is used to denote the size of the card."
},
{
"code": null,
"e": 1180,
"s": 1105,
"text": "tabBarExtraContent: It is used to denote the Extra content in the tab bar."
},
{
"code": null,
"e": 1238,
"s": 1180,
"text": "tabList: It is used to denote the List of TabPane’s head."
},
{
"code": null,
"e": 1284,
"s": 1238,
"text": "tabProps: It is used to denote the Tab props."
},
{
"code": null,
"e": 1328,
"s": 1284,
"text": "title: It is used to denote the Card title."
},
{
"code": null,
"e": 1376,
"s": 1328,
"text": "type: It is used to denote the Card style type."
},
{
"code": null,
"e": 1459,
"s": 1376,
"text": "onTabChange: It is a callback function that is triggered when the tab is switched."
},
{
"code": null,
"e": 1476,
"s": 1459,
"text": "Card.Grid Props:"
},
{
"code": null,
"e": 1540,
"s": 1476,
"text": "className: It is used to denote the className of the container."
},
{
"code": null,
"e": 1602,
"s": 1540,
"text": "hoverable: It is used to Lift up when hovering the card grid."
},
{
"code": null,
"e": 1663,
"s": 1602,
"text": "style: It is used to pass the style object of the container."
},
{
"code": null,
"e": 1680,
"s": 1663,
"text": "Card.Meta Props:"
},
{
"code": null,
"e": 1729,
"s": 1680,
"text": "avatar: It is used to denote the Avatar or icon."
},
{
"code": null,
"e": 1793,
"s": 1729,
"text": "className: It is used to denote the className of the container."
},
{
"code": null,
"e": 1852,
"s": 1793,
"text": "description: It is used to denote the description content."
},
{
"code": null,
"e": 1913,
"s": 1852,
"text": "style: It is used to pass the style object of the container."
},
{
"code": null,
"e": 1960,
"s": 1913,
"text": "title: It is used to denote the title content."
},
{
"code": null,
"e": 2012,
"s": 1962,
"text": "Creating React Application And Installing Module:"
},
{
"code": null,
"e": 2107,
"s": 2012,
"text": "Step 1: Create a React application using the following command:npx create-react-app foldername"
},
{
"code": null,
"e": 2171,
"s": 2107,
"text": "Step 1: Create a React application using the following command:"
},
{
"code": null,
"e": 2203,
"s": 2171,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 2316,
"s": 2203,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername"
},
{
"code": null,
"e": 2416,
"s": 2316,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:"
},
{
"code": null,
"e": 2430,
"s": 2416,
"text": "cd foldername"
},
{
"code": null,
"e": 2551,
"s": 2430,
"text": "Step 3: After creating the ReactJS application, Install the required module using the following command:npm install antd"
},
{
"code": null,
"e": 2656,
"s": 2551,
"text": "Step 3: After creating the ReactJS application, Install the required module using the following command:"
},
{
"code": null,
"e": 2673,
"s": 2656,
"text": "npm install antd"
},
{
"code": null,
"e": 2725,
"s": 2673,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 2743,
"s": 2725,
"text": "Project Structure"
},
{
"code": null,
"e": 2873,
"s": 2743,
"text": "Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code."
},
{
"code": null,
"e": 2880,
"s": 2873,
"text": "App.js"
},
{
"code": "import React from 'react'import \"antd/dist/antd.css\";import { Card } from 'antd'; export default function App() { return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>ReactJS Ant-Design Card Component</h4> <> <Card title=\"Card title\" bordered style={{ width: 500, border: '2px solid black' }}> <p>Sample Card Content 1</p> <p>Sample Card Content 2</p> <p>Sample Card Content 3</p> </Card> </> </div> );}",
"e": 3425,
"s": 2880,
"text": null
},
{
"code": null,
"e": 3538,
"s": 3425,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 3548,
"s": 3538,
"text": "npm start"
},
{
"code": null,
"e": 3647,
"s": 3548,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:"
},
{
"code": null,
"e": 3694,
"s": 3647,
"text": "Reference: https://ant.design/components/card/"
},
{
"code": null,
"e": 3713,
"s": 3694,
"text": "ReactJS-Ant Design"
},
{
"code": null,
"e": 3721,
"s": 3713,
"text": "ReactJS"
},
{
"code": null,
"e": 3738,
"s": 3721,
"text": "Web Technologies"
},
{
"code": null,
"e": 3836,
"s": 3738,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3879,
"s": 3836,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 3924,
"s": 3879,
"text": "How to redirect to another page in ReactJS ?"
},
{
"code": null,
"e": 3962,
"s": 3924,
"text": "Axios in React: A Guide for Beginners"
},
{
"code": null,
"e": 3992,
"s": 3962,
"text": "ReactJS Functional Components"
},
{
"code": null,
"e": 4011,
"s": 3992,
"text": "ReactJS setState()"
},
{
"code": null,
"e": 4073,
"s": 4011,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 4106,
"s": 4073,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 4167,
"s": 4106,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 4217,
"s": 4167,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Python script to shows Laptop Battery Percentage
|
29 Aug, 2020
psutil is a cross-platform library for retrieving information on running processes and system utilization(CPU, memory, disks, networks, sensors) in Python. The Python script below can be run in both Windows and Linux. Install psutil in windows by :
pip install psutil
Install psutil in Linux by:
sudo apt-get install gcc python3-dev
sudo pip3 install psutil
Code:
Python
# python script showing battery detailsimport psutil # function returning time in hh:mm:ssdef convertTime(seconds): minutes, seconds = divmod(seconds, 60) hours, minutes = divmod(minutes, 60) return "%d:%02d:%02d" % (hours, minutes, seconds) # returns a tuplebattery = psutil.sensors_battery() print("Battery percentage : ", battery.percent)print("Power plugged in : ", battery.power_plugged) # converting seconds to hh:mm:ssprint("Battery left : ", convertTime(battery.secsleft))
Output:
Battery percentage : 57
Power plugged in : False
Battery left : 1:58:32
Explanation:
psutil.sensors.battery() returns a named tuple consisting of following values. If no battery is installed or metrics can’t be determined None is returned.
percent: Power left in percentage.
secsleft: Approx seconds left before the power runs out. It is set to psutil.POWER_TIME_UNLIMITED if it is on charging. If this value can’t be determined it is set to psutil.POWER_TIME_UNKNOWN .
power_plugged: True if power is plugged in, False if it isn’t charging or None if it can’t be determined.
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n29 Aug, 2020"
},
{
"code": null,
"e": 301,
"s": 52,
"text": "psutil is a cross-platform library for retrieving information on running processes and system utilization(CPU, memory, disks, networks, sensors) in Python. The Python script below can be run in both Windows and Linux. Install psutil in windows by :"
},
{
"code": null,
"e": 321,
"s": 301,
"text": "pip install psutil\n"
},
{
"code": null,
"e": 349,
"s": 321,
"text": "Install psutil in Linux by:"
},
{
"code": null,
"e": 412,
"s": 349,
"text": "sudo apt-get install gcc python3-dev\nsudo pip3 install psutil\n"
},
{
"code": null,
"e": 418,
"s": 412,
"text": "Code:"
},
{
"code": null,
"e": 425,
"s": 418,
"text": "Python"
},
{
"code": "# python script showing battery detailsimport psutil # function returning time in hh:mm:ssdef convertTime(seconds): minutes, seconds = divmod(seconds, 60) hours, minutes = divmod(minutes, 60) return \"%d:%02d:%02d\" % (hours, minutes, seconds) # returns a tuplebattery = psutil.sensors_battery() print(\"Battery percentage : \", battery.percent)print(\"Power plugged in : \", battery.power_plugged) # converting seconds to hh:mm:ssprint(\"Battery left : \", convertTime(battery.secsleft))",
"e": 919,
"s": 425,
"text": null
},
{
"code": null,
"e": 927,
"s": 919,
"text": "Output:"
},
{
"code": null,
"e": 1003,
"s": 927,
"text": "Battery percentage : 57\nPower plugged in : False\nBattery left : 1:58:32\n"
},
{
"code": null,
"e": 1016,
"s": 1003,
"text": "Explanation:"
},
{
"code": null,
"e": 1171,
"s": 1016,
"text": "psutil.sensors.battery() returns a named tuple consisting of following values. If no battery is installed or metrics can’t be determined None is returned."
},
{
"code": null,
"e": 1206,
"s": 1171,
"text": "percent: Power left in percentage."
},
{
"code": null,
"e": 1401,
"s": 1206,
"text": "secsleft: Approx seconds left before the power runs out. It is set to psutil.POWER_TIME_UNLIMITED if it is on charging. If this value can’t be determined it is set to psutil.POWER_TIME_UNKNOWN ."
},
{
"code": null,
"e": 1507,
"s": 1401,
"text": "power_plugged: True if power is plugged in, False if it isn’t charging or None if it can’t be determined."
},
{
"code": null,
"e": 1522,
"s": 1507,
"text": "python-utility"
},
{
"code": null,
"e": 1529,
"s": 1522,
"text": "Python"
}
] |
jQuery | replaceAll() with Examples
|
13 Feb, 2019
The replaceAll() method is an inbuilt method in jQuery which is used to replace selected elements with new HTML elements.
Syntax:
$(content).replaceAll(selector)
Parameters: This method accepts two parameter as mentioned above and described below:
content: It is the required parameter which is used to specify the content to insert.
selector: It is required parameter which specify the elements to be replaced.
Return Value: This method return the selected elements with new content.
Below program illustrates the above function:
Program:
<!DOCTYPE html><html> <head> <title>The replaceAll Method</title> <script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <!-- jQuery code to show the working of this method --> <script> $(document).ready(function() { $("button").click(function() { $("<h1>GeeksforGeeks!</h1>").replaceAll("p"); $("h1").css({"color":"green"}); }); }); </script> <style> div { width: 60%; height: 150px; padding: 10px; border: 2px solid green; font-size: 20px; text-align:center; } p { font-size:25px; font-weight:bold; } </style> </head> <body> <div> <p>Welcome to </p> <!-- click on this button and see the change --> <button>Click Here!</button> <br> </div> </body></html>
Output:
jQuery-HTML/CSS
JavaScript
JQuery
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
JavaScript | Promises
JQuery | Set the value of an input text field
Form validation using jQuery
How to change selected value of a drop-down list using jQuery?
How to add options to a select element using jQuery?
jQuery | children() with Examples
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Feb, 2019"
},
{
"code": null,
"e": 150,
"s": 28,
"text": "The replaceAll() method is an inbuilt method in jQuery which is used to replace selected elements with new HTML elements."
},
{
"code": null,
"e": 158,
"s": 150,
"text": "Syntax:"
},
{
"code": null,
"e": 190,
"s": 158,
"text": "$(content).replaceAll(selector)"
},
{
"code": null,
"e": 276,
"s": 190,
"text": "Parameters: This method accepts two parameter as mentioned above and described below:"
},
{
"code": null,
"e": 362,
"s": 276,
"text": "content: It is the required parameter which is used to specify the content to insert."
},
{
"code": null,
"e": 440,
"s": 362,
"text": "selector: It is required parameter which specify the elements to be replaced."
},
{
"code": null,
"e": 513,
"s": 440,
"text": "Return Value: This method return the selected elements with new content."
},
{
"code": null,
"e": 559,
"s": 513,
"text": "Below program illustrates the above function:"
},
{
"code": null,
"e": 568,
"s": 559,
"text": "Program:"
},
{
"code": "<!DOCTYPE html><html> <head> <title>The replaceAll Method</title> <script src= \"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <!-- jQuery code to show the working of this method --> <script> $(document).ready(function() { $(\"button\").click(function() { $(\"<h1>GeeksforGeeks!</h1>\").replaceAll(\"p\"); $(\"h1\").css({\"color\":\"green\"}); }); }); </script> <style> div { width: 60%; height: 150px; padding: 10px; border: 2px solid green; font-size: 20px; text-align:center; } p { font-size:25px; font-weight:bold; } </style> </head> <body> <div> <p>Welcome to </p> <!-- click on this button and see the change --> <button>Click Here!</button> <br> </div> </body></html>",
"e": 1672,
"s": 568,
"text": null
},
{
"code": null,
"e": 1680,
"s": 1672,
"text": "Output:"
},
{
"code": null,
"e": 1696,
"s": 1680,
"text": "jQuery-HTML/CSS"
},
{
"code": null,
"e": 1707,
"s": 1696,
"text": "JavaScript"
},
{
"code": null,
"e": 1714,
"s": 1707,
"text": "JQuery"
},
{
"code": null,
"e": 1812,
"s": 1714,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1873,
"s": 1812,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1913,
"s": 1873,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 1954,
"s": 1913,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 1996,
"s": 1954,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 2018,
"s": 1996,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 2064,
"s": 2018,
"text": "JQuery | Set the value of an input text field"
},
{
"code": null,
"e": 2093,
"s": 2064,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 2156,
"s": 2093,
"text": "How to change selected value of a drop-down list using jQuery?"
},
{
"code": null,
"e": 2209,
"s": 2156,
"text": "How to add options to a select element using jQuery?"
}
] |
Database Connectivity using C/C++
|
29 Jun, 2022
SQL (Structured Query Language) is a fourth-generation language (4GL) that is used to define, manipulate, and control an RDBMS (relational database management system).
Before starting the main article, let us get familiar with the used tools.
Compiler: Code::Blocks IDE with MinGW compiler
Download Link: Binary Download Code::Blocks is a cross compiler (It can run on any platform like Windows, Linux and Mac) and it is free to download. This IDE is specially designed for C and C++ and easy to use.
API: We are going to use SQLAPI++ Library
Download Link: SQLAPI Download
SQLAPI++ is a C++ library (basically a set of header files) for accessing multiple SQL databases (Oracle, SQL Server, DB2, Sybase, Informix, InterBase, SQLBase, MySQL, PostgreSQL, SQLite, SQL Anywhere and ODBC). It is easy to implement and simple.
OCCI: Oracle C++ Call Interface
Download Link: OCCI C++ Download OCCI is an interface defined by the database company ORACLE that defines a comfortable interfacefor the C++ programmer to access the Oracle database with classes using parameters that are reminiscent of SQL statements. The interface exists for ORACLE 9i, ORACLE 10 and comes with the Oracle.
We must download and install the above three (if we don’t have them). Now we are almost ready to start.
Some settings before starting: -> Open the code::blocks IDE and go to or click on settings -> compiler and debugger settings (You will now see global compiler settings) -> Now click on “Linker settings” in the linker settings click on ADD button and add the following For Windows OS : Code: C:\SQLAPI\lib\libsqlapiddll.a C:\Program Files\CodeBlocks\MinGW\lib\libuser32.a C:\Program Files\CodeBlocks\MinGW\lib\libversion.a C:\Program Files\CodeBlocks\MinGW\lib\liboleaut32.a C:\Program Files\CodeBlocks\MinGW\lib\libole32.a These will be found in your SQLAPI++ (If you have not extracted in C: drive then select the appropriate location and add the mentioned files to linker settings). The above code is used to add library files to connect C/C++ program with SQLAPI. Basically, there are 2 steps:
Connecting to database (and error handling) Code:
Connecting to database (and error handling) Code:
C
// C++ program for connecting to database (and error handling)#include<stdio.h>#include<SQLAPI.h> // main SQLAPI++ header int main(int argc, char* argv[]){ // create connection object to connect to database SAConnection con; try { // connect to database // in this example, it is Oracle, // but can also be Sybase, Informix, DB2 // SQLServer, InterBase, SQLBase and ODBC con.Connect ("test", // database name "tester", // user name "tester", // password SA_Oracle_Client); //Oracle Client printf("We are connected!\n"); // Disconnect is optional // autodisconnect will occur in destructor if needed con.Disconnect(); printf("We are disconnected!\n"); } catch(SAException & x) { // SAConnection::Rollback() // can also throw an exception // (if a network error for example), // we will be ready try { // on error rollback changes con.Rollback (); } catch(SAException &) { } // print error message printf("%s\n", (const char*)x.ErrText()); } return 0;}
Output:
Output:
We are Connected!
We are Disconnected!
Executing a simple SQL Command Now, we will look out to execute a simple SQL query.Firstly, creating a table for the database: create table tb1(id number, name varchar(20);
Executing a simple SQL Command Now, we will look out to execute a simple SQL query.Firstly, creating a table for the database: create table tb1(id number, name varchar(20);
Now, establish the connection to the database then, after your con.connect; method you should use cmd.setCommandText method to pass the query to the database, it is as shown below:
con.Connect("test", "tester", "tester", SA_Oracle_Client);
cmd.setCommandText("create table tb1(id number, name varchar(20));”);
and now, to execute the query we have to use the following command: cmd.Execute(); Full Code:
and now, to execute the query we have to use the following command: cmd.Execute(); Full Code:
C
#include<stdio.h>#include <SQLAPI.h> // main SQLAPI++ headerint main(int argc, char* argv[]){ SAConnection con; // connection object to connect to database SACommandcmd; // create command object try { // connect to database (Oracle in our example) con.Connect("test", "tester", "tester", SA_Oracle_Client); // associate a command with connection // connection can also be specified in SACommand constructor cmd.setConnection(&con); // create table cmd.setCommandText("create table tbl(id number, name varchar(20));"); cmd.Execute(); // insert value cmd.setCommandText("Insert into tbl(id, name) values (1,”Vinay”)"); cmd.setCommandText("Insert into tbl(id, name) values (2,”Kushal”)"); cmd.setCommandText("Insert into tbl(id, name) values (3,”Saransh”)"); cmd.Execute(); // commit changes on success con.Commit(); printf("Table created, row inserted!\n"); } catch(SAException &x) { // SAConnection::Rollback() // can also throw an exception // (if a network error for example), // we will be ready try { // on error rollback changes con.Rollback(); } catch(SAException &) { } // print error message printf("%s\n", (const char*)x.ErrText()); } return 0;}
As we know, Oracle is not auto committed (committing is making permanent reflection of data in the database) so, we have to commit it.
con.Commit();
and similarly we can roll back the transactions when an exception occurs, so to do that we use:
con.Rollback();
For deleting a row, we use this command.
cmd.setCommandText("delete from tb1 where id= 2");
Thus, by the end of this article, we have learned how to connect your C/C++ program to database and perform manipulations.
This article is contributed by Vinay Garg. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
surinderdawra388
CPP-Library
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Function Pointer in C
Different Methods to Reverse a String in C++
std::string class in C++
Unordered Sets in C++ Standard Template Library
Vector in C++ STL
Map in C++ Standard Template Library (STL)
Initialize a vector in C++ (7 different ways)
Set in C++ Standard Template Library (STL)
Priority Queue in C++ Standard Template Library (STL)
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n29 Jun, 2022"
},
{
"code": null,
"e": 220,
"s": 52,
"text": "SQL (Structured Query Language) is a fourth-generation language (4GL) that is used to define, manipulate, and control an RDBMS (relational database management system)."
},
{
"code": null,
"e": 295,
"s": 220,
"text": "Before starting the main article, let us get familiar with the used tools."
},
{
"code": null,
"e": 342,
"s": 295,
"text": "Compiler: Code::Blocks IDE with MinGW compiler"
},
{
"code": null,
"e": 553,
"s": 342,
"text": "Download Link: Binary Download Code::Blocks is a cross compiler (It can run on any platform like Windows, Linux and Mac) and it is free to download. This IDE is specially designed for C and C++ and easy to use."
},
{
"code": null,
"e": 595,
"s": 553,
"text": "API: We are going to use SQLAPI++ Library"
},
{
"code": null,
"e": 626,
"s": 595,
"text": "Download Link: SQLAPI Download"
},
{
"code": null,
"e": 874,
"s": 626,
"text": "SQLAPI++ is a C++ library (basically a set of header files) for accessing multiple SQL databases (Oracle, SQL Server, DB2, Sybase, Informix, InterBase, SQLBase, MySQL, PostgreSQL, SQLite, SQL Anywhere and ODBC). It is easy to implement and simple."
},
{
"code": null,
"e": 906,
"s": 874,
"text": "OCCI: Oracle C++ Call Interface"
},
{
"code": null,
"e": 1232,
"s": 906,
"text": "Download Link: OCCI C++ Download OCCI is an interface defined by the database company ORACLE that defines a comfortable interfacefor the C++ programmer to access the Oracle database with classes using parameters that are reminiscent of SQL statements. The interface exists for ORACLE 9i, ORACLE 10 and comes with the Oracle."
},
{
"code": null,
"e": 1336,
"s": 1232,
"text": "We must download and install the above three (if we don’t have them). Now we are almost ready to start."
},
{
"code": null,
"e": 2135,
"s": 1336,
"text": " Some settings before starting: -> Open the code::blocks IDE and go to or click on settings -> compiler and debugger settings (You will now see global compiler settings) -> Now click on “Linker settings” in the linker settings click on ADD button and add the following For Windows OS : Code: C:\\SQLAPI\\lib\\libsqlapiddll.a C:\\Program Files\\CodeBlocks\\MinGW\\lib\\libuser32.a C:\\Program Files\\CodeBlocks\\MinGW\\lib\\libversion.a C:\\Program Files\\CodeBlocks\\MinGW\\lib\\liboleaut32.a C:\\Program Files\\CodeBlocks\\MinGW\\lib\\libole32.a These will be found in your SQLAPI++ (If you have not extracted in C: drive then select the appropriate location and add the mentioned files to linker settings). The above code is used to add library files to connect C/C++ program with SQLAPI. Basically, there are 2 steps:"
},
{
"code": null,
"e": 2186,
"s": 2135,
"text": "Connecting to database (and error handling) Code: "
},
{
"code": null,
"e": 2237,
"s": 2186,
"text": "Connecting to database (and error handling) Code: "
},
{
"code": null,
"e": 2239,
"s": 2237,
"text": "C"
},
{
"code": "// C++ program for connecting to database (and error handling)#include<stdio.h>#include<SQLAPI.h> // main SQLAPI++ header int main(int argc, char* argv[]){ // create connection object to connect to database SAConnection con; try { // connect to database // in this example, it is Oracle, // but can also be Sybase, Informix, DB2 // SQLServer, InterBase, SQLBase and ODBC con.Connect (\"test\", // database name \"tester\", // user name \"tester\", // password SA_Oracle_Client); //Oracle Client printf(\"We are connected!\\n\"); // Disconnect is optional // autodisconnect will occur in destructor if needed con.Disconnect(); printf(\"We are disconnected!\\n\"); } catch(SAException & x) { // SAConnection::Rollback() // can also throw an exception // (if a network error for example), // we will be ready try { // on error rollback changes con.Rollback (); } catch(SAException &) { } // print error message printf(\"%s\\n\", (const char*)x.ErrText()); } return 0;}",
"e": 3471,
"s": 2239,
"text": null
},
{
"code": null,
"e": 3479,
"s": 3471,
"text": "Output:"
},
{
"code": null,
"e": 3487,
"s": 3479,
"text": "Output:"
},
{
"code": null,
"e": 3526,
"s": 3487,
"text": "We are Connected!\nWe are Disconnected!"
},
{
"code": null,
"e": 3699,
"s": 3526,
"text": "Executing a simple SQL Command Now, we will look out to execute a simple SQL query.Firstly, creating a table for the database: create table tb1(id number, name varchar(20);"
},
{
"code": null,
"e": 3872,
"s": 3699,
"text": "Executing a simple SQL Command Now, we will look out to execute a simple SQL query.Firstly, creating a table for the database: create table tb1(id number, name varchar(20);"
},
{
"code": null,
"e": 4053,
"s": 3872,
"text": "Now, establish the connection to the database then, after your con.connect; method you should use cmd.setCommandText method to pass the query to the database, it is as shown below:"
},
{
"code": null,
"e": 4182,
"s": 4053,
"text": "con.Connect(\"test\", \"tester\", \"tester\", SA_Oracle_Client);\ncmd.setCommandText(\"create table tb1(id number, name varchar(20));”);"
},
{
"code": null,
"e": 4277,
"s": 4182,
"text": "and now, to execute the query we have to use the following command: cmd.Execute(); Full Code: "
},
{
"code": null,
"e": 4372,
"s": 4277,
"text": "and now, to execute the query we have to use the following command: cmd.Execute(); Full Code: "
},
{
"code": null,
"e": 4374,
"s": 4372,
"text": "C"
},
{
"code": "#include<stdio.h>#include <SQLAPI.h> // main SQLAPI++ headerint main(int argc, char* argv[]){ SAConnection con; // connection object to connect to database SACommandcmd; // create command object try { // connect to database (Oracle in our example) con.Connect(\"test\", \"tester\", \"tester\", SA_Oracle_Client); // associate a command with connection // connection can also be specified in SACommand constructor cmd.setConnection(&con); // create table cmd.setCommandText(\"create table tbl(id number, name varchar(20));\"); cmd.Execute(); // insert value cmd.setCommandText(\"Insert into tbl(id, name) values (1,”Vinay”)\"); cmd.setCommandText(\"Insert into tbl(id, name) values (2,”Kushal”)\"); cmd.setCommandText(\"Insert into tbl(id, name) values (3,”Saransh”)\"); cmd.Execute(); // commit changes on success con.Commit(); printf(\"Table created, row inserted!\\n\"); } catch(SAException &x) { // SAConnection::Rollback() // can also throw an exception // (if a network error for example), // we will be ready try { // on error rollback changes con.Rollback(); } catch(SAException &) { } // print error message printf(\"%s\\n\", (const char*)x.ErrText()); } return 0;}",
"e": 5788,
"s": 4374,
"text": null
},
{
"code": null,
"e": 5923,
"s": 5788,
"text": "As we know, Oracle is not auto committed (committing is making permanent reflection of data in the database) so, we have to commit it."
},
{
"code": null,
"e": 5937,
"s": 5923,
"text": "con.Commit();"
},
{
"code": null,
"e": 6033,
"s": 5937,
"text": "and similarly we can roll back the transactions when an exception occurs, so to do that we use:"
},
{
"code": null,
"e": 6049,
"s": 6033,
"text": "con.Rollback();"
},
{
"code": null,
"e": 6090,
"s": 6049,
"text": "For deleting a row, we use this command."
},
{
"code": null,
"e": 6141,
"s": 6090,
"text": "cmd.setCommandText(\"delete from tb1 where id= 2\");"
},
{
"code": null,
"e": 6264,
"s": 6141,
"text": "Thus, by the end of this article, we have learned how to connect your C/C++ program to database and perform manipulations."
},
{
"code": null,
"e": 6529,
"s": 6264,
"text": "This article is contributed by Vinay Garg. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 6653,
"s": 6529,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above"
},
{
"code": null,
"e": 6670,
"s": 6653,
"text": "surinderdawra388"
},
{
"code": null,
"e": 6682,
"s": 6670,
"text": "CPP-Library"
},
{
"code": null,
"e": 6693,
"s": 6682,
"text": "C Language"
},
{
"code": null,
"e": 6697,
"s": 6693,
"text": "C++"
},
{
"code": null,
"e": 6701,
"s": 6697,
"text": "CPP"
},
{
"code": null,
"e": 6799,
"s": 6701,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6816,
"s": 6799,
"text": "Substring in C++"
},
{
"code": null,
"e": 6838,
"s": 6816,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 6883,
"s": 6838,
"text": "Different Methods to Reverse a String in C++"
},
{
"code": null,
"e": 6908,
"s": 6883,
"text": "std::string class in C++"
},
{
"code": null,
"e": 6956,
"s": 6908,
"text": "Unordered Sets in C++ Standard Template Library"
},
{
"code": null,
"e": 6974,
"s": 6956,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 7017,
"s": 6974,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 7063,
"s": 7017,
"text": "Initialize a vector in C++ (7 different ways)"
},
{
"code": null,
"e": 7106,
"s": 7063,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
What, Why and How of t-SNE. Dimensionality Reduction using t-SNE in... | by Ramya Vidiyala | Towards Data Science
|
Imagine the data we create in a single day; the news generated, posts, videos, images on social media platforms, messages on communication channels, websites which help business and many more... Huge! Right?
Now, imagine the task of analyzing this humongous data and obtaining useful insights to make data-driven decisions. Complex! Right?
What we can do about this problem is that we can remove redundant information and analyze only the high impact information.Dimensionality reduction comes into the picture at this very initial stage of any data analysis or data visualization.
Dimensionality Reduction means projecting data to a lower-dimensional space, which makes it easier for analyzing and visualizing data. However, the reduction of dimension requires a trade-off between accuracy (high dimensions) and interpretability (low dimensions).
But the key here is to retain maximum variance features and eliminate redundant features.
In this article, we will be focussing on the why, what, how, and also what not of t-SNE for Dimensionality Reduction.
Here is the flow of discussion:
Why not PCA? Why t-SNE?What’s t-SNE?How does t-SNE work?How to implement t-SNE?How to effectively use tSNE?
Why not PCA? Why t-SNE?
What’s t-SNE?
How does t-SNE work?
How to implement t-SNE?
How to effectively use tSNE?
When it comes to Dimensionality Reduction, PCA is famous because it is simple, fast, easy to use, and retains the overall variance of the dataset. For more about PCA at a glance, check this.
Though PCA is great, it does have some drawbacks. One of the major drawbacks of PCA is that it does not retain non-linear variance. This means PCA will not be able to get results for figures like this.
In simple terms, PCA works on retaining only global variance, and thus retaining local variance was the motivation behind t-SNE.
t-SNE is a nonlinear dimensionality reduction technique that is well suited for embedding high dimension data into lower dimensional data (2D or 3D) for data visualization.
t-SNE stands for t-distributed Stochastic Neighbor Embedding, which tells the following : Stochastic → not definite but random probability Neighbor →concerned only about retaining the variance of neighbor pointsEmbedding → plotting data into lower dimensions
In short, t-SNE is a machine learning algorithm that generates slightly different results each time on the same data set, focusing on retaining the structure of neighbor points.
2 parameters that can highly influence the results are a) n_iter: The number of iterations that the algorithm runs b) perplexity: This can be thought of as the number of neighboring points t-SNE must consider
Step 1: t-SNE constructs a probability distribution on pairs in higher dimensions such that similar objects are assigned a higher probability and dissimilar objects are assigned lower probability.
Step 2: Then, t-SNE replicates the same probability distribution on lower dimensions iteratively till the Kullback-Leibler divergence is minimized.
Kullback-Leibler divergence is a measure of the difference between the probability distributions from Step1 and Step2. KL divergence is mathematically given as the expected value of the logarithm of the difference of these probability distributions.
In this section, let us use Digit Recognizer data set from Kaggle for Dimensionality Reduction using t-SNE.
www.kaggle.com
Data Description:
The data file contains grey-scale images of hand-drawn digits, from zero through nine.
Each image is 28 pixels in height and 28 pixels in width, for a total of 784 pixels in total. Each pixel has a single pixel-value associated with it, indicating the lightness or darkness of that pixel, with higher numbers meaning darker. This pixel-value is an integer between 0 and 255, inclusive.
The training data set, (train.csv), has 785 columns. The first column, called “label”, is the digit that was drawn by the user. The rest of the columns contain the pixel-values of the associated image.Each pixel column in the data set has a name like pixelx, where x is an integer between 0 and 783, inclusive. To locate this pixel on the image, suppose that we have decomposed x as x = i * 28 + j, where i and j are integers between 0 and 27, inclusive. Then pixelx is located on row i and column j of a 28 x 28 matrix, (indexing by zero).
Loading the data :
import pandas as pdmnist_data = pd.read_csv("mnist.csv")
The data file which is in CSV format (Comma Separated Value) is loaded into the data frame using Pandas.
mnist_data.shape
Output : (42000, 785)
Looking at the data, we observe that there are 42,000 data points and 785 features.
mnist_data.head()
Output:
The first column label is the target variable. And the remaining 784 columns are the features.
target_variable = mnist_data["label"]features_variable=mnist_data.drop("label",axis=1)
Assigning target_variable with label column and features_variable with the remaining columns.
print(target_variable.shape)print(features_variable.shape)
Output: (42000,)(42000, 784)
Now, let us see how this features_variable of dimensions 42000 data points and 784 features are reduced using t-SNE.
Implementing Dimensionality Reduction using t-SNE:
STEP 1: Standardization of data
from sklearn.preprocessing import StandardScalerstandarized_data = StandardScaler().fit_transform(features_variable)
Using StandardScaler( ).fit_transform( ), data can be Standarized in a single step.
STEP 2: Application of t-SNE on standardized data
from sklearn.manifold import TSNEmodel = TSNE(n_components=2, random_state=0,perplexity=50, n_iter=5000)tsne_data = model.fit_transform(standarized_data)
Here, we are creating an object of TSNE, and setting perplexity and n_iter values. We have used the fit_transform( ) method on the standardized data to get dimensionally reduced data using t-SNE.
To check that, let us just print the shape of tsne_data
print(standarized_data.shape)print(tsne_data.shape)
Output: (42000, 784)(42000,2)
We can now play along with various perplexity and n_iter to observe the results.
t-SNE plots are highly influenced by parameters. Thus it is necessary to perform t-SNE using different parameter values before analyzing results.Since t-SNE is stochastic, each run may lead to slightly different output. This can be solved by fixing the value of random_state parameter for all the runs.t-SNE doesn’t retain the distance between clusters from the raw data. Distance between clusters might vary post dimensionality reduction in t-SNE. It is recommended not to obtain any conclusions solely from the distance between the clusters.t-SNE shrinks widespread data and expands densely packed data. It is hence suggested not to decide the size and density/spread/variance of the clusters based on the output.Lower perplexity values might result in fewer clusters. It is hence recommended to try various perplexity values ranging from 2 to the number of data points to obtain better results.
t-SNE plots are highly influenced by parameters. Thus it is necessary to perform t-SNE using different parameter values before analyzing results.
Since t-SNE is stochastic, each run may lead to slightly different output. This can be solved by fixing the value of random_state parameter for all the runs.
t-SNE doesn’t retain the distance between clusters from the raw data. Distance between clusters might vary post dimensionality reduction in t-SNE. It is recommended not to obtain any conclusions solely from the distance between the clusters.
t-SNE shrinks widespread data and expands densely packed data. It is hence suggested not to decide the size and density/spread/variance of the clusters based on the output.
Lower perplexity values might result in fewer clusters. It is hence recommended to try various perplexity values ranging from 2 to the number of data points to obtain better results.
Resources :
This blog post by distill.pub made with the support of Google Brain. Do check this blog for more insights about how t-SNE effectively helps in reducing various data patterns for visualization.
Thanks for the read. I am going to write more beginner-friendly posts in the future. Follow me up on Medium to be informed about them. I welcome feedback and can be reached out on Twitter ramya_vidiyala and LinkedIn RamyaVidiyala. Happy learning!
|
[
{
"code": null,
"e": 380,
"s": 172,
"text": "Imagine the data we create in a single day; the news generated, posts, videos, images on social media platforms, messages on communication channels, websites which help business and many more... Huge! Right?"
},
{
"code": null,
"e": 512,
"s": 380,
"text": "Now, imagine the task of analyzing this humongous data and obtaining useful insights to make data-driven decisions. Complex! Right?"
},
{
"code": null,
"e": 754,
"s": 512,
"text": "What we can do about this problem is that we can remove redundant information and analyze only the high impact information.Dimensionality reduction comes into the picture at this very initial stage of any data analysis or data visualization."
},
{
"code": null,
"e": 1020,
"s": 754,
"text": "Dimensionality Reduction means projecting data to a lower-dimensional space, which makes it easier for analyzing and visualizing data. However, the reduction of dimension requires a trade-off between accuracy (high dimensions) and interpretability (low dimensions)."
},
{
"code": null,
"e": 1110,
"s": 1020,
"text": "But the key here is to retain maximum variance features and eliminate redundant features."
},
{
"code": null,
"e": 1228,
"s": 1110,
"text": "In this article, we will be focussing on the why, what, how, and also what not of t-SNE for Dimensionality Reduction."
},
{
"code": null,
"e": 1260,
"s": 1228,
"text": "Here is the flow of discussion:"
},
{
"code": null,
"e": 1368,
"s": 1260,
"text": "Why not PCA? Why t-SNE?What’s t-SNE?How does t-SNE work?How to implement t-SNE?How to effectively use tSNE?"
},
{
"code": null,
"e": 1392,
"s": 1368,
"text": "Why not PCA? Why t-SNE?"
},
{
"code": null,
"e": 1406,
"s": 1392,
"text": "What’s t-SNE?"
},
{
"code": null,
"e": 1427,
"s": 1406,
"text": "How does t-SNE work?"
},
{
"code": null,
"e": 1451,
"s": 1427,
"text": "How to implement t-SNE?"
},
{
"code": null,
"e": 1480,
"s": 1451,
"text": "How to effectively use tSNE?"
},
{
"code": null,
"e": 1671,
"s": 1480,
"text": "When it comes to Dimensionality Reduction, PCA is famous because it is simple, fast, easy to use, and retains the overall variance of the dataset. For more about PCA at a glance, check this."
},
{
"code": null,
"e": 1873,
"s": 1671,
"text": "Though PCA is great, it does have some drawbacks. One of the major drawbacks of PCA is that it does not retain non-linear variance. This means PCA will not be able to get results for figures like this."
},
{
"code": null,
"e": 2002,
"s": 1873,
"text": "In simple terms, PCA works on retaining only global variance, and thus retaining local variance was the motivation behind t-SNE."
},
{
"code": null,
"e": 2175,
"s": 2002,
"text": "t-SNE is a nonlinear dimensionality reduction technique that is well suited for embedding high dimension data into lower dimensional data (2D or 3D) for data visualization."
},
{
"code": null,
"e": 2434,
"s": 2175,
"text": "t-SNE stands for t-distributed Stochastic Neighbor Embedding, which tells the following : Stochastic → not definite but random probability Neighbor →concerned only about retaining the variance of neighbor pointsEmbedding → plotting data into lower dimensions"
},
{
"code": null,
"e": 2612,
"s": 2434,
"text": "In short, t-SNE is a machine learning algorithm that generates slightly different results each time on the same data set, focusing on retaining the structure of neighbor points."
},
{
"code": null,
"e": 2821,
"s": 2612,
"text": "2 parameters that can highly influence the results are a) n_iter: The number of iterations that the algorithm runs b) perplexity: This can be thought of as the number of neighboring points t-SNE must consider"
},
{
"code": null,
"e": 3018,
"s": 2821,
"text": "Step 1: t-SNE constructs a probability distribution on pairs in higher dimensions such that similar objects are assigned a higher probability and dissimilar objects are assigned lower probability."
},
{
"code": null,
"e": 3166,
"s": 3018,
"text": "Step 2: Then, t-SNE replicates the same probability distribution on lower dimensions iteratively till the Kullback-Leibler divergence is minimized."
},
{
"code": null,
"e": 3416,
"s": 3166,
"text": "Kullback-Leibler divergence is a measure of the difference between the probability distributions from Step1 and Step2. KL divergence is mathematically given as the expected value of the logarithm of the difference of these probability distributions."
},
{
"code": null,
"e": 3524,
"s": 3416,
"text": "In this section, let us use Digit Recognizer data set from Kaggle for Dimensionality Reduction using t-SNE."
},
{
"code": null,
"e": 3539,
"s": 3524,
"text": "www.kaggle.com"
},
{
"code": null,
"e": 3557,
"s": 3539,
"text": "Data Description:"
},
{
"code": null,
"e": 3644,
"s": 3557,
"text": "The data file contains grey-scale images of hand-drawn digits, from zero through nine."
},
{
"code": null,
"e": 3943,
"s": 3644,
"text": "Each image is 28 pixels in height and 28 pixels in width, for a total of 784 pixels in total. Each pixel has a single pixel-value associated with it, indicating the lightness or darkness of that pixel, with higher numbers meaning darker. This pixel-value is an integer between 0 and 255, inclusive."
},
{
"code": null,
"e": 4484,
"s": 3943,
"text": "The training data set, (train.csv), has 785 columns. The first column, called “label”, is the digit that was drawn by the user. The rest of the columns contain the pixel-values of the associated image.Each pixel column in the data set has a name like pixelx, where x is an integer between 0 and 783, inclusive. To locate this pixel on the image, suppose that we have decomposed x as x = i * 28 + j, where i and j are integers between 0 and 27, inclusive. Then pixelx is located on row i and column j of a 28 x 28 matrix, (indexing by zero)."
},
{
"code": null,
"e": 4503,
"s": 4484,
"text": "Loading the data :"
},
{
"code": null,
"e": 4560,
"s": 4503,
"text": "import pandas as pdmnist_data = pd.read_csv(\"mnist.csv\")"
},
{
"code": null,
"e": 4665,
"s": 4560,
"text": "The data file which is in CSV format (Comma Separated Value) is loaded into the data frame using Pandas."
},
{
"code": null,
"e": 4682,
"s": 4665,
"text": "mnist_data.shape"
},
{
"code": null,
"e": 4704,
"s": 4682,
"text": "Output : (42000, 785)"
},
{
"code": null,
"e": 4788,
"s": 4704,
"text": "Looking at the data, we observe that there are 42,000 data points and 785 features."
},
{
"code": null,
"e": 4806,
"s": 4788,
"text": "mnist_data.head()"
},
{
"code": null,
"e": 4814,
"s": 4806,
"text": "Output:"
},
{
"code": null,
"e": 4909,
"s": 4814,
"text": "The first column label is the target variable. And the remaining 784 columns are the features."
},
{
"code": null,
"e": 4996,
"s": 4909,
"text": "target_variable = mnist_data[\"label\"]features_variable=mnist_data.drop(\"label\",axis=1)"
},
{
"code": null,
"e": 5090,
"s": 4996,
"text": "Assigning target_variable with label column and features_variable with the remaining columns."
},
{
"code": null,
"e": 5149,
"s": 5090,
"text": "print(target_variable.shape)print(features_variable.shape)"
},
{
"code": null,
"e": 5178,
"s": 5149,
"text": "Output: (42000,)(42000, 784)"
},
{
"code": null,
"e": 5295,
"s": 5178,
"text": "Now, let us see how this features_variable of dimensions 42000 data points and 784 features are reduced using t-SNE."
},
{
"code": null,
"e": 5346,
"s": 5295,
"text": "Implementing Dimensionality Reduction using t-SNE:"
},
{
"code": null,
"e": 5378,
"s": 5346,
"text": "STEP 1: Standardization of data"
},
{
"code": null,
"e": 5495,
"s": 5378,
"text": "from sklearn.preprocessing import StandardScalerstandarized_data = StandardScaler().fit_transform(features_variable)"
},
{
"code": null,
"e": 5579,
"s": 5495,
"text": "Using StandardScaler( ).fit_transform( ), data can be Standarized in a single step."
},
{
"code": null,
"e": 5629,
"s": 5579,
"text": "STEP 2: Application of t-SNE on standardized data"
},
{
"code": null,
"e": 5783,
"s": 5629,
"text": "from sklearn.manifold import TSNEmodel = TSNE(n_components=2, random_state=0,perplexity=50, n_iter=5000)tsne_data = model.fit_transform(standarized_data)"
},
{
"code": null,
"e": 5979,
"s": 5783,
"text": "Here, we are creating an object of TSNE, and setting perplexity and n_iter values. We have used the fit_transform( ) method on the standardized data to get dimensionally reduced data using t-SNE."
},
{
"code": null,
"e": 6035,
"s": 5979,
"text": "To check that, let us just print the shape of tsne_data"
},
{
"code": null,
"e": 6087,
"s": 6035,
"text": "print(standarized_data.shape)print(tsne_data.shape)"
},
{
"code": null,
"e": 6117,
"s": 6087,
"text": "Output: (42000, 784)(42000,2)"
},
{
"code": null,
"e": 6198,
"s": 6117,
"text": "We can now play along with various perplexity and n_iter to observe the results."
},
{
"code": null,
"e": 7096,
"s": 6198,
"text": "t-SNE plots are highly influenced by parameters. Thus it is necessary to perform t-SNE using different parameter values before analyzing results.Since t-SNE is stochastic, each run may lead to slightly different output. This can be solved by fixing the value of random_state parameter for all the runs.t-SNE doesn’t retain the distance between clusters from the raw data. Distance between clusters might vary post dimensionality reduction in t-SNE. It is recommended not to obtain any conclusions solely from the distance between the clusters.t-SNE shrinks widespread data and expands densely packed data. It is hence suggested not to decide the size and density/spread/variance of the clusters based on the output.Lower perplexity values might result in fewer clusters. It is hence recommended to try various perplexity values ranging from 2 to the number of data points to obtain better results."
},
{
"code": null,
"e": 7242,
"s": 7096,
"text": "t-SNE plots are highly influenced by parameters. Thus it is necessary to perform t-SNE using different parameter values before analyzing results."
},
{
"code": null,
"e": 7400,
"s": 7242,
"text": "Since t-SNE is stochastic, each run may lead to slightly different output. This can be solved by fixing the value of random_state parameter for all the runs."
},
{
"code": null,
"e": 7642,
"s": 7400,
"text": "t-SNE doesn’t retain the distance between clusters from the raw data. Distance between clusters might vary post dimensionality reduction in t-SNE. It is recommended not to obtain any conclusions solely from the distance between the clusters."
},
{
"code": null,
"e": 7815,
"s": 7642,
"text": "t-SNE shrinks widespread data and expands densely packed data. It is hence suggested not to decide the size and density/spread/variance of the clusters based on the output."
},
{
"code": null,
"e": 7998,
"s": 7815,
"text": "Lower perplexity values might result in fewer clusters. It is hence recommended to try various perplexity values ranging from 2 to the number of data points to obtain better results."
},
{
"code": null,
"e": 8010,
"s": 7998,
"text": "Resources :"
},
{
"code": null,
"e": 8203,
"s": 8010,
"text": "This blog post by distill.pub made with the support of Google Brain. Do check this blog for more insights about how t-SNE effectively helps in reducing various data patterns for visualization."
}
] |
How to flip an image on hover using CSS ? - GeeksforGeeks
|
29 Jun, 2020
In this article, you will learn how to flip an image (add mirror effect), both horizontally and vertically when the mouse has hovered over it. This can be done by applying the transformation to the image as shown in the following example:
Example 1: This example represents how to flip image horizontally by transforming it along the X-axis using transform: scaleX(-1) property.
<!DOCTYPE html><html> <head> <style> img:hover{ transform: scaleX(-1); } </style></head> <body> <h2>GeeksforGeeks</h2> <img src="gfg.jpg" width="50%"></body> </html>
Output:
Example 2: This example represents how to flip image vertically by transforming it along the Y-axis using transform: scaleY(-1) property.
<!DOCTYPE html><html> <head> <style> img:hover{ transform: scaleY(-1); } </style></head> <body> <h2>GeeksforGeeks</h2> <img src="gfg.jpg" width="50%"></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.
CSS-Misc
HTML-Misc
CSS
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to create footer to stay at the bottom of a Web page?
Types of CSS (Cascading Style Sheet)
Create a Responsive Navbar using ReactJS
Design a web page using HTML and CSS
How to position a div at the bottom of its container using CSS?
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Types of CSS (Cascading Style Sheet)
Hide or show elements in HTML using display property
How to Insert Form Data into Database using PHP ?
|
[
{
"code": null,
"e": 24495,
"s": 24467,
"text": "\n29 Jun, 2020"
},
{
"code": null,
"e": 24734,
"s": 24495,
"text": "In this article, you will learn how to flip an image (add mirror effect), both horizontally and vertically when the mouse has hovered over it. This can be done by applying the transformation to the image as shown in the following example:"
},
{
"code": null,
"e": 24874,
"s": 24734,
"text": "Example 1: This example represents how to flip image horizontally by transforming it along the X-axis using transform: scaleX(-1) property."
},
{
"code": "<!DOCTYPE html><html> <head> <style> img:hover{ transform: scaleX(-1); } </style></head> <body> <h2>GeeksforGeeks</h2> <img src=\"gfg.jpg\" width=\"50%\"></body> </html>",
"e": 25080,
"s": 24874,
"text": null
},
{
"code": null,
"e": 25088,
"s": 25080,
"text": "Output:"
},
{
"code": null,
"e": 25226,
"s": 25088,
"text": "Example 2: This example represents how to flip image vertically by transforming it along the Y-axis using transform: scaleY(-1) property."
},
{
"code": "<!DOCTYPE html><html> <head> <style> img:hover{ transform: scaleY(-1); } </style></head> <body> <h2>GeeksforGeeks</h2> <img src=\"gfg.jpg\" width=\"50%\"></body> </html>",
"e": 25432,
"s": 25226,
"text": null
},
{
"code": null,
"e": 25440,
"s": 25432,
"text": "Output:"
},
{
"code": null,
"e": 25577,
"s": 25440,
"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": 25586,
"s": 25577,
"text": "CSS-Misc"
},
{
"code": null,
"e": 25596,
"s": 25586,
"text": "HTML-Misc"
},
{
"code": null,
"e": 25600,
"s": 25596,
"text": "CSS"
},
{
"code": null,
"e": 25605,
"s": 25600,
"text": "HTML"
},
{
"code": null,
"e": 25622,
"s": 25605,
"text": "Web Technologies"
},
{
"code": null,
"e": 25649,
"s": 25622,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 25654,
"s": 25649,
"text": "HTML"
},
{
"code": null,
"e": 25752,
"s": 25654,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25761,
"s": 25752,
"text": "Comments"
},
{
"code": null,
"e": 25774,
"s": 25761,
"text": "Old Comments"
},
{
"code": null,
"e": 25832,
"s": 25774,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 25869,
"s": 25832,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 25910,
"s": 25869,
"text": "Create a Responsive Navbar using ReactJS"
},
{
"code": null,
"e": 25947,
"s": 25910,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 26011,
"s": 25947,
"text": "How to position a div at the bottom of its container using CSS?"
},
{
"code": null,
"e": 26071,
"s": 26011,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 26132,
"s": 26071,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 26169,
"s": 26132,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 26222,
"s": 26169,
"text": "Hide or show elements in HTML using display property"
}
] |
How to see the extensions loaded by PHP ? - GeeksforGeeks
|
11 Oct, 2019
To see all the extensions loaded by PHP, firstly we must be sure that PHP is successfully installed in our system. After that, we can use any of the following approaches to see the loaded extension list.
Approach 1: In this approach, we will use command line to check all the loaded PHP extensions.Open Terminal or Command Line Interface and type the following command and hit enter.
php -m
It will display the list of all the loaded PHP extensions.
Approach 2: This approach uses get_loaded_extensions() function to display the list of all the loaded PHP extensions.
Example:
<?php print_r(get_loaded_extensions());?>
Output:
Note: Please note that the list of the extension might vary from system to system.
Picked
PHP
PHP Programs
Technical Scripter
Web Technologies
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to fetch data from localserver database and display on HTML table using PHP ?
How to pass form variables from one page to other page in PHP ?
Create a drop-down list that options fetched from a MySQL database in PHP
How to create admin login page using PHP?
Different ways for passing data to view in Laravel
How to call PHP function on the click of a Button ?
How to fetch data from localserver database and display on HTML table using PHP ?
How to pass form variables from one page to other page in PHP ?
How to create admin login page using PHP?
How to Install php-curl in Ubuntu ?
|
[
{
"code": null,
"e": 24581,
"s": 24553,
"text": "\n11 Oct, 2019"
},
{
"code": null,
"e": 24785,
"s": 24581,
"text": "To see all the extensions loaded by PHP, firstly we must be sure that PHP is successfully installed in our system. After that, we can use any of the following approaches to see the loaded extension list."
},
{
"code": null,
"e": 24965,
"s": 24785,
"text": "Approach 1: In this approach, we will use command line to check all the loaded PHP extensions.Open Terminal or Command Line Interface and type the following command and hit enter."
},
{
"code": null,
"e": 24972,
"s": 24965,
"text": "php -m"
},
{
"code": null,
"e": 25031,
"s": 24972,
"text": "It will display the list of all the loaded PHP extensions."
},
{
"code": null,
"e": 25149,
"s": 25031,
"text": "Approach 2: This approach uses get_loaded_extensions() function to display the list of all the loaded PHP extensions."
},
{
"code": null,
"e": 25158,
"s": 25149,
"text": "Example:"
},
{
"code": "<?php print_r(get_loaded_extensions());?> ",
"e": 25201,
"s": 25158,
"text": null
},
{
"code": null,
"e": 25209,
"s": 25201,
"text": "Output:"
},
{
"code": null,
"e": 25292,
"s": 25209,
"text": "Note: Please note that the list of the extension might vary from system to system."
},
{
"code": null,
"e": 25299,
"s": 25292,
"text": "Picked"
},
{
"code": null,
"e": 25303,
"s": 25299,
"text": "PHP"
},
{
"code": null,
"e": 25316,
"s": 25303,
"text": "PHP Programs"
},
{
"code": null,
"e": 25335,
"s": 25316,
"text": "Technical Scripter"
},
{
"code": null,
"e": 25352,
"s": 25335,
"text": "Web Technologies"
},
{
"code": null,
"e": 25379,
"s": 25352,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 25383,
"s": 25379,
"text": "PHP"
},
{
"code": null,
"e": 25481,
"s": 25383,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25490,
"s": 25481,
"text": "Comments"
},
{
"code": null,
"e": 25503,
"s": 25490,
"text": "Old Comments"
},
{
"code": null,
"e": 25585,
"s": 25503,
"text": "How to fetch data from localserver database and display on HTML table using PHP ?"
},
{
"code": null,
"e": 25649,
"s": 25585,
"text": "How to pass form variables from one page to other page in PHP ?"
},
{
"code": null,
"e": 25723,
"s": 25649,
"text": "Create a drop-down list that options fetched from a MySQL database in PHP"
},
{
"code": null,
"e": 25765,
"s": 25723,
"text": "How to create admin login page using PHP?"
},
{
"code": null,
"e": 25816,
"s": 25765,
"text": "Different ways for passing data to view in Laravel"
},
{
"code": null,
"e": 25868,
"s": 25816,
"text": "How to call PHP function on the click of a Button ?"
},
{
"code": null,
"e": 25950,
"s": 25868,
"text": "How to fetch data from localserver database and display on HTML table using PHP ?"
},
{
"code": null,
"e": 26014,
"s": 25950,
"text": "How to pass form variables from one page to other page in PHP ?"
},
{
"code": null,
"e": 26056,
"s": 26014,
"text": "How to create admin login page using PHP?"
}
] |
How to limit Decimal Places in Android EditText?
|
This example demonstrates about How to limit Decimal Places in Android EditText.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:hint="Enter decimal numbers"
android:id="@+id/etText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:inputType="numberDecimal" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
package app.com.sample;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.Spanned;
import android.widget.EditText;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText etText = findViewById(R.id.etText);
etText.setFilters(new InputFilter[]{new DecimalDigitsInputFilter(5, 2)});
}
}
class DecimalDigitsInputFilter implements InputFilter {
private Pattern mPattern;
DecimalDigitsInputFilter(int digitsBeforeZero, int digitsAfterZero) {
mPattern = Pattern.compile("[0-9]{0," + (digitsBeforeZero - 1) + "}+((\\.[0-9]{0," + (digitsAfterZero - 1) + "})?)||(\\.)?");
}
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
Matcher matcher = mPattern.matcher(dest);
if (!matcher.matches())
return "";
return null;
}
}
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 −
Click here to download the project code.
|
[
{
"code": null,
"e": 1143,
"s": 1062,
"text": "This example demonstrates about How to limit Decimal Places in Android EditText."
},
{
"code": null,
"e": 1272,
"s": 1143,
"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": 1337,
"s": 1272,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1885,
"s": 1337,
"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 tools:context=\".MainActivity\">\n <EditText\n android:hint=\"Enter decimal numbers\"\n android:id=\"@+id/etText\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_marginTop=\"16dp\"\n android:inputType=\"numberDecimal\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 1942,
"s": 1885,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 3086,
"s": 1942,
"text": "package app.com.sample;\nimport androidx.appcompat.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.text.InputFilter;\nimport android.text.Spanned;\nimport android.widget.EditText;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n EditText etText = findViewById(R.id.etText);\n etText.setFilters(new InputFilter[]{new DecimalDigitsInputFilter(5, 2)});\n }\n}\nclass DecimalDigitsInputFilter implements InputFilter {\n private Pattern mPattern;\n DecimalDigitsInputFilter(int digitsBeforeZero, int digitsAfterZero) {\n mPattern = Pattern.compile(\"[0-9]{0,\" + (digitsBeforeZero - 1) + \"}+((\\\\.[0-9]{0,\" + (digitsAfterZero - 1) + \"})?)||(\\\\.)?\");\n }\n @Override\n public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {\n Matcher matcher = mPattern.matcher(dest);\n if (!matcher.matches())\n return \"\";\n return null;\n }\n}"
},
{
"code": null,
"e": 3141,
"s": 3086,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 3811,
"s": 3141,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\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": 4158,
"s": 3811,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −"
},
{
"code": null,
"e": 4199,
"s": 4158,
"text": "Click here to download the project code."
}
] |
Python program to convert int to exponential - GeeksforGeeks
|
05 Jan, 2022
Given a number of int type, the task is to write a Python program to convert it to exponential.
Examples:
Input: 19
Output: 1.900000e+01
Input: 2002
Output: 2.002000e+03
Input: 110102
Output: 1.101020e+05
Approach:
We will first declare and initialise an integer number
Then we will use format method to convert the number from integer to exponential type.
Then we will print the converted value.
Syntax:
String {field_name:conversion} Example.format(value)
Errors and Exceptions:
ValueError: Error occurs during type conversion in this method.
More parameters can be included within the curly braces of our syntax. Use the format code syntax {field_name: conversion}, where field_name specifies the index number of the argument to the str.format() method, and conversion refers to the conversion code of the data type.
Example:
Python3
# Python program to convert int to exponential # Declaring the integer numberint_number = 110102 # Converting the integer number to exponential numberexp_number = "{:e}".format(int_number) # Printing the converted numberprint("Integer Number:",int_number)print("Exponent Number:",exp_number)
Output:
Integer Number: 110102
Exponent Number: 1.101020e+05
clintra
Python-datatype
Technical Scripter 2020
Python
Python Programs
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n05 Jan, 2022"
},
{
"code": null,
"e": 25633,
"s": 25537,
"text": "Given a number of int type, the task is to write a Python program to convert it to exponential."
},
{
"code": null,
"e": 25643,
"s": 25633,
"text": "Examples:"
},
{
"code": null,
"e": 25744,
"s": 25643,
"text": "Input: 19\nOutput: 1.900000e+01\n\nInput: 2002\nOutput: 2.002000e+03\n\nInput: 110102\nOutput: 1.101020e+05"
},
{
"code": null,
"e": 25754,
"s": 25744,
"text": "Approach:"
},
{
"code": null,
"e": 25809,
"s": 25754,
"text": "We will first declare and initialise an integer number"
},
{
"code": null,
"e": 25896,
"s": 25809,
"text": "Then we will use format method to convert the number from integer to exponential type."
},
{
"code": null,
"e": 25936,
"s": 25896,
"text": "Then we will print the converted value."
},
{
"code": null,
"e": 25944,
"s": 25936,
"text": "Syntax:"
},
{
"code": null,
"e": 25997,
"s": 25944,
"text": "String {field_name:conversion} Example.format(value)"
},
{
"code": null,
"e": 26020,
"s": 25997,
"text": "Errors and Exceptions:"
},
{
"code": null,
"e": 26084,
"s": 26020,
"text": "ValueError: Error occurs during type conversion in this method."
},
{
"code": null,
"e": 26359,
"s": 26084,
"text": "More parameters can be included within the curly braces of our syntax. Use the format code syntax {field_name: conversion}, where field_name specifies the index number of the argument to the str.format() method, and conversion refers to the conversion code of the data type."
},
{
"code": null,
"e": 26368,
"s": 26359,
"text": "Example:"
},
{
"code": null,
"e": 26376,
"s": 26368,
"text": "Python3"
},
{
"code": "# Python program to convert int to exponential # Declaring the integer numberint_number = 110102 # Converting the integer number to exponential numberexp_number = \"{:e}\".format(int_number) # Printing the converted numberprint(\"Integer Number:\",int_number)print(\"Exponent Number:\",exp_number)",
"e": 26668,
"s": 26376,
"text": null
},
{
"code": null,
"e": 26679,
"s": 26671,
"text": "Output:"
},
{
"code": null,
"e": 26734,
"s": 26681,
"text": "Integer Number: 110102\nExponent Number: 1.101020e+05"
},
{
"code": null,
"e": 26744,
"s": 26736,
"text": "clintra"
},
{
"code": null,
"e": 26760,
"s": 26744,
"text": "Python-datatype"
},
{
"code": null,
"e": 26784,
"s": 26760,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 26791,
"s": 26784,
"text": "Python"
},
{
"code": null,
"e": 26807,
"s": 26791,
"text": "Python Programs"
},
{
"code": null,
"e": 26826,
"s": 26807,
"text": "Technical Scripter"
},
{
"code": null,
"e": 26924,
"s": 26826,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26956,
"s": 26924,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26998,
"s": 26956,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27040,
"s": 26998,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27067,
"s": 27040,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27123,
"s": 27067,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27145,
"s": 27123,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27184,
"s": 27145,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 27230,
"s": 27184,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 27268,
"s": 27230,
"text": "Python | Convert a list to dictionary"
}
] |
Data Structures | Binary Search Trees | Question 12 - GeeksforGeeks
|
28 Jun, 2021
Consider the following code snippet in C. The function print() receives root of a Binary Search Tree (BST) and a positive integer k as arguments.
// A BST nodestruct node { int data; struct node *left, *right;}; int count = 0; void print(struct node *root, int k){ if (root != NULL && count <= k) { print(root->right, k); count++; if (count == k) printf("%d ", root->data); print(root->left, k); }}
What is the output of print(root, 3) where root represent root of the following BST.
15
/ \
10 20
/ \ / \
8 12 16 25
(A) 10(B) 16(C) 20(D) 20 10Answer: (B)Explanation: The code mainly finds out k’th largest element in BST, see K’th Largest Element in BST for details.Quiz of this Question
Binary Search Trees
Data Structures
Data Structures-Binary Search Trees
Data Structures
Data Structures
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Count number of times each Edge appears in all possible paths of a given Tree
Data Structures | Linked List | Question 5
Data Structures | Tree Traversals | Question 4
Data Structures | Linked List | Question 6
Advantages and Disadvantages of Linked List
FIFO vs LIFO approach in Programming
Data Structures | Graph | Question 9
Introduction to Data Structures
Data Structures | Stack | Question 1
Binary Search Tree | Set 3 (Iterative Delete)
|
[
{
"code": null,
"e": 26397,
"s": 26369,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 26543,
"s": 26397,
"text": "Consider the following code snippet in C. The function print() receives root of a Binary Search Tree (BST) and a positive integer k as arguments."
},
{
"code": "// A BST nodestruct node { int data; struct node *left, *right;}; int count = 0; void print(struct node *root, int k){ if (root != NULL && count <= k) { print(root->right, k); count++; if (count == k) printf(\"%d \", root->data); print(root->left, k); }}",
"e": 26849,
"s": 26543,
"text": null
},
{
"code": null,
"e": 26934,
"s": 26849,
"text": "What is the output of print(root, 3) where root represent root of the following BST."
},
{
"code": null,
"e": 27062,
"s": 26934,
"text": " 15\n / \\\n 10 20\n / \\ / \\\n 8 12 16 25 \n"
},
{
"code": null,
"e": 27234,
"s": 27062,
"text": "(A) 10(B) 16(C) 20(D) 20 10Answer: (B)Explanation: The code mainly finds out k’th largest element in BST, see K’th Largest Element in BST for details.Quiz of this Question"
},
{
"code": null,
"e": 27254,
"s": 27234,
"text": "Binary Search Trees"
},
{
"code": null,
"e": 27270,
"s": 27254,
"text": "Data Structures"
},
{
"code": null,
"e": 27306,
"s": 27270,
"text": "Data Structures-Binary Search Trees"
},
{
"code": null,
"e": 27322,
"s": 27306,
"text": "Data Structures"
},
{
"code": null,
"e": 27338,
"s": 27322,
"text": "Data Structures"
},
{
"code": null,
"e": 27436,
"s": 27338,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27514,
"s": 27436,
"text": "Count number of times each Edge appears in all possible paths of a given Tree"
},
{
"code": null,
"e": 27557,
"s": 27514,
"text": "Data Structures | Linked List | Question 5"
},
{
"code": null,
"e": 27604,
"s": 27557,
"text": "Data Structures | Tree Traversals | Question 4"
},
{
"code": null,
"e": 27647,
"s": 27604,
"text": "Data Structures | Linked List | Question 6"
},
{
"code": null,
"e": 27691,
"s": 27647,
"text": "Advantages and Disadvantages of Linked List"
},
{
"code": null,
"e": 27728,
"s": 27691,
"text": "FIFO vs LIFO approach in Programming"
},
{
"code": null,
"e": 27765,
"s": 27728,
"text": "Data Structures | Graph | Question 9"
},
{
"code": null,
"e": 27797,
"s": 27765,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 27834,
"s": 27797,
"text": "Data Structures | Stack | Question 1"
}
] |
Number of parallelograms when n horizontal parallel lines intersect m vertical parallellines - GeeksforGeeks
|
06 May, 2021
Given two positive integers n and m. The task is to count number of parallelogram that can be formed of any size when n horizontal parallel lines intersect with m vertical parallel lines.
Examples:
Input : n = 3, m = 2
Output : 3
2 parallelograms of size 1x1 and 1 parallelogram
of size 2x1.
Input : n = 5, m = 5
Output : 100
The idea is to use Combination, which state, number of ways to choose k items from given n items is given by nCr. To form a parallelogram, we need two horizontal parallel lines and two vertical parallel lines. So, number of ways to choose two horizontal parallel lines are nC2 and number of ways to choose two vertical parallel lines are mC2. So, total number of possible parallelogram will be nC2 x mC2.Below is C++ implementation of this approach:
C++
Java
Python3
C#
Javascript
// CPP Program to find number of parallelogram when// n horizontal parallel lines intersect m vertical// parallel lines.#include<bits/stdc++.h>#define MAX 10using namespace std; // Find value of Binomial Coefficientint binomialCoeff(int C[][MAX], int n, int k){ // Calculate value of Binomial Coefficient // in bottom up manner for (int i = 0; i <= n; i++) { for (int j = 0; j <= min(i, k); j++) { // Base Cases if (j == 0 || j == i) C[i][j] = 1; // Calculate value using previously // stored values else C[i][j] = C[i-1][j-1] + C[i-1][j]; } }} // Return number of parallelogram when n horizontal// parallel lines intersect m vertical parallel lines.int countParallelogram(int n, int m){ int C[MAX][MAX] = { 0 }; binomialCoeff(C, max(n, m), 2); return C[n][2] * C[m][2];} // Driver Programint main(){ int n = 5, m = 5; cout << countParallelogram(n, m) << endl; return 0;}
// Java Program to find number of parallelogram when// n horizontal parallel lines intersect m vertical// parallel lines.class GFG{ static final int MAX = 10; // Find value of Binomial Coefficient static void binomialCoeff(int C[][], int n, int k) { // Calculate value of Binomial Coefficient // in bottom up manner for (int i = 0; i <= n; i++) { for (int j = 0; j <= Math.min(i, k); j++) { // Base Cases if (j == 0 || j == i) C[i][j] = 1; // Calculate value using previously // stored values else C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; } } } // Return number of parallelogram when n horizontal // parallel lines intersect m vertical parallel lines. static int countParallelogram(int n, int m) { int C[][]=new int[MAX][MAX]; binomialCoeff(C, Math.max(n, m), 2); return C[n][2] * C[m][2]; } // Driver code public static void main(String arg[]) { int n = 5, m = 5; System.out.println(countParallelogram(n, m)); }} // This code is contributed By Anant Agarwal.
# Python Program to find number of parallelogram when# n horizontal parallel lines intersect m vertical# parallel lines.MAX = 10; # Find value of Binomial Coefficientdef binomialCoeff(C, n, k): # Calculate value of Binomial Coefficient # in bottom up manner for i in range(n + 1): for j in range(0, min(i, k) + 1): # Base Cases if (j == 0 or j == i): C[i][j] = 1; # Calculate value using previously # stored values else: C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; # Return number of parallelogram when n horizontal# parallel lines intersect m vertical parallel lines.def countParallelogram(n, m): C = [[0 for i in range(MAX)] for j in range(MAX)] binomialCoeff(C, max(n, m), 2); return C[n][2] * C[m][2]; # Driver codeif __name__ == '__main__': n = 5; m = 5; print(countParallelogram(n, m)); # This code is contributed by 29AjayKumar
// C# Program to find number of parallelogram when// n horizontal parallel lines intersect m vertical// parallel lines.using System; class GFG{ static int MAX = 10; // Find value of Binomial Coefficient static void binomialCoeff(int [,]C, int n, int k) { // Calculate value of Binomial Coefficient // in bottom up manner for (int i = 0; i <= n; i++) { for (int j = 0; j <= Math.Min(i, k); j++) { // Base Cases if (j == 0 || j == i) C[i, j] = 1; // Calculate value using previously // stored values else C[i, j] = C[i - 1, j - 1] + C[i - 1, j]; } } } // Return number of parallelogram when n horizontal // parallel lines intersect m vertical parallel lines. static int countParallelogram(int n, int m) { int [,]C = new int[MAX, MAX]; binomialCoeff(C, Math.Max(n, m), 2); return C[n, 2] * C[m, 2]; } // Driver code public static void Main() { int n = 5, m = 5; Console.WriteLine(countParallelogram(n, m)); }} // This code is contributed By vt_m.
<script> // Javascript Program to find number of parallelogram when// n horizontal parallel lines intersect m vertical// parallel lines.var MAX = 10; // Find value of Binomial Coefficientfunction binomialCoeff(C, n, k){ // Calculate value of Binomial Coefficient // in bottom up manner for (var i = 0; i <= n; i++) { for (var j = 0; j <= Math.min(i, k); j++) { // Base Cases if (j == 0 || j == i) C[i][j] = 1; // Calculate value using previously // stored values else C[i][j] = C[i-1][j-1] + C[i-1][j]; } }} // Return number of parallelogram when n horizontal// parallel lines intersect m vertical parallel lines.function countParallelogram(n, m){ var C = Array.from(Array(MAX), () => Array(MAX).fill(0)); binomialCoeff(C, Math.max(n, m), 2); return C[n][2] * C[m][2];} // Driver Programvar n = 5, m = 5; document.write( countParallelogram(n, m)); // This code is contributed by rdtank.</script>
Output:
100
29AjayKumar
itsok
Geometric
Geometric
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program for distance between two points on earth
Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping)
Line Clipping | Set 1 (Cohen–Sutherland Algorithm)
Convex Hull | Set 2 (Graham Scan)
Check whether a given point lies inside a triangle or not
Optimum location of point to minimize total distance
Closest Pair of Points | O(nlogn) Implementation
Given n line segments, find if any two segments intersect
Convex Hull using Divide and Conquer Algorithm
Polygon Clipping | Sutherland–Hodgman Algorithm
|
[
{
"code": null,
"e": 25773,
"s": 25745,
"text": "\n06 May, 2021"
},
{
"code": null,
"e": 25963,
"s": 25773,
"text": "Given two positive integers n and m. The task is to count number of parallelogram that can be formed of any size when n horizontal parallel lines intersect with m vertical parallel lines. "
},
{
"code": null,
"e": 25975,
"s": 25963,
"text": "Examples: "
},
{
"code": null,
"e": 26105,
"s": 25975,
"text": "Input : n = 3, m = 2\nOutput : 3\n2 parallelograms of size 1x1 and 1 parallelogram \nof size 2x1.\n\nInput : n = 5, m = 5\nOutput : 100"
},
{
"code": null,
"e": 26559,
"s": 26107,
"text": "The idea is to use Combination, which state, number of ways to choose k items from given n items is given by nCr. To form a parallelogram, we need two horizontal parallel lines and two vertical parallel lines. So, number of ways to choose two horizontal parallel lines are nC2 and number of ways to choose two vertical parallel lines are mC2. So, total number of possible parallelogram will be nC2 x mC2.Below is C++ implementation of this approach: "
},
{
"code": null,
"e": 26563,
"s": 26559,
"text": "C++"
},
{
"code": null,
"e": 26568,
"s": 26563,
"text": "Java"
},
{
"code": null,
"e": 26576,
"s": 26568,
"text": "Python3"
},
{
"code": null,
"e": 26579,
"s": 26576,
"text": "C#"
},
{
"code": null,
"e": 26590,
"s": 26579,
"text": "Javascript"
},
{
"code": "// CPP Program to find number of parallelogram when// n horizontal parallel lines intersect m vertical// parallel lines.#include<bits/stdc++.h>#define MAX 10using namespace std; // Find value of Binomial Coefficientint binomialCoeff(int C[][MAX], int n, int k){ // Calculate value of Binomial Coefficient // in bottom up manner for (int i = 0; i <= n; i++) { for (int j = 0; j <= min(i, k); j++) { // Base Cases if (j == 0 || j == i) C[i][j] = 1; // Calculate value using previously // stored values else C[i][j] = C[i-1][j-1] + C[i-1][j]; } }} // Return number of parallelogram when n horizontal// parallel lines intersect m vertical parallel lines.int countParallelogram(int n, int m){ int C[MAX][MAX] = { 0 }; binomialCoeff(C, max(n, m), 2); return C[n][2] * C[m][2];} // Driver Programint main(){ int n = 5, m = 5; cout << countParallelogram(n, m) << endl; return 0;}",
"e": 27613,
"s": 26590,
"text": null
},
{
"code": "// Java Program to find number of parallelogram when// n horizontal parallel lines intersect m vertical// parallel lines.class GFG{ static final int MAX = 10; // Find value of Binomial Coefficient static void binomialCoeff(int C[][], int n, int k) { // Calculate value of Binomial Coefficient // in bottom up manner for (int i = 0; i <= n; i++) { for (int j = 0; j <= Math.min(i, k); j++) { // Base Cases if (j == 0 || j == i) C[i][j] = 1; // Calculate value using previously // stored values else C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; } } } // Return number of parallelogram when n horizontal // parallel lines intersect m vertical parallel lines. static int countParallelogram(int n, int m) { int C[][]=new int[MAX][MAX]; binomialCoeff(C, Math.max(n, m), 2); return C[n][2] * C[m][2]; } // Driver code public static void main(String arg[]) { int n = 5, m = 5; System.out.println(countParallelogram(n, m)); }} // This code is contributed By Anant Agarwal.",
"e": 28869,
"s": 27613,
"text": null
},
{
"code": "# Python Program to find number of parallelogram when# n horizontal parallel lines intersect m vertical# parallel lines.MAX = 10; # Find value of Binomial Coefficientdef binomialCoeff(C, n, k): # Calculate value of Binomial Coefficient # in bottom up manner for i in range(n + 1): for j in range(0, min(i, k) + 1): # Base Cases if (j == 0 or j == i): C[i][j] = 1; # Calculate value using previously # stored values else: C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; # Return number of parallelogram when n horizontal# parallel lines intersect m vertical parallel lines.def countParallelogram(n, m): C = [[0 for i in range(MAX)] for j in range(MAX)] binomialCoeff(C, max(n, m), 2); return C[n][2] * C[m][2]; # Driver codeif __name__ == '__main__': n = 5; m = 5; print(countParallelogram(n, m)); # This code is contributed by 29AjayKumar",
"e": 29837,
"s": 28869,
"text": null
},
{
"code": "// C# Program to find number of parallelogram when// n horizontal parallel lines intersect m vertical// parallel lines.using System; class GFG{ static int MAX = 10; // Find value of Binomial Coefficient static void binomialCoeff(int [,]C, int n, int k) { // Calculate value of Binomial Coefficient // in bottom up manner for (int i = 0; i <= n; i++) { for (int j = 0; j <= Math.Min(i, k); j++) { // Base Cases if (j == 0 || j == i) C[i, j] = 1; // Calculate value using previously // stored values else C[i, j] = C[i - 1, j - 1] + C[i - 1, j]; } } } // Return number of parallelogram when n horizontal // parallel lines intersect m vertical parallel lines. static int countParallelogram(int n, int m) { int [,]C = new int[MAX, MAX]; binomialCoeff(C, Math.Max(n, m), 2); return C[n, 2] * C[m, 2]; } // Driver code public static void Main() { int n = 5, m = 5; Console.WriteLine(countParallelogram(n, m)); }} // This code is contributed By vt_m.",
"e": 31077,
"s": 29837,
"text": null
},
{
"code": "<script> // Javascript Program to find number of parallelogram when// n horizontal parallel lines intersect m vertical// parallel lines.var MAX = 10; // Find value of Binomial Coefficientfunction binomialCoeff(C, n, k){ // Calculate value of Binomial Coefficient // in bottom up manner for (var i = 0; i <= n; i++) { for (var j = 0; j <= Math.min(i, k); j++) { // Base Cases if (j == 0 || j == i) C[i][j] = 1; // Calculate value using previously // stored values else C[i][j] = C[i-1][j-1] + C[i-1][j]; } }} // Return number of parallelogram when n horizontal// parallel lines intersect m vertical parallel lines.function countParallelogram(n, m){ var C = Array.from(Array(MAX), () => Array(MAX).fill(0)); binomialCoeff(C, Math.max(n, m), 2); return C[n][2] * C[m][2];} // Driver Programvar n = 5, m = 5; document.write( countParallelogram(n, m)); // This code is contributed by rdtank.</script>",
"e": 32110,
"s": 31077,
"text": null
},
{
"code": null,
"e": 32120,
"s": 32110,
"text": "Output: "
},
{
"code": null,
"e": 32124,
"s": 32120,
"text": "100"
},
{
"code": null,
"e": 32138,
"s": 32126,
"text": "29AjayKumar"
},
{
"code": null,
"e": 32144,
"s": 32138,
"text": "itsok"
},
{
"code": null,
"e": 32154,
"s": 32144,
"text": "Geometric"
},
{
"code": null,
"e": 32164,
"s": 32154,
"text": "Geometric"
},
{
"code": null,
"e": 32262,
"s": 32164,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32311,
"s": 32262,
"text": "Program for distance between two points on earth"
},
{
"code": null,
"e": 32364,
"s": 32311,
"text": "Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping)"
},
{
"code": null,
"e": 32415,
"s": 32364,
"text": "Line Clipping | Set 1 (Cohen–Sutherland Algorithm)"
},
{
"code": null,
"e": 32449,
"s": 32415,
"text": "Convex Hull | Set 2 (Graham Scan)"
},
{
"code": null,
"e": 32507,
"s": 32449,
"text": "Check whether a given point lies inside a triangle or not"
},
{
"code": null,
"e": 32560,
"s": 32507,
"text": "Optimum location of point to minimize total distance"
},
{
"code": null,
"e": 32609,
"s": 32560,
"text": "Closest Pair of Points | O(nlogn) Implementation"
},
{
"code": null,
"e": 32667,
"s": 32609,
"text": "Given n line segments, find if any two segments intersect"
},
{
"code": null,
"e": 32714,
"s": 32667,
"text": "Convex Hull using Divide and Conquer Algorithm"
}
] |
RxJS - Transformation Operator mergeMap
|
In the case of mergeMap operator a project function is applied on each source value and the output of it is merged with the output Observable.
mergeMap(project_func: function): Observable
project_func − It takes in project_func as the argument which is applied to all the values of source observable.
It returns an Observable that has values based on the project_func applied on each value of source observable.
import { of} from 'rxjs';
import { mergeMap, map } from 'rxjs/operators';
let text = of('Welcome To');
let case1 = text.pipe(mergeMap((value) => of(value + ' Tutorialspoint!')));
case1.subscribe((value) => {console.log(value);});
51 Lectures
4 hours
Daniel Stern
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 1967,
"s": 1824,
"text": "In the case of mergeMap operator a project function is applied on each source value and the output of it is merged with the output Observable."
},
{
"code": null,
"e": 2013,
"s": 1967,
"text": "mergeMap(project_func: function): Observable\n"
},
{
"code": null,
"e": 2126,
"s": 2013,
"text": "project_func − It takes in project_func as the argument which is applied to all the values of source observable."
},
{
"code": null,
"e": 2237,
"s": 2126,
"text": "It returns an Observable that has values based on the project_func applied on each value of source observable."
},
{
"code": null,
"e": 2468,
"s": 2237,
"text": "import { of} from 'rxjs';\nimport { mergeMap, map } from 'rxjs/operators';\n\nlet text = of('Welcome To');\nlet case1 = text.pipe(mergeMap((value) => of(value + ' Tutorialspoint!')));\ncase1.subscribe((value) => {console.log(value);});"
},
{
"code": null,
"e": 2501,
"s": 2468,
"text": "\n 51 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 2515,
"s": 2501,
"text": " Daniel Stern"
},
{
"code": null,
"e": 2522,
"s": 2515,
"text": " Print"
},
{
"code": null,
"e": 2533,
"s": 2522,
"text": " Add Notes"
}
] |
Priority Queue in C++ Standard Template Library (STL) - GeeksforGeeks
|
19 Feb, 2022
Priority queues are a type of container adapters, specifically designed such that the first element of the queue is the greatest of all elements in the queue and elements are in nonincreasing order (hence we can see that each element of the queue has a priority {fixed order}). Following is an example to demonstrate the priority queue and its various methods.
CPP
// CPP Program to demonstrate Priority Queue#include <iostream>#include <queue>using namespace std; void showpq(priority_queue<int> gq){ priority_queue<int> g = gq; while (!g.empty()) { cout << '\t' << g.top(); g.pop(); } cout << '\n';} // Driver Codeint main(){ priority_queue<int> gquiz; gquiz.push(10); gquiz.push(30); gquiz.push(20); gquiz.push(5); gquiz.push(1); cout << "The priority queue gquiz is : "; showpq(gquiz); cout << "\ngquiz.size() : " << gquiz.size(); cout << "\ngquiz.top() : " << gquiz.top(); cout << "\ngquiz.pop() : "; gquiz.pop(); showpq(gquiz); return 0;}
The priority queue gquiz is : 30 20 10 5 1
gquiz.size() : 5
gquiz.top() : 30
gquiz.pop() : 20 10 5 1
Note: By default, C++ creates a max-heap for priority queue.
How to create a min-heap for the priority queue? C++ provides the below syntax for the same.
Syntax:
priority_queue <int, vector<int>, greater<int>> g = gq;
CPP
// C++ program to demonstrate min heap for priority queue#include <iostream>#include <queue>using namespace std; void showpq( priority_queue<int, vector<int>, greater<int> > gq){ priority_queue<int, vector<int>, greater<int> > g = gq; while (!g.empty()) { cout << '\t' << g.top(); g.pop(); } cout << '\n';} // Driver Codeint main(){ priority_queue<int, vector<int>, greater<int> > gquiz; gquiz.push(10); gquiz.push(30); gquiz.push(20); gquiz.push(5); gquiz.push(1); cout << "The priority queue gquiz is : "; showpq(gquiz); cout << "\ngquiz.size() : " << gquiz.size(); cout << "\ngquiz.top() : " << gquiz.top(); cout << "\ngquiz.pop() : "; gquiz.pop(); showpq(gquiz); return 0;}
The priority queue gquiz is : 1 5 10 20 30
gquiz.size() : 5
gquiz.top() : 1
gquiz.pop() : 5 10 20 30
Note: The above syntax may be difficult to remember, so in case of numeric values, we can multiply the values with -1 and use max heap to get the effect of min heap.
Methods of Priority Queue are:
Method
Definition
Must Read: Recent articles on priority queue in STL
YouTubeGeeksforGeeks500K subscribersC++ Programming Language Tutorial | Priority Queue in C++ STL | 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 / 1:55•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=vc7i0bBuQEM" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.
cr7_bullet
harshitagrawal920
manasdtrivedi
2104hiteshdhiman
anshikajain26
aqquilin141
cpp-containers-library
cpp-priority-queue
priority-queue
STL
C++
STL
priority-queue
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Vector in C++ STL
Initialize a vector in C++ (6 different ways)
std::sort() in C++ STL
Bitwise Operators in C/C++
Socket Programming in C/C++
Virtual Function in C++
Templates in C++ with Examples
rand() and srand() in C/C++
vector erase() and clear() in C++
unordered_map in C++ STL
|
[
{
"code": null,
"e": 26569,
"s": 26541,
"text": "\n19 Feb, 2022"
},
{
"code": null,
"e": 26931,
"s": 26569,
"text": "Priority queues are a type of container adapters, specifically designed such that the first element of the queue is the greatest of all elements in the queue and elements are in nonincreasing order (hence we can see that each element of the queue has a priority {fixed order}). Following is an example to demonstrate the priority queue and its various methods. "
},
{
"code": null,
"e": 26935,
"s": 26931,
"text": "CPP"
},
{
"code": "// CPP Program to demonstrate Priority Queue#include <iostream>#include <queue>using namespace std; void showpq(priority_queue<int> gq){ priority_queue<int> g = gq; while (!g.empty()) { cout << '\\t' << g.top(); g.pop(); } cout << '\\n';} // Driver Codeint main(){ priority_queue<int> gquiz; gquiz.push(10); gquiz.push(30); gquiz.push(20); gquiz.push(5); gquiz.push(1); cout << \"The priority queue gquiz is : \"; showpq(gquiz); cout << \"\\ngquiz.size() : \" << gquiz.size(); cout << \"\\ngquiz.top() : \" << gquiz.top(); cout << \"\\ngquiz.pop() : \"; gquiz.pop(); showpq(gquiz); return 0;}",
"e": 27587,
"s": 26935,
"text": null
},
{
"code": null,
"e": 27718,
"s": 27587,
"text": "The priority queue gquiz is : 30 20 10 5 1\n\ngquiz.size() : 5\ngquiz.top() : 30\ngquiz.pop() : 20 10 5 1"
},
{
"code": null,
"e": 27779,
"s": 27718,
"text": "Note: By default, C++ creates a max-heap for priority queue."
},
{
"code": null,
"e": 27874,
"s": 27779,
"text": "How to create a min-heap for the priority queue? C++ provides the below syntax for the same. "
},
{
"code": null,
"e": 27882,
"s": 27874,
"text": "Syntax:"
},
{
"code": null,
"e": 27940,
"s": 27882,
"text": "priority_queue <int, vector<int>, greater<int>> g = gq; "
},
{
"code": null,
"e": 27944,
"s": 27940,
"text": "CPP"
},
{
"code": "// C++ program to demonstrate min heap for priority queue#include <iostream>#include <queue>using namespace std; void showpq( priority_queue<int, vector<int>, greater<int> > gq){ priority_queue<int, vector<int>, greater<int> > g = gq; while (!g.empty()) { cout << '\\t' << g.top(); g.pop(); } cout << '\\n';} // Driver Codeint main(){ priority_queue<int, vector<int>, greater<int> > gquiz; gquiz.push(10); gquiz.push(30); gquiz.push(20); gquiz.push(5); gquiz.push(1); cout << \"The priority queue gquiz is : \"; showpq(gquiz); cout << \"\\ngquiz.size() : \" << gquiz.size(); cout << \"\\ngquiz.top() : \" << gquiz.top(); cout << \"\\ngquiz.pop() : \"; gquiz.pop(); showpq(gquiz); return 0;}",
"e": 28697,
"s": 27944,
"text": null
},
{
"code": null,
"e": 28828,
"s": 28697,
"text": "The priority queue gquiz is : 1 5 10 20 30\n\ngquiz.size() : 5\ngquiz.top() : 1\ngquiz.pop() : 5 10 20 30"
},
{
"code": null,
"e": 28994,
"s": 28828,
"text": "Note: The above syntax may be difficult to remember, so in case of numeric values, we can multiply the values with -1 and use max heap to get the effect of min heap."
},
{
"code": null,
"e": 29026,
"s": 28994,
"text": "Methods of Priority Queue are: "
},
{
"code": null,
"e": 29033,
"s": 29026,
"text": "Method"
},
{
"code": null,
"e": 29044,
"s": 29033,
"text": "Definition"
},
{
"code": null,
"e": 29097,
"s": 29044,
"text": "Must Read: Recent articles on priority queue in STL "
},
{
"code": null,
"e": 29957,
"s": 29097,
"text": "YouTubeGeeksforGeeks500K subscribersC++ Programming Language Tutorial | Priority Queue in C++ STL | 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 / 1:55•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=vc7i0bBuQEM\" 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": 30087,
"s": 29957,
"text": "Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 30098,
"s": 30087,
"text": "cr7_bullet"
},
{
"code": null,
"e": 30116,
"s": 30098,
"text": "harshitagrawal920"
},
{
"code": null,
"e": 30130,
"s": 30116,
"text": "manasdtrivedi"
},
{
"code": null,
"e": 30147,
"s": 30130,
"text": "2104hiteshdhiman"
},
{
"code": null,
"e": 30161,
"s": 30147,
"text": "anshikajain26"
},
{
"code": null,
"e": 30173,
"s": 30161,
"text": "aqquilin141"
},
{
"code": null,
"e": 30196,
"s": 30173,
"text": "cpp-containers-library"
},
{
"code": null,
"e": 30215,
"s": 30196,
"text": "cpp-priority-queue"
},
{
"code": null,
"e": 30230,
"s": 30215,
"text": "priority-queue"
},
{
"code": null,
"e": 30234,
"s": 30230,
"text": "STL"
},
{
"code": null,
"e": 30238,
"s": 30234,
"text": "C++"
},
{
"code": null,
"e": 30242,
"s": 30238,
"text": "STL"
},
{
"code": null,
"e": 30257,
"s": 30242,
"text": "priority-queue"
},
{
"code": null,
"e": 30261,
"s": 30257,
"text": "CPP"
},
{
"code": null,
"e": 30359,
"s": 30261,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30368,
"s": 30359,
"text": "Comments"
},
{
"code": null,
"e": 30381,
"s": 30368,
"text": "Old Comments"
},
{
"code": null,
"e": 30399,
"s": 30381,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 30445,
"s": 30399,
"text": "Initialize a vector in C++ (6 different ways)"
},
{
"code": null,
"e": 30468,
"s": 30445,
"text": "std::sort() in C++ STL"
},
{
"code": null,
"e": 30495,
"s": 30468,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 30523,
"s": 30495,
"text": "Socket Programming in C/C++"
},
{
"code": null,
"e": 30547,
"s": 30523,
"text": "Virtual Function in C++"
},
{
"code": null,
"e": 30578,
"s": 30547,
"text": "Templates in C++ with Examples"
},
{
"code": null,
"e": 30606,
"s": 30578,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 30640,
"s": 30606,
"text": "vector erase() and clear() in C++"
}
] |
Using the latest advancements in deep learning to predict stock price movements | by Boris B | Towards Data Science
|
Link to the complete notebook: https://github.com/borisbanushev/stockpredictionai
In this notebook I will create a complete process for predicting stock price movements. Follow along and we will achieve some pretty good results. For that purpose we will use a Generative Adversarial Network (GAN) with LSTM, a type of Recurrent Neural Network, as generator, and a Convolutional Neural Network, CNN, as a discriminator. We use LSTM for the obvious reason that we are trying to predict time series data. Why we use GAN and specifically CNN as a discriminator? That is a good question: there are special sections on that later.
We will go into greater details for each step, of course, but the most difficult part is the GAN: very tricky part of successfully training a GAN is getting the right set of hyperparameters. For that reason we will use Bayesian optimisation (along with Gaussian processes) and Deep Reinforcement learning (DRL) for deciding when and how to change the GAN’s hyper parameters (the exploration vs. exploitation dilemma). In creating the reinforcement learning I will use the most recent advancements in the field, such as Rainbow and PPO.
We will use a lot of different types of input data. Along with the stock’s historical trading data and technical indicators, we will use the newest advancements in NLP (using ‘Bidirectional Embedding Representations from Transformers’, BERT, sort of a transfer learning for NLP) to create sentiment analysis (as a source for fundamental analysis), Fourier transforms for extracting overall trend directions, stacked autoencoders for identifying other high-level features, Eigen portfolios for finding correlated assets, autoregressive integrated moving average (ARIMA) for the stock function approximation, and many more, in order to capture as much information, patterns, dependencies, etc, as possible about the stock. As we all know, the more (data) the merrier. Predicting stock price movements is an extremely complex task, so the more we know about the stock (from different perspectives) the higher our changes are.
For the purpose of creating all neural nets we will use MXNet and its high-level API — Gluon, and train them on multiple GPUs.
Note: Although I try to get into details of the math and the mechanisms behind almost all algorithms and techniques, this notebook is not explicitly intended to explain how machine/deep learning, or the stock markets, work. The purpose is rather to show how we can use different techniques and algorithms for the purpose of accurately predicting stock price movements, and to also give rationale behind the reason and usefulness of using each technique at each step.
1. Introduction
2. The Data
2.1. Correlated assets
2.2. Technical indicators
2.3. Fundamental analysis
2.3.1. Bidirectional Embedding Representations from Transformers — BERT
2.4. Fourier transforms for trend analysis
2.5. ARIMA as a feature
2.6. Statistical checks
2.6.1. Heteroskedasticity, multicollinearity, serial correlation
2.7. Feature Engineering
2.7.1. Feature importance with XGBoost
2.8. Extracting high-level features with Stacked Autoencoders
2.8.1. Activation function — GELU (Gaussian Error)
3. Generative Adversarial Network (GAN)
3.1. Why GAN for stock market prediction
3.2. Metropolis-Hastings GAN and Wasserstein GAN
3.4. The Generator — One layer RNN
3.4.1. LSTM or GRU
3.4.2. The LSTM architecture
3.4.3. Learning rate scheduler
3.4.4. How to prevent overfitting and the bias-variance trade-off
3.5. The Discriminator — One Dimentional CNN
4.5.1. Why CNN as a discriminator?
3.5.1. The CNN Architecture
3.6. Hyperparameters
4. Hyperparameters optimisation
4.1. Reinforcement learning for hyperparameters optimization
4.1.1. Reinforcement Learning Theory
4.1.1.1. Rainbow
4.1.1.2. PPO
4.1.2. Further work on Reinforcement learning
4.2. Bayesian optimization
4.2.1. Gaussian process
5. The Result
6. What is next?
7. Disclaimer
Accurately predicting the stock markets is a complex task as there are millions of events and pre-conditions for a particular stock to move in a particular direction. So we need to be able to capture as many of these pre-conditions as possible. We also need make several important assumptions: 1) markets are not 100% random, 2) history repeats, 3) markets follow people’s rational behavior, and 4) the markets are ‘perfect’. And, please, do read the Disclaimer at the bottom.
We will try to predict the price movements of Goldman Sachs (NYSE: GS). For the purpose, we will use the daily closing price from January 1st, 2010 to December 31st, 2018 (seven years for training purposes and two years for validation purposes). We will use the terms ‘Goldman Sachs’ and ‘GS’ interchangeably.
We need to understand what affects whether GS’s stock price will move up or down. It is what people as a whole think. Hence, we need to incorporate as much information (depicting the stock from different aspects and angles) as possible. (We will use daily data — 1,585 days to train the various algorithms (70% of the data we have) and predict the next 680 days (test data). Then we will compare the predicted results with a test (hold-out) data. Each type of data (we will refer to it as feature) is explained in greater detail in later sections, but, as a high-level overview, the features we will use are:
Correlated assets — these are other assets (any type, not necessarily stocks, such as commodities, FX, indices, or even fixed income securities). A big company, such as Goldman Sachs, obviously doesn’t ‘live’ in an isolated world — it depends on, and interacts with, many external factors, including its competitors, clients, the global economy, the geo-political situation, fiscal and monetary policies, access to capital, etc. The details are listed later.Technical indicators — a lot of investors follow technical indicators. We will include the most popular indicators as independent features. Among them — 7 and 21 days moving average, exponential moving average, momentum, Bollinger bands, MACD.Fundamental analysis — A very important feature indicating whether a stock might move up or down. There are two features that can be used in fundamental analysis: 1) Analysing the company performance using 10-K and 10-Q reports, analysing ROE and P/E, etc (we will not use this), and 2) News — potentially news can indicate upcoming events that can potentially move the stock in certain direction. We will read all daily news for Goldman Sachs and extract whether the total sentiment about Goldman Sachs on that day is positive, neutral, or negative (as a score from 0 to 1). As many investors closely read the news and make investment decisions based (partially of course) on news, there is a somewhat high chance that if, say, the news for Goldman Sachs today are extremely positive the stock will surge tomorrow. One crucial point, we will perform feature importance (meaning how indicative it is for the movement of GS) on absolutely every feature (including this one) later on and decide whether we will use it. More on that later. For the purpose of creating accurate sentiment prediction, we will use Neural Language Processing (NLP). We will use BERT — Google’s recently announced NLP approach for transfer learning for sentiment classification stock news sentiment extraction.Fourier transforms — Along with the daily closing price, we will create Fourier transforms in order to generalize several long- and short-term trends. Using these transforms we will eliminate a lot of noise (random walks) and create approximations of the real stock movement. Having trend approximations can help the LSTM network pick its prediction trends more accurately.Autoregressive Integrated Moving Average (ARIMA) — This was one of the most popular techniques for predicting future values of time series data (in the pre-neural networks ages). Let’s add it and see if it comes off as an important predictive feature.Stacked autoencoders — most of the aforementioned features (fundamental analysis, technical analysis, etc) were found by people after decades of research. But maybe we have missed something. Maybe there are hidden correlations that people cannot comprehend due to the enormous amount of data points, events, assets, charts, etc. With stacked autoencoders (type of neural networks) we can use the power of computers and probably find new types of features that affect stock movements. Even though we will not be able to understand these features in human language, we will use them in the GAN.Deep Unsupervised learning for anomaly detection in options pricing. We will use one more feature — for every day we will add the price for 90-days call option on Goldman Sachs stock. Options pricing itself combines a lot of data. The price for options contract depends on the future value of the stock (analysts try to also predict the price in order to come up with the most accurate price for the call option). Using deep unsupervised learning (Self-organized Maps) we will try to spot anomalies in every day’s pricing. Anomaly (such as a drastic change in pricing) might indicate an event that might be useful for the LSTM to learn the overall stock pattern.
Correlated assets — these are other assets (any type, not necessarily stocks, such as commodities, FX, indices, or even fixed income securities). A big company, such as Goldman Sachs, obviously doesn’t ‘live’ in an isolated world — it depends on, and interacts with, many external factors, including its competitors, clients, the global economy, the geo-political situation, fiscal and monetary policies, access to capital, etc. The details are listed later.
Technical indicators — a lot of investors follow technical indicators. We will include the most popular indicators as independent features. Among them — 7 and 21 days moving average, exponential moving average, momentum, Bollinger bands, MACD.
Fundamental analysis — A very important feature indicating whether a stock might move up or down. There are two features that can be used in fundamental analysis: 1) Analysing the company performance using 10-K and 10-Q reports, analysing ROE and P/E, etc (we will not use this), and 2) News — potentially news can indicate upcoming events that can potentially move the stock in certain direction. We will read all daily news for Goldman Sachs and extract whether the total sentiment about Goldman Sachs on that day is positive, neutral, or negative (as a score from 0 to 1). As many investors closely read the news and make investment decisions based (partially of course) on news, there is a somewhat high chance that if, say, the news for Goldman Sachs today are extremely positive the stock will surge tomorrow. One crucial point, we will perform feature importance (meaning how indicative it is for the movement of GS) on absolutely every feature (including this one) later on and decide whether we will use it. More on that later. For the purpose of creating accurate sentiment prediction, we will use Neural Language Processing (NLP). We will use BERT — Google’s recently announced NLP approach for transfer learning for sentiment classification stock news sentiment extraction.
Fourier transforms — Along with the daily closing price, we will create Fourier transforms in order to generalize several long- and short-term trends. Using these transforms we will eliminate a lot of noise (random walks) and create approximations of the real stock movement. Having trend approximations can help the LSTM network pick its prediction trends more accurately.
Autoregressive Integrated Moving Average (ARIMA) — This was one of the most popular techniques for predicting future values of time series data (in the pre-neural networks ages). Let’s add it and see if it comes off as an important predictive feature.
Stacked autoencoders — most of the aforementioned features (fundamental analysis, technical analysis, etc) were found by people after decades of research. But maybe we have missed something. Maybe there are hidden correlations that people cannot comprehend due to the enormous amount of data points, events, assets, charts, etc. With stacked autoencoders (type of neural networks) we can use the power of computers and probably find new types of features that affect stock movements. Even though we will not be able to understand these features in human language, we will use them in the GAN.
Deep Unsupervised learning for anomaly detection in options pricing. We will use one more feature — for every day we will add the price for 90-days call option on Goldman Sachs stock. Options pricing itself combines a lot of data. The price for options contract depends on the future value of the stock (analysts try to also predict the price in order to come up with the most accurate price for the call option). Using deep unsupervised learning (Self-organized Maps) we will try to spot anomalies in every day’s pricing. Anomaly (such as a drastic change in pricing) might indicate an event that might be useful for the LSTM to learn the overall stock pattern.
Next, having so many features, we need to perform a couple of important steps:
Perform statistical checks for the ‘quality’ of the data. If the data we create is flawed, then no matter how sophisticated our algorithms are, the results will not be positive. The checks include making sure the data does not suffer from heteroskedasticity, multicollinearity, or serial correlation.Create feature importance. If a feature (e.g. another stock or a technical indicator) has no explanatory power to the stock we want to predict, then there is no need for us to use it in the training of the neural nets. We will using XGBoost (eXtreme Gradient Boosting), a type of boosted tree regression algorithms.
Perform statistical checks for the ‘quality’ of the data. If the data we create is flawed, then no matter how sophisticated our algorithms are, the results will not be positive. The checks include making sure the data does not suffer from heteroskedasticity, multicollinearity, or serial correlation.
Create feature importance. If a feature (e.g. another stock or a technical indicator) has no explanatory power to the stock we want to predict, then there is no need for us to use it in the training of the neural nets. We will using XGBoost (eXtreme Gradient Boosting), a type of boosted tree regression algorithms.
As a final step of our data preparation, we will also create Eigen portfolios using Principal Component Analysis (PCA) in order to reduce the dimensionality of the features created from the autoencoders.
print('There are {} number of days in the dataset.'.format(dataset_ex_df.shape[0]))output >>> There are 2265 number of days in the dataset.
Let’s visualize the stock for the last nine years. The dashed vertical line represents the separation between training and test data.
As explained earlier we will use other assets as features, not only GS.
So what other assets would affect GS’s stock movements? Good understanding of the company, its lines of businesses, competitive landscape, dependencies, suppliers and client type, etc is very important for picking the right set of correlated assets:
First are the companies similar to GS. We will add JPMorgan Chase and Morgan Stanley, among others, to the dataset.
As an investment bank, Goldman Sachs depends on the global economy. Bad or volatile economy means no M&As or IPOs, and possibly limited proprietary trading earnings. That is why we will include global economy indices. Also, we will include LIBOR (USD and GBP denominated) rate, as possibly shocks in the economy might be accounted for by analysts to set these rates, and other FI securities.
Daily volatility index (VIX) — for the reason described in the previous point.
Composite indices — such as NASDAQ and NYSE (from USA), FTSE100 (UK), Nikkei225 (Japan), Hang Seng and BSE Sensex (APAC) indices.
Currencies — global trade is many times reflected into how currencies move, ergo we’ll use a basket of currencies (such as USDJPY, GBPUSD, etc) as features.
We already covered what are technical indicators and why we use them so let’s jump straight to the code. We will create technical indicators only for GS.
""" Function to create the technical indicators """def get_technical_indicators(dataset): # Create 7 and 21 days Moving Average dataset['ma7'] = dataset['price'].rolling(window=7).mean() dataset['ma21'] = dataset['price'].rolling(window=21).mean() # Create MACD dataset['26ema'] = pd.ewma(dataset['price'], span=26) dataset['12ema'] = pd.ewma(dataset['price'], span=12) dataset['MACD'] = (dataset['12ema']-dataset['26ema'])# Create Bollinger Bands dataset['20sd'] = pd.stats.moments.rolling_std(dataset['price'],20) dataset['upper_band'] = dataset['ma21'] + (dataset['20sd']*2) dataset['lower_band'] = dataset['ma21'] - (dataset['20sd']*2) # Create Exponential moving average dataset['ema'] = dataset['price'].ewm(com=0.5).mean() # Create Momentum dataset['momentum'] = dataset['price']-1 return dataset
So we have the technical indicators (including MACD, Bollinger bands, etc) for every trading day. We have in total 12 technical indicators.
Let’s visualise the last 400 days for these indicators.
For fundamental analysis we will perform sentiment analysis on all daily news about GS. Using sigmoid at the end, result will be between 0 and 1. The closer the score is to 0 — the more negative the news is (closer to 1 indicates positive sentiment). For each day, we will create the average daily score (as a number between 0 and 1) and add it as a feature.
For the purpose of classifying news as positive or negative (or neutral) we will use BERT, which is a pre-trained language representation.
Pre-trained BERT models are already available in MXNet/Gluon. We just need to instantiated them and add two (arbitrary number) Dense layers, going to softmax - the score is from 0 to 1.
import bert
Going into the details of BERT and the NLP part is not in the scope of this notebook, but you have interest, do let me know — I will create a new repo only for BERT as it definitely is quite promising when it comes to language processing tasks.
Fourier transforms take a function and create a series of sine waves (with different amplitudes and frames). When combined, these sine waves approximate the original function. Mathematically speaking, the transforms look like this:
We will use Fourier transforms to extract global and local trends in the GS stock, and to also denoise it a little. So let’s see how it works.
""" Code to create the Fuorier trasfrom """data_FT = dataset_ex_df[['Date', 'GS']]close_fft = np.fft.fft(np.asarray(data_FT['GS'].tolist()))fft_df = pd.DataFrame({'fft':close_fft})fft_df['absolute'] = fft_df['fft'].apply(lambda x: np.abs(x))fft_df['angle'] = fft_df['fft'].apply(lambda x: np.angle(x))plt.figure(figsize=(14, 7), dpi=100)fft_list = np.asarray(fft_df['fft'].tolist())for num_ in [3, 6, 9, 100]: fft_list_m10= np.copy(fft_list); fft_list_m10[num_:-num_]=0 plt.plot(np.fft.ifft(fft_list_m10), label='Fourier transform with {} components'.format(num_))plt.plot(data_FT['GS'], label='Real')plt.xlabel('Days')plt.ylabel('USD')plt.title('Figure 3: Goldman Sachs (close) stock prices & Fourier transforms')plt.legend()plt.show()
As you see in Figure 3 the more components from the Fourier transform we use the closer the approximation function is to the real stock price (the 100 components transform is almost identical to the original function — the red and the purple lines almost overlap). We use Fourier transforms for the purpose of extracting long- and short-term trends so we will use the transforms with 3, 6, and 9 components. You can infer that the transform with 3 components serves as the long term trend.
Another technique used to denoise data is called wavelets. Wavelets and Fourier transform gave similar results so we will only use Fourier transforms.
ARIMA is a technique for predicting time series data. We will show how to use it, and althouth ARIMA will not serve as our final prediction, we will use it as a technique to denoise the stock a little and to (possibly) extract some new patters or features.
error = mean_squared_error(test, predictions)print('Test MSE: %.3f' % error)output >>> Test MSE: 10.151
As we can see from Figure 5 ARIMA gives a very good approximation of the real stock price. We will use the predicted price through ARIMA as an input feature into the LSTM because, as we mentioned before, we want to capture as many features and patterns about Goldman Sachs as possible. We go test MSE (mean squared error) of 10.151, which by itself is not a bad result (considering we do have a lot of test data), but still, we will only use it as a feature in the LSTM.
Ensuring that the data has good quality is very important for our models. In order to make sure our data is suitable we will perform a couple of simple checks in order to ensure that the results we achieve and observe are indeed real, rather than compromised due to the fact that the underlying data distribution suffers from fundamental errors.
Conditional Heteroskedasticity occurs when the error terms (the difference between a predicted value by a regression and the real value) are dependent on the data — for example, the error terms grow when the data point (along the x-axis) grow.
Multicollinearity is when error terms (also called residuals) depend on each other.
Serial correlation is when one data (feature) is a formula (or completely depends) of another feature.
We will not go into the code here as it is straightforward and our focus is more on the deep learning parts, but the data is qualitative.
print('Total dataset has {} samples, and {} features.'.format(dataset_total_df.shape[0], dataset_total_df.shape[1]))output >>> Total dataset has 2265 samples, and 112 features.
So, after adding all types of data (the correlated assets, technical indicators, fundamental analysis, Fourier, and Arima) we have a total of 112 features for the 2,265 days (as mentioned before, however, only 1,585 days are for training data).
We will also have some more features generated from the autoencoders.
Having so many features we have to consider whether all of them are really indicative of the direction GS stock will take. For example, we included USD denominated LIBOR rates in the dataset because we think that changes in LIBOR might indicate changes in the economy, that, in turn, might indicate changes in the GS’s stock behavior. But we need to test. There are many ways to test feature importance, but the one we will apply uses XGBoost, because it gives one of the best results in both classification and regression problems.
Since the features dataset is quite large, for the purpose of the presentation here we’ll use only the technical indicators. During the real features importance testing all selected features proved somewhat important so we won’t exclude anything when training the GAN.
regressor = xgb.XGBRegressor(gamma=0.0,n_estimators=150,base_score=0.7,colsample_bytree=1,learning_rate=0.05)xgbModel = regressor.fit(X_train_FI,y_train_FI, eval_set = [(X_train_FI, y_train_FI), (X_test_FI, y_test_FI)], verbose=False)fig = plt.figure(figsize=(8,8))plt.xticks(rotation='vertical')plt.bar([i for i in range(len(xgbModel.feature_importances_))], xgbModel.feature_importances_.tolist(), tick_label=X_test_FI.columns)plt.title('Figure 6: Feature importance of the technical indicators.')plt.show()
Not surprisingly (for those with experience in stock trading) that MA7, MACD, and BB are among the important features.
I followed the same logic for performing feature importance over the whole dataset — just the training took longer and results were a little more difficult to read, as compared with just a handful of features.
Before we proceed to the autoencoders, we’ll explore an alternative activation function.
GELU — Gaussian Error Linear Unites was recently proposed — link. In the paper the authors show several instances in which neural networks using GELU outperform networks using ReLU as an activation. gelu is also used in BERT, the NLP approach we used for news sentiment analysis.
We will use GELU for the autoencoders.
Note: The cell below shows the logic behind the math of GELU. It is not the actual implementation as an activation function. I had to implement GELU inside MXNet. If you follow the code and change act_type='relu' to act_type='gelu' it will not work, unless you change the implementation of MXNet. Make a pull request on the whole project to access the MXNet implementation of GELU.
Let’s visualize GELU, ReLU, and LeakyReLU (the last one is mainly used in GANs - we also use it).
def gelu(x): return 0.5 * x * (1 + math.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * math.pow(x, 3))))def relu(x): return max(x, 0)def lrelu(x): return max(0.01*x, x)plt.figure(figsize=(15, 5))plt.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=.5, hspace=None)ranges_ = (-10, 3, .25)plt.subplot(1, 2, 1)plt.plot([i for i in np.arange(*ranges_)], [relu(i) for i in np.arange(*ranges_)], label='ReLU', marker='.')plt.plot([i for i in np.arange(*ranges_)], [gelu(i) for i in np.arange(*ranges_)], label='GELU')plt.hlines(0, -10, 3, colors='gray', linestyles='--', label='0')plt.title('Figure 7: GELU as an activation function for autoencoders')plt.ylabel('f(x) for GELU and ReLU')plt.xlabel('x')plt.legend()plt.subplot(1, 2, 2)plt.plot([i for i in np.arange(*ranges_)], [lrelu(i) for i in np.arange(*ranges_)], label='Leaky ReLU')plt.hlines(0, -10, 3, colors='gray', linestyles='--', label='0')plt.ylabel('f(x) for Leaky ReLU')plt.xlabel('x')plt.title('Figure 8: LeakyReLU')plt.legend()plt.show()
Note: In future versions of this notebook I will experiment using U-Net (link), and try to utilize the convolutional layer and extract (and create) even more features about the stock’s underlying movement patterns. For now, we will just use a simple autoencoder made only from Dense layers.
Ok, back to the autoencoders, depicted below (the image is only schematic, it doesn’t represent the real number of layers, units, etc.)
Note: One thing that I will explore in a later version is removing the last layer in the decoder. Normally, in autoencoders the number of encoders == number of decoders. We want, however, to extract higher level features (rather than creating the same input), so we can skip the last layer in the decoder. We achieve this creating the encoder and decoder with the same number of layers during the training, but when we create the output we use the layer next to the only one as it would contain the higher level features.
The full code for the autoencoders is available in the accompanying Github — link at top.
We created 112 more features from the autoencoder. As we want to only have high level features (overall patterns) we will create an Eigen portfolio on the newly created 112 features using Principal Component Analysis (PCA). This will reduce the dimension (number of columns) of the data. The descriptive capability of the Eigen portfolio will be the same as the original 112 features.
Note Once again, this is purely experimental. I am not 100% sure the described logic will hold. As everything else in AI and deep learning, this is art and needs experiments.
How GANs work?
As mentioned before, the purpose of this notebook is not to explain in detail the math behind deep learning but to show its applications. Of course, thorough and very solid understanding from the fundamentals down to the smallest details, in my opinion, is extremely imperative. Hence, we will try to balance and give a high-level overview of how GANs work in order for the reader to fully understand the rationale behind using GANs in predicting stock price movements. Feel free to skip this and the next section if you are experienced with GANs (and do check section 4.2.).
A GAN network consists of two models — a Generator (G) and Discriminator (D). The steps in training a GAN are:
The Generator is, using random data (noise denoted z), trying to ‘generate’ data indistinguishable of, or extremely close to, the real data. Its purpose is to learn the distribution of the real data.Randomly, real or generated data is fitted into the Discriminator, which acts as a classifier and tries to understand whether the data is coming from the Generator or is the real data. D estimates the (distributions) probabilities of the incoming sample to the real dataset. (more info on comparing two distributions in section 3.2. below).Then, the losses from G and D are combined and propagated back through the generator. Ergo, the generator’s loss depends on both the generator and the discriminator. This is the step that helps the Generator learn about the real data distribution. If the generator doesn’t do a good job at generating a realistic data (having the same distribution), the Discriminator’s work will be very easy to distinguish generated from real data sets. Hence, the Discriminator’s loss will be very small. Small discriminator loss will result in bigger generator loss (see the equation below for L(D,G)). This makes creating the discriminator a bit tricky, because too good of a discriminator will always result in a huge generator loss, making the generator unable to learn.The process goes on until the Discriminator can no longer distinguish generated from real data.
The Generator is, using random data (noise denoted z), trying to ‘generate’ data indistinguishable of, or extremely close to, the real data. Its purpose is to learn the distribution of the real data.
Randomly, real or generated data is fitted into the Discriminator, which acts as a classifier and tries to understand whether the data is coming from the Generator or is the real data. D estimates the (distributions) probabilities of the incoming sample to the real dataset. (more info on comparing two distributions in section 3.2. below).
Then, the losses from G and D are combined and propagated back through the generator. Ergo, the generator’s loss depends on both the generator and the discriminator. This is the step that helps the Generator learn about the real data distribution. If the generator doesn’t do a good job at generating a realistic data (having the same distribution), the Discriminator’s work will be very easy to distinguish generated from real data sets. Hence, the Discriminator’s loss will be very small. Small discriminator loss will result in bigger generator loss (see the equation below for L(D,G)). This makes creating the discriminator a bit tricky, because too good of a discriminator will always result in a huge generator loss, making the generator unable to learn.
The process goes on until the Discriminator can no longer distinguish generated from real data.
When combined together, D and G as sort of playing a minmax game (the Generator is trying to fool the Discriminator making it increase the probability for on fake examples, i.e. minimize Ez∼pz(z)[log(1−D(G(z)))]. The Discriminator wants to separate the data coming from the Generator, D(G(z)), by maximizing Ex∼pr(x)[logD(x)]. Having separated loss functions, however, it is not clear how both can converge together (that is why we use some advancements over the plain GANs, such as Wasserstein GAN). Overall, the combined loss function looks like:
Note: Really useful tips for training GANs can be found here.
Note: I will not include the complete code behind the GAN and the Reinforcement learning parts in this notebook — only the results from the execution (the cell outputs) will be shown. Make a pull request or contact me for the code.
Generative Adversarial Networks (GAN) have been recently used mainly in creating realistic images, paintings, and video clips. There aren’t many applications of GANs being used for predicting time-series data as in our case. The main idea, however, should be same — we want to predict future stock movements. In the future, the pattern and behavior of GS’s stock should be more or less the same (unless it starts operating in a totally different way, or the economy drastically changes). Hence, we want to ‘generate’ data for the future that will have similar (not absolutely the same, of course) distribution as the one we already have — the historical trading data. So, in theory, it should work.
In our case, we will use LSTM as a time-series generator, and CNN as a discriminator.
Note: The next couple of sections assume some experience with GANs.
A recent improvement over the traditional GANs came out from Uber’s engineering team and is called Metropolis-Hastings GAN (MHGAN). The idea behind Uber’s approach is (as they state it) somewhat similar to another approach created by Google and University of California, Berkeley called Discriminator Rejection Sampling (DRS). Basically, when we train GAN we use the Discriminator (D) for the sole purpose of better training the Generator (G). Often, after training the GAN we do not use the D any more. MHGAN and DRS, however, try to use D in order to choose samples generated by G that are close to the real data distribution (slight difference between is that MHGAN uses Markov Chain Monte Carlo (MCMC) for sampling).
MHGAN takes K samples generated from the G (created from independent noise inputs to the G — z0 to zK in the figure below). Then it sequentially runs through the K outputs (x′0 to x′K) and following an acceptance rule (created from the Discriminator) decides whether to accept the current sample or keep the last accepted one. The last kept output is the one considered the real output of G.
Note: MHGAN is originally implemented by Uber in pytorch. I only transferred it into MXNet/Gluon.
Figure 10: Visual representation of MHGAN (from the original Uber post).
Training GANs is quite difficult. Models may never converge and mode collapse can easily happen. We will use a modification of GAN called Wasserstein GAN — WGAN.
Again, we will not go into details, but the most notable points to make are:
As we know the main goal behind GANs is for the Generator to start transforming random noise into some given data that we want to mimic. Ergo, the idea of comparing the similarity between two distributions is very imperative in GANs. The two most widely used such metrics are:
KL divergence (Kullback–Leibler) — DKL(p‖q)=∫xp(x)logp(x)q(x)dx. DKL is zero when p(x) is equal to q(x),
JS Divergence (Jensen–Shannon). JS divergence is bounded by 0 and 1, and, unlike KL divergence, is symmetric and smoother. Significant success in GAN training was achieved when the loss was switched from KL to JS divergence.
WGAN uses Wasserstein distance, W(pr,pg)=1Ksup‖f‖L≤KEx∼pr[f(x)]−Ex∼pg[f(x)] (where sup stands for supremum), as a loss function (also called Earth Mover’s distance, because it normally is interpreted as moving one pile of, say, sand to another one, both piles having different probability distributions, using minimum energy during the transformation). Compared to KL and JS divergences, Wasserstein metric gives a smooth measure (without sudden jumps in divergence). This makes it much more suitable for creating a stable learning process during the gradient descent.
Also, compared to KL and JS, Wasserstein distance is differentiable nearly everywhere. As we know, during backpropagation, we differentiate the loss function in order to create the gradients, which in turn update the weights. Therefore, having a differentiable loss function is quite important.
As mentioned before, the generator is a LSTM network a type of Recurrent Neural Network (RNN). RNNs are used for time-series data because they keep track of all previous data points and can capture patterns developing through time. Due to their nature, RNNs many time suffer from vanishing gradient — that is, the changes the weights receive during training become so small, that they don’t change, making the network unable to converge to a minimal loss (The opposite problem can also be observed at times — when gradients become too big. This is called gradient exploding, but the solution to this is quite simple — clip gradients if they start exceeding some constant number, i.e. gradient clipping). Two modifications tackle this problem — Gated Recurrent Unit (GRU) and Long-Short Term Memory (LSTM). The biggest differences between the two are: 1) GRU has 2 gates (update and reset) and LSTM has 4 (update, input, forget, and output), 2) LSTM maintains an internal memory state, while GRU doesn’t, and 3) LSTM applies a nonlinearity (sigmoid) before the output gate, GRU doesn’t.
In most cases, LSTM and GRU give similar results in terms of accuracy but GRU is much less computational intensive, as GRU has much fewer trainable params. LSTMs, however, and much more used.
Strictly speaking, the math behind the LSTM cell (the gates) is:
where ⊙is an element-wise multiplication operator, and, for all x=[x1,x2,...,xk]⊤∈R^k the two activation functions:,
The LSTM architecture is very simple — one LSTM layer with 112 input units (as we have 112 features in the dataset) and 500 hidden units, and one Dense layer with 1 output - the price for every day. The initializer is Xavier and we will use L1 loss (which is mean absolute error loss with L1 regularization - see section 3.4.5. for more info on regularization).
Note — In the code you can see we use Adam (with learning rate of .01) as an optimizer. Don't pay too much attention on that now - there is a section specially dedicated to explain what hyperparameters we use (learning rate is excluded as we have learning rate scheduler - section 3.4.3.) and how we optimize these hyperparameters - section 3.6.
gan_num_features = dataset_total_df.shape[1]sequence_length = 17class RNNModel(gluon.Block): def __init__(self, num_embed, num_hidden, num_layers, bidirectional=False, sequence_length=sequence_length, **kwargs): super(RNNModel, self).__init__(**kwargs) self.num_hidden = num_hidden with self.name_scope(): self.rnn = rnn.LSTM(num_hidden, num_layers, input_size=num_embed, bidirectional=bidirectional, layout='TNC') self.decoder = nn.Dense(1, in_units=num_hidden) def forward(self, inputs, hidden): output, hidden = self.rnn(inputs, hidden) decoded = self.decoder(output.reshape((-1,self.num_hidden))) return decoded, hidden def begin_state(self, *args, **kwargs): return self.rnn.begin_state(*args, **kwargs) lstm_model = RNNModel(num_embed=gan_num_features, num_hidden=500, num_layers=1)lstm_model.collect_params().initialize(mx.init.Xavier(), ctx=mx.cpu())trainer = gluon.Trainer(lstm_model.collect_params(), 'adam', {'learning_rate': .01})loss = gluon.loss.L1Loss()
We will use 500 neurons in the LSTM layer and use Xavier initialization. For regularization we’ll use L1. Let’s see what’s inside the LSTM as printed by MXNet.
print(lstm_model)output >>>RNNModel( (rnn): LSTM(112 -> 500, TNC) (decoder): Dense(500 -> 1, linear))
As we can see, the input of the LSTM are the 112 features (dataset_total_df.shape[1]) which then go into 500 neurons in the LSTM layer, and then transformed to a single output - the stock price value.
The logic behind the LSTM is: we take 17 (sequence_length) days of data (again, the data being the stock price for GS stock every day + all the other feature for that day - correlated assets, sentiment, etc.) and try to predict the 18th day. Then we move the 17 days window with one day and again predict the 18th. We iterate like this over the whole dataset (of course in batches).
In another post I will explore whether modification over the vanilla LSTM would be more beneficial, such as:
using bidirectional LSTM layer — in theory, going backwards (from end of the data set towards the beginning) might somehow help the LSTM figure out the pattern of the stock movement.
using stacked RNN architecture — having not only one LSTM layer but 2 or more. This, however, might be dangerous, as we might end up overfitting the model, as we don’t have a lot of data (we have just 1,585 day worth of data).
Exploring GRU — as already explained, GRUs’ cells are much simpler.
Adding attention vectors to the RNN.
One of the most important hyperparameters is the learning rate. Setting the learning rate for almost every optimizer (such as SGD, Adam, or RMSProp) is crucially important when training neural networks because it controls both the speed of convergence and the ultimate performance of the network. One of the simplest learning rate strategies is to have a fixed learning rate throughout the training process. Choosing a small learning rate allows the optimizer find good solutions, but this comes at the expense of limiting the initial speed of convergence. Changing the learning rate over time can overcome this tradeoff.
Recent papers, such as this one, show the benefits of changing the global learning rate during training, in terms of both convergence and time. Let’s plot the learning rates we’ll be using for each epoch.
schedule = CyclicalSchedule(TriangularSchedule, min_lr=0.5, max_lr=2, cycle_length=500)iterations=1500plt.plot([i+1 for i in range(iterations)],[schedule(i) for i in range(iterations)])plt.title('Learning rate for each epoch')plt.xlabel("Epoch")plt.ylabel("Learning Rate")plt.show()
Having a lot of features and neural networks we need to make sure we prevent overfitting and be mindful of the total loss.
We use several techniques for preventing overfitting (not only in the LSTM, but also in the CNN and the auto-encoders):
Ensuring data quality. We already performed statistical checks and made sure the data doesn’t suffer from multicollinearity or serial autocorrelation. Further we performed feature importance check on each feature. Finally, the initial feature selection (e.g. selecting correlated assets, technical indicators, etc.) was done with some domain knowledge about the mechanics behind the way stock markets work.
Regularization (or weights penalty). The two most widely used regularization techniques are LASSO (L1) and Ridge (L2). L1 adds the mean absolute error and L2 adds mean squared error to the loss. Without going into too many mathematical details, the basic differences are: lasso regression (L1) does both variable selection and parameter shrinkage, whereas Ridge regression only does parameter shrinkage and end up including all the coefficients in the model. In presence of correlated variables, ridge regression might be the preferred choice. Also, ridge regression works best in situations where the least square estimates have higher variance. Therefore, it depends on our model objective. The impact of the two types of regularizations is quite different. While they both penalize large weights, L1 regularization leads to a non-differentiable function at zero. L2 regularization favors smaller weights, but L1 regularization favors weights that go to zero. So, with L1 regularization you can end up with a sparse model — one with fewer parameters. In both cases the parameters of the L1 and L2 regularized models “shrink”, but in the case of L1 regularization the shrinkage directly impacts the complexity (the number of parameters) of the model. Precisely, ridge regression works best in situations where the least square estimates have higher variance. L1 is more robust to outliers, is used when data is sparse, and creates feature importance. We will use L1.
Dropout. Dropout layers randomly remove nodes in the hidden layers.
Dense-sparse-dense training. — link
Early stopping.
Another important consideration when building complex neural networks is the bias-variance trade-off. Basically, the error we get when training nets is a function of the bias, the variance, and irreducible error — σ (error due to noise and randomness). The simplest formula of the trade-off is: Error=bias^2+variance+σ.
Bias. Bias measures how well a trained (on training dataset) algorithm can generalize on unseen data. High bias (underfitting) meaning the model cannot work well on unseen data.
Variance. Variance measures the sensitivity of the model to changes in the dataset. High variance is the overfitting.
We usually use CNNs for work related to images (classification, context extraction, etc). They are very powerful at extracting features from features from features, etc. For example, in an image of a dog, the first convolutional layer will detect edges, the second will start detecting circles, and the third will detect a nose. In our case, data points form small trends, small trends form bigger, trends in turn form patterns. CNNs’ ability to detect features can be used for extracting information about patterns in GS’s stock price movements.
Another reason for using CNN is that CNNs work well on spatial data — meaning data points that are closer to each other are more related to each other, than data points spread across. This should hold true for time series data. In our case each data point (for each feature) is for each consecutive day. It is natural to assume that the closer two days are to each other, the more related they are to each other. One thing to consider (although not covered in this work) is seasonality and how it might change (if at all) the work of the CNN.
Note: As many other parts in this notebook, using CNN for time series data is experimental. We will inspect the results, without providing mathematical or other proofs. And results might vary using different data, activation functions, etc.
Without going through the full code, we’ll just show the CNN as printed by MXNet.
Sequential( (0): Conv1D(None -> 32, kernel_size=(5,), stride=(2,)) (1): LeakyReLU(0.01) (2): Conv1D(None -> 64, kernel_size=(5,), stride=(2,)) (3): LeakyReLU(0.01) (4): BatchNorm(axis=1, eps=1e-05, momentum=0.9, fix_gamma=False, use_global_stats=False, in_channels=None) (5): Conv1D(None -> 128, kernel_size=(5,), stride=(2,)) (6): LeakyReLU(0.01) (7): BatchNorm(axis=1, eps=1e-05, momentum=0.9, fix_gamma=False, use_global_stats=False, in_channels=None) (8): Dense(None -> 220, linear) (9): BatchNorm(axis=1, eps=1e-05, momentum=0.9, fix_gamma=False, use_global_stats=False, in_channels=None) (10): LeakyReLU(0.01) (11): Dense(None -> 220, linear) (12): Activation(relu) (13): Dense(None -> 1, linear) )
The hyperparameters that we will track and optimize are:
batch_size : batch size of the LSTM and CNN
cnn_lr: the learningrate of the CNN
strides: the number of strides in the CNN
lrelu_alpha: the alpha for the LeakyReLU in the GAN
batchnorm_momentum: momentum for the batch normalisation in the CNN
padding: the padding in the CNN
kernel_size':1: kernel size in the CNN
dropout: dropout in the LSTM
filters: the initial number of filters
We will train over 200 epochs.
After the GAN trains on the 200 epochs it will record the MAE (which is the error function in the LSTM, the GG) and pass it as a reward value to the Reinforcement learning that will decide whether to change the hyperparameters of keep training with the same set of hyperparameters. As described later, this approach is strictly for experimenting with RL.
If the RL decides it will update the hyperparameters it will call Bayesian optimisation (discussed below) library that will give the next best expected set of the hyperparams
Why do we use reinforcement learning in the hyperparameters optimization? Stock markets change all the time. Even if we manage to train our GAN and LSTM to create extremely accurate results, the results might only be valid for a certain period. Meaning, we need to constantly optimise the whole process. To optimize the process we can:
Add or remove features (e.g. add new stocks or currencies that might be correlated)
Improve our deep learning models. One of the most important ways to improve the models is through the hyper parameters (listed in Section 5). Once having found a certain set of hyperparameters we need to decide when to change them and when to use the already known set (exploration vs. exploitation). Also, stock market represents a continuous space that depends on millions parameters.
Note: The purpose of the whole reinforcement learning part of this notebook is more research oriented. We will explore different RL approaches using the GAN as an environment. There are many ways in which we can successfully perform hyperparameter optimization on our deep learning models without using RL. But... why not.
Note: The next several sections assume you have some knowledge about RL — especially policy methods and Q-learning.
Without explaining the basics of RL we will jump into the details of the specific approaches we implement here. We will use model-free RL algorithms for the obvious reason that we do not know the whole environment, hence there is no defined model for how the environment works — if there was we wouldn’t need to predict stock prices movements — they will just follow the model. We will use the two subdivisions of model-free RL — Policy optimization and Q-learning.
Q-learning — in Q-learning we learn the value of taking an action from a given state. Q-value is the expected return after taking the action. We will use Rainbow which is a combination of seven Q learning algorithms.
Policy Optimization — in policy optimization we learn the action to take from a given state. (if we use methods like Actor/Critic) we also learn the value of being in a given state. We will use Proximal Policy Optimization.
One crucial aspect of building a RL algorithm is accurately setting the reward. It has to capture all aspects of the environment and the agent’s interaction with the environment. We define the reward, R, as:
Reward=2∗lossG+lossD+accuracyG,
where lossG, accuracyG, and lossD are the Generator’s loss and accuracy, and Discriminator’s loss, respectively. The environment is the GAN and the results of the LSTM training. The action the different agents can take is how to change the hyperparameters of the GAN’s D and G nets.
What is Rainbow?
Rainbow (link) is a Q learning based off-policy deep reinforcement learning algorithm combining seven algorithm together:
DQN. DQN is an extension of Q learning algorithm that uses a neural network to represent the Q value. Similar to supervised (deep) learning, in DQN we train a neural network and try to minimize a loss function. We train the network by randomly sampling transitions (state, action, reward). The layers can be not only fully connected ones, but also convolutional, for example.
Double Q Learning. Double QL handles a big problem in Q learning, namely the overestimation bias.
Prioritized replay. In the vanilla DQN, all transitions are stored in a replay buffer and it uniformly samples this buffer. However, not all transitions are equally beneficial during the learning phase (which also makes learning inefficient as more episodes are required). Prioritized experience replay doesn’t sample uniformly, rather it uses a distribution that gives higher probability to samples that have had higher Q loss in previous iterations.
Dueling networks. Dueling networks change the Q learning architecture a little by using two separate streams (i.e. having two different mini-neural networks). One stream is for the value and one for the advantage. Both of them share a convolutional encoder. The tricky part is the merging of the streams — it uses a special aggregator (Wang et al. 2016).
(Advantage, formula is A(s,a)=Q(s,a)−V(s), generally speaking is a comparison of how good an action is compared to the average action for a specific state. Advantages are sometimes used when a ‘wrong’ action cannot be penalized with negative reward. So advantage will try to further reward good actions from the average actions.)
Multi-step learning. The big difference behind Multi-step learning is that it calculates the Q-values using N-step returns (not only the return from the next step), which naturally should be more accurate.
Distributional RL. Q learning uses average estimated Q-value as target value. However, in many cases the Q-values might not be the same in different situations. Distributional RL can directly learn (or approximate) the distribution of Q-values rather than averaging them. Again, the math is much more complicated than that, but for us the benefit is more accurate sampling of the Q-values.
Noisy Nets. Basic DQN implements a simple ε-greedy mechanism to do exploration. This approach to exploration inefficient at times. The way Noisy Nets approach this issue is by adding a noisy linear layer. Over time, the network will learn how to ignore the noise (added as a noisy stream). But this learning comes at different rates in different parts of the space, allowing for state exploration.
Note: Stay tuned — I will upload a MXNet/Gluon implementation on Rainbow to Github in early February 2019.
Proximal Policy Optimization (PPO) is a policy optimization model-free type of reinforcement learning. It is much simpler to implement that other algorithms and gives very good results.
Why do we use PPO? One of the advantages of PPO is that it directly learns the policy, rather than indirectly via the values (the way Q Learning uses Q-values to learn the policy). It can work well in continuous action spaces, which is suitable in our use case and can learn (through mean and standard deviation) the distribution probabilities (if softmax is added as an output).
The problem of policy gradient methods is that they are extremely sensitive to the step size choice — if it is small the progress takes too long (most probably mainly due to the need of a second-order derivatives matrix); if it is large, there is a lot noise which significantly reduces the performance. Input data is nonstationary due to the changes in the policy (also the distributions of the reward and observations change). As compared to supervised learning, poorly chosen step can be much more devastating as it affects the whole distribution of next visits. PPO can solve these issues. What is more, compared to some other approaches, PPO:
is much less complicated, for example compared to ACER, which requires additional code for keeping the off-policy correlations and also a replay buffer, or TRPO which has a constraint imposed on the surrogate objective function (the KL divergence between the old and the new policy). This constraint is used to control the policy of changing too much — which might create instability. PPO reduces the computation (created by the constraint) by utilizing a clipped (between [1- ε, 1+ε]) surrogate objective function and modifying the objective function with a penalty for having too big of an update.
gives compatibility with algos that share parameters between value and policy function or auxiliary losses, as compared to TRPO (although PPO also have the gain of trust region PO).
Note: For the purpose of our exercise we won’t go too much into the research and optimization of RL approaches, PPO and the others included. Rather, we will take what is available and try to fit into our process for hyperparameter optimization for our GAN, LSTM, and CNN models. The code we will reuse and customize is created by OpenAI and is available here.
Some ideas for further exploring reinforcement learning:
One of the first things I will introduce next is using Augmented Random Search (link) as an alternative algorithm. The authors of the algorithm (out of UC, Berkeley) have managed to achieve similar rewards results as other state of the art approaches, such as PPO, but on average 15 times faster.
Choosing a reward function is very important. I stated the currently used reward function above, but I will try to play with different functions as an alternative.
Using Curiosity as an exploration policy.
Create multi-agent architecture as proposed by Berkeley’s AI Research team (BAIR) — link.
Instead of the grid search, that can take a lot of time to find the best combination of hyperparameters, we will use Bayesian optimization. The library that we’ll use is already implemented — link.
Finally we will compare the output of the LSTM when the unseen (test) data is used as an input after different phases of the process.
Plot after the first epoch.
Plot after the first epoch.
from utils import plot_predictionplot_prediction('Predicted and Real price - after first epoch.')
2. Plot after 50 epochs.
plot_prediction('Predicted and Real price - after first 50 epochs.')
plot_prediction('Predicted and Real price - after first 200 epochs.')
The RL run for ten episodes (we define an eposide to be one full GAN training on the 200 epochs.)
plot_prediction('Final result.')
Next, I will try to create a RL environment for testing trading algorithms that decide when and how to trade. The output from the GAN will be one of the parameters in the environment.
This notebook is entirely informative. None of the content presented in this notebook constitutes a recommendation that any particular security, portfolio of securities, transaction or investment strategy is suitable for any specific person. Futures, stocks and options trading involves substantial risk of loss and is not suitable for every investor. The valuation of futures, stocks and options may fluctuate, and, as a result, clients may lose more than their original investment.
All trading strategies are used at your own risk.
There are many many more details to explore — in choosing data features, in choosing algorithms, in tuning the algos, etc. This version of the notebook itself took me 2 weeks to finish. I am sure there are many unaswered parts of the process. So, any comments and suggestion — please do share. I’d be happy to add and test any ideas in the current process.
Thanks for reading.
|
[
{
"code": null,
"e": 253,
"s": 171,
"text": "Link to the complete notebook: https://github.com/borisbanushev/stockpredictionai"
},
{
"code": null,
"e": 796,
"s": 253,
"text": "In this notebook I will create a complete process for predicting stock price movements. Follow along and we will achieve some pretty good results. For that purpose we will use a Generative Adversarial Network (GAN) with LSTM, a type of Recurrent Neural Network, as generator, and a Convolutional Neural Network, CNN, as a discriminator. We use LSTM for the obvious reason that we are trying to predict time series data. Why we use GAN and specifically CNN as a discriminator? That is a good question: there are special sections on that later."
},
{
"code": null,
"e": 1332,
"s": 796,
"text": "We will go into greater details for each step, of course, but the most difficult part is the GAN: very tricky part of successfully training a GAN is getting the right set of hyperparameters. For that reason we will use Bayesian optimisation (along with Gaussian processes) and Deep Reinforcement learning (DRL) for deciding when and how to change the GAN’s hyper parameters (the exploration vs. exploitation dilemma). In creating the reinforcement learning I will use the most recent advancements in the field, such as Rainbow and PPO."
},
{
"code": null,
"e": 2255,
"s": 1332,
"text": "We will use a lot of different types of input data. Along with the stock’s historical trading data and technical indicators, we will use the newest advancements in NLP (using ‘Bidirectional Embedding Representations from Transformers’, BERT, sort of a transfer learning for NLP) to create sentiment analysis (as a source for fundamental analysis), Fourier transforms for extracting overall trend directions, stacked autoencoders for identifying other high-level features, Eigen portfolios for finding correlated assets, autoregressive integrated moving average (ARIMA) for the stock function approximation, and many more, in order to capture as much information, patterns, dependencies, etc, as possible about the stock. As we all know, the more (data) the merrier. Predicting stock price movements is an extremely complex task, so the more we know about the stock (from different perspectives) the higher our changes are."
},
{
"code": null,
"e": 2382,
"s": 2255,
"text": "For the purpose of creating all neural nets we will use MXNet and its high-level API — Gluon, and train them on multiple GPUs."
},
{
"code": null,
"e": 2849,
"s": 2382,
"text": "Note: Although I try to get into details of the math and the mechanisms behind almost all algorithms and techniques, this notebook is not explicitly intended to explain how machine/deep learning, or the stock markets, work. The purpose is rather to show how we can use different techniques and algorithms for the purpose of accurately predicting stock price movements, and to also give rationale behind the reason and usefulness of using each technique at each step."
},
{
"code": null,
"e": 2865,
"s": 2849,
"text": "1. Introduction"
},
{
"code": null,
"e": 2877,
"s": 2865,
"text": "2. The Data"
},
{
"code": null,
"e": 2900,
"s": 2877,
"text": "2.1. Correlated assets"
},
{
"code": null,
"e": 2926,
"s": 2900,
"text": "2.2. Technical indicators"
},
{
"code": null,
"e": 2952,
"s": 2926,
"text": "2.3. Fundamental analysis"
},
{
"code": null,
"e": 3024,
"s": 2952,
"text": "2.3.1. Bidirectional Embedding Representations from Transformers — BERT"
},
{
"code": null,
"e": 3067,
"s": 3024,
"text": "2.4. Fourier transforms for trend analysis"
},
{
"code": null,
"e": 3091,
"s": 3067,
"text": "2.5. ARIMA as a feature"
},
{
"code": null,
"e": 3115,
"s": 3091,
"text": "2.6. Statistical checks"
},
{
"code": null,
"e": 3180,
"s": 3115,
"text": "2.6.1. Heteroskedasticity, multicollinearity, serial correlation"
},
{
"code": null,
"e": 3205,
"s": 3180,
"text": "2.7. Feature Engineering"
},
{
"code": null,
"e": 3244,
"s": 3205,
"text": "2.7.1. Feature importance with XGBoost"
},
{
"code": null,
"e": 3306,
"s": 3244,
"text": "2.8. Extracting high-level features with Stacked Autoencoders"
},
{
"code": null,
"e": 3357,
"s": 3306,
"text": "2.8.1. Activation function — GELU (Gaussian Error)"
},
{
"code": null,
"e": 3397,
"s": 3357,
"text": "3. Generative Adversarial Network (GAN)"
},
{
"code": null,
"e": 3438,
"s": 3397,
"text": "3.1. Why GAN for stock market prediction"
},
{
"code": null,
"e": 3487,
"s": 3438,
"text": "3.2. Metropolis-Hastings GAN and Wasserstein GAN"
},
{
"code": null,
"e": 3522,
"s": 3487,
"text": "3.4. The Generator — One layer RNN"
},
{
"code": null,
"e": 3541,
"s": 3522,
"text": "3.4.1. LSTM or GRU"
},
{
"code": null,
"e": 3570,
"s": 3541,
"text": "3.4.2. The LSTM architecture"
},
{
"code": null,
"e": 3601,
"s": 3570,
"text": "3.4.3. Learning rate scheduler"
},
{
"code": null,
"e": 3667,
"s": 3601,
"text": "3.4.4. How to prevent overfitting and the bias-variance trade-off"
},
{
"code": null,
"e": 3712,
"s": 3667,
"text": "3.5. The Discriminator — One Dimentional CNN"
},
{
"code": null,
"e": 3747,
"s": 3712,
"text": "4.5.1. Why CNN as a discriminator?"
},
{
"code": null,
"e": 3775,
"s": 3747,
"text": "3.5.1. The CNN Architecture"
},
{
"code": null,
"e": 3796,
"s": 3775,
"text": "3.6. Hyperparameters"
},
{
"code": null,
"e": 3828,
"s": 3796,
"text": "4. Hyperparameters optimisation"
},
{
"code": null,
"e": 3889,
"s": 3828,
"text": "4.1. Reinforcement learning for hyperparameters optimization"
},
{
"code": null,
"e": 3926,
"s": 3889,
"text": "4.1.1. Reinforcement Learning Theory"
},
{
"code": null,
"e": 3943,
"s": 3926,
"text": "4.1.1.1. Rainbow"
},
{
"code": null,
"e": 3956,
"s": 3943,
"text": "4.1.1.2. PPO"
},
{
"code": null,
"e": 4002,
"s": 3956,
"text": "4.1.2. Further work on Reinforcement learning"
},
{
"code": null,
"e": 4029,
"s": 4002,
"text": "4.2. Bayesian optimization"
},
{
"code": null,
"e": 4053,
"s": 4029,
"text": "4.2.1. Gaussian process"
},
{
"code": null,
"e": 4067,
"s": 4053,
"text": "5. The Result"
},
{
"code": null,
"e": 4084,
"s": 4067,
"text": "6. What is next?"
},
{
"code": null,
"e": 4098,
"s": 4084,
"text": "7. Disclaimer"
},
{
"code": null,
"e": 4575,
"s": 4098,
"text": "Accurately predicting the stock markets is a complex task as there are millions of events and pre-conditions for a particular stock to move in a particular direction. So we need to be able to capture as many of these pre-conditions as possible. We also need make several important assumptions: 1) markets are not 100% random, 2) history repeats, 3) markets follow people’s rational behavior, and 4) the markets are ‘perfect’. And, please, do read the Disclaimer at the bottom."
},
{
"code": null,
"e": 4885,
"s": 4575,
"text": "We will try to predict the price movements of Goldman Sachs (NYSE: GS). For the purpose, we will use the daily closing price from January 1st, 2010 to December 31st, 2018 (seven years for training purposes and two years for validation purposes). We will use the terms ‘Goldman Sachs’ and ‘GS’ interchangeably."
},
{
"code": null,
"e": 5494,
"s": 4885,
"text": "We need to understand what affects whether GS’s stock price will move up or down. It is what people as a whole think. Hence, we need to incorporate as much information (depicting the stock from different aspects and angles) as possible. (We will use daily data — 1,585 days to train the various algorithms (70% of the data we have) and predict the next 680 days (test data). Then we will compare the predicted results with a test (hold-out) data. Each type of data (we will refer to it as feature) is explained in greater detail in later sections, but, as a high-level overview, the features we will use are:"
},
{
"code": null,
"e": 9360,
"s": 5494,
"text": "Correlated assets — these are other assets (any type, not necessarily stocks, such as commodities, FX, indices, or even fixed income securities). A big company, such as Goldman Sachs, obviously doesn’t ‘live’ in an isolated world — it depends on, and interacts with, many external factors, including its competitors, clients, the global economy, the geo-political situation, fiscal and monetary policies, access to capital, etc. The details are listed later.Technical indicators — a lot of investors follow technical indicators. We will include the most popular indicators as independent features. Among them — 7 and 21 days moving average, exponential moving average, momentum, Bollinger bands, MACD.Fundamental analysis — A very important feature indicating whether a stock might move up or down. There are two features that can be used in fundamental analysis: 1) Analysing the company performance using 10-K and 10-Q reports, analysing ROE and P/E, etc (we will not use this), and 2) News — potentially news can indicate upcoming events that can potentially move the stock in certain direction. We will read all daily news for Goldman Sachs and extract whether the total sentiment about Goldman Sachs on that day is positive, neutral, or negative (as a score from 0 to 1). As many investors closely read the news and make investment decisions based (partially of course) on news, there is a somewhat high chance that if, say, the news for Goldman Sachs today are extremely positive the stock will surge tomorrow. One crucial point, we will perform feature importance (meaning how indicative it is for the movement of GS) on absolutely every feature (including this one) later on and decide whether we will use it. More on that later. For the purpose of creating accurate sentiment prediction, we will use Neural Language Processing (NLP). We will use BERT — Google’s recently announced NLP approach for transfer learning for sentiment classification stock news sentiment extraction.Fourier transforms — Along with the daily closing price, we will create Fourier transforms in order to generalize several long- and short-term trends. Using these transforms we will eliminate a lot of noise (random walks) and create approximations of the real stock movement. Having trend approximations can help the LSTM network pick its prediction trends more accurately.Autoregressive Integrated Moving Average (ARIMA) — This was one of the most popular techniques for predicting future values of time series data (in the pre-neural networks ages). Let’s add it and see if it comes off as an important predictive feature.Stacked autoencoders — most of the aforementioned features (fundamental analysis, technical analysis, etc) were found by people after decades of research. But maybe we have missed something. Maybe there are hidden correlations that people cannot comprehend due to the enormous amount of data points, events, assets, charts, etc. With stacked autoencoders (type of neural networks) we can use the power of computers and probably find new types of features that affect stock movements. Even though we will not be able to understand these features in human language, we will use them in the GAN.Deep Unsupervised learning for anomaly detection in options pricing. We will use one more feature — for every day we will add the price for 90-days call option on Goldman Sachs stock. Options pricing itself combines a lot of data. The price for options contract depends on the future value of the stock (analysts try to also predict the price in order to come up with the most accurate price for the call option). Using deep unsupervised learning (Self-organized Maps) we will try to spot anomalies in every day’s pricing. Anomaly (such as a drastic change in pricing) might indicate an event that might be useful for the LSTM to learn the overall stock pattern."
},
{
"code": null,
"e": 9819,
"s": 9360,
"text": "Correlated assets — these are other assets (any type, not necessarily stocks, such as commodities, FX, indices, or even fixed income securities). A big company, such as Goldman Sachs, obviously doesn’t ‘live’ in an isolated world — it depends on, and interacts with, many external factors, including its competitors, clients, the global economy, the geo-political situation, fiscal and monetary policies, access to capital, etc. The details are listed later."
},
{
"code": null,
"e": 10063,
"s": 9819,
"text": "Technical indicators — a lot of investors follow technical indicators. We will include the most popular indicators as independent features. Among them — 7 and 21 days moving average, exponential moving average, momentum, Bollinger bands, MACD."
},
{
"code": null,
"e": 11350,
"s": 10063,
"text": "Fundamental analysis — A very important feature indicating whether a stock might move up or down. There are two features that can be used in fundamental analysis: 1) Analysing the company performance using 10-K and 10-Q reports, analysing ROE and P/E, etc (we will not use this), and 2) News — potentially news can indicate upcoming events that can potentially move the stock in certain direction. We will read all daily news for Goldman Sachs and extract whether the total sentiment about Goldman Sachs on that day is positive, neutral, or negative (as a score from 0 to 1). As many investors closely read the news and make investment decisions based (partially of course) on news, there is a somewhat high chance that if, say, the news for Goldman Sachs today are extremely positive the stock will surge tomorrow. One crucial point, we will perform feature importance (meaning how indicative it is for the movement of GS) on absolutely every feature (including this one) later on and decide whether we will use it. More on that later. For the purpose of creating accurate sentiment prediction, we will use Neural Language Processing (NLP). We will use BERT — Google’s recently announced NLP approach for transfer learning for sentiment classification stock news sentiment extraction."
},
{
"code": null,
"e": 11724,
"s": 11350,
"text": "Fourier transforms — Along with the daily closing price, we will create Fourier transforms in order to generalize several long- and short-term trends. Using these transforms we will eliminate a lot of noise (random walks) and create approximations of the real stock movement. Having trend approximations can help the LSTM network pick its prediction trends more accurately."
},
{
"code": null,
"e": 11976,
"s": 11724,
"text": "Autoregressive Integrated Moving Average (ARIMA) — This was one of the most popular techniques for predicting future values of time series data (in the pre-neural networks ages). Let’s add it and see if it comes off as an important predictive feature."
},
{
"code": null,
"e": 12569,
"s": 11976,
"text": "Stacked autoencoders — most of the aforementioned features (fundamental analysis, technical analysis, etc) were found by people after decades of research. But maybe we have missed something. Maybe there are hidden correlations that people cannot comprehend due to the enormous amount of data points, events, assets, charts, etc. With stacked autoencoders (type of neural networks) we can use the power of computers and probably find new types of features that affect stock movements. Even though we will not be able to understand these features in human language, we will use them in the GAN."
},
{
"code": null,
"e": 13232,
"s": 12569,
"text": "Deep Unsupervised learning for anomaly detection in options pricing. We will use one more feature — for every day we will add the price for 90-days call option on Goldman Sachs stock. Options pricing itself combines a lot of data. The price for options contract depends on the future value of the stock (analysts try to also predict the price in order to come up with the most accurate price for the call option). Using deep unsupervised learning (Self-organized Maps) we will try to spot anomalies in every day’s pricing. Anomaly (such as a drastic change in pricing) might indicate an event that might be useful for the LSTM to learn the overall stock pattern."
},
{
"code": null,
"e": 13311,
"s": 13232,
"text": "Next, having so many features, we need to perform a couple of important steps:"
},
{
"code": null,
"e": 13927,
"s": 13311,
"text": "Perform statistical checks for the ‘quality’ of the data. If the data we create is flawed, then no matter how sophisticated our algorithms are, the results will not be positive. The checks include making sure the data does not suffer from heteroskedasticity, multicollinearity, or serial correlation.Create feature importance. If a feature (e.g. another stock or a technical indicator) has no explanatory power to the stock we want to predict, then there is no need for us to use it in the training of the neural nets. We will using XGBoost (eXtreme Gradient Boosting), a type of boosted tree regression algorithms."
},
{
"code": null,
"e": 14228,
"s": 13927,
"text": "Perform statistical checks for the ‘quality’ of the data. If the data we create is flawed, then no matter how sophisticated our algorithms are, the results will not be positive. The checks include making sure the data does not suffer from heteroskedasticity, multicollinearity, or serial correlation."
},
{
"code": null,
"e": 14544,
"s": 14228,
"text": "Create feature importance. If a feature (e.g. another stock or a technical indicator) has no explanatory power to the stock we want to predict, then there is no need for us to use it in the training of the neural nets. We will using XGBoost (eXtreme Gradient Boosting), a type of boosted tree regression algorithms."
},
{
"code": null,
"e": 14748,
"s": 14544,
"text": "As a final step of our data preparation, we will also create Eigen portfolios using Principal Component Analysis (PCA) in order to reduce the dimensionality of the features created from the autoencoders."
},
{
"code": null,
"e": 14888,
"s": 14748,
"text": "print('There are {} number of days in the dataset.'.format(dataset_ex_df.shape[0]))output >>> There are 2265 number of days in the dataset."
},
{
"code": null,
"e": 15022,
"s": 14888,
"text": "Let’s visualize the stock for the last nine years. The dashed vertical line represents the separation between training and test data."
},
{
"code": null,
"e": 15094,
"s": 15022,
"text": "As explained earlier we will use other assets as features, not only GS."
},
{
"code": null,
"e": 15344,
"s": 15094,
"text": "So what other assets would affect GS’s stock movements? Good understanding of the company, its lines of businesses, competitive landscape, dependencies, suppliers and client type, etc is very important for picking the right set of correlated assets:"
},
{
"code": null,
"e": 15460,
"s": 15344,
"text": "First are the companies similar to GS. We will add JPMorgan Chase and Morgan Stanley, among others, to the dataset."
},
{
"code": null,
"e": 15852,
"s": 15460,
"text": "As an investment bank, Goldman Sachs depends on the global economy. Bad or volatile economy means no M&As or IPOs, and possibly limited proprietary trading earnings. That is why we will include global economy indices. Also, we will include LIBOR (USD and GBP denominated) rate, as possibly shocks in the economy might be accounted for by analysts to set these rates, and other FI securities."
},
{
"code": null,
"e": 15931,
"s": 15852,
"text": "Daily volatility index (VIX) — for the reason described in the previous point."
},
{
"code": null,
"e": 16061,
"s": 15931,
"text": "Composite indices — such as NASDAQ and NYSE (from USA), FTSE100 (UK), Nikkei225 (Japan), Hang Seng and BSE Sensex (APAC) indices."
},
{
"code": null,
"e": 16218,
"s": 16061,
"text": "Currencies — global trade is many times reflected into how currencies move, ergo we’ll use a basket of currencies (such as USDJPY, GBPUSD, etc) as features."
},
{
"code": null,
"e": 16372,
"s": 16218,
"text": "We already covered what are technical indicators and why we use them so let’s jump straight to the code. We will create technical indicators only for GS."
},
{
"code": null,
"e": 17237,
"s": 16372,
"text": "\"\"\" Function to create the technical indicators \"\"\"def get_technical_indicators(dataset): # Create 7 and 21 days Moving Average dataset['ma7'] = dataset['price'].rolling(window=7).mean() dataset['ma21'] = dataset['price'].rolling(window=21).mean() # Create MACD dataset['26ema'] = pd.ewma(dataset['price'], span=26) dataset['12ema'] = pd.ewma(dataset['price'], span=12) dataset['MACD'] = (dataset['12ema']-dataset['26ema'])# Create Bollinger Bands dataset['20sd'] = pd.stats.moments.rolling_std(dataset['price'],20) dataset['upper_band'] = dataset['ma21'] + (dataset['20sd']*2) dataset['lower_band'] = dataset['ma21'] - (dataset['20sd']*2) # Create Exponential moving average dataset['ema'] = dataset['price'].ewm(com=0.5).mean() # Create Momentum dataset['momentum'] = dataset['price']-1 return dataset"
},
{
"code": null,
"e": 17377,
"s": 17237,
"text": "So we have the technical indicators (including MACD, Bollinger bands, etc) for every trading day. We have in total 12 technical indicators."
},
{
"code": null,
"e": 17433,
"s": 17377,
"text": "Let’s visualise the last 400 days for these indicators."
},
{
"code": null,
"e": 17792,
"s": 17433,
"text": "For fundamental analysis we will perform sentiment analysis on all daily news about GS. Using sigmoid at the end, result will be between 0 and 1. The closer the score is to 0 — the more negative the news is (closer to 1 indicates positive sentiment). For each day, we will create the average daily score (as a number between 0 and 1) and add it as a feature."
},
{
"code": null,
"e": 17931,
"s": 17792,
"text": "For the purpose of classifying news as positive or negative (or neutral) we will use BERT, which is a pre-trained language representation."
},
{
"code": null,
"e": 18117,
"s": 17931,
"text": "Pre-trained BERT models are already available in MXNet/Gluon. We just need to instantiated them and add two (arbitrary number) Dense layers, going to softmax - the score is from 0 to 1."
},
{
"code": null,
"e": 18129,
"s": 18117,
"text": "import bert"
},
{
"code": null,
"e": 18374,
"s": 18129,
"text": "Going into the details of BERT and the NLP part is not in the scope of this notebook, but you have interest, do let me know — I will create a new repo only for BERT as it definitely is quite promising when it comes to language processing tasks."
},
{
"code": null,
"e": 18606,
"s": 18374,
"text": "Fourier transforms take a function and create a series of sine waves (with different amplitudes and frames). When combined, these sine waves approximate the original function. Mathematically speaking, the transforms look like this:"
},
{
"code": null,
"e": 18749,
"s": 18606,
"text": "We will use Fourier transforms to extract global and local trends in the GS stock, and to also denoise it a little. So let’s see how it works."
},
{
"code": null,
"e": 19494,
"s": 18749,
"text": "\"\"\" Code to create the Fuorier trasfrom \"\"\"data_FT = dataset_ex_df[['Date', 'GS']]close_fft = np.fft.fft(np.asarray(data_FT['GS'].tolist()))fft_df = pd.DataFrame({'fft':close_fft})fft_df['absolute'] = fft_df['fft'].apply(lambda x: np.abs(x))fft_df['angle'] = fft_df['fft'].apply(lambda x: np.angle(x))plt.figure(figsize=(14, 7), dpi=100)fft_list = np.asarray(fft_df['fft'].tolist())for num_ in [3, 6, 9, 100]: fft_list_m10= np.copy(fft_list); fft_list_m10[num_:-num_]=0 plt.plot(np.fft.ifft(fft_list_m10), label='Fourier transform with {} components'.format(num_))plt.plot(data_FT['GS'], label='Real')plt.xlabel('Days')plt.ylabel('USD')plt.title('Figure 3: Goldman Sachs (close) stock prices & Fourier transforms')plt.legend()plt.show()"
},
{
"code": null,
"e": 19984,
"s": 19494,
"text": "As you see in Figure 3 the more components from the Fourier transform we use the closer the approximation function is to the real stock price (the 100 components transform is almost identical to the original function — the red and the purple lines almost overlap). We use Fourier transforms for the purpose of extracting long- and short-term trends so we will use the transforms with 3, 6, and 9 components. You can infer that the transform with 3 components serves as the long term trend."
},
{
"code": null,
"e": 20135,
"s": 19984,
"text": "Another technique used to denoise data is called wavelets. Wavelets and Fourier transform gave similar results so we will only use Fourier transforms."
},
{
"code": null,
"e": 20392,
"s": 20135,
"text": "ARIMA is a technique for predicting time series data. We will show how to use it, and althouth ARIMA will not serve as our final prediction, we will use it as a technique to denoise the stock a little and to (possibly) extract some new patters or features."
},
{
"code": null,
"e": 20496,
"s": 20392,
"text": "error = mean_squared_error(test, predictions)print('Test MSE: %.3f' % error)output >>> Test MSE: 10.151"
},
{
"code": null,
"e": 20967,
"s": 20496,
"text": "As we can see from Figure 5 ARIMA gives a very good approximation of the real stock price. We will use the predicted price through ARIMA as an input feature into the LSTM because, as we mentioned before, we want to capture as many features and patterns about Goldman Sachs as possible. We go test MSE (mean squared error) of 10.151, which by itself is not a bad result (considering we do have a lot of test data), but still, we will only use it as a feature in the LSTM."
},
{
"code": null,
"e": 21313,
"s": 20967,
"text": "Ensuring that the data has good quality is very important for our models. In order to make sure our data is suitable we will perform a couple of simple checks in order to ensure that the results we achieve and observe are indeed real, rather than compromised due to the fact that the underlying data distribution suffers from fundamental errors."
},
{
"code": null,
"e": 21557,
"s": 21313,
"text": "Conditional Heteroskedasticity occurs when the error terms (the difference between a predicted value by a regression and the real value) are dependent on the data — for example, the error terms grow when the data point (along the x-axis) grow."
},
{
"code": null,
"e": 21641,
"s": 21557,
"text": "Multicollinearity is when error terms (also called residuals) depend on each other."
},
{
"code": null,
"e": 21744,
"s": 21641,
"text": "Serial correlation is when one data (feature) is a formula (or completely depends) of another feature."
},
{
"code": null,
"e": 21882,
"s": 21744,
"text": "We will not go into the code here as it is straightforward and our focus is more on the deep learning parts, but the data is qualitative."
},
{
"code": null,
"e": 22116,
"s": 21882,
"text": "print('Total dataset has {} samples, and {} features.'.format(dataset_total_df.shape[0], dataset_total_df.shape[1]))output >>> Total dataset has 2265 samples, and 112 features."
},
{
"code": null,
"e": 22361,
"s": 22116,
"text": "So, after adding all types of data (the correlated assets, technical indicators, fundamental analysis, Fourier, and Arima) we have a total of 112 features for the 2,265 days (as mentioned before, however, only 1,585 days are for training data)."
},
{
"code": null,
"e": 22431,
"s": 22361,
"text": "We will also have some more features generated from the autoencoders."
},
{
"code": null,
"e": 22964,
"s": 22431,
"text": "Having so many features we have to consider whether all of them are really indicative of the direction GS stock will take. For example, we included USD denominated LIBOR rates in the dataset because we think that changes in LIBOR might indicate changes in the economy, that, in turn, might indicate changes in the GS’s stock behavior. But we need to test. There are many ways to test feature importance, but the one we will apply uses XGBoost, because it gives one of the best results in both classification and regression problems."
},
{
"code": null,
"e": 23233,
"s": 22964,
"text": "Since the features dataset is quite large, for the purpose of the presentation here we’ll use only the technical indicators. During the real features importance testing all selected features proved somewhat important so we won’t exclude anything when training the GAN."
},
{
"code": null,
"e": 23743,
"s": 23233,
"text": "regressor = xgb.XGBRegressor(gamma=0.0,n_estimators=150,base_score=0.7,colsample_bytree=1,learning_rate=0.05)xgbModel = regressor.fit(X_train_FI,y_train_FI, eval_set = [(X_train_FI, y_train_FI), (X_test_FI, y_test_FI)], verbose=False)fig = plt.figure(figsize=(8,8))plt.xticks(rotation='vertical')plt.bar([i for i in range(len(xgbModel.feature_importances_))], xgbModel.feature_importances_.tolist(), tick_label=X_test_FI.columns)plt.title('Figure 6: Feature importance of the technical indicators.')plt.show()"
},
{
"code": null,
"e": 23862,
"s": 23743,
"text": "Not surprisingly (for those with experience in stock trading) that MA7, MACD, and BB are among the important features."
},
{
"code": null,
"e": 24072,
"s": 23862,
"text": "I followed the same logic for performing feature importance over the whole dataset — just the training took longer and results were a little more difficult to read, as compared with just a handful of features."
},
{
"code": null,
"e": 24161,
"s": 24072,
"text": "Before we proceed to the autoencoders, we’ll explore an alternative activation function."
},
{
"code": null,
"e": 24441,
"s": 24161,
"text": "GELU — Gaussian Error Linear Unites was recently proposed — link. In the paper the authors show several instances in which neural networks using GELU outperform networks using ReLU as an activation. gelu is also used in BERT, the NLP approach we used for news sentiment analysis."
},
{
"code": null,
"e": 24480,
"s": 24441,
"text": "We will use GELU for the autoencoders."
},
{
"code": null,
"e": 24862,
"s": 24480,
"text": "Note: The cell below shows the logic behind the math of GELU. It is not the actual implementation as an activation function. I had to implement GELU inside MXNet. If you follow the code and change act_type='relu' to act_type='gelu' it will not work, unless you change the implementation of MXNet. Make a pull request on the whole project to access the MXNet implementation of GELU."
},
{
"code": null,
"e": 24960,
"s": 24862,
"text": "Let’s visualize GELU, ReLU, and LeakyReLU (the last one is mainly used in GANs - we also use it)."
},
{
"code": null,
"e": 25986,
"s": 24960,
"text": "def gelu(x): return 0.5 * x * (1 + math.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * math.pow(x, 3))))def relu(x): return max(x, 0)def lrelu(x): return max(0.01*x, x)plt.figure(figsize=(15, 5))plt.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=.5, hspace=None)ranges_ = (-10, 3, .25)plt.subplot(1, 2, 1)plt.plot([i for i in np.arange(*ranges_)], [relu(i) for i in np.arange(*ranges_)], label='ReLU', marker='.')plt.plot([i for i in np.arange(*ranges_)], [gelu(i) for i in np.arange(*ranges_)], label='GELU')plt.hlines(0, -10, 3, colors='gray', linestyles='--', label='0')plt.title('Figure 7: GELU as an activation function for autoencoders')plt.ylabel('f(x) for GELU and ReLU')plt.xlabel('x')plt.legend()plt.subplot(1, 2, 2)plt.plot([i for i in np.arange(*ranges_)], [lrelu(i) for i in np.arange(*ranges_)], label='Leaky ReLU')plt.hlines(0, -10, 3, colors='gray', linestyles='--', label='0')plt.ylabel('f(x) for Leaky ReLU')plt.xlabel('x')plt.title('Figure 8: LeakyReLU')plt.legend()plt.show()"
},
{
"code": null,
"e": 26277,
"s": 25986,
"text": "Note: In future versions of this notebook I will experiment using U-Net (link), and try to utilize the convolutional layer and extract (and create) even more features about the stock’s underlying movement patterns. For now, we will just use a simple autoencoder made only from Dense layers."
},
{
"code": null,
"e": 26413,
"s": 26277,
"text": "Ok, back to the autoencoders, depicted below (the image is only schematic, it doesn’t represent the real number of layers, units, etc.)"
},
{
"code": null,
"e": 26935,
"s": 26413,
"text": "Note: One thing that I will explore in a later version is removing the last layer in the decoder. Normally, in autoencoders the number of encoders == number of decoders. We want, however, to extract higher level features (rather than creating the same input), so we can skip the last layer in the decoder. We achieve this creating the encoder and decoder with the same number of layers during the training, but when we create the output we use the layer next to the only one as it would contain the higher level features."
},
{
"code": null,
"e": 27025,
"s": 26935,
"text": "The full code for the autoencoders is available in the accompanying Github — link at top."
},
{
"code": null,
"e": 27410,
"s": 27025,
"text": "We created 112 more features from the autoencoder. As we want to only have high level features (overall patterns) we will create an Eigen portfolio on the newly created 112 features using Principal Component Analysis (PCA). This will reduce the dimension (number of columns) of the data. The descriptive capability of the Eigen portfolio will be the same as the original 112 features."
},
{
"code": null,
"e": 27585,
"s": 27410,
"text": "Note Once again, this is purely experimental. I am not 100% sure the described logic will hold. As everything else in AI and deep learning, this is art and needs experiments."
},
{
"code": null,
"e": 27600,
"s": 27585,
"text": "How GANs work?"
},
{
"code": null,
"e": 28176,
"s": 27600,
"text": "As mentioned before, the purpose of this notebook is not to explain in detail the math behind deep learning but to show its applications. Of course, thorough and very solid understanding from the fundamentals down to the smallest details, in my opinion, is extremely imperative. Hence, we will try to balance and give a high-level overview of how GANs work in order for the reader to fully understand the rationale behind using GANs in predicting stock price movements. Feel free to skip this and the next section if you are experienced with GANs (and do check section 4.2.)."
},
{
"code": null,
"e": 28287,
"s": 28176,
"text": "A GAN network consists of two models — a Generator (G) and Discriminator (D). The steps in training a GAN are:"
},
{
"code": null,
"e": 29682,
"s": 28287,
"text": "The Generator is, using random data (noise denoted z), trying to ‘generate’ data indistinguishable of, or extremely close to, the real data. Its purpose is to learn the distribution of the real data.Randomly, real or generated data is fitted into the Discriminator, which acts as a classifier and tries to understand whether the data is coming from the Generator or is the real data. D estimates the (distributions) probabilities of the incoming sample to the real dataset. (more info on comparing two distributions in section 3.2. below).Then, the losses from G and D are combined and propagated back through the generator. Ergo, the generator’s loss depends on both the generator and the discriminator. This is the step that helps the Generator learn about the real data distribution. If the generator doesn’t do a good job at generating a realistic data (having the same distribution), the Discriminator’s work will be very easy to distinguish generated from real data sets. Hence, the Discriminator’s loss will be very small. Small discriminator loss will result in bigger generator loss (see the equation below for L(D,G)). This makes creating the discriminator a bit tricky, because too good of a discriminator will always result in a huge generator loss, making the generator unable to learn.The process goes on until the Discriminator can no longer distinguish generated from real data."
},
{
"code": null,
"e": 29882,
"s": 29682,
"text": "The Generator is, using random data (noise denoted z), trying to ‘generate’ data indistinguishable of, or extremely close to, the real data. Its purpose is to learn the distribution of the real data."
},
{
"code": null,
"e": 30223,
"s": 29882,
"text": "Randomly, real or generated data is fitted into the Discriminator, which acts as a classifier and tries to understand whether the data is coming from the Generator or is the real data. D estimates the (distributions) probabilities of the incoming sample to the real dataset. (more info on comparing two distributions in section 3.2. below)."
},
{
"code": null,
"e": 30984,
"s": 30223,
"text": "Then, the losses from G and D are combined and propagated back through the generator. Ergo, the generator’s loss depends on both the generator and the discriminator. This is the step that helps the Generator learn about the real data distribution. If the generator doesn’t do a good job at generating a realistic data (having the same distribution), the Discriminator’s work will be very easy to distinguish generated from real data sets. Hence, the Discriminator’s loss will be very small. Small discriminator loss will result in bigger generator loss (see the equation below for L(D,G)). This makes creating the discriminator a bit tricky, because too good of a discriminator will always result in a huge generator loss, making the generator unable to learn."
},
{
"code": null,
"e": 31080,
"s": 30984,
"text": "The process goes on until the Discriminator can no longer distinguish generated from real data."
},
{
"code": null,
"e": 31629,
"s": 31080,
"text": "When combined together, D and G as sort of playing a minmax game (the Generator is trying to fool the Discriminator making it increase the probability for on fake examples, i.e. minimize Ez∼pz(z)[log(1−D(G(z)))]. The Discriminator wants to separate the data coming from the Generator, D(G(z)), by maximizing Ex∼pr(x)[logD(x)]. Having separated loss functions, however, it is not clear how both can converge together (that is why we use some advancements over the plain GANs, such as Wasserstein GAN). Overall, the combined loss function looks like:"
},
{
"code": null,
"e": 31691,
"s": 31629,
"text": "Note: Really useful tips for training GANs can be found here."
},
{
"code": null,
"e": 31923,
"s": 31691,
"text": "Note: I will not include the complete code behind the GAN and the Reinforcement learning parts in this notebook — only the results from the execution (the cell outputs) will be shown. Make a pull request or contact me for the code."
},
{
"code": null,
"e": 32622,
"s": 31923,
"text": "Generative Adversarial Networks (GAN) have been recently used mainly in creating realistic images, paintings, and video clips. There aren’t many applications of GANs being used for predicting time-series data as in our case. The main idea, however, should be same — we want to predict future stock movements. In the future, the pattern and behavior of GS’s stock should be more or less the same (unless it starts operating in a totally different way, or the economy drastically changes). Hence, we want to ‘generate’ data for the future that will have similar (not absolutely the same, of course) distribution as the one we already have — the historical trading data. So, in theory, it should work."
},
{
"code": null,
"e": 32708,
"s": 32622,
"text": "In our case, we will use LSTM as a time-series generator, and CNN as a discriminator."
},
{
"code": null,
"e": 32776,
"s": 32708,
"text": "Note: The next couple of sections assume some experience with GANs."
},
{
"code": null,
"e": 33497,
"s": 32776,
"text": "A recent improvement over the traditional GANs came out from Uber’s engineering team and is called Metropolis-Hastings GAN (MHGAN). The idea behind Uber’s approach is (as they state it) somewhat similar to another approach created by Google and University of California, Berkeley called Discriminator Rejection Sampling (DRS). Basically, when we train GAN we use the Discriminator (D) for the sole purpose of better training the Generator (G). Often, after training the GAN we do not use the D any more. MHGAN and DRS, however, try to use D in order to choose samples generated by G that are close to the real data distribution (slight difference between is that MHGAN uses Markov Chain Monte Carlo (MCMC) for sampling)."
},
{
"code": null,
"e": 33889,
"s": 33497,
"text": "MHGAN takes K samples generated from the G (created from independent noise inputs to the G — z0 to zK in the figure below). Then it sequentially runs through the K outputs (x′0 to x′K) and following an acceptance rule (created from the Discriminator) decides whether to accept the current sample or keep the last accepted one. The last kept output is the one considered the real output of G."
},
{
"code": null,
"e": 33987,
"s": 33889,
"text": "Note: MHGAN is originally implemented by Uber in pytorch. I only transferred it into MXNet/Gluon."
},
{
"code": null,
"e": 34060,
"s": 33987,
"text": "Figure 10: Visual representation of MHGAN (from the original Uber post)."
},
{
"code": null,
"e": 34222,
"s": 34060,
"text": "Training GANs is quite difficult. Models may never converge and mode collapse can easily happen. We will use a modification of GAN called Wasserstein GAN — WGAN."
},
{
"code": null,
"e": 34299,
"s": 34222,
"text": "Again, we will not go into details, but the most notable points to make are:"
},
{
"code": null,
"e": 34576,
"s": 34299,
"text": "As we know the main goal behind GANs is for the Generator to start transforming random noise into some given data that we want to mimic. Ergo, the idea of comparing the similarity between two distributions is very imperative in GANs. The two most widely used such metrics are:"
},
{
"code": null,
"e": 34681,
"s": 34576,
"text": "KL divergence (Kullback–Leibler) — DKL(p‖q)=∫xp(x)logp(x)q(x)dx. DKL is zero when p(x) is equal to q(x),"
},
{
"code": null,
"e": 34906,
"s": 34681,
"text": "JS Divergence (Jensen–Shannon). JS divergence is bounded by 0 and 1, and, unlike KL divergence, is symmetric and smoother. Significant success in GAN training was achieved when the loss was switched from KL to JS divergence."
},
{
"code": null,
"e": 35475,
"s": 34906,
"text": "WGAN uses Wasserstein distance, W(pr,pg)=1Ksup‖f‖L≤KEx∼pr[f(x)]−Ex∼pg[f(x)] (where sup stands for supremum), as a loss function (also called Earth Mover’s distance, because it normally is interpreted as moving one pile of, say, sand to another one, both piles having different probability distributions, using minimum energy during the transformation). Compared to KL and JS divergences, Wasserstein metric gives a smooth measure (without sudden jumps in divergence). This makes it much more suitable for creating a stable learning process during the gradient descent."
},
{
"code": null,
"e": 35770,
"s": 35475,
"text": "Also, compared to KL and JS, Wasserstein distance is differentiable nearly everywhere. As we know, during backpropagation, we differentiate the loss function in order to create the gradients, which in turn update the weights. Therefore, having a differentiable loss function is quite important."
},
{
"code": null,
"e": 36856,
"s": 35770,
"text": "As mentioned before, the generator is a LSTM network a type of Recurrent Neural Network (RNN). RNNs are used for time-series data because they keep track of all previous data points and can capture patterns developing through time. Due to their nature, RNNs many time suffer from vanishing gradient — that is, the changes the weights receive during training become so small, that they don’t change, making the network unable to converge to a minimal loss (The opposite problem can also be observed at times — when gradients become too big. This is called gradient exploding, but the solution to this is quite simple — clip gradients if they start exceeding some constant number, i.e. gradient clipping). Two modifications tackle this problem — Gated Recurrent Unit (GRU) and Long-Short Term Memory (LSTM). The biggest differences between the two are: 1) GRU has 2 gates (update and reset) and LSTM has 4 (update, input, forget, and output), 2) LSTM maintains an internal memory state, while GRU doesn’t, and 3) LSTM applies a nonlinearity (sigmoid) before the output gate, GRU doesn’t."
},
{
"code": null,
"e": 37048,
"s": 36856,
"text": "In most cases, LSTM and GRU give similar results in terms of accuracy but GRU is much less computational intensive, as GRU has much fewer trainable params. LSTMs, however, and much more used."
},
{
"code": null,
"e": 37113,
"s": 37048,
"text": "Strictly speaking, the math behind the LSTM cell (the gates) is:"
},
{
"code": null,
"e": 37230,
"s": 37113,
"text": "where ⊙is an element-wise multiplication operator, and, for all x=[x1,x2,...,xk]⊤∈R^k the two activation functions:,"
},
{
"code": null,
"e": 37592,
"s": 37230,
"text": "The LSTM architecture is very simple — one LSTM layer with 112 input units (as we have 112 features in the dataset) and 500 hidden units, and one Dense layer with 1 output - the price for every day. The initializer is Xavier and we will use L1 loss (which is mean absolute error loss with L1 regularization - see section 3.4.5. for more info on regularization)."
},
{
"code": null,
"e": 37938,
"s": 37592,
"text": "Note — In the code you can see we use Adam (with learning rate of .01) as an optimizer. Don't pay too much attention on that now - there is a section specially dedicated to explain what hyperparameters we use (learning rate is excluded as we have learning rate scheduler - section 3.4.3.) and how we optimize these hyperparameters - section 3.6."
},
{
"code": null,
"e": 38998,
"s": 37938,
"text": "gan_num_features = dataset_total_df.shape[1]sequence_length = 17class RNNModel(gluon.Block): def __init__(self, num_embed, num_hidden, num_layers, bidirectional=False, sequence_length=sequence_length, **kwargs): super(RNNModel, self).__init__(**kwargs) self.num_hidden = num_hidden with self.name_scope(): self.rnn = rnn.LSTM(num_hidden, num_layers, input_size=num_embed, bidirectional=bidirectional, layout='TNC') self.decoder = nn.Dense(1, in_units=num_hidden) def forward(self, inputs, hidden): output, hidden = self.rnn(inputs, hidden) decoded = self.decoder(output.reshape((-1,self.num_hidden))) return decoded, hidden def begin_state(self, *args, **kwargs): return self.rnn.begin_state(*args, **kwargs) lstm_model = RNNModel(num_embed=gan_num_features, num_hidden=500, num_layers=1)lstm_model.collect_params().initialize(mx.init.Xavier(), ctx=mx.cpu())trainer = gluon.Trainer(lstm_model.collect_params(), 'adam', {'learning_rate': .01})loss = gluon.loss.L1Loss()"
},
{
"code": null,
"e": 39158,
"s": 38998,
"text": "We will use 500 neurons in the LSTM layer and use Xavier initialization. For regularization we’ll use L1. Let’s see what’s inside the LSTM as printed by MXNet."
},
{
"code": null,
"e": 39264,
"s": 39158,
"text": "print(lstm_model)output >>>RNNModel( (rnn): LSTM(112 -> 500, TNC) (decoder): Dense(500 -> 1, linear))"
},
{
"code": null,
"e": 39465,
"s": 39264,
"text": "As we can see, the input of the LSTM are the 112 features (dataset_total_df.shape[1]) which then go into 500 neurons in the LSTM layer, and then transformed to a single output - the stock price value."
},
{
"code": null,
"e": 39848,
"s": 39465,
"text": "The logic behind the LSTM is: we take 17 (sequence_length) days of data (again, the data being the stock price for GS stock every day + all the other feature for that day - correlated assets, sentiment, etc.) and try to predict the 18th day. Then we move the 17 days window with one day and again predict the 18th. We iterate like this over the whole dataset (of course in batches)."
},
{
"code": null,
"e": 39957,
"s": 39848,
"text": "In another post I will explore whether modification over the vanilla LSTM would be more beneficial, such as:"
},
{
"code": null,
"e": 40140,
"s": 39957,
"text": "using bidirectional LSTM layer — in theory, going backwards (from end of the data set towards the beginning) might somehow help the LSTM figure out the pattern of the stock movement."
},
{
"code": null,
"e": 40367,
"s": 40140,
"text": "using stacked RNN architecture — having not only one LSTM layer but 2 or more. This, however, might be dangerous, as we might end up overfitting the model, as we don’t have a lot of data (we have just 1,585 day worth of data)."
},
{
"code": null,
"e": 40435,
"s": 40367,
"text": "Exploring GRU — as already explained, GRUs’ cells are much simpler."
},
{
"code": null,
"e": 40472,
"s": 40435,
"text": "Adding attention vectors to the RNN."
},
{
"code": null,
"e": 41094,
"s": 40472,
"text": "One of the most important hyperparameters is the learning rate. Setting the learning rate for almost every optimizer (such as SGD, Adam, or RMSProp) is crucially important when training neural networks because it controls both the speed of convergence and the ultimate performance of the network. One of the simplest learning rate strategies is to have a fixed learning rate throughout the training process. Choosing a small learning rate allows the optimizer find good solutions, but this comes at the expense of limiting the initial speed of convergence. Changing the learning rate over time can overcome this tradeoff."
},
{
"code": null,
"e": 41299,
"s": 41094,
"text": "Recent papers, such as this one, show the benefits of changing the global learning rate during training, in terms of both convergence and time. Let’s plot the learning rates we’ll be using for each epoch."
},
{
"code": null,
"e": 41582,
"s": 41299,
"text": "schedule = CyclicalSchedule(TriangularSchedule, min_lr=0.5, max_lr=2, cycle_length=500)iterations=1500plt.plot([i+1 for i in range(iterations)],[schedule(i) for i in range(iterations)])plt.title('Learning rate for each epoch')plt.xlabel(\"Epoch\")plt.ylabel(\"Learning Rate\")plt.show()"
},
{
"code": null,
"e": 41705,
"s": 41582,
"text": "Having a lot of features and neural networks we need to make sure we prevent overfitting and be mindful of the total loss."
},
{
"code": null,
"e": 41825,
"s": 41705,
"text": "We use several techniques for preventing overfitting (not only in the LSTM, but also in the CNN and the auto-encoders):"
},
{
"code": null,
"e": 42232,
"s": 41825,
"text": "Ensuring data quality. We already performed statistical checks and made sure the data doesn’t suffer from multicollinearity or serial autocorrelation. Further we performed feature importance check on each feature. Finally, the initial feature selection (e.g. selecting correlated assets, technical indicators, etc.) was done with some domain knowledge about the mechanics behind the way stock markets work."
},
{
"code": null,
"e": 43700,
"s": 42232,
"text": "Regularization (or weights penalty). The two most widely used regularization techniques are LASSO (L1) and Ridge (L2). L1 adds the mean absolute error and L2 adds mean squared error to the loss. Without going into too many mathematical details, the basic differences are: lasso regression (L1) does both variable selection and parameter shrinkage, whereas Ridge regression only does parameter shrinkage and end up including all the coefficients in the model. In presence of correlated variables, ridge regression might be the preferred choice. Also, ridge regression works best in situations where the least square estimates have higher variance. Therefore, it depends on our model objective. The impact of the two types of regularizations is quite different. While they both penalize large weights, L1 regularization leads to a non-differentiable function at zero. L2 regularization favors smaller weights, but L1 regularization favors weights that go to zero. So, with L1 regularization you can end up with a sparse model — one with fewer parameters. In both cases the parameters of the L1 and L2 regularized models “shrink”, but in the case of L1 regularization the shrinkage directly impacts the complexity (the number of parameters) of the model. Precisely, ridge regression works best in situations where the least square estimates have higher variance. L1 is more robust to outliers, is used when data is sparse, and creates feature importance. We will use L1."
},
{
"code": null,
"e": 43768,
"s": 43700,
"text": "Dropout. Dropout layers randomly remove nodes in the hidden layers."
},
{
"code": null,
"e": 43804,
"s": 43768,
"text": "Dense-sparse-dense training. — link"
},
{
"code": null,
"e": 43820,
"s": 43804,
"text": "Early stopping."
},
{
"code": null,
"e": 44140,
"s": 43820,
"text": "Another important consideration when building complex neural networks is the bias-variance trade-off. Basically, the error we get when training nets is a function of the bias, the variance, and irreducible error — σ (error due to noise and randomness). The simplest formula of the trade-off is: Error=bias^2+variance+σ."
},
{
"code": null,
"e": 44318,
"s": 44140,
"text": "Bias. Bias measures how well a trained (on training dataset) algorithm can generalize on unseen data. High bias (underfitting) meaning the model cannot work well on unseen data."
},
{
"code": null,
"e": 44436,
"s": 44318,
"text": "Variance. Variance measures the sensitivity of the model to changes in the dataset. High variance is the overfitting."
},
{
"code": null,
"e": 44983,
"s": 44436,
"text": "We usually use CNNs for work related to images (classification, context extraction, etc). They are very powerful at extracting features from features from features, etc. For example, in an image of a dog, the first convolutional layer will detect edges, the second will start detecting circles, and the third will detect a nose. In our case, data points form small trends, small trends form bigger, trends in turn form patterns. CNNs’ ability to detect features can be used for extracting information about patterns in GS’s stock price movements."
},
{
"code": null,
"e": 45526,
"s": 44983,
"text": "Another reason for using CNN is that CNNs work well on spatial data — meaning data points that are closer to each other are more related to each other, than data points spread across. This should hold true for time series data. In our case each data point (for each feature) is for each consecutive day. It is natural to assume that the closer two days are to each other, the more related they are to each other. One thing to consider (although not covered in this work) is seasonality and how it might change (if at all) the work of the CNN."
},
{
"code": null,
"e": 45767,
"s": 45526,
"text": "Note: As many other parts in this notebook, using CNN for time series data is experimental. We will inspect the results, without providing mathematical or other proofs. And results might vary using different data, activation functions, etc."
},
{
"code": null,
"e": 45849,
"s": 45767,
"text": "Without going through the full code, we’ll just show the CNN as printed by MXNet."
},
{
"code": null,
"e": 46595,
"s": 45849,
"text": "Sequential( (0): Conv1D(None -> 32, kernel_size=(5,), stride=(2,)) (1): LeakyReLU(0.01) (2): Conv1D(None -> 64, kernel_size=(5,), stride=(2,)) (3): LeakyReLU(0.01) (4): BatchNorm(axis=1, eps=1e-05, momentum=0.9, fix_gamma=False, use_global_stats=False, in_channels=None) (5): Conv1D(None -> 128, kernel_size=(5,), stride=(2,)) (6): LeakyReLU(0.01) (7): BatchNorm(axis=1, eps=1e-05, momentum=0.9, fix_gamma=False, use_global_stats=False, in_channels=None) (8): Dense(None -> 220, linear) (9): BatchNorm(axis=1, eps=1e-05, momentum=0.9, fix_gamma=False, use_global_stats=False, in_channels=None) (10): LeakyReLU(0.01) (11): Dense(None -> 220, linear) (12): Activation(relu) (13): Dense(None -> 1, linear) )"
},
{
"code": null,
"e": 46652,
"s": 46595,
"text": "The hyperparameters that we will track and optimize are:"
},
{
"code": null,
"e": 46696,
"s": 46652,
"text": "batch_size : batch size of the LSTM and CNN"
},
{
"code": null,
"e": 46732,
"s": 46696,
"text": "cnn_lr: the learningrate of the CNN"
},
{
"code": null,
"e": 46774,
"s": 46732,
"text": "strides: the number of strides in the CNN"
},
{
"code": null,
"e": 46826,
"s": 46774,
"text": "lrelu_alpha: the alpha for the LeakyReLU in the GAN"
},
{
"code": null,
"e": 46894,
"s": 46826,
"text": "batchnorm_momentum: momentum for the batch normalisation in the CNN"
},
{
"code": null,
"e": 46926,
"s": 46894,
"text": "padding: the padding in the CNN"
},
{
"code": null,
"e": 46965,
"s": 46926,
"text": "kernel_size':1: kernel size in the CNN"
},
{
"code": null,
"e": 46994,
"s": 46965,
"text": "dropout: dropout in the LSTM"
},
{
"code": null,
"e": 47033,
"s": 46994,
"text": "filters: the initial number of filters"
},
{
"code": null,
"e": 47064,
"s": 47033,
"text": "We will train over 200 epochs."
},
{
"code": null,
"e": 47419,
"s": 47064,
"text": "After the GAN trains on the 200 epochs it will record the MAE (which is the error function in the LSTM, the GG) and pass it as a reward value to the Reinforcement learning that will decide whether to change the hyperparameters of keep training with the same set of hyperparameters. As described later, this approach is strictly for experimenting with RL."
},
{
"code": null,
"e": 47594,
"s": 47419,
"text": "If the RL decides it will update the hyperparameters it will call Bayesian optimisation (discussed below) library that will give the next best expected set of the hyperparams"
},
{
"code": null,
"e": 47930,
"s": 47594,
"text": "Why do we use reinforcement learning in the hyperparameters optimization? Stock markets change all the time. Even if we manage to train our GAN and LSTM to create extremely accurate results, the results might only be valid for a certain period. Meaning, we need to constantly optimise the whole process. To optimize the process we can:"
},
{
"code": null,
"e": 48014,
"s": 47930,
"text": "Add or remove features (e.g. add new stocks or currencies that might be correlated)"
},
{
"code": null,
"e": 48401,
"s": 48014,
"text": "Improve our deep learning models. One of the most important ways to improve the models is through the hyper parameters (listed in Section 5). Once having found a certain set of hyperparameters we need to decide when to change them and when to use the already known set (exploration vs. exploitation). Also, stock market represents a continuous space that depends on millions parameters."
},
{
"code": null,
"e": 48724,
"s": 48401,
"text": "Note: The purpose of the whole reinforcement learning part of this notebook is more research oriented. We will explore different RL approaches using the GAN as an environment. There are many ways in which we can successfully perform hyperparameter optimization on our deep learning models without using RL. But... why not."
},
{
"code": null,
"e": 48840,
"s": 48724,
"text": "Note: The next several sections assume you have some knowledge about RL — especially policy methods and Q-learning."
},
{
"code": null,
"e": 49306,
"s": 48840,
"text": "Without explaining the basics of RL we will jump into the details of the specific approaches we implement here. We will use model-free RL algorithms for the obvious reason that we do not know the whole environment, hence there is no defined model for how the environment works — if there was we wouldn’t need to predict stock prices movements — they will just follow the model. We will use the two subdivisions of model-free RL — Policy optimization and Q-learning."
},
{
"code": null,
"e": 49523,
"s": 49306,
"text": "Q-learning — in Q-learning we learn the value of taking an action from a given state. Q-value is the expected return after taking the action. We will use Rainbow which is a combination of seven Q learning algorithms."
},
{
"code": null,
"e": 49747,
"s": 49523,
"text": "Policy Optimization — in policy optimization we learn the action to take from a given state. (if we use methods like Actor/Critic) we also learn the value of being in a given state. We will use Proximal Policy Optimization."
},
{
"code": null,
"e": 49955,
"s": 49747,
"text": "One crucial aspect of building a RL algorithm is accurately setting the reward. It has to capture all aspects of the environment and the agent’s interaction with the environment. We define the reward, R, as:"
},
{
"code": null,
"e": 49987,
"s": 49955,
"text": "Reward=2∗lossG+lossD+accuracyG,"
},
{
"code": null,
"e": 50270,
"s": 49987,
"text": "where lossG, accuracyG, and lossD are the Generator’s loss and accuracy, and Discriminator’s loss, respectively. The environment is the GAN and the results of the LSTM training. The action the different agents can take is how to change the hyperparameters of the GAN’s D and G nets."
},
{
"code": null,
"e": 50287,
"s": 50270,
"text": "What is Rainbow?"
},
{
"code": null,
"e": 50409,
"s": 50287,
"text": "Rainbow (link) is a Q learning based off-policy deep reinforcement learning algorithm combining seven algorithm together:"
},
{
"code": null,
"e": 50785,
"s": 50409,
"text": "DQN. DQN is an extension of Q learning algorithm that uses a neural network to represent the Q value. Similar to supervised (deep) learning, in DQN we train a neural network and try to minimize a loss function. We train the network by randomly sampling transitions (state, action, reward). The layers can be not only fully connected ones, but also convolutional, for example."
},
{
"code": null,
"e": 50883,
"s": 50785,
"text": "Double Q Learning. Double QL handles a big problem in Q learning, namely the overestimation bias."
},
{
"code": null,
"e": 51335,
"s": 50883,
"text": "Prioritized replay. In the vanilla DQN, all transitions are stored in a replay buffer and it uniformly samples this buffer. However, not all transitions are equally beneficial during the learning phase (which also makes learning inefficient as more episodes are required). Prioritized experience replay doesn’t sample uniformly, rather it uses a distribution that gives higher probability to samples that have had higher Q loss in previous iterations."
},
{
"code": null,
"e": 51690,
"s": 51335,
"text": "Dueling networks. Dueling networks change the Q learning architecture a little by using two separate streams (i.e. having two different mini-neural networks). One stream is for the value and one for the advantage. Both of them share a convolutional encoder. The tricky part is the merging of the streams — it uses a special aggregator (Wang et al. 2016)."
},
{
"code": null,
"e": 52020,
"s": 51690,
"text": "(Advantage, formula is A(s,a)=Q(s,a)−V(s), generally speaking is a comparison of how good an action is compared to the average action for a specific state. Advantages are sometimes used when a ‘wrong’ action cannot be penalized with negative reward. So advantage will try to further reward good actions from the average actions.)"
},
{
"code": null,
"e": 52226,
"s": 52020,
"text": "Multi-step learning. The big difference behind Multi-step learning is that it calculates the Q-values using N-step returns (not only the return from the next step), which naturally should be more accurate."
},
{
"code": null,
"e": 52616,
"s": 52226,
"text": "Distributional RL. Q learning uses average estimated Q-value as target value. However, in many cases the Q-values might not be the same in different situations. Distributional RL can directly learn (or approximate) the distribution of Q-values rather than averaging them. Again, the math is much more complicated than that, but for us the benefit is more accurate sampling of the Q-values."
},
{
"code": null,
"e": 53014,
"s": 52616,
"text": "Noisy Nets. Basic DQN implements a simple ε-greedy mechanism to do exploration. This approach to exploration inefficient at times. The way Noisy Nets approach this issue is by adding a noisy linear layer. Over time, the network will learn how to ignore the noise (added as a noisy stream). But this learning comes at different rates in different parts of the space, allowing for state exploration."
},
{
"code": null,
"e": 53121,
"s": 53014,
"text": "Note: Stay tuned — I will upload a MXNet/Gluon implementation on Rainbow to Github in early February 2019."
},
{
"code": null,
"e": 53307,
"s": 53121,
"text": "Proximal Policy Optimization (PPO) is a policy optimization model-free type of reinforcement learning. It is much simpler to implement that other algorithms and gives very good results."
},
{
"code": null,
"e": 53687,
"s": 53307,
"text": "Why do we use PPO? One of the advantages of PPO is that it directly learns the policy, rather than indirectly via the values (the way Q Learning uses Q-values to learn the policy). It can work well in continuous action spaces, which is suitable in our use case and can learn (through mean and standard deviation) the distribution probabilities (if softmax is added as an output)."
},
{
"code": null,
"e": 54335,
"s": 53687,
"text": "The problem of policy gradient methods is that they are extremely sensitive to the step size choice — if it is small the progress takes too long (most probably mainly due to the need of a second-order derivatives matrix); if it is large, there is a lot noise which significantly reduces the performance. Input data is nonstationary due to the changes in the policy (also the distributions of the reward and observations change). As compared to supervised learning, poorly chosen step can be much more devastating as it affects the whole distribution of next visits. PPO can solve these issues. What is more, compared to some other approaches, PPO:"
},
{
"code": null,
"e": 54935,
"s": 54335,
"text": "is much less complicated, for example compared to ACER, which requires additional code for keeping the off-policy correlations and also a replay buffer, or TRPO which has a constraint imposed on the surrogate objective function (the KL divergence between the old and the new policy). This constraint is used to control the policy of changing too much — which might create instability. PPO reduces the computation (created by the constraint) by utilizing a clipped (between [1- ε, 1+ε]) surrogate objective function and modifying the objective function with a penalty for having too big of an update."
},
{
"code": null,
"e": 55117,
"s": 54935,
"text": "gives compatibility with algos that share parameters between value and policy function or auxiliary losses, as compared to TRPO (although PPO also have the gain of trust region PO)."
},
{
"code": null,
"e": 55477,
"s": 55117,
"text": "Note: For the purpose of our exercise we won’t go too much into the research and optimization of RL approaches, PPO and the others included. Rather, we will take what is available and try to fit into our process for hyperparameter optimization for our GAN, LSTM, and CNN models. The code we will reuse and customize is created by OpenAI and is available here."
},
{
"code": null,
"e": 55534,
"s": 55477,
"text": "Some ideas for further exploring reinforcement learning:"
},
{
"code": null,
"e": 55831,
"s": 55534,
"text": "One of the first things I will introduce next is using Augmented Random Search (link) as an alternative algorithm. The authors of the algorithm (out of UC, Berkeley) have managed to achieve similar rewards results as other state of the art approaches, such as PPO, but on average 15 times faster."
},
{
"code": null,
"e": 55995,
"s": 55831,
"text": "Choosing a reward function is very important. I stated the currently used reward function above, but I will try to play with different functions as an alternative."
},
{
"code": null,
"e": 56037,
"s": 55995,
"text": "Using Curiosity as an exploration policy."
},
{
"code": null,
"e": 56127,
"s": 56037,
"text": "Create multi-agent architecture as proposed by Berkeley’s AI Research team (BAIR) — link."
},
{
"code": null,
"e": 56325,
"s": 56127,
"text": "Instead of the grid search, that can take a lot of time to find the best combination of hyperparameters, we will use Bayesian optimization. The library that we’ll use is already implemented — link."
},
{
"code": null,
"e": 56459,
"s": 56325,
"text": "Finally we will compare the output of the LSTM when the unseen (test) data is used as an input after different phases of the process."
},
{
"code": null,
"e": 56487,
"s": 56459,
"text": "Plot after the first epoch."
},
{
"code": null,
"e": 56515,
"s": 56487,
"text": "Plot after the first epoch."
},
{
"code": null,
"e": 56613,
"s": 56515,
"text": "from utils import plot_predictionplot_prediction('Predicted and Real price - after first epoch.')"
},
{
"code": null,
"e": 56638,
"s": 56613,
"text": "2. Plot after 50 epochs."
},
{
"code": null,
"e": 56707,
"s": 56638,
"text": "plot_prediction('Predicted and Real price - after first 50 epochs.')"
},
{
"code": null,
"e": 56777,
"s": 56707,
"text": "plot_prediction('Predicted and Real price - after first 200 epochs.')"
},
{
"code": null,
"e": 56875,
"s": 56777,
"text": "The RL run for ten episodes (we define an eposide to be one full GAN training on the 200 epochs.)"
},
{
"code": null,
"e": 56908,
"s": 56875,
"text": "plot_prediction('Final result.')"
},
{
"code": null,
"e": 57092,
"s": 56908,
"text": "Next, I will try to create a RL environment for testing trading algorithms that decide when and how to trade. The output from the GAN will be one of the parameters in the environment."
},
{
"code": null,
"e": 57576,
"s": 57092,
"text": "This notebook is entirely informative. None of the content presented in this notebook constitutes a recommendation that any particular security, portfolio of securities, transaction or investment strategy is suitable for any specific person. Futures, stocks and options trading involves substantial risk of loss and is not suitable for every investor. The valuation of futures, stocks and options may fluctuate, and, as a result, clients may lose more than their original investment."
},
{
"code": null,
"e": 57626,
"s": 57576,
"text": "All trading strategies are used at your own risk."
},
{
"code": null,
"e": 57983,
"s": 57626,
"text": "There are many many more details to explore — in choosing data features, in choosing algorithms, in tuning the algos, etc. This version of the notebook itself took me 2 weeks to finish. I am sure there are many unaswered parts of the process. So, any comments and suggestion — please do share. I’d be happy to add and test any ideas in the current process."
}
] |
Sum of Binary Tree | Practice | GeeksforGeeks
|
Given a Binary Tree of size N, your task is to complete the function sumBt(), that should return the sum of all the nodes of the given binary tree.
Input:
First line of input contains the number of test cases T. For each test case, there will be two lines:
First line of each test case will be an integer N denoting the number of parent child relationships.
Second line of each test case will print the level order traversal of the tree in the form of N space separated triplets. The description of triplets is as follows:
Each triplet will contain three space-separated elements of the form (int, int char).
The first integer element will be the value of parent.
The second integer will be the value of corresponding left or right child. In case the child is null, this value will be -1.
The third element of triplet which is a character can take any of the three values ‘L’, ‘R’ or ‘N’. L denotes that the children is a left child, R denotes that the children is a Right Child and N denotes that the child is NULL.
First line of each test case will be an integer N denoting the number of parent child relationships.
First line of each test case will be an integer N denoting the number of parent child relationships.
Second line of each test case will print the level order traversal of the tree in the form of N space separated triplets. The description of triplets is as follows:
Each triplet will contain three space-separated elements of the form (int, int char).
The first integer element will be the value of parent.
The second integer will be the value of corresponding left or right child. In case the child is null, this value will be -1.
The third element of triplet which is a character can take any of the three values ‘L’, ‘R’ or ‘N’. L denotes that the children is a left child, R denotes that the children is a Right Child and N denotes that the child is NULL.
Second line of each test case will print the level order traversal of the tree in the form of N space separated triplets. The description of triplets is as follows:
Each triplet will contain three space-separated elements of the form (int, int char).
The first integer element will be the value of parent.
The second integer will be the value of corresponding left or right child. In case the child is null, this value will be -1.
The third element of triplet which is a character can take any of the three values ‘L’, ‘R’ or ‘N’. L denotes that the children is a left child, R denotes that the children is a Right Child and N denotes that the child is NULL.
Each triplet will contain three space-separated elements of the form (int, int char).
Each triplet will contain three space-separated elements of the form (int, int char).
The first integer element will be the value of parent.
The first integer element will be the value of parent.
The second integer will be the value of corresponding left or right child. In case the child is null, this value will be -1.
The second integer will be the value of corresponding left or right child. In case the child is null, this value will be -1.
The third element of triplet which is a character can take any of the three values ‘L’, ‘R’ or ‘N’. L denotes that the children is a left child, R denotes that the children is a Right Child and N denotes that the child is NULL.
The third element of triplet which is a character can take any of the three values ‘L’, ‘R’ or ‘N’. L denotes that the children is a left child, R denotes that the children is a Right Child and N denotes that the child is NULL.
Please note that the relationships are printed only for internal nodes and not for leaf nodes.
Output:
The function should return the sum of all the nodes of the binary tree.
User Task:
As it is a functional problem. So, you don't need to worry about the input you just have to complete the function sumBT() that takes a node as a parameter and returns the sum of all the nodes.
Constraints:
1<=T<=100
1<=N<=100
Example:
Input:
2
2
1 2 L 1 -1 N
6
1 2 L 1 3 R 2 -1 N 2 -1 N 3 3 L 3 -1 N
Output:
3
9
Note:The Input/Ouput format and Example given are used for system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console. The task is to complete the function specified, and not to write the full code.
0
superrhitik4582 days ago
//simple recursion based solution..
long int sum=0;void add(Node*root){ if(root==NULL) return ; sum+=root->key; add(root->left); add(root->right);}long int sumBT(Node* root){ // Code hereadd(root);long int s=sum;sum=0;return s; }
0
harshscode1 week ago
BEST SOLUTION C++
if(root==NULL) return 0; if(root->left==NULL and root->right==NULL) return root->key; int l=sumBT(root->left); int r=sumBT(root->right); return root->key+l+r;
0
atif836141 month ago
RECURSION BASED PROBLEM :
class BinaryTree
{
static int sumBT(Node head){
if(head==null){
return 0;
}
int ls=sumBT(head.left);
int rs =sumBT(head.right);
int sum = ls +rs+head.data;
return sum;
}
}
0
0niharika21 month ago
Iterative C++
if(root==NULL) return -1; long int sum=0; stack<Node*> s; s.push(root); while(!s.empty()) { root = s.top(); sum += root->key; s.pop(); if(root->right!=NULL) s.push(root->right); if(root->left!=NULL) s.push(root->left); } return sum;
0
harendersingh78962 months ago
class BinaryTree{ static int sumBT(Node head){ //Code if(head == null) { return 0; } int ls = sumBT(head.left); int rs = sumBT(head.right); int ts = ls + rs + head.data; return ts; }}
0
anjalirajwar1013 months ago
long int sumBT(Node* root){ // Code here if(root==NULL){ return 0; } long int sum; sum= root->key + sumBT(root->left) +sumBT(root->right); return sum;}
0
ishnoorsinghsethi3 months ago
C++ solution using level order traversal
long int sumBT(Node* root){ queue<Node *> q; long int sum = 0; q.push(root); while(q.size()){ Node * p =q.front(); q.pop(); sum+=p->key; if(p->left) q.push(p->left); if(p->right) q.push(p->right); } return sum; // Code here}
+1
kronizerdeltac3 months ago
C++ AND JAVA SOLUTIONS
JAVA
static int sumBT(Node root){
return root == null ? 0 : sumBT(root.left) + sumBT(root.right) + root.data;
}
C++
long int sumBT(Node* root)
{
return root == nullptr ? 0 : sumBT(root->left) + sumBT(root->right) + root->key;
}
0
amiransarimy3 months ago
Python Solution
Total Time Taken:0.2/1.3
def sumBT(root):
if root is None:
return 0
return root.data + sumBT(root.left) + sumBT(root.right)
0
punithrkashi3 months ago
Javascript Solution
class Solution
{
sumBT(root){
var sum = 0;
if(root===null) return (sum + 0);
if(root.left === null && root.right === null){
return (sum + root.data)
}else{
sum = root.data + sum;
return (sum + this.sumBT(root.left) + this.sumBT(root.right))
}
}
}
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": 394,
"s": 238,
"text": "Given a Binary Tree of size N, your task is to complete the function sumBt(), that should return the sum of all the nodes of the given binary tree.\n\nInput:"
},
{
"code": null,
"e": 496,
"s": 394,
"text": "First line of input contains the number of test cases T. For each test case, there will be two lines:"
},
{
"code": null,
"e": 1277,
"s": 496,
"text": "\n\nFirst line of each test case will be an integer N denoting the number of parent child relationships.\n\n\nSecond line of each test case will print the level order traversal of the tree in the form of N space separated triplets. The description of triplets is as follows:\n\n\nEach triplet will contain three space-separated elements of the form (int, int char).\n\n\nThe first integer element will be the value of parent. \n\n\nThe second integer will be the value of corresponding left or right child. In case the child is null, this value will be -1.\n\n\nThe third element of triplet which is a character can take any of the three values ‘L’, ‘R’ or ‘N’. L denotes that the children is a left child, R denotes that the children is a Right Child and N denotes that the child is NULL.\n\t\t \n\n\n\n"
},
{
"code": null,
"e": 1380,
"s": 1277,
"text": "\nFirst line of each test case will be an integer N denoting the number of parent child relationships.\n"
},
{
"code": null,
"e": 1481,
"s": 1380,
"text": "First line of each test case will be an integer N denoting the number of parent child relationships."
},
{
"code": null,
"e": 2157,
"s": 1481,
"text": "\nSecond line of each test case will print the level order traversal of the tree in the form of N space separated triplets. The description of triplets is as follows:\n\n\nEach triplet will contain three space-separated elements of the form (int, int char).\n\n\nThe first integer element will be the value of parent. \n\n\nThe second integer will be the value of corresponding left or right child. In case the child is null, this value will be -1.\n\n\nThe third element of triplet which is a character can take any of the three values ‘L’, ‘R’ or ‘N’. L denotes that the children is a left child, R denotes that the children is a Right Child and N denotes that the child is NULL.\n\t\t \n\n\n"
},
{
"code": null,
"e": 2322,
"s": 2157,
"text": "Second line of each test case will print the level order traversal of the tree in the form of N space separated triplets. The description of triplets is as follows:"
},
{
"code": null,
"e": 2831,
"s": 2322,
"text": "\n\nEach triplet will contain three space-separated elements of the form (int, int char).\n\n\nThe first integer element will be the value of parent. \n\n\nThe second integer will be the value of corresponding left or right child. In case the child is null, this value will be -1.\n\n\nThe third element of triplet which is a character can take any of the three values ‘L’, ‘R’ or ‘N’. L denotes that the children is a left child, R denotes that the children is a Right Child and N denotes that the child is NULL.\n\t\t \n\n"
},
{
"code": null,
"e": 2919,
"s": 2831,
"text": "\nEach triplet will contain three space-separated elements of the form (int, int char).\n"
},
{
"code": null,
"e": 3005,
"s": 2919,
"text": "Each triplet will contain three space-separated elements of the form (int, int char)."
},
{
"code": null,
"e": 3063,
"s": 3005,
"text": "\nThe first integer element will be the value of parent. \n"
},
{
"code": null,
"e": 3119,
"s": 3063,
"text": "The first integer element will be the value of parent. "
},
{
"code": null,
"e": 3246,
"s": 3119,
"text": "\nThe second integer will be the value of corresponding left or right child. In case the child is null, this value will be -1.\n"
},
{
"code": null,
"e": 3371,
"s": 3246,
"text": "The second integer will be the value of corresponding left or right child. In case the child is null, this value will be -1."
},
{
"code": null,
"e": 3605,
"s": 3371,
"text": "\nThe third element of triplet which is a character can take any of the three values ‘L’, ‘R’ or ‘N’. L denotes that the children is a left child, R denotes that the children is a Right Child and N denotes that the child is NULL.\n\t\t \n"
},
{
"code": null,
"e": 3837,
"s": 3605,
"text": "The third element of triplet which is a character can take any of the three values ‘L’, ‘R’ or ‘N’. L denotes that the children is a left child, R denotes that the children is a Right Child and N denotes that the child is NULL.\n\t\t "
},
{
"code": null,
"e": 4339,
"s": 3837,
"text": "Please note that the relationships are printed only for internal nodes and not for leaf nodes.\n\nOutput:\nThe function should return the sum of all the nodes of the binary tree.\n\nUser Task:\nAs it is a functional problem. So, you don't need to worry about the input you just have to complete the function sumBT() that takes a node as a parameter and returns the sum of all the nodes.\n\nConstraints:\n1<=T<=100\n1<=N<=100\n\nExample:\nInput:\n2\n2\n1 2 L 1 -1 N\n6\n1 2 L 1 3 R 2 -1 N 2 -1 N 3 3 L 3 -1 N\nOutput:\n3\n9"
},
{
"code": null,
"e": 4648,
"s": 4339,
"text": "Note:The Input/Ouput format and Example given are used for system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console. The task is to complete the function specified, and not to write the full code."
},
{
"code": null,
"e": 4650,
"s": 4648,
"text": "0"
},
{
"code": null,
"e": 4675,
"s": 4650,
"text": "superrhitik4582 days ago"
},
{
"code": null,
"e": 4711,
"s": 4675,
"text": "//simple recursion based solution.."
},
{
"code": null,
"e": 4921,
"s": 4713,
"text": "long int sum=0;void add(Node*root){ if(root==NULL) return ; sum+=root->key; add(root->left); add(root->right);}long int sumBT(Node* root){ // Code hereadd(root);long int s=sum;sum=0;return s; }"
},
{
"code": null,
"e": 4923,
"s": 4921,
"text": "0"
},
{
"code": null,
"e": 4944,
"s": 4923,
"text": "harshscode1 week ago"
},
{
"code": null,
"e": 4962,
"s": 4944,
"text": "BEST SOLUTION C++"
},
{
"code": null,
"e": 5143,
"s": 4962,
"text": " if(root==NULL) return 0; if(root->left==NULL and root->right==NULL) return root->key; int l=sumBT(root->left); int r=sumBT(root->right); return root->key+l+r;"
},
{
"code": null,
"e": 5145,
"s": 5143,
"text": "0"
},
{
"code": null,
"e": 5166,
"s": 5145,
"text": "atif836141 month ago"
},
{
"code": null,
"e": 5192,
"s": 5166,
"text": "RECURSION BASED PROBLEM :"
},
{
"code": null,
"e": 5453,
"s": 5192,
"text": "class BinaryTree\n{\n static int sumBT(Node head){\n if(head==null){\n return 0;\n }\n int ls=sumBT(head.left);\n int rs =sumBT(head.right);\n int sum = ls +rs+head.data;\n return sum;\n }\n }"
},
{
"code": null,
"e": 5455,
"s": 5453,
"text": "0"
},
{
"code": null,
"e": 5477,
"s": 5455,
"text": "0niharika21 month ago"
},
{
"code": null,
"e": 5491,
"s": 5477,
"text": "Iterative C++"
},
{
"code": null,
"e": 5794,
"s": 5491,
"text": "if(root==NULL) return -1; long int sum=0; stack<Node*> s; s.push(root); while(!s.empty()) { root = s.top(); sum += root->key; s.pop(); if(root->right!=NULL) s.push(root->right); if(root->left!=NULL) s.push(root->left); } return sum;"
},
{
"code": null,
"e": 5796,
"s": 5794,
"text": "0"
},
{
"code": null,
"e": 5826,
"s": 5796,
"text": "harendersingh78962 months ago"
},
{
"code": null,
"e": 6093,
"s": 5826,
"text": "class BinaryTree{ static int sumBT(Node head){ //Code if(head == null) { return 0; } int ls = sumBT(head.left); int rs = sumBT(head.right); int ts = ls + rs + head.data; return ts; }}"
},
{
"code": null,
"e": 6095,
"s": 6093,
"text": "0"
},
{
"code": null,
"e": 6123,
"s": 6095,
"text": "anjalirajwar1013 months ago"
},
{
"code": null,
"e": 6293,
"s": 6123,
"text": "long int sumBT(Node* root){ // Code here if(root==NULL){ return 0; } long int sum; sum= root->key + sumBT(root->left) +sumBT(root->right); return sum;}"
},
{
"code": null,
"e": 6295,
"s": 6293,
"text": "0"
},
{
"code": null,
"e": 6325,
"s": 6295,
"text": "ishnoorsinghsethi3 months ago"
},
{
"code": null,
"e": 6366,
"s": 6325,
"text": "C++ solution using level order traversal"
},
{
"code": null,
"e": 6635,
"s": 6366,
"text": "long int sumBT(Node* root){ queue<Node *> q; long int sum = 0; q.push(root); while(q.size()){ Node * p =q.front(); q.pop(); sum+=p->key; if(p->left) q.push(p->left); if(p->right) q.push(p->right); } return sum; // Code here}"
},
{
"code": null,
"e": 6638,
"s": 6635,
"text": "+1"
},
{
"code": null,
"e": 6665,
"s": 6638,
"text": "kronizerdeltac3 months ago"
},
{
"code": null,
"e": 6688,
"s": 6665,
"text": "C++ AND JAVA SOLUTIONS"
},
{
"code": null,
"e": 6695,
"s": 6690,
"text": "JAVA"
},
{
"code": null,
"e": 6814,
"s": 6695,
"text": "static int sumBT(Node root){\n return root == null ? 0 : sumBT(root.left) + sumBT(root.right) + root.data;\n }"
},
{
"code": null,
"e": 6818,
"s": 6814,
"text": "C++"
},
{
"code": null,
"e": 6933,
"s": 6818,
"text": "long int sumBT(Node* root)\n{\n return root == nullptr ? 0 : sumBT(root->left) + sumBT(root->right) + root->key;\n}"
},
{
"code": null,
"e": 6935,
"s": 6933,
"text": "0"
},
{
"code": null,
"e": 6960,
"s": 6935,
"text": "amiransarimy3 months ago"
},
{
"code": null,
"e": 6976,
"s": 6960,
"text": "Python Solution"
},
{
"code": null,
"e": 7001,
"s": 6976,
"text": "Total Time Taken:0.2/1.3"
},
{
"code": null,
"e": 7115,
"s": 7003,
"text": "def sumBT(root):\n if root is None:\n return 0\n return root.data + sumBT(root.left) + sumBT(root.right)"
},
{
"code": null,
"e": 7117,
"s": 7115,
"text": "0"
},
{
"code": null,
"e": 7142,
"s": 7117,
"text": "punithrkashi3 months ago"
},
{
"code": null,
"e": 7162,
"s": 7142,
"text": "Javascript Solution"
},
{
"code": null,
"e": 7471,
"s": 7164,
"text": "class Solution\n{ \n sumBT(root){\n var sum = 0;\n if(root===null) return (sum + 0);\n if(root.left === null && root.right === null){\n return (sum + root.data)\n }else{\n sum = root.data + sum;\n return (sum + this.sumBT(root.left) + this.sumBT(root.right))\n }\n }\n} "
},
{
"code": null,
"e": 7617,
"s": 7471,
"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": 7653,
"s": 7617,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 7663,
"s": 7653,
"text": "\nProblem\n"
},
{
"code": null,
"e": 7673,
"s": 7663,
"text": "\nContest\n"
},
{
"code": null,
"e": 7736,
"s": 7673,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 7884,
"s": 7736,
"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": 8092,
"s": 7884,
"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": 8198,
"s": 8092,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
How to add items in a JComboBox on runtime in Java
|
The following is an example to add items on runtime on a JComboBox in Java:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
public class SwingDemo {
public static void main(String[] args) throws Exception {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComboBox<String> combo = new JComboBox<>(new String[] { "One","Two", "Three","Four","Five", "Six" });
JButton add = new JButton("Add");
add.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
combo.addItem("New");
}
});
frame.add(combo);
frame.add(add, BorderLayout.NORTH);
frame.setSize(500, 100);
frame.setVisible(true);
}
}
Now, we have the following items:
Now, click “Add” above to add a new item on runtime. After clicking, a new item would be visible in the bottom as shown in the following screenshot:
|
[
{
"code": null,
"e": 1138,
"s": 1062,
"text": "The following is an example to add items on runtime on a JComboBox in Java:"
},
{
"code": null,
"e": 1969,
"s": 1138,
"text": "import java.awt.BorderLayout;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\nimport javax.swing.JButton;\nimport javax.swing.JComboBox;\nimport javax.swing.JFrame;\npublic class SwingDemo {\n public static void main(String[] args) throws Exception {\n JFrame frame = new JFrame();\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n JComboBox<String> combo = new JComboBox<>(new String[] { \"One\",\"Two\", \"Three\",\"Four\",\"Five\", \"Six\" });\n JButton add = new JButton(\"Add\");\n add.addActionListener(new ActionListener() {\n @Override\n public void actionPerformed(ActionEvent e) {\n combo.addItem(\"New\");\n }\n });\n frame.add(combo);\n frame.add(add, BorderLayout.NORTH);\n frame.setSize(500, 100);\n frame.setVisible(true);\n }\n}"
},
{
"code": null,
"e": 2003,
"s": 1969,
"text": "Now, we have the following items:"
},
{
"code": null,
"e": 2152,
"s": 2003,
"text": "Now, click “Add” above to add a new item on runtime. After clicking, a new item would be visible in the bottom as shown in the following screenshot:"
}
] |
How to find prime numbers between two values or up to a value in R?
|
We know that the prime numbers are the numbers that are not divisible by any number except by themselves or 1 and 1 is not considered as a prime number. In R, we can find the prime numbers up to a number or between two numbers by using Prime function of numbers package. If we want to find the total number of prime numbers between 1 and 10, then we just need to pass 10 inside the Prime function, otherwise range will be required.
Loading numbers package −
library("numbers")
Primes(10)
[1] 2 3 5 7
Primes(100)
[1] 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
Primes(50)
[1] 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
Primes(1000)
[1] 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61
[19] 67 71 73 79 83 89 97 101 103 107 109 113 127 131 137 139 149 151
[37] 157 163 167 173 179 181 191 193 197 199 211 223 227 229 233 239 241 251
[55] 257 263 269 271 277 281 283 293 307 311 313 317 331 337 347 349 353 359
[73] 367 373 379 383 389 397 401 409 419 421 431 433 439 443 449 457 461 463
[91] 467 479 487 491 499 503 509 521 523 541 547 557 563 569 571 577 587 593
[109] 599 601 607 613 617 619 631 641 643 647 653 659 661 673 677 683 691 701
[127] 709 719 727 733 739 743 751 757 761 769 773 787 797 809 811 821 823 827
[145] 829 839 853 857 859 863 877 881 883 887 907 911 919 929 937 941 947 953
[163] 967 971 977 983 991 997
Primes(250)
[1] 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67
[20] 71 73 79 83 89 97 101 103 107 109 113 127 131 137 139 149 151 157 163
[39] 167 173 179 181 191 193 197 199 211 223 227 229 233 239 241
Primes(500)
[1] 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67
[20] 71 73 79 83 89 97 101 103 107 109 113 127 131 137 139 149 151 157 163
[39] 167 173 179 181 191 193 197 199 211 223 227 229 233 239 241 251 257 263 269
[58] 271 277 281 283 293 307 311 313 317 331 337 347 349 353 359 367 373 379 383
[77] 389 397 401 409 419 421 431 433 439 443 449 457 461 463 467 479 487 491 499
Primes(365)
[1] 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67
[20] 71 73 79 83 89 97 101 103 107 109 113 127 131 137 139 149 151 157 163
[39] 167 173 179 181 191 193 197 199 211 223 227 229 233 239 241 251 257 263 269
[58] 271 277 281 283 293 307 311 313 317 331 337 347 349 353 359
Primes(12)
[1] 2 3 5 7 11
Primes(121)
[1] 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67
[20] 71 73 79 83 89 97 101 103 107 109 113
Primes(20)
[1] 2 3 5 7 11 13 17 19
Primes(30)
[1] 2 3 5 7 11 13 17 19 23 29
Primes(45)
[1] 2 3 5 7 11 13 17 19 23 29 31 37 41 43
Primes(10,20)
[1] 11 13 17 19
Primes(10,400)
[1] 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83
[20] 89 97 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181
[39] 191 193 197 199 211 223 227 229 233 239 241 251 257 263 269 271 277 281 283
[58] 293 307 311 313 317 331 337 347 349 353 359 367 373 379 383 389 397
Primes(10,50)
[1] 11 13 17 19 23 29 31 37 41 43 47
Primes(10,500)
[1] 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83
[20] 89 97 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181
[39] 191 193 197 199 211 223 227 229 233 239 241 251 257 263 269 271 277 281 283
[58] 293 307 311 313 317 331 337 347 349 353 359 367 373 379 383 389 397 401 409
[77] 419 421 431 433 439 443 449 457 461 463 467 479 487 491 499
Primes(100,500)
[1] 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193
[20] 197 199 211 223 227 229 233 239 241 251 257 263 269 271 277 281 283 293 307
[39] 311 313 317 331 337 347 349 353 359 367 373 379 383 389 397 401 409 419 421
[58] 431 433 439 443 449 457 461 463 467 479 487 491 499
Primes(100,500)
[1] 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191
[19] 193 197 199 211 223 227 229 233 239 241 251 257 263 269 271 277 281 283
[37] 293 307 311 313 317 331 337 347 349 353 359 367 373 379 383 389 397 401
[55] 409 419 421 431 433 439 443 449 457 461 463 467 479 487 491 499 503 509
[73] 521 523 541 547 557 563 569 571 577 587 593 599 601 607 613 617 619 631
[91] 641 643 647 653 659 661 673 677 683 691 701 709 719 727 733 739 743 751
[109] 757 761 769 773 787 797 809 811 821 823 827 829 839 853 857 859 863 877
[127] 881 883 887 907 911 919 929 937 941 947 953 967 971 977 983 991 997
|
[
{
"code": null,
"e": 1494,
"s": 1062,
"text": "We know that the prime numbers are the numbers that are not divisible by any number except by themselves or 1 and 1 is not considered as a prime number. In R, we can find the prime numbers up to a number or between two numbers by using Prime function of numbers package. If we want to find the total number of prime numbers between 1 and 10, then we just need to pass 10 inside the Prime function, otherwise range will be required."
},
{
"code": null,
"e": 1520,
"s": 1494,
"text": "Loading numbers package −"
},
{
"code": null,
"e": 1539,
"s": 1520,
"text": "library(\"numbers\")"
},
{
"code": null,
"e": 1550,
"s": 1539,
"text": "Primes(10)"
},
{
"code": null,
"e": 1562,
"s": 1550,
"text": "[1] 2 3 5 7"
},
{
"code": null,
"e": 1574,
"s": 1562,
"text": "Primes(100)"
},
{
"code": null,
"e": 1649,
"s": 1574,
"text": "[1] 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97"
},
{
"code": null,
"e": 1660,
"s": 1649,
"text": "Primes(50)"
},
{
"code": null,
"e": 1706,
"s": 1660,
"text": "[1] 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47\n"
},
{
"code": null,
"e": 1719,
"s": 1706,
"text": "Primes(1000)"
},
{
"code": null,
"e": 2415,
"s": 1719,
"text": "[1] 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61\n[19] 67 71 73 79 83 89 97 101 103 107 109 113 127 131 137 139 149 151\n[37] 157 163 167 173 179 181 191 193 197 199 211 223 227 229 233 239 241 251\n[55] 257 263 269 271 277 281 283 293 307 311 313 317 331 337 347 349 353 359\n[73] 367 373 379 383 389 397 401 409 419 421 431 433 439 443 449 457 461 463\n[91] 467 479 487 491 499 503 509 521 523 541 547 557 563 569 571 577 587 593\n[109] 599 601 607 613 617 619 631 641 643 647 653 659 661 673 677 683 691 701\n[127] 709 719 727 733 739 743 751 757 761 769 773 787 797 809 811 821 823 827\n[145] 829 839 853 857 859 863 877 881 883 887 907 911 919 929 937 941 947 953\n[163] 967 971 977 983 991 997"
},
{
"code": null,
"e": 2427,
"s": 2415,
"text": "Primes(250)"
},
{
"code": null,
"e": 2624,
"s": 2427,
"text": "[1] 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67\n[20] 71 73 79 83 89 97 101 103 107 109 113 127 131 137 139 149 151 157 163\n[39] 167 173 179 181 191 193 197 199 211 223 227 229 233 239 241"
},
{
"code": null,
"e": 2636,
"s": 2624,
"text": "Primes(500)"
},
{
"code": null,
"e": 3011,
"s": 2636,
"text": "[1] 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67\n[20] 71 73 79 83 89 97 101 103 107 109 113 127 131 137 139 149 151 157 163\n[39] 167 173 179 181 191 193 197 199 211 223 227 229 233 239 241 251 257 263 269\n[58] 271 277 281 283 293 307 311 313 317 331 337 347 349 353 359 367 373 379 383\n[77] 389 397 401 409 419 421 431 433 439 443 449 457 461 463 467 479 487 491 499"
},
{
"code": null,
"e": 3023,
"s": 3011,
"text": "Primes(365)"
},
{
"code": null,
"e": 3301,
"s": 3023,
"text": "[1] 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67\n[20] 71 73 79 83 89 97 101 103 107 109 113 127 131 137 139 149 151 157 163\n[39] 167 173 179 181 191 193 197 199 211 223 227 229 233 239 241 251 257 263 269\n[58] 271 277 281 283 293 307 311 313 317 331 337 347 349 353 359"
},
{
"code": null,
"e": 3312,
"s": 3301,
"text": "Primes(12)"
},
{
"code": null,
"e": 3327,
"s": 3312,
"text": "[1] 2 3 5 7 11"
},
{
"code": null,
"e": 3339,
"s": 3327,
"text": "Primes(121)"
},
{
"code": null,
"e": 3439,
"s": 3339,
"text": "[1] 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67\n[20] 71 73 79 83 89 97 101 103 107 109 113"
},
{
"code": null,
"e": 3450,
"s": 3439,
"text": "Primes(20)"
},
{
"code": null,
"e": 3474,
"s": 3450,
"text": "[1] 2 3 5 7 11 13 17 19"
},
{
"code": null,
"e": 3485,
"s": 3474,
"text": "Primes(30)"
},
{
"code": null,
"e": 3515,
"s": 3485,
"text": "[1] 2 3 5 7 11 13 17 19 23 29"
},
{
"code": null,
"e": 3526,
"s": 3515,
"text": "Primes(45)"
},
{
"code": null,
"e": 3569,
"s": 3526,
"text": "[1] 2 3 5 7 11 13 17 19 23 29 31 37 41 43\n"
},
{
"code": null,
"e": 3583,
"s": 3569,
"text": "Primes(10,20)"
},
{
"code": null,
"e": 3599,
"s": 3583,
"text": "[1] 11 13 17 19"
},
{
"code": null,
"e": 3614,
"s": 3599,
"text": "Primes(10,400)"
},
{
"code": null,
"e": 3908,
"s": 3614,
"text": "[1] 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83\n[20] 89 97 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181\n[39] 191 193 197 199 211 223 227 229 233 239 241 251 257 263 269 271 277 281 283\n[58] 293 307 311 313 317 331 337 347 349 353 359 367 373 379 383 389 397"
},
{
"code": null,
"e": 3922,
"s": 3908,
"text": "Primes(10,50)"
},
{
"code": null,
"e": 3959,
"s": 3922,
"text": "[1] 11 13 17 19 23 29 31 37 41 43 47"
},
{
"code": null,
"e": 3974,
"s": 3959,
"text": "Primes(10,500)"
},
{
"code": null,
"e": 4342,
"s": 3974,
"text": "[1] 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83\n[20] 89 97 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181\n[39] 191 193 197 199 211 223 227 229 233 239 241 251 257 263 269 271 277 281 283\n[58] 293 307 311 313 317 331 337 347 349 353 359 367 373 379 383 389 397 401 409\n [77] 419 421 431 433 439 443 449 457 461 463 467 479 487 491 499"
},
{
"code": null,
"e": 4358,
"s": 4342,
"text": "Primes(100,500)"
},
{
"code": null,
"e": 4657,
"s": 4358,
"text": "[1] 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193\n[20] 197 199 211 223 227 229 233 239 241 251 257 263 269 271 277 281 283 293 307\n[39] 311 313 317 331 337 347 349 353 359 367 373 379 383 389 397 401 409 419 421\n[58] 431 433 439 443 449 457 461 463 467 479 487 491 499"
},
{
"code": null,
"e": 4673,
"s": 4657,
"text": "Primes(100,500)"
},
{
"code": null,
"e": 5286,
"s": 4673,
"text": "[1] 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191\n[19] 193 197 199 211 223 227 229 233 239 241 251 257 263 269 271 277 281 283\n[37] 293 307 311 313 317 331 337 347 349 353 359 367 373 379 383 389 397 401\n[55] 409 419 421 431 433 439 443 449 457 461 463 467 479 487 491 499 503 509\n[73] 521 523 541 547 557 563 569 571 577 587 593 599 601 607 613 617 619 631\n[91] 641 643 647 653 659 661 673 677 683 691 701 709 719 727 733 739 743 751\n[109] 757 761 769 773 787 797 809 811 821 823 827 829 839 853 857 859 863 877\n[127] 881 883 887 907 911 919 929 937 941 947 953 967 971 977 983 991 997"
}
] |
How to move a Tkinter canvas with Mouse?
|
Tkinter Canvas widget is one of the versatile widgets in the Tkinter library. It is used to create different shapes, images, and animating objects. We can move images in a particular direction on the Canvas widget using the move() method.
Define the image and the coordinates as a parameter in the move(Image, x,y) method to move the object in the Canvas. We declare images globally in order to move or change the position.
We can follow these steps to allow our image to move within the canvas,
First, define the Canvas widget and add images to it.
First, define the Canvas widget and add images to it.
Define the move() function to allow the image to be dynamic within the Canvas.
Define the move() function to allow the image to be dynamic within the Canvas.
Bind the mouse buttons with the function that allows images to be moved within the Canvas.
Bind the mouse buttons with the function that allows images to be moved within the Canvas.
# Import the required libraries
from tkinter import *
from PIL import Image, ImageTk
# Create an instance of tkinter frame
win = Tk()
# Set the size of the tkinter window
win.geometry("700x350")
# Define a Canvas widget
canvas = Canvas(win, width=600, height=400, bg="white")
canvas.pack(pady=20)
# Add Images to Canvas widget
image = ImageTk.PhotoImage(Image.open('logo.png'))
img = canvas.create_image(250, 120, anchor=NW, image=image)
def left(e):
x = -20
y = 0
canvas.move(img, x, y)
def right(e):
x = 20
y = 0
canvas.move(img, x, y)
def up(e):
x = 0
y = -20
canvas.move(img, x, y)
def down(e):
x = 0
y = 20
canvas.move(img, x, y)
# Define a function to allow the image to move within the canvas
def move(e):
global image
image = ImageTk.PhotoImage(Image.open('logo.png'))
img = canvas.create_image(e.x, e.y, image=image)
# Bind the move function
canvas.bind("<B1-Motion>", move)
win.mainloop()
Running the above code will display a window that contains an image that can be moved across the window using the mouse buttons.
Now, click on the Canvas and drag the object around with your mouse.
|
[
{
"code": null,
"e": 1301,
"s": 1062,
"text": "Tkinter Canvas widget is one of the versatile widgets in the Tkinter library. It is used to create different shapes, images, and animating objects. We can move images in a particular direction on the Canvas widget using the move() method."
},
{
"code": null,
"e": 1486,
"s": 1301,
"text": "Define the image and the coordinates as a parameter in the move(Image, x,y) method to move the object in the Canvas. We declare images globally in order to move or change the position."
},
{
"code": null,
"e": 1558,
"s": 1486,
"text": "We can follow these steps to allow our image to move within the canvas,"
},
{
"code": null,
"e": 1612,
"s": 1558,
"text": "First, define the Canvas widget and add images to it."
},
{
"code": null,
"e": 1666,
"s": 1612,
"text": "First, define the Canvas widget and add images to it."
},
{
"code": null,
"e": 1745,
"s": 1666,
"text": "Define the move() function to allow the image to be dynamic within the Canvas."
},
{
"code": null,
"e": 1824,
"s": 1745,
"text": "Define the move() function to allow the image to be dynamic within the Canvas."
},
{
"code": null,
"e": 1915,
"s": 1824,
"text": "Bind the mouse buttons with the function that allows images to be moved within the Canvas."
},
{
"code": null,
"e": 2006,
"s": 1915,
"text": "Bind the mouse buttons with the function that allows images to be moved within the Canvas."
},
{
"code": null,
"e": 2961,
"s": 2006,
"text": "# Import the required libraries\nfrom tkinter import *\nfrom PIL import Image, ImageTk\n\n# Create an instance of tkinter frame\nwin = Tk()\n\n# Set the size of the tkinter window\nwin.geometry(\"700x350\")\n\n# Define a Canvas widget\ncanvas = Canvas(win, width=600, height=400, bg=\"white\")\ncanvas.pack(pady=20)\n\n# Add Images to Canvas widget\nimage = ImageTk.PhotoImage(Image.open('logo.png'))\nimg = canvas.create_image(250, 120, anchor=NW, image=image)\n\ndef left(e):\n x = -20\n y = 0\n canvas.move(img, x, y)\n\ndef right(e):\n x = 20\n y = 0\n canvas.move(img, x, y)\n\ndef up(e):\n x = 0\n y = -20\n canvas.move(img, x, y)\n\ndef down(e):\n x = 0\n y = 20\n canvas.move(img, x, y)\n\n# Define a function to allow the image to move within the canvas\ndef move(e):\n global image\n image = ImageTk.PhotoImage(Image.open('logo.png'))\n img = canvas.create_image(e.x, e.y, image=image)\n\n# Bind the move function\ncanvas.bind(\"<B1-Motion>\", move)\n\nwin.mainloop()"
},
{
"code": null,
"e": 3090,
"s": 2961,
"text": "Running the above code will display a window that contains an image that can be moved across the window using the mouse buttons."
},
{
"code": null,
"e": 3159,
"s": 3090,
"text": "Now, click on the Canvas and drag the object around with your mouse."
}
] |
How to get file character encoding in Node.js ? - GeeksforGeeks
|
13 Apr, 2021
Computer reads data in binary representation, that is why we need a way to convert text characters into binary data, this is done with the help of character encoding.
Most popular character encoding types are ASCII and Unicode. Unicode is defined as UTF-8, UTF-16, etc.
We can use a module called ‘detect-file-encoding-and-language‘ to get the character encoding of file in node.js
Syntax:
languageEncoding(pathToFile).then(
fileInfo => // Do anything
);
Parameters:
pathToFile: (Relative or Absolute)Path of the actual file.
Return Value:
An Object having following values, { language: french, encoding: CP1252, confidence: 0.99 }
Setting up environment and Execution:
Step 1: Initialize node.js project
npm init
Step 2: Install required modules
npm install detect-file-encoding-and-language
Step 3: Create a text file
Filename- a.txt
Geeks for Geeks
Step 4: Code in index.js file
index.js
import languageEncoding from "detect-file-encoding-and-language" const pathToFile = "./a.txt" languageEncoding(pathToFile) .then(fileInfo => console.log(fileInfo.encoding)) .catch(err => console.log(err));
Step 5: Run index.js File
node index.js
Output: See output in console
NodeJS-Questions
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to build a basic CRUD app with Node.js and ReactJS ?
How to connect Node.js with React.js ?
Mongoose Populate() Method
Express.js req.params Property
Mongoose find() Function
Top 10 Front End Developer Skills That You Need in 2022
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 24531,
"s": 24503,
"text": "\n13 Apr, 2021"
},
{
"code": null,
"e": 24698,
"s": 24531,
"text": "Computer reads data in binary representation, that is why we need a way to convert text characters into binary data, this is done with the help of character encoding."
},
{
"code": null,
"e": 24801,
"s": 24698,
"text": "Most popular character encoding types are ASCII and Unicode. Unicode is defined as UTF-8, UTF-16, etc."
},
{
"code": null,
"e": 24913,
"s": 24801,
"text": "We can use a module called ‘detect-file-encoding-and-language‘ to get the character encoding of file in node.js"
},
{
"code": null,
"e": 24921,
"s": 24913,
"text": "Syntax:"
},
{
"code": null,
"e": 24990,
"s": 24921,
"text": "languageEncoding(pathToFile).then(\n fileInfo => // Do anything\n);"
},
{
"code": null,
"e": 25002,
"s": 24990,
"text": "Parameters:"
},
{
"code": null,
"e": 25061,
"s": 25002,
"text": "pathToFile: (Relative or Absolute)Path of the actual file."
},
{
"code": null,
"e": 25075,
"s": 25061,
"text": "Return Value:"
},
{
"code": null,
"e": 25167,
"s": 25075,
"text": "An Object having following values, { language: french, encoding: CP1252, confidence: 0.99 }"
},
{
"code": null,
"e": 25205,
"s": 25167,
"text": "Setting up environment and Execution:"
},
{
"code": null,
"e": 25240,
"s": 25205,
"text": "Step 1: Initialize node.js project"
},
{
"code": null,
"e": 25249,
"s": 25240,
"text": "npm init"
},
{
"code": null,
"e": 25282,
"s": 25249,
"text": "Step 2: Install required modules"
},
{
"code": null,
"e": 25328,
"s": 25282,
"text": "npm install detect-file-encoding-and-language"
},
{
"code": null,
"e": 25355,
"s": 25328,
"text": "Step 3: Create a text file"
},
{
"code": null,
"e": 25371,
"s": 25355,
"text": "Filename- a.txt"
},
{
"code": null,
"e": 25387,
"s": 25371,
"text": "Geeks for Geeks"
},
{
"code": null,
"e": 25417,
"s": 25387,
"text": "Step 4: Code in index.js file"
},
{
"code": null,
"e": 25426,
"s": 25417,
"text": "index.js"
},
{
"code": "import languageEncoding from \"detect-file-encoding-and-language\" const pathToFile = \"./a.txt\" languageEncoding(pathToFile) .then(fileInfo => console.log(fileInfo.encoding)) .catch(err => console.log(err));",
"e": 25640,
"s": 25426,
"text": null
},
{
"code": null,
"e": 25666,
"s": 25640,
"text": "Step 5: Run index.js File"
},
{
"code": null,
"e": 25680,
"s": 25666,
"text": "node index.js"
},
{
"code": null,
"e": 25710,
"s": 25680,
"text": "Output: See output in console"
},
{
"code": null,
"e": 25727,
"s": 25710,
"text": "NodeJS-Questions"
},
{
"code": null,
"e": 25734,
"s": 25727,
"text": "Picked"
},
{
"code": null,
"e": 25742,
"s": 25734,
"text": "Node.js"
},
{
"code": null,
"e": 25759,
"s": 25742,
"text": "Web Technologies"
},
{
"code": null,
"e": 25857,
"s": 25759,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25866,
"s": 25857,
"text": "Comments"
},
{
"code": null,
"e": 25879,
"s": 25866,
"text": "Old Comments"
},
{
"code": null,
"e": 25936,
"s": 25879,
"text": "How to build a basic CRUD app with Node.js and ReactJS ?"
},
{
"code": null,
"e": 25975,
"s": 25936,
"text": "How to connect Node.js with React.js ?"
},
{
"code": null,
"e": 26002,
"s": 25975,
"text": "Mongoose Populate() Method"
},
{
"code": null,
"e": 26033,
"s": 26002,
"text": "Express.js req.params Property"
},
{
"code": null,
"e": 26058,
"s": 26033,
"text": "Mongoose find() Function"
},
{
"code": null,
"e": 26114,
"s": 26058,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 26176,
"s": 26114,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 26219,
"s": 26176,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 26269,
"s": 26219,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Extract all integers from the given string in Java - GeeksforGeeks
|
14 Oct, 2019
Given a string str consisting of digits, alphabets and special characters. The task is to extract all the integers from the given string.
Examples:
Input: str = “geeksforgeeks A-118, Sector-136, Uttar Pradesh-201305”Output: 118 136 201305
Input: str = ” 1abc35de 99fgh, dd11′′Output: 1 35 99 11
Approach:
Replace all the non-digit characters with spaces (” “).
Now replace every consecutive group of spaces with a single space.
Eliminate the leading and the trailing spaces (if any) and the final string will only contain the required integers.
Below is the implementation of the above approach:
// Java implementation of the approachpublic class GFG { // Function to return the modified string static String extractInt(String str) { // Replacing every non-digit number // with a space(" ") str = str.replaceAll("[^\\d]", " "); // Remove extra spaces from the beginning // and the ending of the string str = str.trim(); // Replace all the consecutive white // spaces with a single space str = str.replaceAll(" +", " "); if (str.equals("")) return "-1"; return str; } // Driver code public static void main(String[] args) { String str = "avbkjd1122klj4 543 af"; System.out.print(extractInt(str)); }}
1122 4 543
Java
Java Programs
Strings
Strings
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
How to iterate any Map in Java
Initialize an ArrayList in Java
Interfaces in Java
Convert a String to Character array in Java
Initializing a List in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
|
[
{
"code": null,
"e": 24669,
"s": 24641,
"text": "\n14 Oct, 2019"
},
{
"code": null,
"e": 24807,
"s": 24669,
"text": "Given a string str consisting of digits, alphabets and special characters. The task is to extract all the integers from the given string."
},
{
"code": null,
"e": 24817,
"s": 24807,
"text": "Examples:"
},
{
"code": null,
"e": 24908,
"s": 24817,
"text": "Input: str = “geeksforgeeks A-118, Sector-136, Uttar Pradesh-201305”Output: 118 136 201305"
},
{
"code": null,
"e": 24964,
"s": 24908,
"text": "Input: str = ” 1abc35de 99fgh, dd11′′Output: 1 35 99 11"
},
{
"code": null,
"e": 24974,
"s": 24964,
"text": "Approach:"
},
{
"code": null,
"e": 25030,
"s": 24974,
"text": "Replace all the non-digit characters with spaces (” “)."
},
{
"code": null,
"e": 25097,
"s": 25030,
"text": "Now replace every consecutive group of spaces with a single space."
},
{
"code": null,
"e": 25214,
"s": 25097,
"text": "Eliminate the leading and the trailing spaces (if any) and the final string will only contain the required integers."
},
{
"code": null,
"e": 25265,
"s": 25214,
"text": "Below is the implementation of the above approach:"
},
{
"code": "// Java implementation of the approachpublic class GFG { // Function to return the modified string static String extractInt(String str) { // Replacing every non-digit number // with a space(\" \") str = str.replaceAll(\"[^\\\\d]\", \" \"); // Remove extra spaces from the beginning // and the ending of the string str = str.trim(); // Replace all the consecutive white // spaces with a single space str = str.replaceAll(\" +\", \" \"); if (str.equals(\"\")) return \"-1\"; return str; } // Driver code public static void main(String[] args) { String str = \"avbkjd1122klj4 543 af\"; System.out.print(extractInt(str)); }}",
"e": 26006,
"s": 25265,
"text": null
},
{
"code": null,
"e": 26018,
"s": 26006,
"text": "1122 4 543\n"
},
{
"code": null,
"e": 26023,
"s": 26018,
"text": "Java"
},
{
"code": null,
"e": 26037,
"s": 26023,
"text": "Java Programs"
},
{
"code": null,
"e": 26045,
"s": 26037,
"text": "Strings"
},
{
"code": null,
"e": 26053,
"s": 26045,
"text": "Strings"
},
{
"code": null,
"e": 26058,
"s": 26053,
"text": "Java"
},
{
"code": null,
"e": 26156,
"s": 26058,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26165,
"s": 26156,
"text": "Comments"
},
{
"code": null,
"e": 26178,
"s": 26165,
"text": "Old Comments"
},
{
"code": null,
"e": 26229,
"s": 26178,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 26259,
"s": 26229,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 26290,
"s": 26259,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 26322,
"s": 26290,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 26341,
"s": 26322,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 26385,
"s": 26341,
"text": "Convert a String to Character array in Java"
},
{
"code": null,
"e": 26413,
"s": 26385,
"text": "Initializing a List in Java"
},
{
"code": null,
"e": 26439,
"s": 26413,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 26473,
"s": 26439,
"text": "Convert Double to Integer in Java"
}
] |
How to set Large icon instead of small icon on Android Notification?
|
This example demonstrate about How to set Large icon instead of small icon on Android Notification .
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<? xml version = "1.0" encoding = "utf-8" ?>
<RelativeLayout xmlns: android = "http://schemas.android.com/apk/res/android"
xmlns: tools = "http://schemas.android.com/tools"
android :layout_width = "match_parent"
android :layout_height = "match_parent"
tools :context = ".MainActivity" >
<Button
android :layout_width = "match_parent"
android :layout_height = "wrap_content"
android :layout_centerInParent = "true"
android :layout_margin = "16dp"
android :onClick = "createNotification"
android :text = "create notification" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.
package app.tutorialspoint.com.notifyme ;
import android.app.NotificationChannel ;
import android.app.NotificationManager ;
import android.graphics.BitmapFactory ;
import android.os.Bundle ;
import android.support.v4.app.NotificationCompat ;
import android.support.v7.app.AppCompatActivity ;
import android.view.View ;
import android.widget.RemoteViews ;
public class MainActivity extends AppCompatActivity {
public static final String NOTIFICATION_CHANNEL_ID = "10001" ;
private final static String default_notification_channel_id = "default" ;
@Override
protected void onCreate (Bundle savedInstanceState) {
super .onCreate(savedInstanceState) ;
setContentView(R.layout. activity_main ) ;
}
public void createNotification (View view) {
NotificationManager mNotificationManager = (NotificationManager) getSystemService( NOTIFICATION_SERVICE ) ;
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(MainActivity. this, default_notification_channel_id ) ;
mBuilder.setContentTitle( "Notification Title" ) ;
mBuilder.setContentText( "Content to be added" ) ;
mBuilder.setLargeIcon(BitmapFactory. decodeResource (getResources() , R.drawable. ic_launcher_foreground )) ;
mBuilder.setSmallIcon(R.drawable. ic_launcher_foreground ) ;
mBuilder.setAutoCancel( true ) ;
if (android.os.Build.VERSION. SDK_INT >= android.os.Build.VERSION_CODES. O ) {
int importance = NotificationManager. IMPORTANCE_HIGH ;
NotificationChannel notificationChannel = new NotificationChannel( NOTIFICATION_CHANNEL_ID , "NOTIFICATION_CHANNEL_NAME" , importance) ;
mBuilder.setChannelId( NOTIFICATION_CHANNEL_ID ) ;
assert mNotificationManager != null;
mNotificationManager.createNotificationChannel(notificationChannel) ;
}
assert mNotificationManager != null;
mNotificationManager.notify(( int ) System. currentTimeMillis () , mBuilder.build()) ;
}
}
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.tutorialspoint.com.notifyme" >
<uses-permission android :name = "android.permission.VIBRATE" />
<application
android :allowBackup = "true"
android :icon = "@mipmap/ic_launcher"
android :label = "@string/app_name"
android :roundIcon = "@mipmap/ic_launcher_round"
android :supportsRtl = "true"
android :theme = "@style/AppTheme" >
<activity android :name = ".MainActivity" >
<intent-filter>
<action android :name = "android.intent.action.MAIN" />
<category android :name = "android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
Click here to download the project code
|
[
{
"code": null,
"e": 1163,
"s": 1062,
"text": "This example demonstrate about How to set Large icon instead of small icon on Android Notification ."
},
{
"code": null,
"e": 1292,
"s": 1163,
"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": 1357,
"s": 1292,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1953,
"s": 1357,
"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 tools :context = \".MainActivity\" >\n <Button\n android :layout_width = \"match_parent\"\n android :layout_height = \"wrap_content\"\n android :layout_centerInParent = \"true\"\n android :layout_margin = \"16dp\"\n android :onClick = \"createNotification\"\n android :text = \"create notification\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 2006,
"s": 1953,
"text": "Step 3 − Add the following code to src/MainActivity."
},
{
"code": null,
"e": 3987,
"s": 2006,
"text": "package app.tutorialspoint.com.notifyme ;\nimport android.app.NotificationChannel ;\nimport android.app.NotificationManager ;\nimport android.graphics.BitmapFactory ;\nimport android.os.Bundle ;\nimport android.support.v4.app.NotificationCompat ;\nimport android.support.v7.app.AppCompatActivity ;\nimport android.view.View ;\nimport android.widget.RemoteViews ;\npublic class MainActivity extends AppCompatActivity {\n public static final String NOTIFICATION_CHANNEL_ID = \"10001\" ;\n private final static String default_notification_channel_id = \"default\" ;\n @Override\n protected void onCreate (Bundle savedInstanceState) {\n super .onCreate(savedInstanceState) ;\n setContentView(R.layout. activity_main ) ;\n }\n public void createNotification (View view) {\n NotificationManager mNotificationManager = (NotificationManager) getSystemService( NOTIFICATION_SERVICE ) ;\n NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(MainActivity. this, default_notification_channel_id ) ;\n mBuilder.setContentTitle( \"Notification Title\" ) ;\n mBuilder.setContentText( \"Content to be added\" ) ;\n mBuilder.setLargeIcon(BitmapFactory. decodeResource (getResources() , R.drawable. ic_launcher_foreground )) ;\n mBuilder.setSmallIcon(R.drawable. ic_launcher_foreground ) ;\n mBuilder.setAutoCancel( true ) ;\n if (android.os.Build.VERSION. SDK_INT >= android.os.Build.VERSION_CODES. O ) {\n int importance = NotificationManager. IMPORTANCE_HIGH ;\n NotificationChannel notificationChannel = new NotificationChannel( NOTIFICATION_CHANNEL_ID , \"NOTIFICATION_CHANNEL_NAME\" , importance) ;\n mBuilder.setChannelId( NOTIFICATION_CHANNEL_ID ) ;\n assert mNotificationManager != null;\n mNotificationManager.createNotificationChannel(notificationChannel) ;\n }\n assert mNotificationManager != null;\n mNotificationManager.notify(( int ) System. currentTimeMillis () , mBuilder.build()) ;\n }\n}"
},
{
"code": null,
"e": 4042,
"s": 3987,
"text": "Step 4 − Add the following code to AndroidManifest.xml"
},
{
"code": null,
"e": 4841,
"s": 4042,
"text": "<? xml version = \"1.0\" encoding = \"utf-8\" ?>\n<manifest xmlns: android = \"http://schemas.android.com/apk/res/android\"\n package = \"app.tutorialspoint.com.notifyme\" >\n <uses-permission android :name = \"android.permission.VIBRATE\" />\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": 5188,
"s": 4841,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −"
},
{
"code": null,
"e": 5230,
"s": 5188,
"text": "Click here to download the project code"
}
] |
How do I loop through a JSON file with multiple keys/sub-keys in Python?
|
You can parse JSON files using the json module in Python. This module parses the json and puts it in a dict. You can then get the values from this like a normal dict. For example, if you have a json with the following content −
{
"id": "file",
"value": "File",
"popup": {
"menuitem": [
{"value": "New", "onclick": "CreateNewDoc()"},
{"value": "Open", "onclick": "OpenDoc()"},
{"value": "Close", "onclick": "CloseDoc()"}
]
}
}
You can load it in your python program and loop over its keys in the following way −
import json
f = open('data.json')
data = json.load(f)
f.close()
# Now you can use data as a normal dict −
for (k, v) in data.items():
print("Key: " + k)
print("Value: " + str(v))
This will give the output −
Key: id
Value: file
Key: value
Value: File
Key: popup
Value: {'menuitem': [{'value': 'New', 'onclick': 'CreateNewDoc()'}, {'value': 'Open', 'onclick': 'OpenDoc()'}, {'value': 'Close', 'onclick': 'CloseDoc()'}]}
If you want to iterate over sub values as well, you'd have to write a recursive function that can iterate over this tree-like dict.
|
[
{
"code": null,
"e": 1290,
"s": 1062,
"text": "You can parse JSON files using the json module in Python. This module parses the json and puts it in a dict. You can then get the values from this like a normal dict. For example, if you have a json with the following content −"
},
{
"code": null,
"e": 1539,
"s": 1290,
"text": "{\n \"id\": \"file\",\n \"value\": \"File\",\n \"popup\": {\n \"menuitem\": [\n {\"value\": \"New\", \"onclick\": \"CreateNewDoc()\"},\n {\"value\": \"Open\", \"onclick\": \"OpenDoc()\"},\n {\"value\": \"Close\", \"onclick\": \"CloseDoc()\"}\n ]\n }\n}"
},
{
"code": null,
"e": 1624,
"s": 1539,
"text": "You can load it in your python program and loop over its keys in the following way −"
},
{
"code": null,
"e": 1688,
"s": 1624,
"text": "import json\nf = open('data.json')\ndata = json.load(f)\nf.close()"
},
{
"code": null,
"e": 1730,
"s": 1688,
"text": "# Now you can use data as a normal dict −"
},
{
"code": null,
"e": 1809,
"s": 1730,
"text": "for (k, v) in data.items():\n print(\"Key: \" + k)\n print(\"Value: \" + str(v))"
},
{
"code": null,
"e": 1837,
"s": 1809,
"text": "This will give the output −"
},
{
"code": null,
"e": 2048,
"s": 1837,
"text": "Key: id\nValue: file\nKey: value\nValue: File\nKey: popup\nValue: {'menuitem': [{'value': 'New', 'onclick': 'CreateNewDoc()'}, {'value': 'Open', 'onclick': 'OpenDoc()'}, {'value': 'Close', 'onclick': 'CloseDoc()'}]}"
},
{
"code": null,
"e": 2180,
"s": 2048,
"text": "If you want to iterate over sub values as well, you'd have to write a recursive function that can iterate over this tree-like dict."
}
] |
Man is to Doctor as Woman is to Nurse: the Gender Bias of Word Embeddings | by Tommaso Buonocore | Towards Data Science
|
Imagine you are stepping in the elevator of a hospital with two people: a man and a woman. They wear the same white coat, but their badges are covered so you can’t tell what is their role within the hospital. At some point, the elevator doors open and a young lady pops up saying: “good morning, doctor Smith!”. Which one do you think is going to greet her back?
Common sense says that both are equally likely to be doctor Smith, but several experiments show that individuals are much more likely to associate women with nursing and men with doctoring. That being said, you’d probably end up turning your head towards the white-coated guy, expecting him to say something.
Gender stereotypes are still deeply rooted in our society, and women grow up and live being treated very differently from men through conscious and unconscious gender biases.
Language is one of the most powerful means through which sexism and gender discrimination are perpetrated and reproduced. Lexical choices and everyday communication constantly reflects this long-standing bias, to the point that language itself is designed to reflect social asymmetries. For example, grammatical and syntactical rules are built in such a way that feminine terms are usually derived from their corresponding masculine form (e.g. princ-ess, god-dess, etc.) [Menegatti et al, 2017]. Similarly, masculine nouns and pronouns are often used with a generic function to refer to both men and women (e.g. man-kind, states-men, etc.), often being perceived as discriminating against women.These issues are common to most languages, highlighting how gender discrimination spreads across the whole world, involving the society in its entirety.
Since language and culture are so deeply related to eachother, it’s easy to understand the dangerous implication that stereotypes could have on automatic tasks which are based on understanding and processing human languages, from web browsers’ autocompletion to AI-powered bots (remember that time when Microsoft’s AI chatbot went full nazi?) and query results ranking.
Let’s get a bit deeper into it with some techincal-ish details (no hard math involved!).
Natural Language Pocessing (NLP) is a branch of Artificial Intelligence (AI) that helps computers to understand, to interpret and to manipulate natural (i.e. human) language.Imagine NLP-powered machines as black boxes that are capable of understanding and evaluating the context of the input documents (i.e. collection of words), outputting meaningful results that depend on the task the machine is designed for.
Just like any other machine learning algorithm, biased data results in biased outcomes. And just like any other algorithm, results debiasing is painfully annoying, to the point that it might be simpler to unbias the society itself.
Dear humanity: please stop being sexist.Sincerly, your friendly neighborhood data scientist.
Now, let’s see how the gender bias propagates through NLP models.
Words must be represented as numeric vectors in order to be fed into machine learning algorithms. One of the most powerful (and popular) ways to do it is through Word Embeddings. In word embedding models, each word in a given language is assigned to a high-dimensional vector, such that the geometry of the vectors captures relations between the words. For instance, the cosine similarity between the vector representation of the word king will be closer to the word queen than to potato. Remember that the cosine similarity is just the cosine of the angle between two vectors and can be defined as:
Therefore, the higher the cosine similarity is, the closer vector directions are. Let’s try to turn this into a simple R script, using a pretrained GloVe Word Embedding (you can find it here).
> word_vec = read.csv('./glove.6B.300d.csv')> cosine_sim = function(v1,v2){+ return(dot(v1, v2) / (sqrt(sum(v1^2)) * sqrt(sum(v1^2)))+}> cosine_sim(word_vec["king",],word_vec["queen",])[1] 0.67> cosine_sim(word_vec["king",],word_vec["potato",])[1] 0.23
These astonishing results can be achieved thanks to the way word embeddings are learned: following the Distributional Hypotesis, embeddings evaluate in an unsupervised way each target word along with its context (i.e. set of words that comes before and after the target word), building and processing co-occurences matrices (GloVe) or feeding cleverly designed neural networks to solve a word prediction task (Word2Vec and FastText).
In order to preserve the semantics of the natural language in its entirety, word embeddings are usually trained on massive text databases like Wikipedia dumps (6 millions english pages) or Google News (about 100 billion words), inheriting from them all the biases we pointed out previously. Of course, context-specific embeddings can always be learned using smaller datasets.
Let’s stick with the words king and queen. As human beings, we know that kings are royal male figures that rule countries, while we use the word queen to describe a woman who is married to a king or is leading a kingdom by herself (queens ruling king-doms...can you see it?). The set of semantic relations revolving around kings and queens are quite straight forward to us, but can be very hard to get for a machine that can’t read between the lines. Word embeddings allow machines to capture (part of) these analogies and relations, including gender.
Since we are talking about numeric vectors, we can estimate the direction of a semantic relation simply by taking the difference between the vector representations of king and man. What happens then if we try to project the woman vector through the same direction? Surprise: we get the word queen.The information that queen is the feminine of king has never been fed directly into the model, but the model is able to capture this relation anyway.
At this point, you’ll probably guess where this thing is going to end: what if we try to do the same for — let’s say — occupations? As expected, here is where the gender stereotype really strikes in.
> get_analogy = function(v1,v2,v3){+ x = v2-v1+v3+ return(names(get_closest(x,word_vec))[1])+}> get_analogy(word_vec["man",],+ word_vec["doctor",],+ word_vec["woman",])[1] "nurse"
Damn! Apparently, our algorithm experienced the elevator-in-hospital situation too.
Similar results can be obtained for many different occupations. For instance, if we try to get the missing piece of the man : programmer = female : X analogy we unbelievably end up with X = homemaker. Of course the word programmer (as well as the word homemaker) is neutral to gender by its definition, but an embedding model trained on a news corpus tends to see programmer closer with male than female because of the social perception we have of this job, which is reflected in the language we use. [Bolukbasi et al, 2016]
Sexism is even easier to spot when we look at the K-nearest embedding neighbours of man and women. You can guess the target gender of the two clouds even without looking at the description.
In the man subgroup, we can find words like thug, businessman, mechanic, lieutenant, butcher and cop. Among the most related words in the woman subgroup, instead, we observe terms like midwife, nurse, receptionist, waitress flight attendant and...prostitute. Horrific.
Even scarier results can be retrieved switching the domain of interest from occupations to adjectives. According to the embeddings, men are cocky, decent, crafty, brilliant, clever and humble. Women instead — unsurprisingly at this point — are described as sassy, sexy, tasteful, attractive and gorgeous.
Is this really all we have to describe a woman?
You can try this by yourself with this incredible visualization tool crafted at the Hacking Discrimination hackathon held at Microsoft New England Research & Development Center on 2017.
Given the fact that gender biases in Natural Language Processing do exist and should be avoided even just because of ethical reasons, what are the implications of a stereotypes-influenced AI for humans’ everyday life? In other words, why should we care about it?
Among all the pros of automatic systems, being uncorruptible, dedicated and dutiful workaholics is probably one of the most important ones. Machine learning systems can determine the eligibility for a loan without being influenced by the race of the applicant, they can provide access to information and services without gender-based discrimination, they can recruit the best candidate for a company without being affected by his/her sexual orientation, etc. However, when machine learning systems start becoming more human-like in their predictions, they could also start perpetuating human behaviours, losing one of their main advantages on humans: not being human.
Let’s consider the job recruitment example. We would like to design a NLP-powered automatic system to generate a job fitness score based on candidates’ motivation letters. Assuming the company HR’s database isn’t big enough to train its own embeddings, we decide to use a 300-dimensional GloVe word embedding pretrained on Wikipedia.Chances to find positive adjectives like crafty, brilliant and clever in a motivation letter are high, but we observed that these terms are closer to man than to woman in the pretrained embedding space. Moreover, let’s say we’re evaluating candidates for a junior programmer position, that we know not to be considered gender neutral by our embeddings.In this scenario, if the model succeeds in retrieving the gender of the candidate, it will be strongly influenced by it during the candidates selection.
Gender inequality is still deeply rooted in our society and the blind application of machine learning algorithms runs the risk of propagating and amplifying all the biases that are present in the original context. Perpetrating this unpleasant human behavior is not only profoundly unethical, but it may also have alarming consequences in many different decision-making scenarios.
Nowadays, data scientists are working hard to solve the problem, ending up with very clever de-biasing strategies [Bolukbasi et al., 2016][Chakraborty et al., 2016] which reduce the gender polarization while preserving the useful properties of the embedding. Nevertheless, we should be very careful in applying NLP techniques in every context where social biases aren’t supposed to make the difference. Acting this way will improve the efficiency of our models, eventually improving ourselves as human beings.
Here you can find my main sources, along with some very interesting readings which I suggest you to have a look at if you are interested in digging deeper into word embeddings and bias removal.
Learning Gender-Neutral Word Embeddings
Word embeddings quantify 100 years of gender and ethnic stereotypes
Examining Gender and Race Bias in Two Hundred Sentiment Analysis Systems
Man is to Computer Programmer as Woman is to Homemaker? Debiasing Word Embeddings
Male Doctors, Female Nurses: Subconscious Stereotypes Hard to Budge
Oh, are you a nurse? The physician gender bias
Gender Bias in Neural Natural Language Processing
Gender Bias and Sexism in Language
An easy introduction to Natural Language Processing
Why your AI might be racist
Hopefully this blog post has been able to highlight the gender inequality liying within our society and the reason why we should worry about gender stereotypes in NLP. Please leave your thoughts in the comments section and share if you find this helpful!
|
[
{
"code": null,
"e": 534,
"s": 171,
"text": "Imagine you are stepping in the elevator of a hospital with two people: a man and a woman. They wear the same white coat, but their badges are covered so you can’t tell what is their role within the hospital. At some point, the elevator doors open and a young lady pops up saying: “good morning, doctor Smith!”. Which one do you think is going to greet her back?"
},
{
"code": null,
"e": 843,
"s": 534,
"text": "Common sense says that both are equally likely to be doctor Smith, but several experiments show that individuals are much more likely to associate women with nursing and men with doctoring. That being said, you’d probably end up turning your head towards the white-coated guy, expecting him to say something."
},
{
"code": null,
"e": 1018,
"s": 843,
"text": "Gender stereotypes are still deeply rooted in our society, and women grow up and live being treated very differently from men through conscious and unconscious gender biases."
},
{
"code": null,
"e": 1866,
"s": 1018,
"text": "Language is one of the most powerful means through which sexism and gender discrimination are perpetrated and reproduced. Lexical choices and everyday communication constantly reflects this long-standing bias, to the point that language itself is designed to reflect social asymmetries. For example, grammatical and syntactical rules are built in such a way that feminine terms are usually derived from their corresponding masculine form (e.g. princ-ess, god-dess, etc.) [Menegatti et al, 2017]. Similarly, masculine nouns and pronouns are often used with a generic function to refer to both men and women (e.g. man-kind, states-men, etc.), often being perceived as discriminating against women.These issues are common to most languages, highlighting how gender discrimination spreads across the whole world, involving the society in its entirety."
},
{
"code": null,
"e": 2236,
"s": 1866,
"text": "Since language and culture are so deeply related to eachother, it’s easy to understand the dangerous implication that stereotypes could have on automatic tasks which are based on understanding and processing human languages, from web browsers’ autocompletion to AI-powered bots (remember that time when Microsoft’s AI chatbot went full nazi?) and query results ranking."
},
{
"code": null,
"e": 2325,
"s": 2236,
"text": "Let’s get a bit deeper into it with some techincal-ish details (no hard math involved!)."
},
{
"code": null,
"e": 2738,
"s": 2325,
"text": "Natural Language Pocessing (NLP) is a branch of Artificial Intelligence (AI) that helps computers to understand, to interpret and to manipulate natural (i.e. human) language.Imagine NLP-powered machines as black boxes that are capable of understanding and evaluating the context of the input documents (i.e. collection of words), outputting meaningful results that depend on the task the machine is designed for."
},
{
"code": null,
"e": 2970,
"s": 2738,
"text": "Just like any other machine learning algorithm, biased data results in biased outcomes. And just like any other algorithm, results debiasing is painfully annoying, to the point that it might be simpler to unbias the society itself."
},
{
"code": null,
"e": 3063,
"s": 2970,
"text": "Dear humanity: please stop being sexist.Sincerly, your friendly neighborhood data scientist."
},
{
"code": null,
"e": 3129,
"s": 3063,
"text": "Now, let’s see how the gender bias propagates through NLP models."
},
{
"code": null,
"e": 3729,
"s": 3129,
"text": "Words must be represented as numeric vectors in order to be fed into machine learning algorithms. One of the most powerful (and popular) ways to do it is through Word Embeddings. In word embedding models, each word in a given language is assigned to a high-dimensional vector, such that the geometry of the vectors captures relations between the words. For instance, the cosine similarity between the vector representation of the word king will be closer to the word queen than to potato. Remember that the cosine similarity is just the cosine of the angle between two vectors and can be defined as:"
},
{
"code": null,
"e": 3922,
"s": 3729,
"text": "Therefore, the higher the cosine similarity is, the closer vector directions are. Let’s try to turn this into a simple R script, using a pretrained GloVe Word Embedding (you can find it here)."
},
{
"code": null,
"e": 4178,
"s": 3922,
"text": "> word_vec = read.csv('./glove.6B.300d.csv')> cosine_sim = function(v1,v2){+ return(dot(v1, v2) / (sqrt(sum(v1^2)) * sqrt(sum(v1^2)))+}> cosine_sim(word_vec[\"king\",],word_vec[\"queen\",])[1] 0.67> cosine_sim(word_vec[\"king\",],word_vec[\"potato\",])[1] 0.23"
},
{
"code": null,
"e": 4612,
"s": 4178,
"text": "These astonishing results can be achieved thanks to the way word embeddings are learned: following the Distributional Hypotesis, embeddings evaluate in an unsupervised way each target word along with its context (i.e. set of words that comes before and after the target word), building and processing co-occurences matrices (GloVe) or feeding cleverly designed neural networks to solve a word prediction task (Word2Vec and FastText)."
},
{
"code": null,
"e": 4988,
"s": 4612,
"text": "In order to preserve the semantics of the natural language in its entirety, word embeddings are usually trained on massive text databases like Wikipedia dumps (6 millions english pages) or Google News (about 100 billion words), inheriting from them all the biases we pointed out previously. Of course, context-specific embeddings can always be learned using smaller datasets."
},
{
"code": null,
"e": 5540,
"s": 4988,
"text": "Let’s stick with the words king and queen. As human beings, we know that kings are royal male figures that rule countries, while we use the word queen to describe a woman who is married to a king or is leading a kingdom by herself (queens ruling king-doms...can you see it?). The set of semantic relations revolving around kings and queens are quite straight forward to us, but can be very hard to get for a machine that can’t read between the lines. Word embeddings allow machines to capture (part of) these analogies and relations, including gender."
},
{
"code": null,
"e": 5987,
"s": 5540,
"text": "Since we are talking about numeric vectors, we can estimate the direction of a semantic relation simply by taking the difference between the vector representations of king and man. What happens then if we try to project the woman vector through the same direction? Surprise: we get the word queen.The information that queen is the feminine of king has never been fed directly into the model, but the model is able to capture this relation anyway."
},
{
"code": null,
"e": 6187,
"s": 5987,
"text": "At this point, you’ll probably guess where this thing is going to end: what if we try to do the same for — let’s say — occupations? As expected, here is where the gender stereotype really strikes in."
},
{
"code": null,
"e": 6397,
"s": 6187,
"text": "> get_analogy = function(v1,v2,v3){+ x = v2-v1+v3+ return(names(get_closest(x,word_vec))[1])+}> get_analogy(word_vec[\"man\",],+ word_vec[\"doctor\",],+ word_vec[\"woman\",])[1] \"nurse\""
},
{
"code": null,
"e": 6481,
"s": 6397,
"text": "Damn! Apparently, our algorithm experienced the elevator-in-hospital situation too."
},
{
"code": null,
"e": 7006,
"s": 6481,
"text": "Similar results can be obtained for many different occupations. For instance, if we try to get the missing piece of the man : programmer = female : X analogy we unbelievably end up with X = homemaker. Of course the word programmer (as well as the word homemaker) is neutral to gender by its definition, but an embedding model trained on a news corpus tends to see programmer closer with male than female because of the social perception we have of this job, which is reflected in the language we use. [Bolukbasi et al, 2016]"
},
{
"code": null,
"e": 7196,
"s": 7006,
"text": "Sexism is even easier to spot when we look at the K-nearest embedding neighbours of man and women. You can guess the target gender of the two clouds even without looking at the description."
},
{
"code": null,
"e": 7465,
"s": 7196,
"text": "In the man subgroup, we can find words like thug, businessman, mechanic, lieutenant, butcher and cop. Among the most related words in the woman subgroup, instead, we observe terms like midwife, nurse, receptionist, waitress flight attendant and...prostitute. Horrific."
},
{
"code": null,
"e": 7770,
"s": 7465,
"text": "Even scarier results can be retrieved switching the domain of interest from occupations to adjectives. According to the embeddings, men are cocky, decent, crafty, brilliant, clever and humble. Women instead — unsurprisingly at this point — are described as sassy, sexy, tasteful, attractive and gorgeous."
},
{
"code": null,
"e": 7818,
"s": 7770,
"text": "Is this really all we have to describe a woman?"
},
{
"code": null,
"e": 8004,
"s": 7818,
"text": "You can try this by yourself with this incredible visualization tool crafted at the Hacking Discrimination hackathon held at Microsoft New England Research & Development Center on 2017."
},
{
"code": null,
"e": 8267,
"s": 8004,
"text": "Given the fact that gender biases in Natural Language Processing do exist and should be avoided even just because of ethical reasons, what are the implications of a stereotypes-influenced AI for humans’ everyday life? In other words, why should we care about it?"
},
{
"code": null,
"e": 8935,
"s": 8267,
"text": "Among all the pros of automatic systems, being uncorruptible, dedicated and dutiful workaholics is probably one of the most important ones. Machine learning systems can determine the eligibility for a loan without being influenced by the race of the applicant, they can provide access to information and services without gender-based discrimination, they can recruit the best candidate for a company without being affected by his/her sexual orientation, etc. However, when machine learning systems start becoming more human-like in their predictions, they could also start perpetuating human behaviours, losing one of their main advantages on humans: not being human."
},
{
"code": null,
"e": 9773,
"s": 8935,
"text": "Let’s consider the job recruitment example. We would like to design a NLP-powered automatic system to generate a job fitness score based on candidates’ motivation letters. Assuming the company HR’s database isn’t big enough to train its own embeddings, we decide to use a 300-dimensional GloVe word embedding pretrained on Wikipedia.Chances to find positive adjectives like crafty, brilliant and clever in a motivation letter are high, but we observed that these terms are closer to man than to woman in the pretrained embedding space. Moreover, let’s say we’re evaluating candidates for a junior programmer position, that we know not to be considered gender neutral by our embeddings.In this scenario, if the model succeeds in retrieving the gender of the candidate, it will be strongly influenced by it during the candidates selection."
},
{
"code": null,
"e": 10153,
"s": 9773,
"text": "Gender inequality is still deeply rooted in our society and the blind application of machine learning algorithms runs the risk of propagating and amplifying all the biases that are present in the original context. Perpetrating this unpleasant human behavior is not only profoundly unethical, but it may also have alarming consequences in many different decision-making scenarios."
},
{
"code": null,
"e": 10663,
"s": 10153,
"text": "Nowadays, data scientists are working hard to solve the problem, ending up with very clever de-biasing strategies [Bolukbasi et al., 2016][Chakraborty et al., 2016] which reduce the gender polarization while preserving the useful properties of the embedding. Nevertheless, we should be very careful in applying NLP techniques in every context where social biases aren’t supposed to make the difference. Acting this way will improve the efficiency of our models, eventually improving ourselves as human beings."
},
{
"code": null,
"e": 10857,
"s": 10663,
"text": "Here you can find my main sources, along with some very interesting readings which I suggest you to have a look at if you are interested in digging deeper into word embeddings and bias removal."
},
{
"code": null,
"e": 10897,
"s": 10857,
"text": "Learning Gender-Neutral Word Embeddings"
},
{
"code": null,
"e": 10965,
"s": 10897,
"text": "Word embeddings quantify 100 years of gender and ethnic stereotypes"
},
{
"code": null,
"e": 11038,
"s": 10965,
"text": "Examining Gender and Race Bias in Two Hundred Sentiment Analysis Systems"
},
{
"code": null,
"e": 11120,
"s": 11038,
"text": "Man is to Computer Programmer as Woman is to Homemaker? Debiasing Word Embeddings"
},
{
"code": null,
"e": 11188,
"s": 11120,
"text": "Male Doctors, Female Nurses: Subconscious Stereotypes Hard to Budge"
},
{
"code": null,
"e": 11235,
"s": 11188,
"text": "Oh, are you a nurse? The physician gender bias"
},
{
"code": null,
"e": 11285,
"s": 11235,
"text": "Gender Bias in Neural Natural Language Processing"
},
{
"code": null,
"e": 11320,
"s": 11285,
"text": "Gender Bias and Sexism in Language"
},
{
"code": null,
"e": 11372,
"s": 11320,
"text": "An easy introduction to Natural Language Processing"
},
{
"code": null,
"e": 11400,
"s": 11372,
"text": "Why your AI might be racist"
}
] |
Urban Logistics Network Simulation in Python | by Wladimir Hofmann | Towards Data Science
|
Anylogic is probably one of the most popular simulation packages for logistics applications which is out there. A really nice and quite unique feature is the possibility to include GIS-maps into simulation models. It allows to place simulated elements on a map and move them along existing routes, based on real spatial information. This is cool because it can be used to simulate entire supply chains, including means to provide a great, tangible visualization for complex problems. That project, for example, uses Anylogic to evaluate different designs and delivery schemes for a more sustainable urban logistics network in the city center of Grenoble in France. The data-driven simulation model allows calculating KPIs for various transshipment node locations and different types of transport equipment in a multi-tier supply-chain network.
Following the success of the feature, the guys from Anylogic even built anyLogistix, combining pre-built & customizable simulation models with a commercial solver for integrated supply chain planning & optimization.
Obviously, those commercial features come at a price, so let’s see whether this kind of model can also be realized with different means.
Get the repo from github.
The simulation model of this post will be based on a mini-case-study.
Facing the fact that humanity gets more and more used to home-delivery of even everyday necessities, the small (but awesome) French bakery Die Patisserie in Hamburg-Altona wants to deliver sweet pastries to nearby customers.
3 major purchasers were identified: the lost-and-found office Zentrales Fundbüro, Monkeys Music Club, and the publishing house Carlsen Verlag.
Coordinates of the different locations (latitude, longitude):
Die Patisserie (53.55668, 9.92815)Zentrales Fundbüro (53.55817, 9.92829)Monkeys Music Club (53.55706, 9.93161)Carlsen Verlag (53.55703, 9.92684)
Die Patisserie (53.55668, 9.92815)
Zentrales Fundbüro (53.55817, 9.92829)
Monkeys Music Club (53.55706, 9.93161)
Carlsen Verlag (53.55703, 9.92684)
For the sake of simplicity, the order in which nodes are visited is assumed to be fixed. The tour starts & ends at the patisserie (1.):
The simulation model for the simplistic scenario is created with:
OSMnx/networkx for retrieving geo-information and calculating shortest-paths (Python)
SimPy/Casymda for simulating the tour (Python)
Leaflet.js for browser-based animation (JavaScript)
The awesome OSMnx package provides the possibility to obtain a networkx-graph representation of a street-network from OpenStreetMap with a single line of code. A relevant section for our scenario can be obtained by specifying center and distance for OSM-nodes to be included:
CENTER = (53.55668, 9.92815) DISTANCE = 300G = ox.graph_from_point(CENTER, distance=DISTANCE, network_type='drive')
OSMnx lets us pick the nearest OSM-node for each of the 4 locations of the tour, and also offers convenient means to plot the network. Blue dots represent OSM-nodes, connected by edges. The 4 relevant locations are shown in red:
To prepare all information needed by the simulation model, now all shortest paths between the 4 relevant nodes in the network are computed with networkx, and detailed information on all piece-wise linear segments for each route is included. The results are pickled and saved to disk to avoid fetching and recalculation for each run of the model (and of course its kind to keep the load for the OSM-servers as low as possible).
The above-described approach could be improved, e.g. by automatically determining the area to be loaded from the given relevant locations. Instead of just picking the closest OSM-node for each relevant location, it would be more precise to first go for the closest edge in the network. And as the network size grows, it might be a better idea to directly query the shortest path between relevant nodes from the OSM-server, instead of fetching the network as a whole (the way Anylogic seems to do it).
Casymda provides block-based modelling of discrete-event-simulation models on top of SimPy.Our model can be characterized by a simple process:
A truck-entity is created at a parameterized Source and then processed at a custom DriveTour-block, which contains the logic for elapsing time according to the length of a route and the movement speed of the truck. It also provides the option to calculate intermediate entity positions for animation (at an interval depending on the real-time factor at which the simulation is running). The simulation model might as well be run without scheduling any animation-related behavior to minimize the execution time. The nodes to be visited and their order are specified via the text-annotation stops=["ZFB", "MMC", "CAV"].
The animation is implemented by exposing information and resources via flask (similar to the tile-map-based animation described in this post).
To visualize the location of nodes and entities on a map, Leaflet only requires a few lines. For setting the rotation angle, there is a Rotated.Marker-plugin serving our needs.
marker = L.marker(element.coords, { icon: new L.Icon({iconUrl: element.icon_path}) }).addTo(map);marker.bindPopup(element.text);marker.setRotationAngle(element.direction);
To run the simulation via http://localhost:5000 from the cloned repository:
docker-compose up geo-web-animation
The screencast below shows a complete tour of a truck visiting all nodes in the defined order (Patisserie — Lost-and-found — Monkey’s — Carlsen Publishing — Patisserie). One-way streets are correctly taken into account, e.g. when moving from Monkeys Music Club (3., right-most node) to Carlsen Verlag (4., left-most node) along the Völckersstraße.
|
[
{
"code": null,
"e": 1016,
"s": 172,
"text": "Anylogic is probably one of the most popular simulation packages for logistics applications which is out there. A really nice and quite unique feature is the possibility to include GIS-maps into simulation models. It allows to place simulated elements on a map and move them along existing routes, based on real spatial information. This is cool because it can be used to simulate entire supply chains, including means to provide a great, tangible visualization for complex problems. That project, for example, uses Anylogic to evaluate different designs and delivery schemes for a more sustainable urban logistics network in the city center of Grenoble in France. The data-driven simulation model allows calculating KPIs for various transshipment node locations and different types of transport equipment in a multi-tier supply-chain network."
},
{
"code": null,
"e": 1232,
"s": 1016,
"text": "Following the success of the feature, the guys from Anylogic even built anyLogistix, combining pre-built & customizable simulation models with a commercial solver for integrated supply chain planning & optimization."
},
{
"code": null,
"e": 1369,
"s": 1232,
"text": "Obviously, those commercial features come at a price, so let’s see whether this kind of model can also be realized with different means."
},
{
"code": null,
"e": 1395,
"s": 1369,
"text": "Get the repo from github."
},
{
"code": null,
"e": 1465,
"s": 1395,
"text": "The simulation model of this post will be based on a mini-case-study."
},
{
"code": null,
"e": 1690,
"s": 1465,
"text": "Facing the fact that humanity gets more and more used to home-delivery of even everyday necessities, the small (but awesome) French bakery Die Patisserie in Hamburg-Altona wants to deliver sweet pastries to nearby customers."
},
{
"code": null,
"e": 1834,
"s": 1690,
"text": "3 major purchasers were identified: the lost-and-found office Zentrales Fundbüro, Monkeys Music Club, and the publishing house Carlsen Verlag."
},
{
"code": null,
"e": 1896,
"s": 1834,
"text": "Coordinates of the different locations (latitude, longitude):"
},
{
"code": null,
"e": 2042,
"s": 1896,
"text": "Die Patisserie (53.55668, 9.92815)Zentrales Fundbüro (53.55817, 9.92829)Monkeys Music Club (53.55706, 9.93161)Carlsen Verlag (53.55703, 9.92684)"
},
{
"code": null,
"e": 2077,
"s": 2042,
"text": "Die Patisserie (53.55668, 9.92815)"
},
{
"code": null,
"e": 2117,
"s": 2077,
"text": "Zentrales Fundbüro (53.55817, 9.92829)"
},
{
"code": null,
"e": 2156,
"s": 2117,
"text": "Monkeys Music Club (53.55706, 9.93161)"
},
{
"code": null,
"e": 2191,
"s": 2156,
"text": "Carlsen Verlag (53.55703, 9.92684)"
},
{
"code": null,
"e": 2327,
"s": 2191,
"text": "For the sake of simplicity, the order in which nodes are visited is assumed to be fixed. The tour starts & ends at the patisserie (1.):"
},
{
"code": null,
"e": 2393,
"s": 2327,
"text": "The simulation model for the simplistic scenario is created with:"
},
{
"code": null,
"e": 2479,
"s": 2393,
"text": "OSMnx/networkx for retrieving geo-information and calculating shortest-paths (Python)"
},
{
"code": null,
"e": 2526,
"s": 2479,
"text": "SimPy/Casymda for simulating the tour (Python)"
},
{
"code": null,
"e": 2578,
"s": 2526,
"text": "Leaflet.js for browser-based animation (JavaScript)"
},
{
"code": null,
"e": 2854,
"s": 2578,
"text": "The awesome OSMnx package provides the possibility to obtain a networkx-graph representation of a street-network from OpenStreetMap with a single line of code. A relevant section for our scenario can be obtained by specifying center and distance for OSM-nodes to be included:"
},
{
"code": null,
"e": 2971,
"s": 2854,
"text": "CENTER = (53.55668, 9.92815) DISTANCE = 300G = ox.graph_from_point(CENTER, distance=DISTANCE, network_type='drive')"
},
{
"code": null,
"e": 3200,
"s": 2971,
"text": "OSMnx lets us pick the nearest OSM-node for each of the 4 locations of the tour, and also offers convenient means to plot the network. Blue dots represent OSM-nodes, connected by edges. The 4 relevant locations are shown in red:"
},
{
"code": null,
"e": 3627,
"s": 3200,
"text": "To prepare all information needed by the simulation model, now all shortest paths between the 4 relevant nodes in the network are computed with networkx, and detailed information on all piece-wise linear segments for each route is included. The results are pickled and saved to disk to avoid fetching and recalculation for each run of the model (and of course its kind to keep the load for the OSM-servers as low as possible)."
},
{
"code": null,
"e": 4128,
"s": 3627,
"text": "The above-described approach could be improved, e.g. by automatically determining the area to be loaded from the given relevant locations. Instead of just picking the closest OSM-node for each relevant location, it would be more precise to first go for the closest edge in the network. And as the network size grows, it might be a better idea to directly query the shortest path between relevant nodes from the OSM-server, instead of fetching the network as a whole (the way Anylogic seems to do it)."
},
{
"code": null,
"e": 4271,
"s": 4128,
"text": "Casymda provides block-based modelling of discrete-event-simulation models on top of SimPy.Our model can be characterized by a simple process:"
},
{
"code": null,
"e": 4889,
"s": 4271,
"text": "A truck-entity is created at a parameterized Source and then processed at a custom DriveTour-block, which contains the logic for elapsing time according to the length of a route and the movement speed of the truck. It also provides the option to calculate intermediate entity positions for animation (at an interval depending on the real-time factor at which the simulation is running). The simulation model might as well be run without scheduling any animation-related behavior to minimize the execution time. The nodes to be visited and their order are specified via the text-annotation stops=[\"ZFB\", \"MMC\", \"CAV\"]."
},
{
"code": null,
"e": 5032,
"s": 4889,
"text": "The animation is implemented by exposing information and resources via flask (similar to the tile-map-based animation described in this post)."
},
{
"code": null,
"e": 5209,
"s": 5032,
"text": "To visualize the location of nodes and entities on a map, Leaflet only requires a few lines. For setting the rotation angle, there is a Rotated.Marker-plugin serving our needs."
},
{
"code": null,
"e": 5381,
"s": 5209,
"text": "marker = L.marker(element.coords, { icon: new L.Icon({iconUrl: element.icon_path}) }).addTo(map);marker.bindPopup(element.text);marker.setRotationAngle(element.direction);"
},
{
"code": null,
"e": 5457,
"s": 5381,
"text": "To run the simulation via http://localhost:5000 from the cloned repository:"
},
{
"code": null,
"e": 5493,
"s": 5457,
"text": "docker-compose up geo-web-animation"
}
] |
CSS | ::-webkit-scrollbar - GeeksforGeeks
|
23 Dec, 2019
::-webkit-scrollbar is a pseudo-element in CSS employed to modify the look of a browser’s scrollbar.Before we start with how it works and how can it be implemented, we need to know some facts about the element.
Browsers like Chrome, Safari and Opera support this standard
Browsers like firefox don’t support this
For the webkit browsers, you can use the following pseudo elements to customize the browser’s scrollbar:
::-webkit-scrollbar : the scrollbar
::-webkit-scrollbar-button : the arrows that point up or down on the scrollbar
::-webkit-scrollbar-thumb : the scrolling handle that can be dragged
::-webkit-scrollbar-track : progress bar
::-webkit-scrollbar-track-piece : the area not covered by the handle
::-webkit-scrollbar-corner : the bottom corner of the scrollbar where vertical and horizontal scrollbars meet
::-webkit-resizer : the draggable resizing handle that appears at the bottom corner of some elements
The following example takes each and every element and explains its proper usage (I have also tried to use different colors for each element so that the purpose of each tag can be highlighted separately):
<!Doctype><html> <head> <title>scroll customization</title> <style type="text/css"> body { font-size: 20pt; } /* tells the browser how the bar will look */ ::-webkit-scrollbar { width: 15px; border: 2px solid blue; } /*tells the browser how the arrows will appear*/ ::-webkit-scrollbar-button:single-button { background-color: red; height: 16px; width: 16px; } /* tells the browser how the scrollable handle would look like */ ::-webkit-scrollbar-thumb { background: black; } /* tells the browser how will the path of the handle will look like */ ::-webkit-scrollbar-track { background: yellow; } /* works the same as ::-webkit-scrollbar-track but tells the browser how the path where the handle is not present currently*/ /* ::-webkit-scrollbar-track-piece{ background: green; } */ /* tells the browser how will the point where vertical and horizontal meet will look like*/ /* ::-webkit-scrollbar-corner{ background: orange ; display: solid; } */ /* resizer*/ ::-webkit-resizer { background: pink; } </style></head> <body> <center> <h1 style="color:green">GeeksforGeeks</h1> <h2>CSS |::-webkit-scrollbar</h2> <p>HTML stands for Hyper Text Markup Language. It is used to design web pages using markup language. HTML is the combination of Hypertext and Markup language. Hypertext defines the link between the web pages. Markup language is used to define the text document within tag which defines the structure of web pages.</p> <br> <p>HTML is a markup language which is used by the browser to manipulate text, images and other content to display it in required format.</p> <br> <p>Cascading Style Sheets, fondly referred to as CSS, is a simply designed language intended to simplify the process of making web pages presentable. CSS allows you to apply styles to web pages. More importantly, CSS enables you to do this independent of the HTML that makes up each web page.</p> </center></body> </html>
Output:
Supported Browsers: The browsers supported by CSS | ::-webkit-scrollbar are listed below:
Google Chrome
Apple Safari
Opera
CSS-Misc
Picked
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Types of CSS (Cascading Style Sheet)
How to position a div at the bottom of its container using CSS?
Create a Responsive Navbar using ReactJS
Design a web page using HTML and CSS
How to Upload Image into Database and Display it using PHP ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 25076,
"s": 25048,
"text": "\n23 Dec, 2019"
},
{
"code": null,
"e": 25287,
"s": 25076,
"text": "::-webkit-scrollbar is a pseudo-element in CSS employed to modify the look of a browser’s scrollbar.Before we start with how it works and how can it be implemented, we need to know some facts about the element."
},
{
"code": null,
"e": 25348,
"s": 25287,
"text": "Browsers like Chrome, Safari and Opera support this standard"
},
{
"code": null,
"e": 25389,
"s": 25348,
"text": "Browsers like firefox don’t support this"
},
{
"code": null,
"e": 25494,
"s": 25389,
"text": "For the webkit browsers, you can use the following pseudo elements to customize the browser’s scrollbar:"
},
{
"code": null,
"e": 25530,
"s": 25494,
"text": "::-webkit-scrollbar : the scrollbar"
},
{
"code": null,
"e": 25609,
"s": 25530,
"text": "::-webkit-scrollbar-button : the arrows that point up or down on the scrollbar"
},
{
"code": null,
"e": 25678,
"s": 25609,
"text": "::-webkit-scrollbar-thumb : the scrolling handle that can be dragged"
},
{
"code": null,
"e": 25719,
"s": 25678,
"text": "::-webkit-scrollbar-track : progress bar"
},
{
"code": null,
"e": 25788,
"s": 25719,
"text": "::-webkit-scrollbar-track-piece : the area not covered by the handle"
},
{
"code": null,
"e": 25898,
"s": 25788,
"text": "::-webkit-scrollbar-corner : the bottom corner of the scrollbar where vertical and horizontal scrollbars meet"
},
{
"code": null,
"e": 25999,
"s": 25898,
"text": "::-webkit-resizer : the draggable resizing handle that appears at the bottom corner of some elements"
},
{
"code": null,
"e": 26204,
"s": 25999,
"text": "The following example takes each and every element and explains its proper usage (I have also tried to use different colors for each element so that the purpose of each tag can be highlighted separately):"
},
{
"code": "<!Doctype><html> <head> <title>scroll customization</title> <style type=\"text/css\"> body { font-size: 20pt; } /* tells the browser how the bar will look */ ::-webkit-scrollbar { width: 15px; border: 2px solid blue; } /*tells the browser how the arrows will appear*/ ::-webkit-scrollbar-button:single-button { background-color: red; height: 16px; width: 16px; } /* tells the browser how the scrollable handle would look like */ ::-webkit-scrollbar-thumb { background: black; } /* tells the browser how will the path of the handle will look like */ ::-webkit-scrollbar-track { background: yellow; } /* works the same as ::-webkit-scrollbar-track but tells the browser how the path where the handle is not present currently*/ /* ::-webkit-scrollbar-track-piece{ background: green; } */ /* tells the browser how will the point where vertical and horizontal meet will look like*/ /* ::-webkit-scrollbar-corner{ background: orange ; display: solid; } */ /* resizer*/ ::-webkit-resizer { background: pink; } </style></head> <body> <center> <h1 style=\"color:green\">GeeksforGeeks</h1> <h2>CSS |::-webkit-scrollbar</h2> <p>HTML stands for Hyper Text Markup Language. It is used to design web pages using markup language. HTML is the combination of Hypertext and Markup language. Hypertext defines the link between the web pages. Markup language is used to define the text document within tag which defines the structure of web pages.</p> <br> <p>HTML is a markup language which is used by the browser to manipulate text, images and other content to display it in required format.</p> <br> <p>Cascading Style Sheets, fondly referred to as CSS, is a simply designed language intended to simplify the process of making web pages presentable. CSS allows you to apply styles to web pages. More importantly, CSS enables you to do this independent of the HTML that makes up each web page.</p> </center></body> </html>",
"e": 28733,
"s": 26204,
"text": null
},
{
"code": null,
"e": 28741,
"s": 28733,
"text": "Output:"
},
{
"code": null,
"e": 28831,
"s": 28741,
"text": "Supported Browsers: The browsers supported by CSS | ::-webkit-scrollbar are listed below:"
},
{
"code": null,
"e": 28845,
"s": 28831,
"text": "Google Chrome"
},
{
"code": null,
"e": 28858,
"s": 28845,
"text": "Apple Safari"
},
{
"code": null,
"e": 28864,
"s": 28858,
"text": "Opera"
},
{
"code": null,
"e": 28873,
"s": 28864,
"text": "CSS-Misc"
},
{
"code": null,
"e": 28880,
"s": 28873,
"text": "Picked"
},
{
"code": null,
"e": 28884,
"s": 28880,
"text": "CSS"
},
{
"code": null,
"e": 28901,
"s": 28884,
"text": "Web Technologies"
},
{
"code": null,
"e": 28999,
"s": 28901,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29036,
"s": 28999,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 29100,
"s": 29036,
"text": "How to position a div at the bottom of its container using CSS?"
},
{
"code": null,
"e": 29141,
"s": 29100,
"text": "Create a Responsive Navbar using ReactJS"
},
{
"code": null,
"e": 29178,
"s": 29141,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 29239,
"s": 29178,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 29281,
"s": 29239,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 29314,
"s": 29281,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29357,
"s": 29314,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 29402,
"s": 29357,
"text": "Convert a string to an integer in JavaScript"
}
] |
Installing atop Tool To Monitor the System Process in Linux - GeeksforGeeks
|
12 Mar, 2021
atop is an ASCII full-screen interactive performance monitor which is kind of similar to the top command to view the load over a Linux system. The job of the most critical hardware resources (from a performance point of view) at the system level, i.e. CPU, memory, disk, and network can be seen. atop enable us to identify which processes are actually responsible for the indicated load. In brief atop can report the activities of all processes, including the completed ones.
Here we guide you regarding how to install atop and configure atop on Linux systems ( Debian/Ubuntu-based) and also make you familiar with atop’s system-level information & Process level information so that you can easily monitor and understand your system processes.
atop can be installed from the default repositories by using the following command:-
sudo apt-get install atop
Install Atop Under Debian Systems like I am using kali Linux
You can access atop the main window by typing the following command:
atop
atop
NOTE:
ALWAYS remember to exit atop by pressing ‘q’ or with kill -15 otherwise if you stop it with any other way that will not allow it to stop the accounting mechanism which will continue to generate a huge file on disk.
When the atop window is displayed, we can see two parts in the output portion. The 1st portion shows System-level information & the second part shows Process level information Let us discuss more in deep about both of them.
The system-level information consists of the following output lines:
This section shows the total CPU time consumed in system mode (‘sys’) and in user mode (‘user’), the processes in total running (‘#proc’), the total number of threads running’ (‘#trun’), ‘sleeping interruptible’ (‘#tslpi’) and ‘sleeping uninterruptible’ (‘#tslpu’), zombie processes (‘#zombie’), clone system calls (‘clones’), and the number of processes that ended during the interval (‘#exit’), which shows ‘?’ if process accounting is not used).
The total occupation of all CPUs together is shown in this line(can be more than 1 line) i.e. The percentage of CPU time spent in kernel mode by all active processes (‘sys’), the percentage of CPU time consumed in user mode (‘user’) for all active processes the, percentage of CPU time spent for interrupt handling (‘irq’)and the percentage of unused CPU time while at least one process was waiting for disk-I/O (‘wait’). For virtual machines, the steal-percentage is shown (‘steal’), for displaying the percentage of CPU time that was stolen by other virtual machines that are running on the same hardware. The average frequency (‘avgf’) and the average scaling percentage (‘avgscal’) is also displayed .The current frequency (‘curf’) and the current scaling percentage (‘curscal’) is also displayed.
CPL line row contains the load average figures showing the number of threads available to run on a CPU or the ones that are waiting for disk I/O.All these figures are averaged over 1 (‘avg1’), 5 (‘avg5’) and 15 (‘avg15’) minutes.
Also, the number of context switches (‘csw’), the number of serviced interrupts (‘intr’), and the number of available cpu’s are displayed.
The total amount of physical memory (‘tot’), the amount of memory that is currently free (‘free’), the amount of memory page cache (‘cache’) is using, the amount of memory used for filesystem metadata (‘buff’) and the memory that is used for kernel mallocs are displayed in this MEM line section row.
The total amount of swap space (‘tot’), free swap space (‘free’) on the disk is shown in this line. Including the committed virtual memory space (‘vmcom’) and the maximum limit of the committed space (‘vmlim’),( by reading default swap size plus 50% of memory size) is shown.
This line contains the number of scanned pages (‘scan’) due to the fact that free memory drops below a particular threshold and the number of times that the kernel tries to reclaim pages due to an urgent need (‘stall’).
Also, the number of memory pages the system read from swap space (‘swin’) and the number of memory pages the system wrote to swap space (‘swout’) are shown.
This line shows the unit that was busy handling requests (‘busy’), the number of read requests issued (‘read’), the number of write requests issued (‘write’), the number of KiBytes per reading (‘KiB/r’) . the average queue depth (‘avq’) and the average number of milliseconds needed by a request (‘avio’) for seek, latency, and data transfer.
There are 3 lines of NET, one is for the transport layer (TCP and UDP), one, for the IP layer, and one for per active interface.
Transport layer
IP layer
Active Interface
Transport layer:
The number of received TCP segments including those received in error (‘tcpi’), transmitted TCP segments excluding those containing only retransmitted octets (‘tcpo’), UDP datagrams received (‘udpi’), UDP datagrams transmitted (‘udpo’), active TCP opens (‘tcpao’), passive TCP opens (‘tcppo’), TCP output retransmissions (‘tcprs’), TCP input errors (‘tcpie’), TCP output resets (‘tcpie’), TCP output retransmissions (‘tcpor’), UDP no ports (‘udpnp’), and the number of UDP input errors (‘tcpie’) are displayed.
IP layer:
This line shows the number of IP datagrams received from interfaces, including those received in error (‘ipi’), IP datagrams that local higher-layer protocols offered for transmission (‘ipo’), IP datagrams received which were forwarded to other interfaces (‘ipfrw’), IP datagrams delivered to local higher-layer protocols (‘deliv’), ICMP datagrams (‘icmpi’) received, and the number of transmitted ICMP datagrams (‘icmpo’) are displayed.
For every active network interface:
The number of received packets (‘pcki’), transmitted packets (‘pcko’), the effective amount of bits received per second (‘si’), the effective amount of bits transmitted per second (‘so’), collisions (‘coll’), multicast packets (‘mlti’) received, errors while receiving a packet (‘erri’), errors while transmitting a packet (‘erro’), packets dropped (‘drpi’) received, and the number of transmitted packets dropped (‘drpo’) are shown in this line.
The Process level information consists of the following output lines:
PID(Process-id): We can see ‘?’ when a process has been started and finished during the last interval because the process-id is not part of the standard process accounting record.
YSCPU: Due to system call handling CPU time consumption of this process in system mode (kernel mode) is displayed.
USRCPU: Due to processing the own program text CPU time consumption of this process in user mode is shown.
RGROW: This shows the amount of resident memory that the process has grown during the last interval.
VGROW: This shows the amount of virtual memory that the process has grown during the last interval.
EXC: The exit code of a terminated process is shown.
THR: The total number of threads within this process is shown.
S: The current state of the main thread of the process: ‘R’ for currently processing or in the run queue, ‘S’ for wait for an event to occur, ‘D’ for sleeping non-interruptible, ‘Z’ for zombie, ‘T’ for stop, ‘W’ for swapping and ‘E’ (exit) for processes which have finished during the last interval is shown.
CPUNR: This shows the identification of the CPU on which the main thread of the process is running on or has recently been running on.
CPU: The occupation percentage of any process related to the available capacity for the resource on the system level is shown.
CMD: The name of the process. That is running or has been finished during the last interval.
Linux-Tools
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Thread functions in C/C++
mv command in Linux with examples
nohup Command in Linux with Examples
scp command in Linux with Examples
Docker - COPY Instruction
chown command in Linux with Examples
nslookup command in Linux with Examples
SED command in Linux | Set 2
Named Pipe or FIFO with example C program
uniq Command in LINUX with examples
|
[
{
"code": null,
"e": 24015,
"s": 23987,
"text": "\n12 Mar, 2021"
},
{
"code": null,
"e": 24491,
"s": 24015,
"text": "atop is an ASCII full-screen interactive performance monitor which is kind of similar to the top command to view the load over a Linux system. The job of the most critical hardware resources (from a performance point of view) at the system level, i.e. CPU, memory, disk, and network can be seen. atop enable us to identify which processes are actually responsible for the indicated load. In brief atop can report the activities of all processes, including the completed ones."
},
{
"code": null,
"e": 24759,
"s": 24491,
"text": "Here we guide you regarding how to install atop and configure atop on Linux systems ( Debian/Ubuntu-based) and also make you familiar with atop’s system-level information & Process level information so that you can easily monitor and understand your system processes."
},
{
"code": null,
"e": 24844,
"s": 24759,
"text": "atop can be installed from the default repositories by using the following command:-"
},
{
"code": null,
"e": 24870,
"s": 24844,
"text": "sudo apt-get install atop"
},
{
"code": null,
"e": 24931,
"s": 24870,
"text": "Install Atop Under Debian Systems like I am using kali Linux"
},
{
"code": null,
"e": 25000,
"s": 24931,
"text": "You can access atop the main window by typing the following command:"
},
{
"code": null,
"e": 25005,
"s": 25000,
"text": "atop"
},
{
"code": null,
"e": 25010,
"s": 25005,
"text": "atop"
},
{
"code": null,
"e": 25018,
"s": 25010,
"text": " NOTE: "
},
{
"code": null,
"e": 25233,
"s": 25018,
"text": "ALWAYS remember to exit atop by pressing ‘q’ or with kill -15 otherwise if you stop it with any other way that will not allow it to stop the accounting mechanism which will continue to generate a huge file on disk."
},
{
"code": null,
"e": 25458,
"s": 25233,
"text": "When the atop window is displayed, we can see two parts in the output portion. The 1st portion shows System-level information & the second part shows Process level information Let us discuss more in deep about both of them. "
},
{
"code": null,
"e": 25528,
"s": 25458,
"text": "The system-level information consists of the following output lines: "
},
{
"code": null,
"e": 25977,
"s": 25528,
"text": "This section shows the total CPU time consumed in system mode (‘sys’) and in user mode (‘user’), the processes in total running (‘#proc’), the total number of threads running’ (‘#trun’), ‘sleeping interruptible’ (‘#tslpi’) and ‘sleeping uninterruptible’ (‘#tslpu’), zombie processes (‘#zombie’), clone system calls (‘clones’), and the number of processes that ended during the interval (‘#exit’), which shows ‘?’ if process accounting is not used)."
},
{
"code": null,
"e": 26779,
"s": 25977,
"text": "The total occupation of all CPUs together is shown in this line(can be more than 1 line) i.e. The percentage of CPU time spent in kernel mode by all active processes (‘sys’), the percentage of CPU time consumed in user mode (‘user’) for all active processes the, percentage of CPU time spent for interrupt handling (‘irq’)and the percentage of unused CPU time while at least one process was waiting for disk-I/O (‘wait’). For virtual machines, the steal-percentage is shown (‘steal’), for displaying the percentage of CPU time that was stolen by other virtual machines that are running on the same hardware. The average frequency (‘avgf’) and the average scaling percentage (‘avgscal’) is also displayed .The current frequency (‘curf’) and the current scaling percentage (‘curscal’) is also displayed."
},
{
"code": null,
"e": 27009,
"s": 26779,
"text": "CPL line row contains the load average figures showing the number of threads available to run on a CPU or the ones that are waiting for disk I/O.All these figures are averaged over 1 (‘avg1’), 5 (‘avg5’) and 15 (‘avg15’) minutes."
},
{
"code": null,
"e": 27149,
"s": 27009,
"text": "Also, the number of context switches (‘csw’), the number of serviced interrupts (‘intr’), and the number of available cpu’s are displayed. "
},
{
"code": null,
"e": 27451,
"s": 27149,
"text": "The total amount of physical memory (‘tot’), the amount of memory that is currently free (‘free’), the amount of memory page cache (‘cache’) is using, the amount of memory used for filesystem metadata (‘buff’) and the memory that is used for kernel mallocs are displayed in this MEM line section row. "
},
{
"code": null,
"e": 27727,
"s": 27451,
"text": "The total amount of swap space (‘tot’), free swap space (‘free’) on the disk is shown in this line. Including the committed virtual memory space (‘vmcom’) and the maximum limit of the committed space (‘vmlim’),( by reading default swap size plus 50% of memory size) is shown."
},
{
"code": null,
"e": 27947,
"s": 27727,
"text": "This line contains the number of scanned pages (‘scan’) due to the fact that free memory drops below a particular threshold and the number of times that the kernel tries to reclaim pages due to an urgent need (‘stall’)."
},
{
"code": null,
"e": 28105,
"s": 27947,
"text": "Also, the number of memory pages the system read from swap space (‘swin’) and the number of memory pages the system wrote to swap space (‘swout’) are shown. "
},
{
"code": null,
"e": 28449,
"s": 28105,
"text": "This line shows the unit that was busy handling requests (‘busy’), the number of read requests issued (‘read’), the number of write requests issued (‘write’), the number of KiBytes per reading (‘KiB/r’) . the average queue depth (‘avq’) and the average number of milliseconds needed by a request (‘avio’) for seek, latency, and data transfer."
},
{
"code": null,
"e": 28578,
"s": 28449,
"text": "There are 3 lines of NET, one is for the transport layer (TCP and UDP), one, for the IP layer, and one for per active interface."
},
{
"code": null,
"e": 28594,
"s": 28578,
"text": "Transport layer"
},
{
"code": null,
"e": 28603,
"s": 28594,
"text": "IP layer"
},
{
"code": null,
"e": 28620,
"s": 28603,
"text": "Active Interface"
},
{
"code": null,
"e": 28637,
"s": 28620,
"text": "Transport layer:"
},
{
"code": null,
"e": 29150,
"s": 28637,
"text": " The number of received TCP segments including those received in error (‘tcpi’), transmitted TCP segments excluding those containing only retransmitted octets (‘tcpo’), UDP datagrams received (‘udpi’), UDP datagrams transmitted (‘udpo’), active TCP opens (‘tcpao’), passive TCP opens (‘tcppo’), TCP output retransmissions (‘tcprs’), TCP input errors (‘tcpie’), TCP output resets (‘tcpie’), TCP output retransmissions (‘tcpor’), UDP no ports (‘udpnp’), and the number of UDP input errors (‘tcpie’) are displayed."
},
{
"code": null,
"e": 29160,
"s": 29150,
"text": "IP layer:"
},
{
"code": null,
"e": 29598,
"s": 29160,
"text": "This line shows the number of IP datagrams received from interfaces, including those received in error (‘ipi’), IP datagrams that local higher-layer protocols offered for transmission (‘ipo’), IP datagrams received which were forwarded to other interfaces (‘ipfrw’), IP datagrams delivered to local higher-layer protocols (‘deliv’), ICMP datagrams (‘icmpi’) received, and the number of transmitted ICMP datagrams (‘icmpo’) are displayed."
},
{
"code": null,
"e": 29634,
"s": 29598,
"text": "For every active network interface:"
},
{
"code": null,
"e": 30081,
"s": 29634,
"text": "The number of received packets (‘pcki’), transmitted packets (‘pcko’), the effective amount of bits received per second (‘si’), the effective amount of bits transmitted per second (‘so’), collisions (‘coll’), multicast packets (‘mlti’) received, errors while receiving a packet (‘erri’), errors while transmitting a packet (‘erro’), packets dropped (‘drpi’) received, and the number of transmitted packets dropped (‘drpo’) are shown in this line."
},
{
"code": null,
"e": 30152,
"s": 30081,
"text": "The Process level information consists of the following output lines: "
},
{
"code": null,
"e": 30333,
"s": 30152,
"text": "PID(Process-id): We can see ‘?’ when a process has been started and finished during the last interval because the process-id is not part of the standard process accounting record. "
},
{
"code": null,
"e": 30448,
"s": 30333,
"text": "YSCPU: Due to system call handling CPU time consumption of this process in system mode (kernel mode) is displayed."
},
{
"code": null,
"e": 30555,
"s": 30448,
"text": "USRCPU: Due to processing the own program text CPU time consumption of this process in user mode is shown."
},
{
"code": null,
"e": 30656,
"s": 30555,
"text": "RGROW: This shows the amount of resident memory that the process has grown during the last interval."
},
{
"code": null,
"e": 30756,
"s": 30656,
"text": "VGROW: This shows the amount of virtual memory that the process has grown during the last interval."
},
{
"code": null,
"e": 30809,
"s": 30756,
"text": "EXC: The exit code of a terminated process is shown."
},
{
"code": null,
"e": 30872,
"s": 30809,
"text": "THR: The total number of threads within this process is shown."
},
{
"code": null,
"e": 31181,
"s": 30872,
"text": "S: The current state of the main thread of the process: ‘R’ for currently processing or in the run queue, ‘S’ for wait for an event to occur, ‘D’ for sleeping non-interruptible, ‘Z’ for zombie, ‘T’ for stop, ‘W’ for swapping and ‘E’ (exit) for processes which have finished during the last interval is shown."
},
{
"code": null,
"e": 31317,
"s": 31181,
"text": "CPUNR: This shows the identification of the CPU on which the main thread of the process is running on or has recently been running on. "
},
{
"code": null,
"e": 31444,
"s": 31317,
"text": "CPU: The occupation percentage of any process related to the available capacity for the resource on the system level is shown."
},
{
"code": null,
"e": 31537,
"s": 31444,
"text": "CMD: The name of the process. That is running or has been finished during the last interval."
},
{
"code": null,
"e": 31549,
"s": 31537,
"text": "Linux-Tools"
},
{
"code": null,
"e": 31556,
"s": 31549,
"text": "Picked"
},
{
"code": null,
"e": 31567,
"s": 31556,
"text": "Linux-Unix"
},
{
"code": null,
"e": 31665,
"s": 31567,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31674,
"s": 31665,
"text": "Comments"
},
{
"code": null,
"e": 31687,
"s": 31674,
"text": "Old Comments"
},
{
"code": null,
"e": 31713,
"s": 31687,
"text": "Thread functions in C/C++"
},
{
"code": null,
"e": 31747,
"s": 31713,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 31784,
"s": 31747,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 31819,
"s": 31784,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 31845,
"s": 31819,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 31882,
"s": 31845,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 31922,
"s": 31882,
"text": "nslookup command in Linux with Examples"
},
{
"code": null,
"e": 31951,
"s": 31922,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 31993,
"s": 31951,
"text": "Named Pipe or FIFO with example C program"
}
] |
C/C++ Program to Count set bits in an integer - GeeksforGeeks
|
02 Jan, 2019
Write an efficient program to count number of 1s in binary representation of an integer.
Examples :
Input : n = 6
Output : 2
Binary representation of 6 is 110 and has 2 set bits
Input : n = 13
Output : 3
Binary representation of 11 is 1101 and has 3 set bits
1. Simple Method Loop through all bits in an integer, check if a bit is set and if it is then increment the set bit count. See below program.
C
#include <stdio.h> /* Function to get no of set bits in binary representation of positive integer n */unsigned int countSetBits(unsigned int n){ unsigned int count = 0; while (n) { count += n & 1; n >>= 1; } return count;} /* Program to test function countSetBits */int main(){ int i = 9; printf("%d", countSetBits(i)); return 0;}
2
Recursive Approach :
C++
// Cpp implementation of recursive// approach to find the number// of set bits in binary representation// of positive integer n#include <bits/stdc++.h>using namespace std; // recursive function to count set bitsint countSetBits(int n){ // base case if (n == 0) return 0; else // if last bit set add 1 else add 0 return (n & 1) + countSetBits(n >> 1);} // driver codeint main(){ // get value from user int n = 9; // function calling cout << countSetBits(n); return 0;} // This code is contributed by Raj.
2
Please refer complete article on Count set bits in an integer for more details!
C Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C Program to read contents of Whole File
Header files in C/C++ and its uses
How to return multiple values from a function in C or C++?
How to Append a Character to a String in C
Program to print ASCII Value of a character
C program to sort an array in ascending order
Program to find Prime Numbers Between given Interval
time() function in C
Flex (Fast Lexical Analyzer Generator )
C Program to Swap two Numbers
|
[
{
"code": null,
"e": 25031,
"s": 25003,
"text": "\n02 Jan, 2019"
},
{
"code": null,
"e": 25120,
"s": 25031,
"text": "Write an efficient program to count number of 1s in binary representation of an integer."
},
{
"code": null,
"e": 25131,
"s": 25120,
"text": "Examples :"
},
{
"code": null,
"e": 25292,
"s": 25131,
"text": "Input : n = 6\nOutput : 2\nBinary representation of 6 is 110 and has 2 set bits\n\nInput : n = 13\nOutput : 3\nBinary representation of 11 is 1101 and has 3 set bits\n"
},
{
"code": null,
"e": 25434,
"s": 25292,
"text": "1. Simple Method Loop through all bits in an integer, check if a bit is set and if it is then increment the set bit count. See below program."
},
{
"code": null,
"e": 25436,
"s": 25434,
"text": "C"
},
{
"code": "#include <stdio.h> /* Function to get no of set bits in binary representation of positive integer n */unsigned int countSetBits(unsigned int n){ unsigned int count = 0; while (n) { count += n & 1; n >>= 1; } return count;} /* Program to test function countSetBits */int main(){ int i = 9; printf(\"%d\", countSetBits(i)); return 0;}",
"e": 25806,
"s": 25436,
"text": null
},
{
"code": null,
"e": 25809,
"s": 25806,
"text": "2\n"
},
{
"code": null,
"e": 25830,
"s": 25809,
"text": "Recursive Approach :"
},
{
"code": null,
"e": 25834,
"s": 25830,
"text": "C++"
},
{
"code": "// Cpp implementation of recursive// approach to find the number// of set bits in binary representation// of positive integer n#include <bits/stdc++.h>using namespace std; // recursive function to count set bitsint countSetBits(int n){ // base case if (n == 0) return 0; else // if last bit set add 1 else add 0 return (n & 1) + countSetBits(n >> 1);} // driver codeint main(){ // get value from user int n = 9; // function calling cout << countSetBits(n); return 0;} // This code is contributed by Raj.",
"e": 26394,
"s": 25834,
"text": null
},
{
"code": null,
"e": 26397,
"s": 26394,
"text": "2\n"
},
{
"code": null,
"e": 26477,
"s": 26397,
"text": "Please refer complete article on Count set bits in an integer for more details!"
},
{
"code": null,
"e": 26488,
"s": 26477,
"text": "C Programs"
},
{
"code": null,
"e": 26586,
"s": 26488,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26595,
"s": 26586,
"text": "Comments"
},
{
"code": null,
"e": 26608,
"s": 26595,
"text": "Old Comments"
},
{
"code": null,
"e": 26649,
"s": 26608,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 26684,
"s": 26649,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 26743,
"s": 26684,
"text": "How to return multiple values from a function in C or C++?"
},
{
"code": null,
"e": 26786,
"s": 26743,
"text": "How to Append a Character to a String in C"
},
{
"code": null,
"e": 26830,
"s": 26786,
"text": "Program to print ASCII Value of a character"
},
{
"code": null,
"e": 26876,
"s": 26830,
"text": "C program to sort an array in ascending order"
},
{
"code": null,
"e": 26929,
"s": 26876,
"text": "Program to find Prime Numbers Between given Interval"
},
{
"code": null,
"e": 26950,
"s": 26929,
"text": "time() function in C"
},
{
"code": null,
"e": 26990,
"s": 26950,
"text": "Flex (Fast Lexical Analyzer Generator )"
}
] |
java.util.regex.Pattern.matches() Method
|
The java.util.regex.Pattern.matches(String regex, CharSequence input) method compiles the given regular expression and attempts to match the given input against it.
Following is the declaration for java.util.regex.Pattern.matches(String regex, CharSequence input) method.
public static boolean matches(String regex, CharSequence input)
regex − The expression to be compiled.
regex − The expression to be compiled.
input − The character sequence to be matched.
input − The character sequence to be matched.
PatternSyntaxException − If the expression's syntax is invalid.
PatternSyntaxException − If the expression's syntax is invalid.
The following example shows the usage of java.util.regex.Pattern.matches(String regex, CharSequence input) method.
package com.tutorialspoint;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PatternDemo {
private static final String REGEX = "foo*";
private static final String INPUT = "fooooooooooooooooo";
public static void main( String args[] ) {
System.out.println("Current REGEX is: "+REGEX);
System.out.println("Current INPUT is: "+INPUT);
System.out.println("matches(): "+Pattern.matches(REGEX,INPUT));
}
}
Let us compile and run the above program, this will produce the following result −
Current REGEX is: foo*
Current INPUT is: fooooooooooooooooo
matches(): true
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2289,
"s": 2124,
"text": "The java.util.regex.Pattern.matches(String regex, CharSequence input) method compiles the given regular expression and attempts to match the given input against it."
},
{
"code": null,
"e": 2396,
"s": 2289,
"text": "Following is the declaration for java.util.regex.Pattern.matches(String regex, CharSequence input) method."
},
{
"code": null,
"e": 2461,
"s": 2396,
"text": "public static boolean matches(String regex, CharSequence input)\n"
},
{
"code": null,
"e": 2500,
"s": 2461,
"text": "regex − The expression to be compiled."
},
{
"code": null,
"e": 2539,
"s": 2500,
"text": "regex − The expression to be compiled."
},
{
"code": null,
"e": 2585,
"s": 2539,
"text": "input − The character sequence to be matched."
},
{
"code": null,
"e": 2631,
"s": 2585,
"text": "input − The character sequence to be matched."
},
{
"code": null,
"e": 2695,
"s": 2631,
"text": "PatternSyntaxException − If the expression's syntax is invalid."
},
{
"code": null,
"e": 2759,
"s": 2695,
"text": "PatternSyntaxException − If the expression's syntax is invalid."
},
{
"code": null,
"e": 2874,
"s": 2759,
"text": "The following example shows the usage of java.util.regex.Pattern.matches(String regex, CharSequence input) method."
},
{
"code": null,
"e": 3335,
"s": 2874,
"text": "package com.tutorialspoint;\n\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class PatternDemo {\n private static final String REGEX = \"foo*\";\n private static final String INPUT = \"fooooooooooooooooo\";\n\n public static void main( String args[] ) {\n System.out.println(\"Current REGEX is: \"+REGEX);\n System.out.println(\"Current INPUT is: \"+INPUT);\n System.out.println(\"matches(): \"+Pattern.matches(REGEX,INPUT));\n }\n}"
},
{
"code": null,
"e": 3418,
"s": 3335,
"text": "Let us compile and run the above program, this will produce the following result −"
},
{
"code": null,
"e": 3495,
"s": 3418,
"text": "Current REGEX is: foo*\nCurrent INPUT is: fooooooooooooooooo\nmatches(): true\n"
},
{
"code": null,
"e": 3502,
"s": 3495,
"text": " Print"
},
{
"code": null,
"e": 3513,
"s": 3502,
"text": " Add Notes"
}
] |
HTML - <dt> Tag
|
The HTML <dt> tag is used to define the start of a term in a definition list.
A definition list is similar to other lists but in a definition list, each list item contains two entries; a term and a description.
<!DOCTYPE html>
<html>
<head>
<title>HTML dt Tag</title>
</head>
<body>
<dl>
<dt>Definition List</dt>
<dd>A list of terms and their definitions/descriptions.</dd>
<dt>JAVA</dt>
<dd>Tutorial on JAVA Programming Language.</dd>
<dt>Android</dt>
<dd>Tutorial on Android Operating System.</dd>
</dl>
</body>
</html>
This will produce the following result −
This tag supports all the global attributes described in HTML Attribute Reference
This tag supports all the event attributes described in HTML Events Reference
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": 2452,
"s": 2374,
"text": "The HTML <dt> tag is used to define the start of a term in a definition list."
},
{
"code": null,
"e": 2585,
"s": 2452,
"text": "A definition list is similar to other lists but in a definition list, each list item contains two entries; a term and a description."
},
{
"code": null,
"e": 2983,
"s": 2585,
"text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>HTML dt Tag</title>\n </head>\n\n <body>\n <dl>\n <dt>Definition List</dt>\n <dd>A list of terms and their definitions/descriptions.</dd>\n <dt>JAVA</dt>\n <dd>Tutorial on JAVA Programming Language.</dd>\n <dt>Android</dt>\n <dd>Tutorial on Android Operating System.</dd>\n </dl>\n </body>\n\n</html>"
},
{
"code": null,
"e": 3024,
"s": 2983,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 3106,
"s": 3024,
"text": "This tag supports all the global attributes described in HTML Attribute Reference"
},
{
"code": null,
"e": 3184,
"s": 3106,
"text": "This tag supports all the event attributes described in HTML Events Reference"
},
{
"code": null,
"e": 3217,
"s": 3184,
"text": "\n 19 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3231,
"s": 3217,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3266,
"s": 3231,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3280,
"s": 3266,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3315,
"s": 3280,
"text": "\n 18 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3332,
"s": 3315,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3367,
"s": 3332,
"text": "\n 57 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3398,
"s": 3367,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 3431,
"s": 3398,
"text": "\n 54 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3462,
"s": 3431,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 3497,
"s": 3462,
"text": "\n 45 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3528,
"s": 3497,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 3535,
"s": 3528,
"text": " Print"
},
{
"code": null,
"e": 3546,
"s": 3535,
"text": " Add Notes"
}
] |
Are Slots and Entities the same?. Building Chatbots with Rasa — part II | by Aniruddha Karajgi | Towards Data Science
|
I’m been working with Rasa for the past few months and was initially pretty confused with the difference between slots and entities.
In this post, we’ll discuss how slots and entities are alike, and more importantly, how they are different.
Table of Contents- Defining Entities and Slots- Are slots and entities interchangeable?- When to use one over the other- Setting Slots- Extracting Entities
Quick Note
This is the next post in my series on Rasa. You can check out the previous post below.
towardsdatascience.com
There, we covered some of the building blocks of Rasa and chatbots in general and if you’re new to Rasa, going through that article first would help.
A quick refresher: this is how you could define these terms.
Slots are the bot's memory. Anywhere you need persistence in saving values, you use slots.
Rasa gives you a lot of flexibility when it comes to defining and using slots. You can give them a type — text, boolean, and even custom types — and you can also choose whether a slot should or shouldn’t affect how the conversation goes.
Entities are key pieces of information that the bot extracts from user messages, like a user’s contact information.
The extraction itself is done by the NLU part of your chatbot using an entity extractor.
At first glance, they seem to be pretty similar — both store information, albeit one doing it for longer and more importantly, they seem to be interchangeable.
They aren’t. They are related, but only to an extent.
Both store information
Both can affect how the conversation flows
Entities are more abstract and are extracted by NLU components called entity extractors.
Slots cannot be populated by “extraction” directly — only through already extracted entities or custom actions.
Entities can have more complex structuring and grouping using features like roles, groups, synonyms and regex, while slots do not.
Slots have types and rasa lets you configure them to a great extent.
This is a really important question to ask when designing your bot. In theory, you could map every entity to a slot, and have everything persist on your tracker. But that isn’t always necessary.
Remember that slots are required only when you want the information to persist, like the name of a user. Otherwise, entities themselves are sufficient.
Entities can often have slots associated with them since slots can be considered as “more persistent” entities. But think of cases where you need to extract something temporarily and that piece of information vital for the bot to appropriately respond to the user’s query.
A simple example? Take a “calculator” bot. The user mentions simple arithmetic queries, and the bot calculates the answer.
The user says something like:
Could you add 1223239 and 190239?
The required info can be extracted as entities: operand (which the two operands would fall into) and operator (which is “add” in this case).
Since this information is useful only temporarily — that is, before the next question— storing them in slots is not a great idea, though you could do that if you wanted to.
This one’s a lot easier to think of a use case for. If you need a hint, slots don’t need to be filled via entities. You could use actions as well.
Slots can be used just like global variables. You could maybe maintain a slot called is_existing which keeps track of whether a user is an existing user or not.
Here, it wouldn’t make sense to have a corresponding entity called is_existing as well, since this information can’t be provided by the user and hence, can’t be extracted— it must be verified by a database query.
Slots are defined under the slots key, located in a file called the domain. Rasa let’s organize your data in many ways — for smaller projects, you can choose to dump everything into a single file, or you could keep everything separate.
A defined slot looks like this:
slots: email: type: text initial_value: null auto_fill: true influence_conversation: true
You can decide the type, set a default value, ensure that any corresponding entity (having the same name as your slot) automatically populates it and also decide whether it can affect your conversation or not.
Slots can be set in two ways:
through entities with the same name (when autofill and store_entities_as_slots are set, which — by default — they are)
Through custom actions.
When entities and slots have the same name, it's possible to automatically populate slots with their corresponding extracted entities. This can be done with the help of two properties that are True by default.
auto_fill (set to True by default for each slot). Looks something like this:
slots: email: type: text auto_fill: <true|false>
store_entities_as_slots (set as a config parameter in your domain file)
config: store_entities_as_slots: false
Slots can also be set through custom actions. A custom action is defined in a file as a class, with a name and a run method. It inherits from Rasa’s Action class.
Slots are set by returning SlotSet objects in a list, like this:
return [SlotSet("my_slot", value), .. ]
Remember that custom actions can be used to query databases, make API calls and also respond to a user using the dispatcher .
So, a custom action to check if a user has already signed up for a newsletter could be implemented something like this:
Action action_check_if_existing_user does the following:
reads the user’s email from email slot
passes it to a helper function that queries a database
gets the response and sets the is_existing boolean slot
class ActionCheckIfExistingUser(Action): def name(self): return "action_check_if_existing_user" def run(self, dispatcher, tracker, domain): email = tracker.get_slot('email') # some helper method that queries the database action_utils = ActionUtils() is_existing = action_utils.check_if_user_exists(email) if is_existing: dispatcher.utter_message(text="You're signed up.") else: dispatcher.utter_message(text="You aren't signed up.") return [SlotSet("is_existing", is_existing)]
Entities are extracted by EntityExtractors. These are components you mention in the pipeline of your config file.
There are several existing ones, which you can find in Rasa’s documentation, and you can always design custom components.
We’ll cover the details of entity extraction in a future post.
This was a feature released last year, that gives you a little more flexibility in defining entities.
Roles
Think of role as a way to add a more nuanced meaning to a particular entity.
Say you’re building a bot to help users trade in their old mobile devices. You have an entity modelthat, well, extracts smartphone models.
Now, both the old device and the one the user wants to buy are technically smartphone models, but distinguishing between them is important for the bot.
So, we can add a role to the model entity. You can add training data like this:
My existing device is an [iphone 11]{"entity": "model", "role": "existing_device"} and I want to buy an [iphone 13]{"entity": "model", "role": "new_device"}.
Groups
Groups let you group entities together so that they make more sense. Let’s say you have two entities — name and age , and a user says something like:
My friend John is 20 while David is 25.
Here, the bot needs to identify that there’s a grouping between the two sets of names and ages. John’s age must be associated with his name, and likewise for David. This is where groups come in.
You can do something like this:
My friend [John]{"entity": "name", "group": "1"} is [20]{"entity": "age", "group": "1"} while [David]{"entity": "name", "group": "2"} is [25]{"entity": "age", "group": "2"}
Links to pages in the Rasa documentation
Entities
Entity extractors
Slots
Slot behaviour in affecting conversation
Part I: Building a Chatbot with Rasa
Part III: Handling Chatbot Failure
Part IV: How do Chatbots understand?
We discussed slots and entities in this post, specifically talking about how they are related, but not interchangeable. The goal of this post is to make it easier to understand what each of these is, and which ones to use in which scenarios.
This is just the tip of the iceberg when it comes to what Rasa offers. I’ll be adding more parts to this series.
Hope it helped!
20.3.2022
Add links to the other posts in the series
|
[
{
"code": null,
"e": 304,
"s": 171,
"text": "I’m been working with Rasa for the past few months and was initially pretty confused with the difference between slots and entities."
},
{
"code": null,
"e": 412,
"s": 304,
"text": "In this post, we’ll discuss how slots and entities are alike, and more importantly, how they are different."
},
{
"code": null,
"e": 568,
"s": 412,
"text": "Table of Contents- Defining Entities and Slots- Are slots and entities interchangeable?- When to use one over the other- Setting Slots- Extracting Entities"
},
{
"code": null,
"e": 579,
"s": 568,
"text": "Quick Note"
},
{
"code": null,
"e": 666,
"s": 579,
"text": "This is the next post in my series on Rasa. You can check out the previous post below."
},
{
"code": null,
"e": 689,
"s": 666,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 839,
"s": 689,
"text": "There, we covered some of the building blocks of Rasa and chatbots in general and if you’re new to Rasa, going through that article first would help."
},
{
"code": null,
"e": 900,
"s": 839,
"text": "A quick refresher: this is how you could define these terms."
},
{
"code": null,
"e": 991,
"s": 900,
"text": "Slots are the bot's memory. Anywhere you need persistence in saving values, you use slots."
},
{
"code": null,
"e": 1229,
"s": 991,
"text": "Rasa gives you a lot of flexibility when it comes to defining and using slots. You can give them a type — text, boolean, and even custom types — and you can also choose whether a slot should or shouldn’t affect how the conversation goes."
},
{
"code": null,
"e": 1345,
"s": 1229,
"text": "Entities are key pieces of information that the bot extracts from user messages, like a user’s contact information."
},
{
"code": null,
"e": 1434,
"s": 1345,
"text": "The extraction itself is done by the NLU part of your chatbot using an entity extractor."
},
{
"code": null,
"e": 1594,
"s": 1434,
"text": "At first glance, they seem to be pretty similar — both store information, albeit one doing it for longer and more importantly, they seem to be interchangeable."
},
{
"code": null,
"e": 1648,
"s": 1594,
"text": "They aren’t. They are related, but only to an extent."
},
{
"code": null,
"e": 1671,
"s": 1648,
"text": "Both store information"
},
{
"code": null,
"e": 1714,
"s": 1671,
"text": "Both can affect how the conversation flows"
},
{
"code": null,
"e": 1803,
"s": 1714,
"text": "Entities are more abstract and are extracted by NLU components called entity extractors."
},
{
"code": null,
"e": 1915,
"s": 1803,
"text": "Slots cannot be populated by “extraction” directly — only through already extracted entities or custom actions."
},
{
"code": null,
"e": 2046,
"s": 1915,
"text": "Entities can have more complex structuring and grouping using features like roles, groups, synonyms and regex, while slots do not."
},
{
"code": null,
"e": 2115,
"s": 2046,
"text": "Slots have types and rasa lets you configure them to a great extent."
},
{
"code": null,
"e": 2310,
"s": 2115,
"text": "This is a really important question to ask when designing your bot. In theory, you could map every entity to a slot, and have everything persist on your tracker. But that isn’t always necessary."
},
{
"code": null,
"e": 2462,
"s": 2310,
"text": "Remember that slots are required only when you want the information to persist, like the name of a user. Otherwise, entities themselves are sufficient."
},
{
"code": null,
"e": 2735,
"s": 2462,
"text": "Entities can often have slots associated with them since slots can be considered as “more persistent” entities. But think of cases where you need to extract something temporarily and that piece of information vital for the bot to appropriately respond to the user’s query."
},
{
"code": null,
"e": 2858,
"s": 2735,
"text": "A simple example? Take a “calculator” bot. The user mentions simple arithmetic queries, and the bot calculates the answer."
},
{
"code": null,
"e": 2888,
"s": 2858,
"text": "The user says something like:"
},
{
"code": null,
"e": 2922,
"s": 2888,
"text": "Could you add 1223239 and 190239?"
},
{
"code": null,
"e": 3063,
"s": 2922,
"text": "The required info can be extracted as entities: operand (which the two operands would fall into) and operator (which is “add” in this case)."
},
{
"code": null,
"e": 3236,
"s": 3063,
"text": "Since this information is useful only temporarily — that is, before the next question— storing them in slots is not a great idea, though you could do that if you wanted to."
},
{
"code": null,
"e": 3383,
"s": 3236,
"text": "This one’s a lot easier to think of a use case for. If you need a hint, slots don’t need to be filled via entities. You could use actions as well."
},
{
"code": null,
"e": 3544,
"s": 3383,
"text": "Slots can be used just like global variables. You could maybe maintain a slot called is_existing which keeps track of whether a user is an existing user or not."
},
{
"code": null,
"e": 3757,
"s": 3544,
"text": "Here, it wouldn’t make sense to have a corresponding entity called is_existing as well, since this information can’t be provided by the user and hence, can’t be extracted— it must be verified by a database query."
},
{
"code": null,
"e": 3993,
"s": 3757,
"text": "Slots are defined under the slots key, located in a file called the domain. Rasa let’s organize your data in many ways — for smaller projects, you can choose to dump everything into a single file, or you could keep everything separate."
},
{
"code": null,
"e": 4025,
"s": 3993,
"text": "A defined slot looks like this:"
},
{
"code": null,
"e": 4128,
"s": 4025,
"text": "slots: email: type: text initial_value: null auto_fill: true influence_conversation: true"
},
{
"code": null,
"e": 4338,
"s": 4128,
"text": "You can decide the type, set a default value, ensure that any corresponding entity (having the same name as your slot) automatically populates it and also decide whether it can affect your conversation or not."
},
{
"code": null,
"e": 4368,
"s": 4338,
"text": "Slots can be set in two ways:"
},
{
"code": null,
"e": 4487,
"s": 4368,
"text": "through entities with the same name (when autofill and store_entities_as_slots are set, which — by default — they are)"
},
{
"code": null,
"e": 4511,
"s": 4487,
"text": "Through custom actions."
},
{
"code": null,
"e": 4721,
"s": 4511,
"text": "When entities and slots have the same name, it's possible to automatically populate slots with their corresponding extracted entities. This can be done with the help of two properties that are True by default."
},
{
"code": null,
"e": 4798,
"s": 4721,
"text": "auto_fill (set to True by default for each slot). Looks something like this:"
},
{
"code": null,
"e": 4854,
"s": 4798,
"text": "slots: email: type: text auto_fill: <true|false>"
},
{
"code": null,
"e": 4926,
"s": 4854,
"text": "store_entities_as_slots (set as a config parameter in your domain file)"
},
{
"code": null,
"e": 4966,
"s": 4926,
"text": "config: store_entities_as_slots: false"
},
{
"code": null,
"e": 5129,
"s": 4966,
"text": "Slots can also be set through custom actions. A custom action is defined in a file as a class, with a name and a run method. It inherits from Rasa’s Action class."
},
{
"code": null,
"e": 5194,
"s": 5129,
"text": "Slots are set by returning SlotSet objects in a list, like this:"
},
{
"code": null,
"e": 5234,
"s": 5194,
"text": "return [SlotSet(\"my_slot\", value), .. ]"
},
{
"code": null,
"e": 5360,
"s": 5234,
"text": "Remember that custom actions can be used to query databases, make API calls and also respond to a user using the dispatcher ."
},
{
"code": null,
"e": 5480,
"s": 5360,
"text": "So, a custom action to check if a user has already signed up for a newsletter could be implemented something like this:"
},
{
"code": null,
"e": 5537,
"s": 5480,
"text": "Action action_check_if_existing_user does the following:"
},
{
"code": null,
"e": 5576,
"s": 5537,
"text": "reads the user’s email from email slot"
},
{
"code": null,
"e": 5631,
"s": 5576,
"text": "passes it to a helper function that queries a database"
},
{
"code": null,
"e": 5687,
"s": 5631,
"text": "gets the response and sets the is_existing boolean slot"
},
{
"code": null,
"e": 6253,
"s": 5687,
"text": "class ActionCheckIfExistingUser(Action): def name(self): return \"action_check_if_existing_user\" def run(self, dispatcher, tracker, domain): email = tracker.get_slot('email') # some helper method that queries the database action_utils = ActionUtils() is_existing = action_utils.check_if_user_exists(email) if is_existing: dispatcher.utter_message(text=\"You're signed up.\") else: dispatcher.utter_message(text=\"You aren't signed up.\") return [SlotSet(\"is_existing\", is_existing)]"
},
{
"code": null,
"e": 6367,
"s": 6253,
"text": "Entities are extracted by EntityExtractors. These are components you mention in the pipeline of your config file."
},
{
"code": null,
"e": 6489,
"s": 6367,
"text": "There are several existing ones, which you can find in Rasa’s documentation, and you can always design custom components."
},
{
"code": null,
"e": 6552,
"s": 6489,
"text": "We’ll cover the details of entity extraction in a future post."
},
{
"code": null,
"e": 6654,
"s": 6552,
"text": "This was a feature released last year, that gives you a little more flexibility in defining entities."
},
{
"code": null,
"e": 6660,
"s": 6654,
"text": "Roles"
},
{
"code": null,
"e": 6737,
"s": 6660,
"text": "Think of role as a way to add a more nuanced meaning to a particular entity."
},
{
"code": null,
"e": 6876,
"s": 6737,
"text": "Say you’re building a bot to help users trade in their old mobile devices. You have an entity modelthat, well, extracts smartphone models."
},
{
"code": null,
"e": 7028,
"s": 6876,
"text": "Now, both the old device and the one the user wants to buy are technically smartphone models, but distinguishing between them is important for the bot."
},
{
"code": null,
"e": 7108,
"s": 7028,
"text": "So, we can add a role to the model entity. You can add training data like this:"
},
{
"code": null,
"e": 7266,
"s": 7108,
"text": "My existing device is an [iphone 11]{\"entity\": \"model\", \"role\": \"existing_device\"} and I want to buy an [iphone 13]{\"entity\": \"model\", \"role\": \"new_device\"}."
},
{
"code": null,
"e": 7273,
"s": 7266,
"text": "Groups"
},
{
"code": null,
"e": 7423,
"s": 7273,
"text": "Groups let you group entities together so that they make more sense. Let’s say you have two entities — name and age , and a user says something like:"
},
{
"code": null,
"e": 7463,
"s": 7423,
"text": "My friend John is 20 while David is 25."
},
{
"code": null,
"e": 7658,
"s": 7463,
"text": "Here, the bot needs to identify that there’s a grouping between the two sets of names and ages. John’s age must be associated with his name, and likewise for David. This is where groups come in."
},
{
"code": null,
"e": 7690,
"s": 7658,
"text": "You can do something like this:"
},
{
"code": null,
"e": 7863,
"s": 7690,
"text": "My friend [John]{\"entity\": \"name\", \"group\": \"1\"} is [20]{\"entity\": \"age\", \"group\": \"1\"} while [David]{\"entity\": \"name\", \"group\": \"2\"} is [25]{\"entity\": \"age\", \"group\": \"2\"}"
},
{
"code": null,
"e": 7904,
"s": 7863,
"text": "Links to pages in the Rasa documentation"
},
{
"code": null,
"e": 7913,
"s": 7904,
"text": "Entities"
},
{
"code": null,
"e": 7931,
"s": 7913,
"text": "Entity extractors"
},
{
"code": null,
"e": 7937,
"s": 7931,
"text": "Slots"
},
{
"code": null,
"e": 7978,
"s": 7937,
"text": "Slot behaviour in affecting conversation"
},
{
"code": null,
"e": 8015,
"s": 7978,
"text": "Part I: Building a Chatbot with Rasa"
},
{
"code": null,
"e": 8050,
"s": 8015,
"text": "Part III: Handling Chatbot Failure"
},
{
"code": null,
"e": 8087,
"s": 8050,
"text": "Part IV: How do Chatbots understand?"
},
{
"code": null,
"e": 8329,
"s": 8087,
"text": "We discussed slots and entities in this post, specifically talking about how they are related, but not interchangeable. The goal of this post is to make it easier to understand what each of these is, and which ones to use in which scenarios."
},
{
"code": null,
"e": 8442,
"s": 8329,
"text": "This is just the tip of the iceberg when it comes to what Rasa offers. I’ll be adding more parts to this series."
},
{
"code": null,
"e": 8458,
"s": 8442,
"text": "Hope it helped!"
},
{
"code": null,
"e": 8468,
"s": 8458,
"text": "20.3.2022"
}
] |
5 Open Source Tools You Can Use to Train and Deploy an OCR Project | by Lai Woen Yon | Towards Data Science
|
Part I - 5 open-source tools you can use to train your own data and deploy it for your next OCR project!Part II - From labelling to serving your OCR model! (Coming soon)
There are a number of cases we need to detect text in an image.
To digitalize their operations, banks need to store all paperwork into a cloud database. For this, the documents must be scanned and converted into a machine-readable format.In the property industry, home buyers and agents typically fill out their agreement forms in paper form. To save the forms in the cloud, you need OCR software, which converts the text into machine-readable files.Among Edtech startups, there are some who heavily rely on OCR. As one example, Photomath, a startup that breaks down problems into simple steps to help people understand mathematics. The app offers users the convenience of scanning questions they have on paper and having them translated into machine-readable format through scanning.
To digitalize their operations, banks need to store all paperwork into a cloud database. For this, the documents must be scanned and converted into a machine-readable format.
In the property industry, home buyers and agents typically fill out their agreement forms in paper form. To save the forms in the cloud, you need OCR software, which converts the text into machine-readable files.
Among Edtech startups, there are some who heavily rely on OCR. As one example, Photomath, a startup that breaks down problems into simple steps to help people understand mathematics. The app offers users the convenience of scanning questions they have on paper and having them translated into machine-readable format through scanning.
OCR can be done using either traditional computer vision techniques or more advanced deep learning techniques. The focus of this article will only be on tools that use deep learning models. As a bonus, I will also include scripts that will allow you to experience all the models at once.
github.com
EasyOCR is an open-source and ready-to-use OCR with almost 80 supported languages. You can choose to train the model with your own data (you can follow their example dataset to format your own dataset) or use the existing models to serve your own application.
The following script can be used to run the code:
# installationpip install easyocr# importimport easyocr# inferencereader = easyocr.Reader(['en'])result = reader.readtext(img_path)
Here’s a quick test to see how accurate this OCR software is. The image below is from pexels.com, and the OCR tool will detect the text in the picture. In a perfect model, it should be able to output “MAKE THIS DAY GREAT!”.
Here is the result:
You can see that the result is not perfect. It misinterpreted the character ‘G’ and misidentified ‘H’ as the small letter ‘h’.
github.com
PaddleOCR is an open-source product developed by the Baidu team in China. I have been using this software tool for quite a while and I am really amazed by how much the team has done to make this free product as powerful as any commercial OCR software in the market. The models used in the framework were trained using State-Of-The-Art (SOTA) techniques (such as CML knowledge distillation and CopyPaste data expansion strategy) and with tons of printed and handwritten images. This makes it one of the most powerful open-source OCR software. Here is a number of things that you can do with the open-source code:
You can use their existing models for your applications. They also provide an extremely lightweight and yet powerful model called PP-OCRv2 so that you don’t need to worry about a large memory problem.They support multiple languages such as Chinese, English, Korean, Japanese, German and etc.They have multiple tools to support you for data labeling. For example, they provide the PPOCRLabel for you to quickly label the text in the image. As data is important to train the OCR model, they also have a tool called Style-text for you to quickly synthesize your image so that you have more images to train your model, making it robust to use in the production environment.You can fine-tune the model on your dataset with the provided script.
You can use their existing models for your applications. They also provide an extremely lightweight and yet powerful model called PP-OCRv2 so that you don’t need to worry about a large memory problem.
They support multiple languages such as Chinese, English, Korean, Japanese, German and etc.
They have multiple tools to support you for data labeling. For example, they provide the PPOCRLabel for you to quickly label the text in the image. As data is important to train the OCR model, they also have a tool called Style-text for you to quickly synthesize your image so that you have more images to train your model, making it robust to use in the production environment.
You can fine-tune the model on your dataset with the provided script.
Here is how you can use it:
# installationpip install paddleocr paddlepaddle# importfrom paddleocr import PaddleOCR# inferenceocr = PaddleOCR(use_angle_cls=True, lang='en')result = ocr.ocr(img_path, cls=True)
Let’s use the same image above to examine the model performance:
It is amazing to see such an accurate output from a model that has yet been trained on a similar image before.
huggingface.co
github.com
TrOCR was initially proposed in TrOCR: Transformer-based Optical Character Recognition with Pre-trained Models by Minghao Li, Tengchao Lv, Lei Cui and etc. It is developed based on the image Transformer encoder and an autoregressive text decoder (Similar to GPT-2). The code has been included in the famous Huggingface library so we can use the trained model directly from the library.
# installationpip install transformers# importfrom transformers import TrOCRProcessor, VisionEncoderDecoderModelfrom PIL import Image# inferencemodel_version = "microsoft/trocr-base-printed"processor = TrOCRProcessor.from_pretrained(model_version)model = VisionEncoderDecoderModel.from_pretrained(model_version)image = Image.open(img_path).convert("RGB")pixel_values = processor(image, return_tensors="pt").pixel_valuesgenerated_ids = model.generate(pixel_values)generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
Unlike the other two, the models only output the final text output without the text location. The model is meant for text recognition so you should not expect it to detect the text in the image. The output that you would receive after running the above script is “MASKAY”. As expected, the result is poor because there isn’t a text detection model in the pipeline.
github.com
MMOCR is another open-source OCR tool that was developed under the famous OpenMMLab project. The project is developed by the team from The Chinese University of Hong Kong and has been one of the leading projects in the area of Computer Vision.
It supports multiple SOTA models and also allows you for training and deployment. Among the highlights of this open-source tool is its ability to provide a key information extraction model in addition to other modules (Text detection and recognition) in the same pipeline. Key information extraction solves problems in which users must match a certain template in order to extract data from a document. The conventional approach would make it difficult to use documents with unknown templates.
Once we have installed the tool (yes, it is not as convenient as the first two tools), we can use it to detect our sample image and test its performance. We get a similar result to PaddleOCR, except that the exclamation mark does not appear at the end of “GREAT”. As a whole, this tool provides almost everything into a single pipeline, so it’s quite powerful to use.
github.com
pypi.org
For people who have done OCR projects before, you should be very familiar with this library. Here is a little bit of history about Tesseract-OCR:
Tesseract was originally developed at Hewlett-Packard Laboratories Bristol and at Hewlett-Packard Co, Greeley Colorado between 1985 and 1994, with some more changes made in 1996 to port to Windows, and some C++izing in 1998. In 2005 Tesseract was open sourced by HP. From 2006 until November 2018 it was developed by Google. — from https://github.com/tesseract-ocr/tesseract
Python-Pytesseract is a wrapper for the Tesseract-OCR engine. Using it is very straightforward. Since the model hasn’t been updated since December 26, 2019, and uses a very simple LSTM-based model, the result might not be as desirable as the rest of the approach. In spite of this, the model can be trained using new data, so that you can tailor it to your needs.
To test the tool, I used the same image above. Despite preprocessing the image with OpenCV, I got an empty result. It seems that the tool does not work well with text on scenes. The performance should be better for normal documents with relatively clean backgrounds.
Here is a comparison of the different open-source OCR tools:
This rating is solely based on my own experience with the open-source tools. Each of them has its own advantages. Our project requires that we select the right tool based on a set of specific requirements.
Here is the Colab notebook if you want to give them a try!
Open-source tools cannot be completely relied upon when deployed for real-world service. Especially for some applications, it requires more than 99% accuracy. In order to accomplish this, we can collect data from our business and label them before training the open-source tool. My next step will be to show you how Label Studio can streamline the entire process. From labeling to serving models, I’ll cover it all!
If you have not read my Label Studio article, feel free to read it here:
towardsdatascience.com
Do follow me and like my post to get the latest updates on the series.
Woen Yon is a Data Scientist based in Singapore. His experience includes developing advanced artificial intelligence products for several multinational enterprises.
Woen Yon has worked with a handful of smart people to offer web solutions including web crawling services and website development for local and international start-up business owners. They are well aware of the challenges of building quality software. Please do not hesitate to drop him an email at [email protected] if you need assistance.
He loves making friends! Feel free to connect with him on LinkedIn and Medium
|
[
{
"code": null,
"e": 344,
"s": 172,
"text": "Part I - 5 open-source tools you can use to train your own data and deploy it for your next OCR project!Part II - From labelling to serving your OCR model! (Coming soon)"
},
{
"code": null,
"e": 408,
"s": 344,
"text": "There are a number of cases we need to detect text in an image."
},
{
"code": null,
"e": 1129,
"s": 408,
"text": "To digitalize their operations, banks need to store all paperwork into a cloud database. For this, the documents must be scanned and converted into a machine-readable format.In the property industry, home buyers and agents typically fill out their agreement forms in paper form. To save the forms in the cloud, you need OCR software, which converts the text into machine-readable files.Among Edtech startups, there are some who heavily rely on OCR. As one example, Photomath, a startup that breaks down problems into simple steps to help people understand mathematics. The app offers users the convenience of scanning questions they have on paper and having them translated into machine-readable format through scanning."
},
{
"code": null,
"e": 1304,
"s": 1129,
"text": "To digitalize their operations, banks need to store all paperwork into a cloud database. For this, the documents must be scanned and converted into a machine-readable format."
},
{
"code": null,
"e": 1517,
"s": 1304,
"text": "In the property industry, home buyers and agents typically fill out their agreement forms in paper form. To save the forms in the cloud, you need OCR software, which converts the text into machine-readable files."
},
{
"code": null,
"e": 1852,
"s": 1517,
"text": "Among Edtech startups, there are some who heavily rely on OCR. As one example, Photomath, a startup that breaks down problems into simple steps to help people understand mathematics. The app offers users the convenience of scanning questions they have on paper and having them translated into machine-readable format through scanning."
},
{
"code": null,
"e": 2140,
"s": 1852,
"text": "OCR can be done using either traditional computer vision techniques or more advanced deep learning techniques. The focus of this article will only be on tools that use deep learning models. As a bonus, I will also include scripts that will allow you to experience all the models at once."
},
{
"code": null,
"e": 2151,
"s": 2140,
"text": "github.com"
},
{
"code": null,
"e": 2411,
"s": 2151,
"text": "EasyOCR is an open-source and ready-to-use OCR with almost 80 supported languages. You can choose to train the model with your own data (you can follow their example dataset to format your own dataset) or use the existing models to serve your own application."
},
{
"code": null,
"e": 2461,
"s": 2411,
"text": "The following script can be used to run the code:"
},
{
"code": null,
"e": 2593,
"s": 2461,
"text": "# installationpip install easyocr# importimport easyocr# inferencereader = easyocr.Reader(['en'])result = reader.readtext(img_path)"
},
{
"code": null,
"e": 2817,
"s": 2593,
"text": "Here’s a quick test to see how accurate this OCR software is. The image below is from pexels.com, and the OCR tool will detect the text in the picture. In a perfect model, it should be able to output “MAKE THIS DAY GREAT!”."
},
{
"code": null,
"e": 2837,
"s": 2817,
"text": "Here is the result:"
},
{
"code": null,
"e": 2964,
"s": 2837,
"text": "You can see that the result is not perfect. It misinterpreted the character ‘G’ and misidentified ‘H’ as the small letter ‘h’."
},
{
"code": null,
"e": 2975,
"s": 2964,
"text": "github.com"
},
{
"code": null,
"e": 3587,
"s": 2975,
"text": "PaddleOCR is an open-source product developed by the Baidu team in China. I have been using this software tool for quite a while and I am really amazed by how much the team has done to make this free product as powerful as any commercial OCR software in the market. The models used in the framework were trained using State-Of-The-Art (SOTA) techniques (such as CML knowledge distillation and CopyPaste data expansion strategy) and with tons of printed and handwritten images. This makes it one of the most powerful open-source OCR software. Here is a number of things that you can do with the open-source code:"
},
{
"code": null,
"e": 4326,
"s": 3587,
"text": "You can use their existing models for your applications. They also provide an extremely lightweight and yet powerful model called PP-OCRv2 so that you don’t need to worry about a large memory problem.They support multiple languages such as Chinese, English, Korean, Japanese, German and etc.They have multiple tools to support you for data labeling. For example, they provide the PPOCRLabel for you to quickly label the text in the image. As data is important to train the OCR model, they also have a tool called Style-text for you to quickly synthesize your image so that you have more images to train your model, making it robust to use in the production environment.You can fine-tune the model on your dataset with the provided script."
},
{
"code": null,
"e": 4527,
"s": 4326,
"text": "You can use their existing models for your applications. They also provide an extremely lightweight and yet powerful model called PP-OCRv2 so that you don’t need to worry about a large memory problem."
},
{
"code": null,
"e": 4619,
"s": 4527,
"text": "They support multiple languages such as Chinese, English, Korean, Japanese, German and etc."
},
{
"code": null,
"e": 4998,
"s": 4619,
"text": "They have multiple tools to support you for data labeling. For example, they provide the PPOCRLabel for you to quickly label the text in the image. As data is important to train the OCR model, they also have a tool called Style-text for you to quickly synthesize your image so that you have more images to train your model, making it robust to use in the production environment."
},
{
"code": null,
"e": 5068,
"s": 4998,
"text": "You can fine-tune the model on your dataset with the provided script."
},
{
"code": null,
"e": 5096,
"s": 5068,
"text": "Here is how you can use it:"
},
{
"code": null,
"e": 5277,
"s": 5096,
"text": "# installationpip install paddleocr paddlepaddle# importfrom paddleocr import PaddleOCR# inferenceocr = PaddleOCR(use_angle_cls=True, lang='en')result = ocr.ocr(img_path, cls=True)"
},
{
"code": null,
"e": 5342,
"s": 5277,
"text": "Let’s use the same image above to examine the model performance:"
},
{
"code": null,
"e": 5453,
"s": 5342,
"text": "It is amazing to see such an accurate output from a model that has yet been trained on a similar image before."
},
{
"code": null,
"e": 5468,
"s": 5453,
"text": "huggingface.co"
},
{
"code": null,
"e": 5479,
"s": 5468,
"text": "github.com"
},
{
"code": null,
"e": 5865,
"s": 5479,
"text": "TrOCR was initially proposed in TrOCR: Transformer-based Optical Character Recognition with Pre-trained Models by Minghao Li, Tengchao Lv, Lei Cui and etc. It is developed based on the image Transformer encoder and an autoregressive text decoder (Similar to GPT-2). The code has been included in the famous Huggingface library so we can use the trained model directly from the library."
},
{
"code": null,
"e": 6412,
"s": 5865,
"text": "# installationpip install transformers# importfrom transformers import TrOCRProcessor, VisionEncoderDecoderModelfrom PIL import Image# inferencemodel_version = \"microsoft/trocr-base-printed\"processor = TrOCRProcessor.from_pretrained(model_version)model = VisionEncoderDecoderModel.from_pretrained(model_version)image = Image.open(img_path).convert(\"RGB\")pixel_values = processor(image, return_tensors=\"pt\").pixel_valuesgenerated_ids = model.generate(pixel_values)generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]"
},
{
"code": null,
"e": 6777,
"s": 6412,
"text": "Unlike the other two, the models only output the final text output without the text location. The model is meant for text recognition so you should not expect it to detect the text in the image. The output that you would receive after running the above script is “MASKAY”. As expected, the result is poor because there isn’t a text detection model in the pipeline."
},
{
"code": null,
"e": 6788,
"s": 6777,
"text": "github.com"
},
{
"code": null,
"e": 7032,
"s": 6788,
"text": "MMOCR is another open-source OCR tool that was developed under the famous OpenMMLab project. The project is developed by the team from The Chinese University of Hong Kong and has been one of the leading projects in the area of Computer Vision."
},
{
"code": null,
"e": 7526,
"s": 7032,
"text": "It supports multiple SOTA models and also allows you for training and deployment. Among the highlights of this open-source tool is its ability to provide a key information extraction model in addition to other modules (Text detection and recognition) in the same pipeline. Key information extraction solves problems in which users must match a certain template in order to extract data from a document. The conventional approach would make it difficult to use documents with unknown templates."
},
{
"code": null,
"e": 7894,
"s": 7526,
"text": "Once we have installed the tool (yes, it is not as convenient as the first two tools), we can use it to detect our sample image and test its performance. We get a similar result to PaddleOCR, except that the exclamation mark does not appear at the end of “GREAT”. As a whole, this tool provides almost everything into a single pipeline, so it’s quite powerful to use."
},
{
"code": null,
"e": 7905,
"s": 7894,
"text": "github.com"
},
{
"code": null,
"e": 7914,
"s": 7905,
"text": "pypi.org"
},
{
"code": null,
"e": 8060,
"s": 7914,
"text": "For people who have done OCR projects before, you should be very familiar with this library. Here is a little bit of history about Tesseract-OCR:"
},
{
"code": null,
"e": 8435,
"s": 8060,
"text": "Tesseract was originally developed at Hewlett-Packard Laboratories Bristol and at Hewlett-Packard Co, Greeley Colorado between 1985 and 1994, with some more changes made in 1996 to port to Windows, and some C++izing in 1998. In 2005 Tesseract was open sourced by HP. From 2006 until November 2018 it was developed by Google. — from https://github.com/tesseract-ocr/tesseract"
},
{
"code": null,
"e": 8799,
"s": 8435,
"text": "Python-Pytesseract is a wrapper for the Tesseract-OCR engine. Using it is very straightforward. Since the model hasn’t been updated since December 26, 2019, and uses a very simple LSTM-based model, the result might not be as desirable as the rest of the approach. In spite of this, the model can be trained using new data, so that you can tailor it to your needs."
},
{
"code": null,
"e": 9066,
"s": 8799,
"text": "To test the tool, I used the same image above. Despite preprocessing the image with OpenCV, I got an empty result. It seems that the tool does not work well with text on scenes. The performance should be better for normal documents with relatively clean backgrounds."
},
{
"code": null,
"e": 9127,
"s": 9066,
"text": "Here is a comparison of the different open-source OCR tools:"
},
{
"code": null,
"e": 9333,
"s": 9127,
"text": "This rating is solely based on my own experience with the open-source tools. Each of them has its own advantages. Our project requires that we select the right tool based on a set of specific requirements."
},
{
"code": null,
"e": 9392,
"s": 9333,
"text": "Here is the Colab notebook if you want to give them a try!"
},
{
"code": null,
"e": 9808,
"s": 9392,
"text": "Open-source tools cannot be completely relied upon when deployed for real-world service. Especially for some applications, it requires more than 99% accuracy. In order to accomplish this, we can collect data from our business and label them before training the open-source tool. My next step will be to show you how Label Studio can streamline the entire process. From labeling to serving models, I’ll cover it all!"
},
{
"code": null,
"e": 9881,
"s": 9808,
"text": "If you have not read my Label Studio article, feel free to read it here:"
},
{
"code": null,
"e": 9904,
"s": 9881,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 9975,
"s": 9904,
"text": "Do follow me and like my post to get the latest updates on the series."
},
{
"code": null,
"e": 10140,
"s": 9975,
"text": "Woen Yon is a Data Scientist based in Singapore. His experience includes developing advanced artificial intelligence products for several multinational enterprises."
},
{
"code": null,
"e": 10481,
"s": 10140,
"text": "Woen Yon has worked with a handful of smart people to offer web solutions including web crawling services and website development for local and international start-up business owners. They are well aware of the challenges of building quality software. Please do not hesitate to drop him an email at [email protected] if you need assistance."
}
] |
Perl unshift Function
|
This function places the elements from LIST, in order, at the beginning of ARRAY. This is opposite function to shift().
Following is the simple syntax for this function −
unshift ARRAY, LIST
This function returns the number of new elements in ARRAY.
Following is the example code showing its basic usage −
#!/usr/bin/perl -w
@array = ( 1, 2, 3, 4);
print "Value of array is @array\n" ;
unshift( @array, 20, 30, 40 );
print "Now value of array is @array\n" ;
When above code is executed, it produces the following result −
Value of array is 1 2 3 4
Now value of array is 20 30 40 1 2 3 4
46 Lectures
4.5 hours
Devi Killada
11 Lectures
1.5 hours
Harshit Srivastava
30 Lectures
6 hours
TELCOMA Global
24 Lectures
2 hours
Mohammad Nauman
68 Lectures
7 hours
Stone River ELearning
58 Lectures
6.5 hours
Stone River ELearning
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2340,
"s": 2220,
"text": "This function places the elements from LIST, in order, at the beginning of ARRAY. This is opposite function to shift()."
},
{
"code": null,
"e": 2391,
"s": 2340,
"text": "Following is the simple syntax for this function −"
},
{
"code": null,
"e": 2412,
"s": 2391,
"text": "unshift ARRAY, LIST\n"
},
{
"code": null,
"e": 2471,
"s": 2412,
"text": "This function returns the number of new elements in ARRAY."
},
{
"code": null,
"e": 2527,
"s": 2471,
"text": "Following is the example code showing its basic usage −"
},
{
"code": null,
"e": 2684,
"s": 2527,
"text": "#!/usr/bin/perl -w\n\n@array = ( 1, 2, 3, 4);\n\nprint \"Value of array is @array\\n\" ;\n\nunshift( @array, 20, 30, 40 );\n\nprint \"Now value of array is @array\\n\" ;"
},
{
"code": null,
"e": 2748,
"s": 2684,
"text": "When above code is executed, it produces the following result −"
},
{
"code": null,
"e": 2814,
"s": 2748,
"text": "Value of array is 1 2 3 4\nNow value of array is 20 30 40 1 2 3 4\n"
},
{
"code": null,
"e": 2849,
"s": 2814,
"text": "\n 46 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 2863,
"s": 2849,
"text": " Devi Killada"
},
{
"code": null,
"e": 2898,
"s": 2863,
"text": "\n 11 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 2918,
"s": 2898,
"text": " Harshit Srivastava"
},
{
"code": null,
"e": 2951,
"s": 2918,
"text": "\n 30 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 2967,
"s": 2951,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 3000,
"s": 2967,
"text": "\n 24 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3017,
"s": 3000,
"text": " Mohammad Nauman"
},
{
"code": null,
"e": 3050,
"s": 3017,
"text": "\n 68 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3073,
"s": 3050,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 3108,
"s": 3073,
"text": "\n 58 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 3131,
"s": 3108,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 3138,
"s": 3131,
"text": " Print"
},
{
"code": null,
"e": 3149,
"s": 3138,
"text": " Add Notes"
}
] |
Java Examples - Create a frame
|
How to display a message in a new frame?
Following example demonstrates how to display message in a new frame by creating a frame using JFrame() & using JFrames getContentPanel(), setSize() & setVisible() methods to display this frame.
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.geom.Rectangle2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main extends JPanel {
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setFont(new Font("Serif", Font.PLAIN, 48));
paintHorizontallyCenteredText(g2, "Java Source", 200, 75);
paintHorizontallyCenteredText(g2, "and", 200, 125);
paintHorizontallyCenteredText(g2, "Support", 200, 175);
}
protected void paintHorizontallyCenteredText(
Graphics2D g2, String s, float centerX, float baselineY) {
FontRenderContext frc = g2.getFontRenderContext();
Rectangle2D bounds = g2.getFont().getStringBounds(s, frc);
float width = (float) bounds.getWidth();
g2.drawString(s, centerX - width / 2, baselineY);
}
public static void main(String[] args) {
JFrame f = new JFrame();
f.getContentPane().add(new Main());
f.setSize(450, 350);
f.setVisible(true);
}
}
The above code sample will produce the following result.
JAVA and J2EE displayed in a new Frame.
The following is an example to display a message in a new frame.
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Component;
import java.awt.Frame;
import java.awt.TextArea;
public class Main {
public static void main(String[] args) {
Frame f = new Frame("Tutorialspoint");
Component text = new TextArea("Sairamkrishna Mamamahe");
Component button = new Button("Button");
f.add(text, BorderLayout.NORTH);
f.add(button, BorderLayout.SOUTH);
int width = 300;
int height = 300;
f.setSize(width, height);
f.setVisible(true);
}
}
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2109,
"s": 2068,
"text": "How to display a message in a new frame?"
},
{
"code": null,
"e": 2304,
"s": 2109,
"text": "Following example demonstrates how to display message in a new frame by creating a frame using JFrame() & using JFrames getContentPanel(), setSize() & setVisible() methods to display this frame."
},
{
"code": null,
"e": 3426,
"s": 2304,
"text": "import java.awt.*;\nimport java.awt.font.FontRenderContext;\nimport java.awt.geom.Rectangle2D;\nimport javax.swing.JFrame;\nimport javax.swing.JPanel;\n\npublic class Main extends JPanel {\n public void paint(Graphics g) {\n Graphics2D g2 = (Graphics2D) g;\n g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);\n g2.setFont(new Font(\"Serif\", Font.PLAIN, 48));\n paintHorizontallyCenteredText(g2, \"Java Source\", 200, 75);\n paintHorizontallyCenteredText(g2, \"and\", 200, 125);\n paintHorizontallyCenteredText(g2, \"Support\", 200, 175);\n }\n protected void paintHorizontallyCenteredText(\n Graphics2D g2, String s, float centerX, float baselineY) {\n \n FontRenderContext frc = g2.getFontRenderContext();\n Rectangle2D bounds = g2.getFont().getStringBounds(s, frc);\n float width = (float) bounds.getWidth();\n g2.drawString(s, centerX - width / 2, baselineY);\n }\n public static void main(String[] args) {\n JFrame f = new JFrame();\n f.getContentPane().add(new Main());\n f.setSize(450, 350);\n f.setVisible(true);\n }\n}"
},
{
"code": null,
"e": 3483,
"s": 3426,
"text": "The above code sample will produce the following result."
},
{
"code": null,
"e": 3524,
"s": 3483,
"text": "JAVA and J2EE displayed in a new Frame.\n"
},
{
"code": null,
"e": 3589,
"s": 3524,
"text": "The following is an example to display a message in a new frame."
},
{
"code": null,
"e": 4132,
"s": 3589,
"text": "import java.awt.BorderLayout;\nimport java.awt.Button;\nimport java.awt.Component;\nimport java.awt.Frame;\nimport java.awt.TextArea;\n\npublic class Main {\n public static void main(String[] args) {\n Frame f = new Frame(\"Tutorialspoint\");\n Component text = new TextArea(\"Sairamkrishna Mamamahe\");\n Component button = new Button(\"Button\");\n f.add(text, BorderLayout.NORTH);\n f.add(button, BorderLayout.SOUTH);\n int width = 300;\n int height = 300;\n f.setSize(width, height);\n f.setVisible(true);\n } \n}"
},
{
"code": null,
"e": 4139,
"s": 4132,
"text": " Print"
},
{
"code": null,
"e": 4150,
"s": 4139,
"text": " Add Notes"
}
] |
Machine Learning Basics: Naive Bayes Classification | by Gurucharan M K | Towards Data Science
|
In the previous stories, I had given an explanation of the program for implementation of various Regression models. Also, I had described the implementation of the Logistic Regression, KNN and SVM Classification model. In this article, we shall go through the algorithm of the famous Naive Bayes Classification model with an example.
Naive Bayes is one such algorithm in classification that can never be overlooked upon due to its special characteristic of being “naive”. It makes the assumption that features of a measurement are independent of each other.
For example, an animal may be considered as a cat if it has cat eyes, whiskers and a long tail. Even if these features depend on each other or upon the existence of the other features, all of these properties independently contribute to the probability that this animal is a cat and that is why it is known as ‘Naive’.
According to Bayes Theorem, the various features are mutually independent. For two independent events, P(A,B) = P(A)P(B). This assumption of Bayes Theorem is probably never encountered in practice, hence it accounts for the “naive” part in Naive Bayes. Bayes’ Theorem is stated as: P(a|b) = (P(b|a) * P(a)) / P(b). Where P(a|b) is the probability of a given b.
Let us understand this algorithm with a simple example. The Student will be a pass if he wears a “red” color dress on the exam day. We can solve it using above discussed method of posterior probability.
By Bayes Theorem, P(Pass| Red) = P( Red| Pass) * P(Pass) / P (Red).
From the values, let us assume P (Red|Pass) = 3/9 = 0.33, P(Red) = 5/14 = 0.36, P( Pass)= 9/14 = 0.64. Now, P (Pass| Red) = 0.33 * 0.64 / 0.36 = 0.60, which has higher probability.
In this way, Naive Bayes uses a similar method to predict the probability of different class based on various attributes.
To implement the Naive Bayes Classification, we shall use a very famous Iris Flower Dataset that consists of 3 classes of flowers. In this, there are 4 independent variables namely the, sepal_length, sepal_width, petal_length and petal_width. The dependent variable is the species which we will predict using the four independent features of the flowers.
There are 3 classes of species namely setosa, versicolor and the virginica. This dataset was originally introduced in 1936 by Ronald Fisher. Using the various features of the flower (independent variables), we have to classify a given flower using Naive Bayes Classification model.
As always, the first step will always include importing the libraries which are the NumPy, Pandas and the Matplotlib.
import numpy as npimport matplotlib.pyplot as pltimport pandas as pd
In this step, we shall import the Iris Flower dataset which is stored in my github repository as IrisDataset.csv and save it to the variable dataset. After this, we assign the 4 independent variables to X and the dependent variable ‘species’ to Y. The first 5 rows of the dataset are displayed.
dataset = pd.read_csv('https://raw.githubusercontent.com/mk-gurucharan/Classification/master/IrisDataset.csv')X = dataset.iloc[:,:4].valuesy = dataset['species'].valuesdataset.head(5)>>sepal_length sepal_width petal_length petal_width species5.1 3.5 1.4 0.2 setosa4.9 3.0 1.4 0.2 setosa4.7 3.2 1.3 0.2 setosa4.6 3.1 1.5 0.2 setosa5.0 3.6 1.4 0.2 setosa
Once we have obtained our data set, we have to split the data into the training set and the test set. In this data set, there are 150 rows with 50 rows of each of the 3 classes. As each class is given in a continuous order, we need to randomly split the dataset. Here, we have the test_size=0.2, which means that 20% of the dataset will be used for testing purpose as the test set and the remaining 80% will be used as the training set for training the Naive Bayes classification model.
from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2)
The dataset is scaled down to a smaller range using the Feature Scaling option. In this, both the X_train and X_test values are scaled down to smaller values to improve the speed of the program.
from sklearn.preprocessing import StandardScalersc = StandardScaler()X_train = sc.fit_transform(X_train)X_test = sc.transform(X_test)
In this step, we introduce the class GaussianNB that is used from the sklearn.naive_bayes library. Here, we have used a Gaussian model, there are several other models such as Bernoulli, Categorical and Multinomial. Here, we assign the GaussianNB class to the variable classifier and fit the X_train and y_train values to it for training purpose.
from sklearn.naive_bayes import GaussianNBclassifier = GaussianNB()classifier.fit(X_train, y_train)
Once the model is trained, we use the the classifier.predict() to predict the values for the Test set and the values predicted are stored to the variable y_pred.
y_pred = classifier.predict(X_test) y_pred
This is a step that is mostly used in classification techniques. In this, we see the Accuracy of the trained model and plot the confusion matrix.
The confusion matrix is a table that is used to show the number of correct and incorrect predictions on a classification problem when the real values of the Test Set are known. It is of the format
The True values are the number of correct predictions made.
from sklearn.metrics import confusion_matrixcm = confusion_matrix(y_test, y_pred)from sklearn.metrics import accuracy_score print ("Accuracy : ", accuracy_score(y_test, y_pred))cm>>Accuracy : 0.9666666666666667>>array([[14, 0, 0], [ 0, 7, 0], [ 0, 1, 8]])
From the above confusion matrix, we infer that, out of 30 test set data, 29 were correctly classified and only 1 was incorrectly classified. This gives us a high accuracy of 96.67%.
In this step, a Pandas DataFrame is created to compare the classified values of both the original Test set (y_test) and the predicted results (y_pred).
df = pd.DataFrame({'Real Values':y_test, 'Predicted Values':y_pred})df>> Real Values Predicted Valuessetosa setosasetosa setosavirginica virginicaversicolor versicolorsetosa setosasetosa setosa... ... ... ... ...virginica versicolorvirginica virginicasetosa setosasetosa setosaversicolor versicolorversicolor versicolor
This step is an additional step which is not much informative as the Confusion matrix and is mainly used in regression to check the accuracy of the predicted value.
As you can see, there is one incorrect prediction that has predicted versicolor instead of virginica.
Thus in this story, we have successfully been able to build a Naive Bayes Classification Model that is able to classify a flower depending upon 4 characteristic features. This model can be implemented and tested with several other classification datasets that are available on the net.
I am also attaching the link to my GitHub repository where you can download this Google Colab notebook and the data files for your reference.
github.com
You can also find the explanation of the program for other Classification models below:
Logistic Regression
K-Nearest Neighbours (KNN) Classification
Support Vector Machine (SVM) Classification
Naive Bayes Classification
Random Forest Classification (Coming Soon)
We will come across the more complex models of Regression, Classification and Clustering in the upcoming articles. Till then, Happy Machine Learning!
|
[
{
"code": null,
"e": 506,
"s": 172,
"text": "In the previous stories, I had given an explanation of the program for implementation of various Regression models. Also, I had described the implementation of the Logistic Regression, KNN and SVM Classification model. In this article, we shall go through the algorithm of the famous Naive Bayes Classification model with an example."
},
{
"code": null,
"e": 730,
"s": 506,
"text": "Naive Bayes is one such algorithm in classification that can never be overlooked upon due to its special characteristic of being “naive”. It makes the assumption that features of a measurement are independent of each other."
},
{
"code": null,
"e": 1049,
"s": 730,
"text": "For example, an animal may be considered as a cat if it has cat eyes, whiskers and a long tail. Even if these features depend on each other or upon the existence of the other features, all of these properties independently contribute to the probability that this animal is a cat and that is why it is known as ‘Naive’."
},
{
"code": null,
"e": 1410,
"s": 1049,
"text": "According to Bayes Theorem, the various features are mutually independent. For two independent events, P(A,B) = P(A)P(B). This assumption of Bayes Theorem is probably never encountered in practice, hence it accounts for the “naive” part in Naive Bayes. Bayes’ Theorem is stated as: P(a|b) = (P(b|a) * P(a)) / P(b). Where P(a|b) is the probability of a given b."
},
{
"code": null,
"e": 1613,
"s": 1410,
"text": "Let us understand this algorithm with a simple example. The Student will be a pass if he wears a “red” color dress on the exam day. We can solve it using above discussed method of posterior probability."
},
{
"code": null,
"e": 1681,
"s": 1613,
"text": "By Bayes Theorem, P(Pass| Red) = P( Red| Pass) * P(Pass) / P (Red)."
},
{
"code": null,
"e": 1862,
"s": 1681,
"text": "From the values, let us assume P (Red|Pass) = 3/9 = 0.33, P(Red) = 5/14 = 0.36, P( Pass)= 9/14 = 0.64. Now, P (Pass| Red) = 0.33 * 0.64 / 0.36 = 0.60, which has higher probability."
},
{
"code": null,
"e": 1984,
"s": 1862,
"text": "In this way, Naive Bayes uses a similar method to predict the probability of different class based on various attributes."
},
{
"code": null,
"e": 2339,
"s": 1984,
"text": "To implement the Naive Bayes Classification, we shall use a very famous Iris Flower Dataset that consists of 3 classes of flowers. In this, there are 4 independent variables namely the, sepal_length, sepal_width, petal_length and petal_width. The dependent variable is the species which we will predict using the four independent features of the flowers."
},
{
"code": null,
"e": 2621,
"s": 2339,
"text": "There are 3 classes of species namely setosa, versicolor and the virginica. This dataset was originally introduced in 1936 by Ronald Fisher. Using the various features of the flower (independent variables), we have to classify a given flower using Naive Bayes Classification model."
},
{
"code": null,
"e": 2739,
"s": 2621,
"text": "As always, the first step will always include importing the libraries which are the NumPy, Pandas and the Matplotlib."
},
{
"code": null,
"e": 2808,
"s": 2739,
"text": "import numpy as npimport matplotlib.pyplot as pltimport pandas as pd"
},
{
"code": null,
"e": 3103,
"s": 2808,
"text": "In this step, we shall import the Iris Flower dataset which is stored in my github repository as IrisDataset.csv and save it to the variable dataset. After this, we assign the 4 independent variables to X and the dependent variable ‘species’ to Y. The first 5 rows of the dataset are displayed."
},
{
"code": null,
"e": 3656,
"s": 3103,
"text": "dataset = pd.read_csv('https://raw.githubusercontent.com/mk-gurucharan/Classification/master/IrisDataset.csv')X = dataset.iloc[:,:4].valuesy = dataset['species'].valuesdataset.head(5)>>sepal_length sepal_width petal_length petal_width species5.1 3.5 1.4 0.2 setosa4.9 3.0 1.4 0.2 setosa4.7 3.2 1.3 0.2 setosa4.6 3.1 1.5 0.2 setosa5.0 3.6 1.4 0.2 setosa"
},
{
"code": null,
"e": 4143,
"s": 3656,
"text": "Once we have obtained our data set, we have to split the data into the training set and the test set. In this data set, there are 150 rows with 50 rows of each of the 3 classes. As each class is given in a continuous order, we need to randomly split the dataset. Here, we have the test_size=0.2, which means that 20% of the dataset will be used for testing purpose as the test set and the remaining 80% will be used as the training set for training the Naive Bayes classification model."
},
{
"code": null,
"e": 4270,
"s": 4143,
"text": "from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2)"
},
{
"code": null,
"e": 4465,
"s": 4270,
"text": "The dataset is scaled down to a smaller range using the Feature Scaling option. In this, both the X_train and X_test values are scaled down to smaller values to improve the speed of the program."
},
{
"code": null,
"e": 4599,
"s": 4465,
"text": "from sklearn.preprocessing import StandardScalersc = StandardScaler()X_train = sc.fit_transform(X_train)X_test = sc.transform(X_test)"
},
{
"code": null,
"e": 4945,
"s": 4599,
"text": "In this step, we introduce the class GaussianNB that is used from the sklearn.naive_bayes library. Here, we have used a Gaussian model, there are several other models such as Bernoulli, Categorical and Multinomial. Here, we assign the GaussianNB class to the variable classifier and fit the X_train and y_train values to it for training purpose."
},
{
"code": null,
"e": 5045,
"s": 4945,
"text": "from sklearn.naive_bayes import GaussianNBclassifier = GaussianNB()classifier.fit(X_train, y_train)"
},
{
"code": null,
"e": 5207,
"s": 5045,
"text": "Once the model is trained, we use the the classifier.predict() to predict the values for the Test set and the values predicted are stored to the variable y_pred."
},
{
"code": null,
"e": 5250,
"s": 5207,
"text": "y_pred = classifier.predict(X_test) y_pred"
},
{
"code": null,
"e": 5396,
"s": 5250,
"text": "This is a step that is mostly used in classification techniques. In this, we see the Accuracy of the trained model and plot the confusion matrix."
},
{
"code": null,
"e": 5593,
"s": 5396,
"text": "The confusion matrix is a table that is used to show the number of correct and incorrect predictions on a classification problem when the real values of the Test Set are known. It is of the format"
},
{
"code": null,
"e": 5653,
"s": 5593,
"text": "The True values are the number of correct predictions made."
},
{
"code": null,
"e": 5928,
"s": 5653,
"text": "from sklearn.metrics import confusion_matrixcm = confusion_matrix(y_test, y_pred)from sklearn.metrics import accuracy_score print (\"Accuracy : \", accuracy_score(y_test, y_pred))cm>>Accuracy : 0.9666666666666667>>array([[14, 0, 0], [ 0, 7, 0], [ 0, 1, 8]])"
},
{
"code": null,
"e": 6110,
"s": 5928,
"text": "From the above confusion matrix, we infer that, out of 30 test set data, 29 were correctly classified and only 1 was incorrectly classified. This gives us a high accuracy of 96.67%."
},
{
"code": null,
"e": 6262,
"s": 6110,
"text": "In this step, a Pandas DataFrame is created to compare the classified values of both the original Test set (y_test) and the predicted results (y_pred)."
},
{
"code": null,
"e": 6652,
"s": 6262,
"text": "df = pd.DataFrame({'Real Values':y_test, 'Predicted Values':y_pred})df>> Real Values Predicted Valuessetosa setosasetosa setosavirginica virginicaversicolor versicolorsetosa setosasetosa setosa... ... ... ... ...virginica versicolorvirginica virginicasetosa setosasetosa setosaversicolor versicolorversicolor versicolor"
},
{
"code": null,
"e": 6817,
"s": 6652,
"text": "This step is an additional step which is not much informative as the Confusion matrix and is mainly used in regression to check the accuracy of the predicted value."
},
{
"code": null,
"e": 6919,
"s": 6817,
"text": "As you can see, there is one incorrect prediction that has predicted versicolor instead of virginica."
},
{
"code": null,
"e": 7205,
"s": 6919,
"text": "Thus in this story, we have successfully been able to build a Naive Bayes Classification Model that is able to classify a flower depending upon 4 characteristic features. This model can be implemented and tested with several other classification datasets that are available on the net."
},
{
"code": null,
"e": 7347,
"s": 7205,
"text": "I am also attaching the link to my GitHub repository where you can download this Google Colab notebook and the data files for your reference."
},
{
"code": null,
"e": 7358,
"s": 7347,
"text": "github.com"
},
{
"code": null,
"e": 7446,
"s": 7358,
"text": "You can also find the explanation of the program for other Classification models below:"
},
{
"code": null,
"e": 7466,
"s": 7446,
"text": "Logistic Regression"
},
{
"code": null,
"e": 7508,
"s": 7466,
"text": "K-Nearest Neighbours (KNN) Classification"
},
{
"code": null,
"e": 7552,
"s": 7508,
"text": "Support Vector Machine (SVM) Classification"
},
{
"code": null,
"e": 7579,
"s": 7552,
"text": "Naive Bayes Classification"
},
{
"code": null,
"e": 7622,
"s": 7579,
"text": "Random Forest Classification (Coming Soon)"
}
] |
Currency Converter in Python - GeeksforGeeks
|
12 Dec, 2019
Python is a very versatile programming language. Python is being used in almost each mainstream technology and one can develop literally any application with it. Let’s see a Python program to convert the currency of one country to that of another country. To use this service, one must need the API key, which can be get form here.We will use fixer API to get the live conversion rates and convert the corresponding amount.
requests: This module does not built-in with python. To install it type the below command in the terminal or cmd.
pip install requests
Below is the implementation:
# Python program to convert the currency# of one country to that of another country # Import the modules neededimport requests class Currency_convertor: # empty dict to store the conversion rates rates = {} def __init__(self, url): data = requests.get(url).json() # Extracting only the rates from the json data self.rates = data["rates"] # function to do a simple cross multiplication between # the amount and the conversion rates def convert(self, from_currency, to_currency, amount): initial_amount = amount if from_currency != 'EUR' : amount = amount / self.rates[from_currency] # limiting the precision to 2 decimal places amount = round(amount * self.rates[to_currency], 2) print('{} {} = {} {}'.format(initial_amount, from_currency, amount, to_currency)) # Driver codeif __name__ == "__main__": # YOUR_ACCESS_KEY = 'GET YOUR ACCESS KEY FROM fixer.io' url = str.__add__('http://data.fixer.io/api/latest?access_key=', YOUR_ACCESS_KEY) c = Currency_convertor(url) from_country = input("From Country: ") to_country = input("TO Country: ") amount = int(input("Amount: ")) c.convert(from_country, to_country, amount)
Input :
From Country: USD
TO Country: INR
Amount: 1
Output :
1 USD = 70.69 INR
python-utility
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Defaultdict in Python
Different ways to create Pandas Dataframe
sum() function in Python
Deque in Python
How to Install PIP on Windows ?
Python String | replace()
Convert integer to string in Python
Stack in Python
|
[
{
"code": null,
"e": 24037,
"s": 24009,
"text": "\n12 Dec, 2019"
},
{
"code": null,
"e": 24461,
"s": 24037,
"text": "Python is a very versatile programming language. Python is being used in almost each mainstream technology and one can develop literally any application with it. Let’s see a Python program to convert the currency of one country to that of another country. To use this service, one must need the API key, which can be get form here.We will use fixer API to get the live conversion rates and convert the corresponding amount."
},
{
"code": null,
"e": 24575,
"s": 24461,
"text": "requests: This module does not built-in with python. To install it type the below command in the terminal or cmd."
},
{
"code": null,
"e": 24597,
"s": 24575,
"text": "pip install requests\n"
},
{
"code": null,
"e": 24626,
"s": 24597,
"text": "Below is the implementation:"
},
{
"code": "# Python program to convert the currency# of one country to that of another country # Import the modules neededimport requests class Currency_convertor: # empty dict to store the conversion rates rates = {} def __init__(self, url): data = requests.get(url).json() # Extracting only the rates from the json data self.rates = data[\"rates\"] # function to do a simple cross multiplication between # the amount and the conversion rates def convert(self, from_currency, to_currency, amount): initial_amount = amount if from_currency != 'EUR' : amount = amount / self.rates[from_currency] # limiting the precision to 2 decimal places amount = round(amount * self.rates[to_currency], 2) print('{} {} = {} {}'.format(initial_amount, from_currency, amount, to_currency)) # Driver codeif __name__ == \"__main__\": # YOUR_ACCESS_KEY = 'GET YOUR ACCESS KEY FROM fixer.io' url = str.__add__('http://data.fixer.io/api/latest?access_key=', YOUR_ACCESS_KEY) c = Currency_convertor(url) from_country = input(\"From Country: \") to_country = input(\"TO Country: \") amount = int(input(\"Amount: \")) c.convert(from_country, to_country, amount)",
"e": 25868,
"s": 24626,
"text": null
},
{
"code": null,
"e": 25876,
"s": 25868,
"text": "Input :"
},
{
"code": null,
"e": 25924,
"s": 25876,
"text": "From Country: USD \nTO Country: INR \nAmount: 1 \n"
},
{
"code": null,
"e": 25933,
"s": 25924,
"text": "Output :"
},
{
"code": null,
"e": 25952,
"s": 25933,
"text": "1 USD = 70.69 INR\n"
},
{
"code": null,
"e": 25967,
"s": 25952,
"text": "python-utility"
},
{
"code": null,
"e": 25974,
"s": 25967,
"text": "Python"
},
{
"code": null,
"e": 25993,
"s": 25974,
"text": "Technical Scripter"
},
{
"code": null,
"e": 26091,
"s": 25993,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26100,
"s": 26091,
"text": "Comments"
},
{
"code": null,
"e": 26113,
"s": 26100,
"text": "Old Comments"
},
{
"code": null,
"e": 26131,
"s": 26113,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26166,
"s": 26131,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26188,
"s": 26166,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26230,
"s": 26188,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26255,
"s": 26230,
"text": "sum() function in Python"
},
{
"code": null,
"e": 26271,
"s": 26255,
"text": "Deque in Python"
},
{
"code": null,
"e": 26303,
"s": 26271,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26329,
"s": 26303,
"text": "Python String | replace()"
},
{
"code": null,
"e": 26365,
"s": 26329,
"text": "Convert integer to string in Python"
}
] |
How to Add Cookies in Postman?
|
We can add cookies in Postman. To add a cookie, the below steps need to be followed −
Step1 − Navigate to the Params tab below the address bar and then click on Cookies.
Step2 − The MANAGE COOKIES window shall open. It lists down all the current cookies. To add a cookie, click on the Add Cookie button. An edit box with pre-populated values of the cookie are displayed. We can update the value and Save it.
Step3 − Send the request to the server.
Step4 − After the request has been successfully completed, the Cookies tab in the Response will show the newly added cookie – Cookie_Postman.
We can also add a cookie programmatically and not from the GUI. For that, we have to first create a Cookie jar object with the help of the pm.cookies.jar method.
const cnt = pm.cookies.jar()
Then to create a cookie we have to use the function - .set. This function takes the URL, cookie name and value as parameters.
const cnt = pm.cookies.jar();
cnt.set(URL, cookie name, cookie value, callback(error, cookie))
|
[
{
"code": null,
"e": 1148,
"s": 1062,
"text": "We can add cookies in Postman. To add a cookie, the below steps need to be followed −"
},
{
"code": null,
"e": 1232,
"s": 1148,
"text": "Step1 − Navigate to the Params tab below the address bar and then click on Cookies."
},
{
"code": null,
"e": 1470,
"s": 1232,
"text": "Step2 − The MANAGE COOKIES window shall open. It lists down all the current cookies. To add a cookie, click on the Add Cookie button. An edit box with pre-populated values of the cookie are displayed. We can update the value and Save it."
},
{
"code": null,
"e": 1510,
"s": 1470,
"text": "Step3 − Send the request to the server."
},
{
"code": null,
"e": 1652,
"s": 1510,
"text": "Step4 − After the request has been successfully completed, the Cookies tab in the Response will show the newly added cookie – Cookie_Postman."
},
{
"code": null,
"e": 1814,
"s": 1652,
"text": "We can also add a cookie programmatically and not from the GUI. For that, we have to first create a Cookie jar object with the help of the pm.cookies.jar method."
},
{
"code": null,
"e": 1843,
"s": 1814,
"text": "const cnt = pm.cookies.jar()"
},
{
"code": null,
"e": 1969,
"s": 1843,
"text": "Then to create a cookie we have to use the function - .set. This function takes the URL, cookie name and value as parameters."
},
{
"code": null,
"e": 2064,
"s": 1969,
"text": "const cnt = pm.cookies.jar();\ncnt.set(URL, cookie name, cookie value, callback(error, cookie))"
}
] |
Your Cool Folium Maps on the Web. Leveraging flask and heroku to share... | by Alberta Odamea Anim-Ayeko | Towards Data Science
|
This is the second part of the series, aimed at sharing the steps to go through to get your interactive map hosted on the web or deployed as a web application. If you’re just here for the code, here you go. This article is broken down into six sections:
∘ Introduction ∘ Files needed and file structure ∘ Deploying Using Github ∘ Deploying Using Heroku CLI ∘ Final thoughts ∘ References
You can’t just have your interactive map lying on your computer. For others to use and benefit from it, it would have to be on the web. Let’s see how we can make this possible.
Heroku needs specific files for the deployment process to go smoothly. They are:
Procfile: It tells heroku how to run our flask app. The Procfile has no file extension.
Gunicorn is a Python WSGI HTTP server, which helps heroku, our cloud application platform, communicate with Flask through a WSGI protocol.
WSGI stands for “Web Server Gateway Interface”. It is used to forward requests from a web server (such as Apache or NGINX) to a backend Python web application or framework. From there, responses are then passed back to the webserver to reply to the requestor.
Requirements file: This is a text file, which contains the libraries needed for the python file to run i.e. Flask and gunicorn, with the specific versions used. Heroku needs this to be able to create the exact environment you used to produce your exact results.
Templates folder: After creating your folium map and saving it as an html file, you need to put the_map.html into this templates folder. flask will search for it here and render it to the web application.
Python file: The python file was named app.py
In the file:
The Flask class and render_template function are imported.
app object is created, and is the instance of the Flask class, which together with gunicorn will help heroku deploy our map as a web app.
Your route decorator is created, and a function is defined for it. The decorator tells the application which URL should call the function (render_the_map()). The function returns the rendered template from the templates folder. Rendering a template means converting it into an HTML page.
Since the file will be run via the terminal(see in the paragraph below), ‘if __name__ == __main__’ evaluates to true and the app.is run.
You first have to make sure that the web app runs on your computer. If it does, it’ll run on heroku. To check this:
open a terminal
navigate to the directory you’re working in
run python app.py
If the map shows up at the address shown in the terminal, you can proceed to heroku.
File Structure
Making-Cool-Maps-In-Python/ |---> app.py |---> requirements.txt |---> Procfile |---> templates/ |---> the_map.html
By following steps below, you can deploy the map with github:
Head to heroku.com and log in or sign up
Click the create a new app button and enter an a name for it and click the create app button
Choose a deployment method — Connect to github and sign in
Choose a repository to connect to and connect
You can chose the automatic deploy option, which ensures that every change you make to your main branch affects the web app
Click the deploy branch and wait for heroku to install and detect the files in your branch
Download the CLI from here. Use the following commands:
heroku login and enter your details
heroku create ‘app-name’ where ‘app-name’ is your own application name
git push heroku master
heroku config:set DEPLOY=heroku.
heroku open or open your file via your heroku profile
I hope this was helpful. Go on then, try it and thank me later! Check out the deployed folium map here. Thanks for reading! 😃👋
I hear and I forget. I see and I remember. I do and I understand. — Confucious
What is wsgi?
Flask documentation
Stack overflow folium question
|
[
{
"code": null,
"e": 426,
"s": 172,
"text": "This is the second part of the series, aimed at sharing the steps to go through to get your interactive map hosted on the web or deployed as a web application. If you’re just here for the code, here you go. This article is broken down into six sections:"
},
{
"code": null,
"e": 559,
"s": 426,
"text": "∘ Introduction ∘ Files needed and file structure ∘ Deploying Using Github ∘ Deploying Using Heroku CLI ∘ Final thoughts ∘ References"
},
{
"code": null,
"e": 736,
"s": 559,
"text": "You can’t just have your interactive map lying on your computer. For others to use and benefit from it, it would have to be on the web. Let’s see how we can make this possible."
},
{
"code": null,
"e": 817,
"s": 736,
"text": "Heroku needs specific files for the deployment process to go smoothly. They are:"
},
{
"code": null,
"e": 905,
"s": 817,
"text": "Procfile: It tells heroku how to run our flask app. The Procfile has no file extension."
},
{
"code": null,
"e": 1044,
"s": 905,
"text": "Gunicorn is a Python WSGI HTTP server, which helps heroku, our cloud application platform, communicate with Flask through a WSGI protocol."
},
{
"code": null,
"e": 1304,
"s": 1044,
"text": "WSGI stands for “Web Server Gateway Interface”. It is used to forward requests from a web server (such as Apache or NGINX) to a backend Python web application or framework. From there, responses are then passed back to the webserver to reply to the requestor."
},
{
"code": null,
"e": 1566,
"s": 1304,
"text": "Requirements file: This is a text file, which contains the libraries needed for the python file to run i.e. Flask and gunicorn, with the specific versions used. Heroku needs this to be able to create the exact environment you used to produce your exact results."
},
{
"code": null,
"e": 1771,
"s": 1566,
"text": "Templates folder: After creating your folium map and saving it as an html file, you need to put the_map.html into this templates folder. flask will search for it here and render it to the web application."
},
{
"code": null,
"e": 1817,
"s": 1771,
"text": "Python file: The python file was named app.py"
},
{
"code": null,
"e": 1830,
"s": 1817,
"text": "In the file:"
},
{
"code": null,
"e": 1889,
"s": 1830,
"text": "The Flask class and render_template function are imported."
},
{
"code": null,
"e": 2027,
"s": 1889,
"text": "app object is created, and is the instance of the Flask class, which together with gunicorn will help heroku deploy our map as a web app."
},
{
"code": null,
"e": 2315,
"s": 2027,
"text": "Your route decorator is created, and a function is defined for it. The decorator tells the application which URL should call the function (render_the_map()). The function returns the rendered template from the templates folder. Rendering a template means converting it into an HTML page."
},
{
"code": null,
"e": 2452,
"s": 2315,
"text": "Since the file will be run via the terminal(see in the paragraph below), ‘if __name__ == __main__’ evaluates to true and the app.is run."
},
{
"code": null,
"e": 2568,
"s": 2452,
"text": "You first have to make sure that the web app runs on your computer. If it does, it’ll run on heroku. To check this:"
},
{
"code": null,
"e": 2584,
"s": 2568,
"text": "open a terminal"
},
{
"code": null,
"e": 2628,
"s": 2584,
"text": "navigate to the directory you’re working in"
},
{
"code": null,
"e": 2646,
"s": 2628,
"text": "run python app.py"
},
{
"code": null,
"e": 2731,
"s": 2646,
"text": "If the map shows up at the address shown in the terminal, you can proceed to heroku."
},
{
"code": null,
"e": 2746,
"s": 2731,
"text": "File Structure"
},
{
"code": null,
"e": 2898,
"s": 2746,
"text": "Making-Cool-Maps-In-Python/ |---> app.py |---> requirements.txt |---> Procfile |---> templates/ |---> the_map.html"
},
{
"code": null,
"e": 2960,
"s": 2898,
"text": "By following steps below, you can deploy the map with github:"
},
{
"code": null,
"e": 3001,
"s": 2960,
"text": "Head to heroku.com and log in or sign up"
},
{
"code": null,
"e": 3094,
"s": 3001,
"text": "Click the create a new app button and enter an a name for it and click the create app button"
},
{
"code": null,
"e": 3153,
"s": 3094,
"text": "Choose a deployment method — Connect to github and sign in"
},
{
"code": null,
"e": 3199,
"s": 3153,
"text": "Choose a repository to connect to and connect"
},
{
"code": null,
"e": 3323,
"s": 3199,
"text": "You can chose the automatic deploy option, which ensures that every change you make to your main branch affects the web app"
},
{
"code": null,
"e": 3414,
"s": 3323,
"text": "Click the deploy branch and wait for heroku to install and detect the files in your branch"
},
{
"code": null,
"e": 3470,
"s": 3414,
"text": "Download the CLI from here. Use the following commands:"
},
{
"code": null,
"e": 3506,
"s": 3470,
"text": "heroku login and enter your details"
},
{
"code": null,
"e": 3577,
"s": 3506,
"text": "heroku create ‘app-name’ where ‘app-name’ is your own application name"
},
{
"code": null,
"e": 3600,
"s": 3577,
"text": "git push heroku master"
},
{
"code": null,
"e": 3633,
"s": 3600,
"text": "heroku config:set DEPLOY=heroku."
},
{
"code": null,
"e": 3687,
"s": 3633,
"text": "heroku open or open your file via your heroku profile"
},
{
"code": null,
"e": 3814,
"s": 3687,
"text": "I hope this was helpful. Go on then, try it and thank me later! Check out the deployed folium map here. Thanks for reading! 😃👋"
},
{
"code": null,
"e": 3893,
"s": 3814,
"text": "I hear and I forget. I see and I remember. I do and I understand. — Confucious"
},
{
"code": null,
"e": 3907,
"s": 3893,
"text": "What is wsgi?"
},
{
"code": null,
"e": 3927,
"s": 3907,
"text": "Flask documentation"
}
] |
Keep Jupyter Notebook Running Even After Browser is Closed | by Fienny Angelina | Towards Data Science
|
Keeping the browser tab open to run Jupyter Notebook files for days is not the most exciting work. It can be troublesome. Here are some ways I found to solve the issues. Each solution has its benefits and drawbacks, so without further ado, let’s start exploring each of them!
Colaboratory, or “Colab” for short, allows us to run Python code with zero configuration and computation resources, like GPU / TPU, available. Using this, we can even run some bash commands by putting a prefix % before the CLI command. The benefit of this approach is that it is free and it allows importing files/dataset from Drive or Github. It is well integrated with Google Drive that we can write code to automatically load some dataset from Drive and save the network/result to Drive.
Yet, it has several drawbacks. First, it has limited computation usage. Once the limit is reached, it will stop running the code and shortly after, the files / variable values are lost. However, the limit is not that restricting. I found it to be good enough for training a Neural Network on some dataset, such as the Leaf Classification dataset. Moreover, it is possible to connect to a local runtime in case you need bigger computation usage/resource.
Another drawback is that you can’t close the browser tab for too long, that is for more than 90 minutes. In my experience, this can be prolonged by connecting to a local runtime.
Lastly, it may lose the log written when the tab is closed. This may be an issue when you need to keep all the log written in the Jupyter Notebook file. Some ways to handle this is to log the outputs into another file or use a specific logger.
There are ways to run a Jupyter Notebook file as a python script.
1.Convert it into a python file
The simplest way is to open the Jupyter Notebook file in a browser, click File > Download as > Python (.py). After that, we can run the output file the way we run a typical python file:
python file_name.py
However, log printed on the Jupyter Notebook files will get lost.
2.Run using command prompt directly
Another way is to run the jupyter notebook using CLI directly. It will allow us to keep all the logging printed in the jupyter notebook files throughout execution. There are two choices of program to use for this purpose, runipy or nbconvert. To install runipy or nbconvert, we can use pip/conda.
# Using pippip install ipython# Using condaconda install ipython
If we use runipy and have it installed, to run a jupyter notebook we can type:
runipy MyNotebookFileName.ipynb
To save the output of each cell back to the notebook file, run:
runipy MyNotebookFileName.ipynb
If we use nbconvert and have it installed, to run a jupyter notebook we can type:
jupyter nbconvert --to notebook --execute mynotebook.ipynb
There are several other configuration options, such as timeout, report generation, and output files generation which can be found in these two sites, for runipy and nbconvert respectively.
To keep this command running in a remote server even when we disconnect from the remote server, we can configure screen or tmux and run the Jupyter’s command inside either one of them.
However, one drawback I found from this approach is the lack of logging displayed to the user. Thus, even though the script will stop the execution in error, it may be hard to track the progress of our code. When I used this approach, I utilize nvidia-smi and htop bash command to try to guess the current state of the program.
This is by far my favorite approach. TLDR, it handles all the disadvantages of the previous methods. It allows me to see the progress of the code as well as the output of each cell. The script stays running even when I’m disconnected.
1.Configure a remote desktop on the server
You may skip this step if the server has had a remote desktop configured. This step is probably the trickiest step of all, especially when the server’s OS version is outdated.
a. Connect to the server through SSH
b. Install some packages
sudo apt updatesudo apt install -y ubuntu-desktop xrdp
PS: If you don’t have a sudo permission in the server, alternatively, you may install the package from Github using wget and build it from source. You may also need to do so to downgrade the version of xrdp if the xrdp version downloaded has some bugs or incompatibility with the OS.
c. Edit the RDP configuration file, /etc/xrdp/xrdp.ini, on the server. A minimal configuration might look like this:
[globals]bitmap_cache=yesbitmap_compression=yesport=3389crypt_level=lowchannel_code=1max_bpp=24[xrdp1]name=sesman-Xvnclib=libvnc.sousername=askpassword=askip=127.0.0.1port=ask-1
Note the port written, it is important for making connection. Also, if your server is an EC2 instance, we need to edit the security group appropriately to allow inbound TCP connection in port 3389 .
d. Restart the xrdp
sudo service xrdp restart
e. Install Window Manager for RDP connection. This involves changing the contents of a user’s .xsession file.
sudo apt install -y xfce4 xfce4-goodiesecho xfce4-session >~/.xsession
You’re ready to connect! 💃🏽💃🏽
2.Setup Remote Desktop Client in your computer
This step will allow your computer to connect to the server. The way to do it varies based on the OS of your computer.
For Linux, install vinagre and open it. Enter the IP address for the server, username and the RDP port. Then, click Connect.
For Windows or others, the above step can be done using Remote Desktop Viewer.
For Mac, I use the Microsoft Remote Desktop. Fill the form appropriately and click Add.
After that, you will be prompted to enter your credentials. Leave port as it is.
Once you’re authenticated you should see your desktop.
3.Run the jupyter notebook in the browser of the server
This can be done by typing jupyter notebook in the terminal, which will open a browser. Then, navigate to the respective jupyter notebook file in the browser and open it.
Click Cell > Run All on the toolbar.
Then close the Remote Desktop Client application. Remember not to close the browser instead! 😉😉
All done! Now you can leave the browser running in the remote desktop and disconnect to it anytime you want to. You can also check back the progress of the program by reconnecting.
|
[
{
"code": null,
"e": 448,
"s": 172,
"text": "Keeping the browser tab open to run Jupyter Notebook files for days is not the most exciting work. It can be troublesome. Here are some ways I found to solve the issues. Each solution has its benefits and drawbacks, so without further ado, let’s start exploring each of them!"
},
{
"code": null,
"e": 939,
"s": 448,
"text": "Colaboratory, or “Colab” for short, allows us to run Python code with zero configuration and computation resources, like GPU / TPU, available. Using this, we can even run some bash commands by putting a prefix % before the CLI command. The benefit of this approach is that it is free and it allows importing files/dataset from Drive or Github. It is well integrated with Google Drive that we can write code to automatically load some dataset from Drive and save the network/result to Drive."
},
{
"code": null,
"e": 1393,
"s": 939,
"text": "Yet, it has several drawbacks. First, it has limited computation usage. Once the limit is reached, it will stop running the code and shortly after, the files / variable values are lost. However, the limit is not that restricting. I found it to be good enough for training a Neural Network on some dataset, such as the Leaf Classification dataset. Moreover, it is possible to connect to a local runtime in case you need bigger computation usage/resource."
},
{
"code": null,
"e": 1572,
"s": 1393,
"text": "Another drawback is that you can’t close the browser tab for too long, that is for more than 90 minutes. In my experience, this can be prolonged by connecting to a local runtime."
},
{
"code": null,
"e": 1816,
"s": 1572,
"text": "Lastly, it may lose the log written when the tab is closed. This may be an issue when you need to keep all the log written in the Jupyter Notebook file. Some ways to handle this is to log the outputs into another file or use a specific logger."
},
{
"code": null,
"e": 1882,
"s": 1816,
"text": "There are ways to run a Jupyter Notebook file as a python script."
},
{
"code": null,
"e": 1914,
"s": 1882,
"text": "1.Convert it into a python file"
},
{
"code": null,
"e": 2100,
"s": 1914,
"text": "The simplest way is to open the Jupyter Notebook file in a browser, click File > Download as > Python (.py). After that, we can run the output file the way we run a typical python file:"
},
{
"code": null,
"e": 2120,
"s": 2100,
"text": "python file_name.py"
},
{
"code": null,
"e": 2186,
"s": 2120,
"text": "However, log printed on the Jupyter Notebook files will get lost."
},
{
"code": null,
"e": 2222,
"s": 2186,
"text": "2.Run using command prompt directly"
},
{
"code": null,
"e": 2519,
"s": 2222,
"text": "Another way is to run the jupyter notebook using CLI directly. It will allow us to keep all the logging printed in the jupyter notebook files throughout execution. There are two choices of program to use for this purpose, runipy or nbconvert. To install runipy or nbconvert, we can use pip/conda."
},
{
"code": null,
"e": 2584,
"s": 2519,
"text": "# Using pippip install ipython# Using condaconda install ipython"
},
{
"code": null,
"e": 2663,
"s": 2584,
"text": "If we use runipy and have it installed, to run a jupyter notebook we can type:"
},
{
"code": null,
"e": 2695,
"s": 2663,
"text": "runipy MyNotebookFileName.ipynb"
},
{
"code": null,
"e": 2759,
"s": 2695,
"text": "To save the output of each cell back to the notebook file, run:"
},
{
"code": null,
"e": 2791,
"s": 2759,
"text": "runipy MyNotebookFileName.ipynb"
},
{
"code": null,
"e": 2873,
"s": 2791,
"text": "If we use nbconvert and have it installed, to run a jupyter notebook we can type:"
},
{
"code": null,
"e": 2932,
"s": 2873,
"text": "jupyter nbconvert --to notebook --execute mynotebook.ipynb"
},
{
"code": null,
"e": 3121,
"s": 2932,
"text": "There are several other configuration options, such as timeout, report generation, and output files generation which can be found in these two sites, for runipy and nbconvert respectively."
},
{
"code": null,
"e": 3306,
"s": 3121,
"text": "To keep this command running in a remote server even when we disconnect from the remote server, we can configure screen or tmux and run the Jupyter’s command inside either one of them."
},
{
"code": null,
"e": 3634,
"s": 3306,
"text": "However, one drawback I found from this approach is the lack of logging displayed to the user. Thus, even though the script will stop the execution in error, it may be hard to track the progress of our code. When I used this approach, I utilize nvidia-smi and htop bash command to try to guess the current state of the program."
},
{
"code": null,
"e": 3869,
"s": 3634,
"text": "This is by far my favorite approach. TLDR, it handles all the disadvantages of the previous methods. It allows me to see the progress of the code as well as the output of each cell. The script stays running even when I’m disconnected."
},
{
"code": null,
"e": 3912,
"s": 3869,
"text": "1.Configure a remote desktop on the server"
},
{
"code": null,
"e": 4088,
"s": 3912,
"text": "You may skip this step if the server has had a remote desktop configured. This step is probably the trickiest step of all, especially when the server’s OS version is outdated."
},
{
"code": null,
"e": 4125,
"s": 4088,
"text": "a. Connect to the server through SSH"
},
{
"code": null,
"e": 4150,
"s": 4125,
"text": "b. Install some packages"
},
{
"code": null,
"e": 4205,
"s": 4150,
"text": "sudo apt updatesudo apt install -y ubuntu-desktop xrdp"
},
{
"code": null,
"e": 4489,
"s": 4205,
"text": "PS: If you don’t have a sudo permission in the server, alternatively, you may install the package from Github using wget and build it from source. You may also need to do so to downgrade the version of xrdp if the xrdp version downloaded has some bugs or incompatibility with the OS."
},
{
"code": null,
"e": 4606,
"s": 4489,
"text": "c. Edit the RDP configuration file, /etc/xrdp/xrdp.ini, on the server. A minimal configuration might look like this:"
},
{
"code": null,
"e": 4784,
"s": 4606,
"text": "[globals]bitmap_cache=yesbitmap_compression=yesport=3389crypt_level=lowchannel_code=1max_bpp=24[xrdp1]name=sesman-Xvnclib=libvnc.sousername=askpassword=askip=127.0.0.1port=ask-1"
},
{
"code": null,
"e": 4983,
"s": 4784,
"text": "Note the port written, it is important for making connection. Also, if your server is an EC2 instance, we need to edit the security group appropriately to allow inbound TCP connection in port 3389 ."
},
{
"code": null,
"e": 5003,
"s": 4983,
"text": "d. Restart the xrdp"
},
{
"code": null,
"e": 5029,
"s": 5003,
"text": "sudo service xrdp restart"
},
{
"code": null,
"e": 5139,
"s": 5029,
"text": "e. Install Window Manager for RDP connection. This involves changing the contents of a user’s .xsession file."
},
{
"code": null,
"e": 5210,
"s": 5139,
"text": "sudo apt install -y xfce4 xfce4-goodiesecho xfce4-session >~/.xsession"
},
{
"code": null,
"e": 5240,
"s": 5210,
"text": "You’re ready to connect! 💃🏽💃🏽"
},
{
"code": null,
"e": 5287,
"s": 5240,
"text": "2.Setup Remote Desktop Client in your computer"
},
{
"code": null,
"e": 5406,
"s": 5287,
"text": "This step will allow your computer to connect to the server. The way to do it varies based on the OS of your computer."
},
{
"code": null,
"e": 5531,
"s": 5406,
"text": "For Linux, install vinagre and open it. Enter the IP address for the server, username and the RDP port. Then, click Connect."
},
{
"code": null,
"e": 5610,
"s": 5531,
"text": "For Windows or others, the above step can be done using Remote Desktop Viewer."
},
{
"code": null,
"e": 5698,
"s": 5610,
"text": "For Mac, I use the Microsoft Remote Desktop. Fill the form appropriately and click Add."
},
{
"code": null,
"e": 5779,
"s": 5698,
"text": "After that, you will be prompted to enter your credentials. Leave port as it is."
},
{
"code": null,
"e": 5834,
"s": 5779,
"text": "Once you’re authenticated you should see your desktop."
},
{
"code": null,
"e": 5890,
"s": 5834,
"text": "3.Run the jupyter notebook in the browser of the server"
},
{
"code": null,
"e": 6061,
"s": 5890,
"text": "This can be done by typing jupyter notebook in the terminal, which will open a browser. Then, navigate to the respective jupyter notebook file in the browser and open it."
},
{
"code": null,
"e": 6098,
"s": 6061,
"text": "Click Cell > Run All on the toolbar."
},
{
"code": null,
"e": 6194,
"s": 6098,
"text": "Then close the Remote Desktop Client application. Remember not to close the browser instead! 😉😉"
}
] |
C# - Encapsulation
|
Encapsulation is defined 'as the process of enclosing one or more items within a physical or logical package'. Encapsulation, in object oriented programming methodology, prevents access to implementation details.
Abstraction and encapsulation are related features in object oriented programming. Abstraction allows making relevant information visible and encapsulation enables a programmer to implement the desired level of abstraction.
Encapsulation is implemented by using access specifiers. An access specifier defines the scope and visibility of a class member. C# supports the following access specifiers −
Public
Private
Protected
Internal
Protected internal
Public access specifier allows a class to expose its member variables and member functions to other functions and objects. Any public member can be accessed from outside the class.
The following example illustrates this −
using System;
namespace RectangleApplication {
class Rectangle {
//member variables
public double length;
public double width;
public double GetArea() {
return length * width;
}
public void Display() {
Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", GetArea());
}
}//end class Rectangle
class ExecuteRectangle {
static void Main(string[] args) {
Rectangle r = new Rectangle();
r.length = 4.5;
r.width = 3.5;
r.Display();
Console.ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result −
Length: 4.5
Width: 3.5
Area: 15.75
In the preceding example, the member variables length and width are declared public, so they can be accessed from the function Main() using an instance of the Rectangle class, named r.
The member function Display() and GetArea() can also access these variables directly without using any instance of the class.
The member functions Display() is also declared public, so it can also be accessed from Main() using an instance of the Rectangle class, named r.
Private access specifier allows a class to hide its member variables and member functions from other functions and objects. Only functions of the same class can access its private members. Even an instance of a class cannot access its private members.
The following example illustrates this −
using System;
namespace RectangleApplication {
class Rectangle {
//member variables
private double length;
private double width;
public void Acceptdetails() {
Console.WriteLine("Enter Length: ");
length = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Enter Width: ");
width = Convert.ToDouble(Console.ReadLine());
}
public double GetArea() {
return length * width;
}
public void Display() {
Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", GetArea());
}
}//end class Rectangle
class ExecuteRectangle {
static void Main(string[] args) {
Rectangle r = new Rectangle();
r.Acceptdetails();
r.Display();
Console.ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result −
Enter Length:
4.4
Enter Width:
3.3
Length: 4.4
Width: 3.3
Area: 14.52
In the preceding example, the member variables length and width are declared private, so they cannot be accessed from the function Main(). The member functions AcceptDetails() and Display() can access these variables. Since the member functions AcceptDetails() and Display() are declared public, they can be accessed from Main() using an instance of the Rectangle class, named r.
Protected access specifier allows a child class to access the member variables and member functions of its base class. This way it helps in implementing inheritance. We will discuss this in more details in the inheritance chapter.
Internal access specifier allows a class to expose its member variables and member functions to other functions and objects in the current assembly. In other words, any member with internal access specifier can be accessed from any class or method defined within the application in which the member is defined.
The following program illustrates this −
using System;
namespace RectangleApplication {
class Rectangle {
//member variables
internal double length;
internal double width;
double GetArea() {
return length * width;
}
public void Display() {
Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", GetArea());
}
}//end class Rectangle
class ExecuteRectangle {
static void Main(string[] args) {
Rectangle r = new Rectangle();
r.length = 4.5;
r.width = 3.5;
r.Display();
Console.ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result −
Length: 4.5
Width: 3.5
Area: 15.75
In the preceding example, notice that the member function GetArea() is not declared with any access specifier. Then what would be the default access specifier of a class member if we don't mention any? It is private.
The protected internal access specifier allows a class to hide its member variables and member functions from other class objects and functions, except a child class within the same application. This is also used while implementing inheritance.
119 Lectures
23.5 hours
Raja Biswas
37 Lectures
13 hours
Trevoir Williams
16 Lectures
1 hours
Peter Jepson
159 Lectures
21.5 hours
Ebenezer Ogbu
193 Lectures
17 hours
Arnold Higuit
24 Lectures
2.5 hours
Eric Frick
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2483,
"s": 2270,
"text": "Encapsulation is defined 'as the process of enclosing one or more items within a physical or logical package'. Encapsulation, in object oriented programming methodology, prevents access to implementation details."
},
{
"code": null,
"e": 2707,
"s": 2483,
"text": "Abstraction and encapsulation are related features in object oriented programming. Abstraction allows making relevant information visible and encapsulation enables a programmer to implement the desired level of abstraction."
},
{
"code": null,
"e": 2882,
"s": 2707,
"text": "Encapsulation is implemented by using access specifiers. An access specifier defines the scope and visibility of a class member. C# supports the following access specifiers −"
},
{
"code": null,
"e": 2889,
"s": 2882,
"text": "Public"
},
{
"code": null,
"e": 2897,
"s": 2889,
"text": "Private"
},
{
"code": null,
"e": 2907,
"s": 2897,
"text": "Protected"
},
{
"code": null,
"e": 2916,
"s": 2907,
"text": "Internal"
},
{
"code": null,
"e": 2935,
"s": 2916,
"text": "Protected internal"
},
{
"code": null,
"e": 3116,
"s": 2935,
"text": "Public access specifier allows a class to expose its member variables and member functions to other functions and objects. Any public member can be accessed from outside the class."
},
{
"code": null,
"e": 3157,
"s": 3116,
"text": "The following example illustrates this −"
},
{
"code": null,
"e": 3828,
"s": 3157,
"text": "using System;\n\nnamespace RectangleApplication {\n class Rectangle {\n //member variables\n public double length;\n public double width;\n \n public double GetArea() {\n return length * width;\n }\n public void Display() {\n Console.WriteLine(\"Length: {0}\", length);\n Console.WriteLine(\"Width: {0}\", width);\n Console.WriteLine(\"Area: {0}\", GetArea());\n }\n }//end class Rectangle\n \n class ExecuteRectangle {\n static void Main(string[] args) {\n Rectangle r = new Rectangle();\n r.length = 4.5;\n r.width = 3.5;\n r.Display();\n Console.ReadLine();\n }\n }\n}"
},
{
"code": null,
"e": 3909,
"s": 3828,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 3945,
"s": 3909,
"text": "Length: 4.5\nWidth: 3.5\nArea: 15.75\n"
},
{
"code": null,
"e": 4130,
"s": 3945,
"text": "In the preceding example, the member variables length and width are declared public, so they can be accessed from the function Main() using an instance of the Rectangle class, named r."
},
{
"code": null,
"e": 4256,
"s": 4130,
"text": "The member function Display() and GetArea() can also access these variables directly without using any instance of the class."
},
{
"code": null,
"e": 4402,
"s": 4256,
"text": "The member functions Display() is also declared public, so it can also be accessed from Main() using an instance of the Rectangle class, named r."
},
{
"code": null,
"e": 4654,
"s": 4402,
"text": "Private access specifier allows a class to hide its member variables and member functions from other functions and objects. Only functions of the same class can access its private members. Even an instance of a class cannot access its private members."
},
{
"code": null,
"e": 4695,
"s": 4654,
"text": "The following example illustrates this −"
},
{
"code": null,
"e": 5593,
"s": 4695,
"text": "using System;\n\nnamespace RectangleApplication {\n class Rectangle {\n //member variables\n private double length;\n private double width;\n \n public void Acceptdetails() {\n Console.WriteLine(\"Enter Length: \");\n length = Convert.ToDouble(Console.ReadLine());\n Console.WriteLine(\"Enter Width: \");\n width = Convert.ToDouble(Console.ReadLine());\n }\n public double GetArea() {\n return length * width;\n }\n public void Display() {\n Console.WriteLine(\"Length: {0}\", length);\n Console.WriteLine(\"Width: {0}\", width);\n Console.WriteLine(\"Area: {0}\", GetArea());\n }\n }//end class Rectangle\n \n class ExecuteRectangle {\n static void Main(string[] args) {\n Rectangle r = new Rectangle();\n r.Acceptdetails();\n r.Display();\n Console.ReadLine();\n }\n }\n}"
},
{
"code": null,
"e": 5674,
"s": 5593,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 5745,
"s": 5674,
"text": "Enter Length:\n4.4\nEnter Width:\n3.3\nLength: 4.4\nWidth: 3.3\nArea: 14.52\n"
},
{
"code": null,
"e": 6125,
"s": 5745,
"text": "In the preceding example, the member variables length and width are declared private, so they cannot be accessed from the function Main(). The member functions AcceptDetails() and Display() can access these variables. Since the member functions AcceptDetails() and Display() are declared public, they can be accessed from Main() using an instance of the Rectangle class, named r."
},
{
"code": null,
"e": 6356,
"s": 6125,
"text": "Protected access specifier allows a child class to access the member variables and member functions of its base class. This way it helps in implementing inheritance. We will discuss this in more details in the inheritance chapter."
},
{
"code": null,
"e": 6667,
"s": 6356,
"text": "Internal access specifier allows a class to expose its member variables and member functions to other functions and objects in the current assembly. In other words, any member with internal access specifier can be accessed from any class or method defined within the application in which the member is defined."
},
{
"code": null,
"e": 6708,
"s": 6667,
"text": "The following program illustrates this −"
},
{
"code": null,
"e": 7376,
"s": 6708,
"text": "using System;\n\nnamespace RectangleApplication {\n class Rectangle {\n //member variables\n internal double length;\n internal double width;\n \n double GetArea() {\n return length * width;\n }\n public void Display() {\n Console.WriteLine(\"Length: {0}\", length);\n Console.WriteLine(\"Width: {0}\", width);\n Console.WriteLine(\"Area: {0}\", GetArea());\n }\n }//end class Rectangle\n \n class ExecuteRectangle {\n static void Main(string[] args) {\n Rectangle r = new Rectangle();\n r.length = 4.5;\n r.width = 3.5;\n r.Display();\n Console.ReadLine();\n }\n }\n}"
},
{
"code": null,
"e": 7457,
"s": 7376,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 7493,
"s": 7457,
"text": "Length: 4.5\nWidth: 3.5\nArea: 15.75\n"
},
{
"code": null,
"e": 7710,
"s": 7493,
"text": "In the preceding example, notice that the member function GetArea() is not declared with any access specifier. Then what would be the default access specifier of a class member if we don't mention any? It is private."
},
{
"code": null,
"e": 7955,
"s": 7710,
"text": "The protected internal access specifier allows a class to hide its member variables and member functions from other class objects and functions, except a child class within the same application. This is also used while implementing inheritance."
},
{
"code": null,
"e": 7992,
"s": 7955,
"text": "\n 119 Lectures \n 23.5 hours \n"
},
{
"code": null,
"e": 8005,
"s": 7992,
"text": " Raja Biswas"
},
{
"code": null,
"e": 8039,
"s": 8005,
"text": "\n 37 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 8057,
"s": 8039,
"text": " Trevoir Williams"
},
{
"code": null,
"e": 8090,
"s": 8057,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8104,
"s": 8090,
"text": " Peter Jepson"
},
{
"code": null,
"e": 8141,
"s": 8104,
"text": "\n 159 Lectures \n 21.5 hours \n"
},
{
"code": null,
"e": 8156,
"s": 8141,
"text": " Ebenezer Ogbu"
},
{
"code": null,
"e": 8191,
"s": 8156,
"text": "\n 193 Lectures \n 17 hours \n"
},
{
"code": null,
"e": 8206,
"s": 8191,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 8241,
"s": 8206,
"text": "\n 24 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 8253,
"s": 8241,
"text": " Eric Frick"
},
{
"code": null,
"e": 8260,
"s": 8253,
"text": " Print"
},
{
"code": null,
"e": 8271,
"s": 8260,
"text": " Add Notes"
}
] |
Instruction type ANA R in 8085 Microprocessor
|
In 8085 Instruction set, ANA is a mnemonic, which stands for “ANd Accumulator” and “R” stands for any one of the following registers, or memory location M pointed by HL pair.
R = A, B, C, D, E, H, L, or M
This instruction is used to AND contents of R with Accumulator’s content. The result thus produced for this AND operation will be stored back in to the Accumulator over writing its previous content. As R can have any of the eight values, there are eight opcodes for this type of instruction. It occupies only 1-Byte in memory.
Let us consider ANA E is an example instruction of this type. As it is a 1-Byte instruction so in memory only a single Byte will get allocated for it during execution. Let us consider the initial content of Accumulator is ABH and register E is CDH. So after The result of execution of this instruction has been depicted in the following tracing table −
(E)
(A)
(F)
The internal calculation will be done as shown below −
(A) ABH ---> 1010 1011
(d8) CDH ---> 1100 1101
---------
ANA E ---> 1000 1001 (89H)
The timing diagram against this instruction ANA E execution is as follows −
Summary − So this instruction ANA E requires 1-Byte, 1-Machine Cycle (Opcode Fetch) and 4 T-States for execution as shown in the timing diagram.
|
[
{
"code": null,
"e": 1237,
"s": 1062,
"text": "In 8085 Instruction set, ANA is a mnemonic, which stands for “ANd Accumulator” and “R” stands for any one of the following registers, or memory location M pointed by HL pair."
},
{
"code": null,
"e": 1268,
"s": 1237,
"text": "R = A, B, C, D, E, H, L, or M\n"
},
{
"code": null,
"e": 1595,
"s": 1268,
"text": "This instruction is used to AND contents of R with Accumulator’s content. The result thus produced for this AND operation will be stored back in to the Accumulator over writing its previous content. As R can have any of the eight values, there are eight opcodes for this type of instruction. It occupies only 1-Byte in memory."
},
{
"code": null,
"e": 1948,
"s": 1595,
"text": "Let us consider ANA E is an example instruction of this type. As it is a 1-Byte instruction so in memory only a single Byte will get allocated for it during execution. Let us consider the initial content of Accumulator is ABH and register E is CDH. So after The result of execution of this instruction has been depicted in the following tracing table −"
},
{
"code": null,
"e": 1952,
"s": 1948,
"text": "(E)"
},
{
"code": null,
"e": 1956,
"s": 1952,
"text": "(A)"
},
{
"code": null,
"e": 1960,
"s": 1956,
"text": "(F)"
},
{
"code": null,
"e": 2015,
"s": 1960,
"text": "The internal calculation will be done as shown below −"
},
{
"code": null,
"e": 2120,
"s": 2015,
"text": "(A) ABH ---> 1010 1011\n(d8) CDH ---> 1100 1101\n ---------\n ANA E ---> 1000 1001 (89H)\n"
},
{
"code": null,
"e": 2196,
"s": 2120,
"text": "The timing diagram against this instruction ANA E execution is as follows −"
},
{
"code": null,
"e": 2341,
"s": 2196,
"text": "Summary − So this instruction ANA E requires 1-Byte, 1-Machine Cycle (Opcode Fetch) and 4 T-States for execution as shown in the timing diagram."
}
] |
Best Practices for Writing a Dockerfile - GeeksforGeeks
|
21 Oct, 2020
If you are a Docker developer or you have been trying to get your hands dirty on Docker, you must have noticed the importance of creating an efficient dockerfile. A Dockerfile allows you to mention a sequence of instructions that are executed step by step and each execution creates an intermediate image layer on top of the base image. After executing the last instruction, you get your final Docker image. It helps you automate the entire process and helps to keep track of all the changes that you make. Basically, it’s a blueprint of your image.
The performance of the Docker Container can vary depending upon the sequence of steps you have specified in your dockerfile. Thus, it’s very important that you take the utmost care of the steps that you include inside your dockerfile. In this article, we are going to discuss the best practices that you can adopt in order to make sure that your final Docker Image builds and runs efficiently with low resource consumption.
If you install unnecessary packages in your dockerfile, it will increase the build time and the size of the image. Also, each time you make changes in the dockerfile, you will have to go through all the steps to build that same large image again and again. This creates a cascading downward effect on the performance. To avoid this, it’s always advised that only include those packages that are of utmost importance and try avoiding installing the same packages again and again.
You can use a requirements file to install all the packages you require. Use the command below to do so.
RUN pip3 install -r requirements.txt
Each RUN command creates a cacheable unit and builds a new intermediate image layer every time. You can avoid this by chaining all your RUN commands into a single RUN command. Also, try to avoid chaining too much cacheable RUN commands because it would then lead to the creation of a large cache and would ultimately lead to cache burst.
RUN apt-get -y install firefox
RUN apt-get -y install vim
RUN apt-get -y update
The above commands can be chained into a single RUN command.
RUN apt-get -y install firefox \
&& apt-get -y install vim \
&& apt-get -y update
Similar to .gitignore file, you can specify files and directories inside .dockerignore file which you would like to exclude from your Docker build context. This would result in removing unnecessary files from your Docker Container, reduce the size of the Docker Image, and boost up the build performance.
Include the most frequently changing statements at the end of your dockerfile. The reason behind this is that when you change a statement in your dockerfile, its cache gets invalidated and all the subsequent statements cache will also break. For example, include RUN commands to the top and COPY commands to the bottom. Include the CMD, ENTRYPOINT commands at the end of the dockerfile.
You can use the –no-install-recommends flag while building the image. It will tell the apt package manager to not install redundant dependencies. Installing unnecessary packages only increases the build time and size of the image which would lead to degraded performance.
To conclude, how not choosing the proper order while writing your dockerfile can increase the build time, size of the image, and decrease the performance of the whole process. We also discussed some of the top tips you can follow to improve the overall build performance, reduce the number of caches that builds an intermediate image layer.
AWS
Docker Container
How To
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install FFmpeg on Windows?
How to Set Git Username and Password in GitBash?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Install Jupyter Notebook on MacOS?
How to Check the OS Version in Linux?
Sed Command in Linux/Unix with examples
AWK command in Unix/Linux with examples
grep command in Unix/Linux
cut command in Linux with examples
TCP Server-Client implementation in C
|
[
{
"code": null,
"e": 24858,
"s": 24830,
"text": "\n21 Oct, 2020"
},
{
"code": null,
"e": 25408,
"s": 24858,
"text": "If you are a Docker developer or you have been trying to get your hands dirty on Docker, you must have noticed the importance of creating an efficient dockerfile. A Dockerfile allows you to mention a sequence of instructions that are executed step by step and each execution creates an intermediate image layer on top of the base image. After executing the last instruction, you get your final Docker image. It helps you automate the entire process and helps to keep track of all the changes that you make. Basically, it’s a blueprint of your image."
},
{
"code": null,
"e": 25833,
"s": 25408,
"text": "The performance of the Docker Container can vary depending upon the sequence of steps you have specified in your dockerfile. Thus, it’s very important that you take the utmost care of the steps that you include inside your dockerfile. In this article, we are going to discuss the best practices that you can adopt in order to make sure that your final Docker Image builds and runs efficiently with low resource consumption. "
},
{
"code": null,
"e": 26313,
"s": 25833,
"text": "If you install unnecessary packages in your dockerfile, it will increase the build time and the size of the image. Also, each time you make changes in the dockerfile, you will have to go through all the steps to build that same large image again and again. This creates a cascading downward effect on the performance. To avoid this, it’s always advised that only include those packages that are of utmost importance and try avoiding installing the same packages again and again. "
},
{
"code": null,
"e": 26418,
"s": 26313,
"text": "You can use a requirements file to install all the packages you require. Use the command below to do so."
},
{
"code": null,
"e": 26456,
"s": 26418,
"text": "RUN pip3 install -r requirements.txt\n"
},
{
"code": null,
"e": 26794,
"s": 26456,
"text": "Each RUN command creates a cacheable unit and builds a new intermediate image layer every time. You can avoid this by chaining all your RUN commands into a single RUN command. Also, try to avoid chaining too much cacheable RUN commands because it would then lead to the creation of a large cache and would ultimately lead to cache burst."
},
{
"code": null,
"e": 26875,
"s": 26794,
"text": "RUN apt-get -y install firefox\nRUN apt-get -y install vim\nRUN apt-get -y update\n"
},
{
"code": null,
"e": 26936,
"s": 26875,
"text": "The above commands can be chained into a single RUN command."
},
{
"code": null,
"e": 27025,
"s": 26936,
"text": "RUN apt-get -y install firefox \\\n && apt-get -y install vim \\\n && apt-get -y update\n"
},
{
"code": null,
"e": 27330,
"s": 27025,
"text": "Similar to .gitignore file, you can specify files and directories inside .dockerignore file which you would like to exclude from your Docker build context. This would result in removing unnecessary files from your Docker Container, reduce the size of the Docker Image, and boost up the build performance."
},
{
"code": null,
"e": 27717,
"s": 27330,
"text": "Include the most frequently changing statements at the end of your dockerfile. The reason behind this is that when you change a statement in your dockerfile, its cache gets invalidated and all the subsequent statements cache will also break. For example, include RUN commands to the top and COPY commands to the bottom. Include the CMD, ENTRYPOINT commands at the end of the dockerfile."
},
{
"code": null,
"e": 27989,
"s": 27717,
"text": "You can use the –no-install-recommends flag while building the image. It will tell the apt package manager to not install redundant dependencies. Installing unnecessary packages only increases the build time and size of the image which would lead to degraded performance."
},
{
"code": null,
"e": 28331,
"s": 27989,
"text": "To conclude, how not choosing the proper order while writing your dockerfile can increase the build time, size of the image, and decrease the performance of the whole process. We also discussed some of the top tips you can follow to improve the overall build performance, reduce the number of caches that builds an intermediate image layer. "
},
{
"code": null,
"e": 28335,
"s": 28331,
"text": "AWS"
},
{
"code": null,
"e": 28352,
"s": 28335,
"text": "Docker Container"
},
{
"code": null,
"e": 28359,
"s": 28352,
"text": "How To"
},
{
"code": null,
"e": 28370,
"s": 28359,
"text": "Linux-Unix"
},
{
"code": null,
"e": 28468,
"s": 28370,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28502,
"s": 28468,
"text": "How to Install FFmpeg on Windows?"
},
{
"code": null,
"e": 28551,
"s": 28502,
"text": "How to Set Git Username and Password in GitBash?"
},
{
"code": null,
"e": 28609,
"s": 28551,
"text": "How to Add External JAR File to an IntelliJ IDEA Project?"
},
{
"code": null,
"e": 28651,
"s": 28609,
"text": "How to Install Jupyter Notebook on MacOS?"
},
{
"code": null,
"e": 28689,
"s": 28651,
"text": "How to Check the OS Version in Linux?"
},
{
"code": null,
"e": 28729,
"s": 28689,
"text": "Sed Command in Linux/Unix with examples"
},
{
"code": null,
"e": 28769,
"s": 28729,
"text": "AWK command in Unix/Linux with examples"
},
{
"code": null,
"e": 28796,
"s": 28769,
"text": "grep command in Unix/Linux"
},
{
"code": null,
"e": 28831,
"s": 28796,
"text": "cut command in Linux with examples"
}
] |
Build a DFA to accept a binary string containing "01" i times and "1" 2j times - GeeksforGeeks
|
07 Jun, 2021
Given a binary string str, the task is to build a DFA that accepts given binary string if it contains “01” i times and “1” 2j times, i.e.,
Examples:
Input: str = “011111” Output: Accepted Explanation: The string follows the language as: (01)1(1)2*2
Input: str = “01111” Output: Not Accepted
DFA or Deterministic Finite Automata is a finite state machine which accepts a string(under some specific condition) if it reaches a final state, otherwise rejects it.In DFA, there is no concept of memory, therefore we have to check the string character by character, beginning with the 0th character. The input set of characters for the problem is {0, 1}. For a DFA to be valid, there must a transition rule defined for each symbol of the input set at every state to a valid state. Therefore, the following steps are followed to design the DFA:
Create initial stage and make the transition of 0 and 1 to next possible state.Transition of 0 is always followed by transition of 1.Make an initial state and transit its input alphabets, i.e, 0 and 1 to two different states.Check for acceptance of string after each transition to ignore errors.First, make DfA for minimum length string then go ahead step by step.Define Final State(s) according to the acceptance of string.
Create initial stage and make the transition of 0 and 1 to next possible state.
Transition of 0 is always followed by transition of 1.
Make an initial state and transit its input alphabets, i.e, 0 and 1 to two different states.
Check for acceptance of string after each transition to ignore errors.
First, make DfA for minimum length string then go ahead step by step.
Define Final State(s) according to the acceptance of string.
Step by Step Approach to design a DFA:
Step 1: Minimum possible acceptable string is 0111, i.e, (01)1 (11)1. So, create an initial state “A” that make transition of 0 to state “B” and then transition of 1 from “B” to state “C” then transition of 1 from “C” to “D”, then transition of 1 from “D” to “E” as shown in diagram make this stage “E” is final state.
Step 2: Now, think about the string having consecutive (01) and then followed by consecutive (11) to end the string. Hence, when i>1, make a transition of “0” from state “C” to state “B” and make a transition of “1” from the state “E” to state “D”. Hence, strings like 010111, 011111, 0101111111, etc. are acceptable now.
Step 3: We have done with all kind of strings possible to accept. But, there are few input alphabets which are not transited to any of the states. In this case, all these kind of input will be sent to some dead state to block their further transitions that are not acceptable. Input alphabets of the dead state will be sent to the dead state itself. Therefore, the final design of the DFA is:
Below is the implementation of the above approach:
Java
Python3
C#
Javascript
// Java code for the above DFAimport java.util.*; class GFG{ // Function for the state Astatic void checkstatea(String n){ if (n.length() % 2 != 0 || n.length() < 4) System.out.print("string not accepted"); else { int i = 0; // State transition to B // if the character is 0 if (n.charAt(i) == '0') stateb(n.substring(1)); else System.out.print("string not accepted"); }} // Function for the state Bstatic void stateb(String n){ int i = 0; if (n.charAt(i) == '0') System.out.print("string not accepted"); // State transition to C // if the character is 1 else statec(n.substring(1));} // Function for the state Cstatic void statec(String n){ int i = 0; // State transition to D // if the character is 1 if (n.charAt(i) == '1') stated(n.substring(1)); // State transition to B // if the character is 0 else stateb(n.substring(1));} // Function for the state Dstatic void stated(String n){ int i = 0; if (n.length() == 1) { if (n.charAt(i) == '1') System.out.print("string accepted"); else System.out.print("string not accepted"); } else { // State transition to E // if the character is 1 if (n.charAt(i) == '1') statee(n.substring(1)); else System.out.print("string not accepted"); }} // Function for the state E static void statee(String n){ int i = 0; if (n.length() == 1) { if (n.charAt(i) == '0') System.out.print("string not accepted"); else System.out.print("string accepted"); } else { if (n.charAt(i) == '0') System.out.print("string not accepted"); stated(n.substring(1)); }} // Driver codepublic static void main(String []args){ // Take string input String n ="011111"; // Call stateA to check the input checkstatea(n);}} // This code is contributed by pratham76
# Python3 program for the given# language # Function for the state Adef checkstatea(n): if(len(n)%2!=0 or len(n)<4): print("string not accepted") else: i=0 # State transition to B # if the character is 0 if(n[i]=='0'): stateb(n[1:]) else: print("string not accepted") # Function for the state Bdef stateb(n): i=0 if(n[i]=='0'): print("string not accepted") # State transition to C # if the character is 1 else: statec(n[1:]) # Function for the state Cdef statec(n): i=0 # State transition to D # if the character is 1 if(n[i]=='1'): stated(n[1:]) # State transition to B # if the character is 0 else: stateb(n[1:]) # Function for the state Ddef stated(n): i=0 if(len(n)==1): if(n[i]=='1'): print("string accepted") else: print("string not accepted") else: # State transition to E # if the character is 1 if(n[i]=='1'): statee(n[1:]) else: print("string not accepted") # Function for the state E def statee(n): i=0 if(len(n)==1): if(n[i]=='0'): print("string not accepted") else: print("string accepted") else: if(n[i]=='0'): print("string not accepted") stated(n[1:]) # Driver codeif __name__ == "__main__": n = "011111" checkstatea(n)
// C# code for the above DFAusing System;using System.Collections;using System.Collections.Generic;class GFG{ // Function for the state Astatic void checkstatea(string n){ if(n.Length % 2 != 0 || n.Length < 4) Console.Write("string not accepted"); else { int i = 0; // State transition to B // if the character is 0 if(n[i] == '0') stateb(n.Substring(1)); else Console.Write("string not accepted"); }} // Function for the state Bstatic void stateb(string n){ int i = 0; if(n[i] == '0') Console.Write("string not accepted"); // State transition to C // if the character is 1 else statec(n.Substring(1));} // Function for the state Cstatic void statec(string n){ int i = 0; // State transition to D // if the character is 1 if(n[i] == '1') stated(n.Substring(1)); // State transition to B // if the character is 0 else stateb(n.Substring(1));} // Function for the state Dstatic void stated(string n){ int i = 0; if(n.Length == 1) { if(n[i] == '1') Console.Write("string accepted"); else Console.Write("string not accepted"); } else { // State transition to E // if the character is 1 if(n[i] == '1') statee(n.Substring(1)); else Console.Write("string not accepted"); }} // Function for the state E static void statee(string n){ int i = 0; if(n.Length == 1) { if(n[i] == '0') Console.Write("string not accepted"); else Console.Write("string accepted"); } else { if(n[i] == '0') Console.Write("string not accepted"); stated(n.Substring(1)); }} // Driver codepublic static void Main(string []args){ // Take string input string n ="011111"; // Call stateA to check the input checkstatea(n);}} // This code is contributed by rutvik_56
<script> // JavaScript code for the above DFA // Function for the state A function checkstatea(n) { if (n.length % 2 !== 0 || n.length < 4) document.write("string not accepted"); else { var i = 0; // State transition to B // if the character is 0 if (n[i] === "0") stateb(n.substring(1)); else document.write("string not accepted"); } } // Function for the state B function stateb(n) { var i = 0; if (n[i] === "0") document.write("string not accepted"); // State transition to C // if the character is 1 else statec(n.substring(1)); } // Function for the state C function statec(n) { var i = 0; // State transition to D // if the character is 1 if (n[i] === "1") stated(n.substring(1)); // State transition to B // if the character is 0 else stateb(n.substring(1)); } // Function for the state D function stated(n) { var i = 0; if (n.length === 1) { if (n[i] === "1") document.write("string accepted"); else document.write("string not accepted"); } else { // State transition to E // if the character is 1 if (n[i] === "1") statee(n.substring(1)); else document.write("string not accepted"); } } // Function for the state E function statee(n) { var i = 0; if (n.length == 1) { if (n[i] === "0") document.write("string not accepted"); else document.write("string accepted"); } else { if (n[i] === "0") document.write("string not accepted"); stated(n.substring(1)); } } // Driver code // Take string input var n = "011111"; // Call stateA to check the input checkstatea(n); </script>
string accepted
rutvik_56
pratham76
rdtank
binary-string
DFA
Algorithms
Theory of Computation & Automata
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
SCAN (Elevator) Disk Scheduling Algorithms
Program for SSTF disk scheduling algorithm
Rail Fence Cipher - Encryption and Decryption
Quadratic Probing in Hashing
Regular Expressions, Regular Grammar and Regular Languages
Difference between DFA and NFA
Introduction of Finite Automata
Difference between Mealy machine and Moore machine
Pumping Lemma in Theory of Computation
|
[
{
"code": null,
"e": 24676,
"s": 24648,
"text": "\n07 Jun, 2021"
},
{
"code": null,
"e": 24816,
"s": 24676,
"text": "Given a binary string str, the task is to build a DFA that accepts given binary string if it contains “01” i times and “1” 2j times, i.e., "
},
{
"code": null,
"e": 24829,
"s": 24818,
"text": "Examples: "
},
{
"code": null,
"e": 24929,
"s": 24829,
"text": "Input: str = “011111” Output: Accepted Explanation: The string follows the language as: (01)1(1)2*2"
},
{
"code": null,
"e": 24971,
"s": 24929,
"text": "Input: str = “01111” Output: Not Accepted"
},
{
"code": null,
"e": 25517,
"s": 24971,
"text": "DFA or Deterministic Finite Automata is a finite state machine which accepts a string(under some specific condition) if it reaches a final state, otherwise rejects it.In DFA, there is no concept of memory, therefore we have to check the string character by character, beginning with the 0th character. The input set of characters for the problem is {0, 1}. For a DFA to be valid, there must a transition rule defined for each symbol of the input set at every state to a valid state. Therefore, the following steps are followed to design the DFA:"
},
{
"code": null,
"e": 25942,
"s": 25517,
"text": "Create initial stage and make the transition of 0 and 1 to next possible state.Transition of 0 is always followed by transition of 1.Make an initial state and transit its input alphabets, i.e, 0 and 1 to two different states.Check for acceptance of string after each transition to ignore errors.First, make DfA for minimum length string then go ahead step by step.Define Final State(s) according to the acceptance of string."
},
{
"code": null,
"e": 26022,
"s": 25942,
"text": "Create initial stage and make the transition of 0 and 1 to next possible state."
},
{
"code": null,
"e": 26077,
"s": 26022,
"text": "Transition of 0 is always followed by transition of 1."
},
{
"code": null,
"e": 26170,
"s": 26077,
"text": "Make an initial state and transit its input alphabets, i.e, 0 and 1 to two different states."
},
{
"code": null,
"e": 26241,
"s": 26170,
"text": "Check for acceptance of string after each transition to ignore errors."
},
{
"code": null,
"e": 26311,
"s": 26241,
"text": "First, make DfA for minimum length string then go ahead step by step."
},
{
"code": null,
"e": 26372,
"s": 26311,
"text": "Define Final State(s) according to the acceptance of string."
},
{
"code": null,
"e": 26413,
"s": 26372,
"text": "Step by Step Approach to design a DFA: "
},
{
"code": null,
"e": 26732,
"s": 26413,
"text": "Step 1: Minimum possible acceptable string is 0111, i.e, (01)1 (11)1. So, create an initial state “A” that make transition of 0 to state “B” and then transition of 1 from “B” to state “C” then transition of 1 from “C” to “D”, then transition of 1 from “D” to “E” as shown in diagram make this stage “E” is final state."
},
{
"code": null,
"e": 27054,
"s": 26732,
"text": "Step 2: Now, think about the string having consecutive (01) and then followed by consecutive (11) to end the string. Hence, when i>1, make a transition of “0” from state “C” to state “B” and make a transition of “1” from the state “E” to state “D”. Hence, strings like 010111, 011111, 0101111111, etc. are acceptable now."
},
{
"code": null,
"e": 27447,
"s": 27054,
"text": "Step 3: We have done with all kind of strings possible to accept. But, there are few input alphabets which are not transited to any of the states. In this case, all these kind of input will be sent to some dead state to block their further transitions that are not acceptable. Input alphabets of the dead state will be sent to the dead state itself. Therefore, the final design of the DFA is:"
},
{
"code": null,
"e": 27499,
"s": 27447,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27504,
"s": 27499,
"text": "Java"
},
{
"code": null,
"e": 27512,
"s": 27504,
"text": "Python3"
},
{
"code": null,
"e": 27515,
"s": 27512,
"text": "C#"
},
{
"code": null,
"e": 27526,
"s": 27515,
"text": "Javascript"
},
{
"code": "// Java code for the above DFAimport java.util.*; class GFG{ // Function for the state Astatic void checkstatea(String n){ if (n.length() % 2 != 0 || n.length() < 4) System.out.print(\"string not accepted\"); else { int i = 0; // State transition to B // if the character is 0 if (n.charAt(i) == '0') stateb(n.substring(1)); else System.out.print(\"string not accepted\"); }} // Function for the state Bstatic void stateb(String n){ int i = 0; if (n.charAt(i) == '0') System.out.print(\"string not accepted\"); // State transition to C // if the character is 1 else statec(n.substring(1));} // Function for the state Cstatic void statec(String n){ int i = 0; // State transition to D // if the character is 1 if (n.charAt(i) == '1') stated(n.substring(1)); // State transition to B // if the character is 0 else stateb(n.substring(1));} // Function for the state Dstatic void stated(String n){ int i = 0; if (n.length() == 1) { if (n.charAt(i) == '1') System.out.print(\"string accepted\"); else System.out.print(\"string not accepted\"); } else { // State transition to E // if the character is 1 if (n.charAt(i) == '1') statee(n.substring(1)); else System.out.print(\"string not accepted\"); }} // Function for the state E static void statee(String n){ int i = 0; if (n.length() == 1) { if (n.charAt(i) == '0') System.out.print(\"string not accepted\"); else System.out.print(\"string accepted\"); } else { if (n.charAt(i) == '0') System.out.print(\"string not accepted\"); stated(n.substring(1)); }} // Driver codepublic static void main(String []args){ // Take string input String n =\"011111\"; // Call stateA to check the input checkstatea(n);}} // This code is contributed by pratham76",
"e": 29397,
"s": 27526,
"text": null
},
{
"code": "# Python3 program for the given# language # Function for the state Adef checkstatea(n): if(len(n)%2!=0 or len(n)<4): print(\"string not accepted\") else: i=0 # State transition to B # if the character is 0 if(n[i]=='0'): stateb(n[1:]) else: print(\"string not accepted\") # Function for the state Bdef stateb(n): i=0 if(n[i]=='0'): print(\"string not accepted\") # State transition to C # if the character is 1 else: statec(n[1:]) # Function for the state Cdef statec(n): i=0 # State transition to D # if the character is 1 if(n[i]=='1'): stated(n[1:]) # State transition to B # if the character is 0 else: stateb(n[1:]) # Function for the state Ddef stated(n): i=0 if(len(n)==1): if(n[i]=='1'): print(\"string accepted\") else: print(\"string not accepted\") else: # State transition to E # if the character is 1 if(n[i]=='1'): statee(n[1:]) else: print(\"string not accepted\") # Function for the state E def statee(n): i=0 if(len(n)==1): if(n[i]=='0'): print(\"string not accepted\") else: print(\"string accepted\") else: if(n[i]=='0'): print(\"string not accepted\") stated(n[1:]) # Driver codeif __name__ == \"__main__\": n = \"011111\" checkstatea(n) ",
"e": 30877,
"s": 29397,
"text": null
},
{
"code": "// C# code for the above DFAusing System;using System.Collections;using System.Collections.Generic;class GFG{ // Function for the state Astatic void checkstatea(string n){ if(n.Length % 2 != 0 || n.Length < 4) Console.Write(\"string not accepted\"); else { int i = 0; // State transition to B // if the character is 0 if(n[i] == '0') stateb(n.Substring(1)); else Console.Write(\"string not accepted\"); }} // Function for the state Bstatic void stateb(string n){ int i = 0; if(n[i] == '0') Console.Write(\"string not accepted\"); // State transition to C // if the character is 1 else statec(n.Substring(1));} // Function for the state Cstatic void statec(string n){ int i = 0; // State transition to D // if the character is 1 if(n[i] == '1') stated(n.Substring(1)); // State transition to B // if the character is 0 else stateb(n.Substring(1));} // Function for the state Dstatic void stated(string n){ int i = 0; if(n.Length == 1) { if(n[i] == '1') Console.Write(\"string accepted\"); else Console.Write(\"string not accepted\"); } else { // State transition to E // if the character is 1 if(n[i] == '1') statee(n.Substring(1)); else Console.Write(\"string not accepted\"); }} // Function for the state E static void statee(string n){ int i = 0; if(n.Length == 1) { if(n[i] == '0') Console.Write(\"string not accepted\"); else Console.Write(\"string accepted\"); } else { if(n[i] == '0') Console.Write(\"string not accepted\"); stated(n.Substring(1)); }} // Driver codepublic static void Main(string []args){ // Take string input string n =\"011111\"; // Call stateA to check the input checkstatea(n);}} // This code is contributed by rutvik_56",
"e": 32668,
"s": 30877,
"text": null
},
{
"code": "<script> // JavaScript code for the above DFA // Function for the state A function checkstatea(n) { if (n.length % 2 !== 0 || n.length < 4) document.write(\"string not accepted\"); else { var i = 0; // State transition to B // if the character is 0 if (n[i] === \"0\") stateb(n.substring(1)); else document.write(\"string not accepted\"); } } // Function for the state B function stateb(n) { var i = 0; if (n[i] === \"0\") document.write(\"string not accepted\"); // State transition to C // if the character is 1 else statec(n.substring(1)); } // Function for the state C function statec(n) { var i = 0; // State transition to D // if the character is 1 if (n[i] === \"1\") stated(n.substring(1)); // State transition to B // if the character is 0 else stateb(n.substring(1)); } // Function for the state D function stated(n) { var i = 0; if (n.length === 1) { if (n[i] === \"1\") document.write(\"string accepted\"); else document.write(\"string not accepted\"); } else { // State transition to E // if the character is 1 if (n[i] === \"1\") statee(n.substring(1)); else document.write(\"string not accepted\"); } } // Function for the state E function statee(n) { var i = 0; if (n.length == 1) { if (n[i] === \"0\") document.write(\"string not accepted\"); else document.write(\"string accepted\"); } else { if (n[i] === \"0\") document.write(\"string not accepted\"); stated(n.substring(1)); } } // Driver code // Take string input var n = \"011111\"; // Call stateA to check the input checkstatea(n); </script>",
"e": 34575,
"s": 32668,
"text": null
},
{
"code": null,
"e": 34591,
"s": 34575,
"text": "string accepted"
},
{
"code": null,
"e": 34603,
"s": 34593,
"text": "rutvik_56"
},
{
"code": null,
"e": 34613,
"s": 34603,
"text": "pratham76"
},
{
"code": null,
"e": 34620,
"s": 34613,
"text": "rdtank"
},
{
"code": null,
"e": 34634,
"s": 34620,
"text": "binary-string"
},
{
"code": null,
"e": 34638,
"s": 34634,
"text": "DFA"
},
{
"code": null,
"e": 34649,
"s": 34638,
"text": "Algorithms"
},
{
"code": null,
"e": 34682,
"s": 34649,
"text": "Theory of Computation & Automata"
},
{
"code": null,
"e": 34693,
"s": 34682,
"text": "Algorithms"
},
{
"code": null,
"e": 34791,
"s": 34693,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34816,
"s": 34791,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 34859,
"s": 34816,
"text": "SCAN (Elevator) Disk Scheduling Algorithms"
},
{
"code": null,
"e": 34902,
"s": 34859,
"text": "Program for SSTF disk scheduling algorithm"
},
{
"code": null,
"e": 34948,
"s": 34902,
"text": "Rail Fence Cipher - Encryption and Decryption"
},
{
"code": null,
"e": 34977,
"s": 34948,
"text": "Quadratic Probing in Hashing"
},
{
"code": null,
"e": 35036,
"s": 34977,
"text": "Regular Expressions, Regular Grammar and Regular Languages"
},
{
"code": null,
"e": 35067,
"s": 35036,
"text": "Difference between DFA and NFA"
},
{
"code": null,
"e": 35099,
"s": 35067,
"text": "Introduction of Finite Automata"
},
{
"code": null,
"e": 35150,
"s": 35099,
"text": "Difference between Mealy machine and Moore machine"
}
] |
How to modify a const variable in C? - GeeksforGeeks
|
05 Sep, 2018
Whenever we use const qualifier with variable name, it becomes a read-only variable and get stored in .rodata segment. Any attempt to modify this read-only variable will then result in a compilation error: “assignment of read-only variable”.
In the below program, a read-only variable declared using the const qualifier is tried to modify:
#include<stdio.h>int main(){ const int var = 10; var = 15; printf("var = %d\n", var); return 0;}
Output:
prog.c: In function 'main':
prog.c:5:9: error: assignment of read-only variable 'var'
Changing Value of a const variable through pointer
The variables declared using const keyword, get stored in .rodata segment, but we can still access the variable through the pointer and change the value of that variable. By assigning the address of the variable to a non-constant pointer, We are casting a constant variable to a non-constant pointer. The compiler will give warning while typecasting and will discard the const qualifier. Compiler optimization is different for variables and pointers. That is why we are able to change the value of a constant variable through a non-constant pointer.
Below program illustrates this:
//Write C code here#include<stdio.h>#include<stdlib.h>int main(){ const int var = 10; int *ptr = &var; *ptr = 12; printf("var = %d\n", var); return 0;}
Output:
prog.c: In function 'main':
prog.c:6:16: warning: initialization discards 'const' qualifier
from pointer target type [-Wdiscarded-qualifiers]
int *ptr = &var;
var = 12
Note: If we try to change the value through constant pointer then we will get an error because we are trying to change the read-only segment.
C++-const keyword
C-Pointers
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
Multithreading in C
Exception Handling in C++
Arrow operator -> in C/C++ with Examples
'this' pointer in C++
UDP Server-Client implementation in C
Understanding "extern" keyword in C
Smart Pointers in C++ and How to Use Them
Multiple Inheritance in C++
How to split a string in C/C++, Python and Java?
|
[
{
"code": null,
"e": 24233,
"s": 24205,
"text": "\n05 Sep, 2018"
},
{
"code": null,
"e": 24475,
"s": 24233,
"text": "Whenever we use const qualifier with variable name, it becomes a read-only variable and get stored in .rodata segment. Any attempt to modify this read-only variable will then result in a compilation error: “assignment of read-only variable”."
},
{
"code": null,
"e": 24573,
"s": 24475,
"text": "In the below program, a read-only variable declared using the const qualifier is tried to modify:"
},
{
"code": "#include<stdio.h>int main(){ const int var = 10; var = 15; printf(\"var = %d\\n\", var); return 0;}",
"e": 24682,
"s": 24573,
"text": null
},
{
"code": null,
"e": 24690,
"s": 24682,
"text": "Output:"
},
{
"code": null,
"e": 24777,
"s": 24690,
"text": "prog.c: In function 'main':\nprog.c:5:9: error: assignment of read-only variable 'var'\n"
},
{
"code": null,
"e": 24828,
"s": 24777,
"text": "Changing Value of a const variable through pointer"
},
{
"code": null,
"e": 25378,
"s": 24828,
"text": "The variables declared using const keyword, get stored in .rodata segment, but we can still access the variable through the pointer and change the value of that variable. By assigning the address of the variable to a non-constant pointer, We are casting a constant variable to a non-constant pointer. The compiler will give warning while typecasting and will discard the const qualifier. Compiler optimization is different for variables and pointers. That is why we are able to change the value of a constant variable through a non-constant pointer."
},
{
"code": null,
"e": 25410,
"s": 25378,
"text": "Below program illustrates this:"
},
{
"code": "//Write C code here#include<stdio.h>#include<stdlib.h>int main(){ const int var = 10; int *ptr = &var; *ptr = 12; printf(\"var = %d\\n\", var); return 0;}",
"e": 25583,
"s": 25410,
"text": null
},
{
"code": null,
"e": 25591,
"s": 25583,
"text": "Output:"
},
{
"code": null,
"e": 25766,
"s": 25591,
"text": "prog.c: In function 'main':\nprog.c:6:16: warning: initialization discards 'const' qualifier \nfrom pointer target type [-Wdiscarded-qualifiers]\n int *ptr = &var;\nvar = 12\n"
},
{
"code": null,
"e": 25908,
"s": 25766,
"text": "Note: If we try to change the value through constant pointer then we will get an error because we are trying to change the read-only segment."
},
{
"code": null,
"e": 25926,
"s": 25908,
"text": "C++-const keyword"
},
{
"code": null,
"e": 25937,
"s": 25926,
"text": "C-Pointers"
},
{
"code": null,
"e": 25948,
"s": 25937,
"text": "C Language"
},
{
"code": null,
"e": 26046,
"s": 25948,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26084,
"s": 26046,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 26104,
"s": 26084,
"text": "Multithreading in C"
},
{
"code": null,
"e": 26130,
"s": 26104,
"text": "Exception Handling in C++"
},
{
"code": null,
"e": 26171,
"s": 26130,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 26193,
"s": 26171,
"text": "'this' pointer in C++"
},
{
"code": null,
"e": 26231,
"s": 26193,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 26267,
"s": 26231,
"text": "Understanding \"extern\" keyword in C"
},
{
"code": null,
"e": 26309,
"s": 26267,
"text": "Smart Pointers in C++ and How to Use Them"
},
{
"code": null,
"e": 26337,
"s": 26309,
"text": "Multiple Inheritance in C++"
}
] |
How to fetch a property value dynamically in C#?
|
We can make use of Reflection to fetch a property value dynamically.
Reflection provides objects (of type Type) that describe assemblies, modules and types. We can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties. If we use attributes in our code, reflection enables us to access them.
The System.Reflection namespace and System.Type class play an important role in .NET Reflection. These two works together and allows us to reflect over many other aspects of a type.
Live Demo
using System;
using System.Text;
namespace DemoApplication {
public class Program {
static void Main(string[] args) {
var employeeType = typeof(Employee);
var employee = Activator.CreateInstance(employeeType);
SetPropertyValue(employeeType, "EmployeeId", employee, 1);
SetPropertyValue(employeeType, "EmployeeName", employee, "Mark");
GetPropertyValue(employeeType, "EmployeeId", employee);
GetPropertyValue(employeeType, "EmployeeName", employee);
Console.ReadLine();
}
static void SetPropertyValue(Type type, string propertyName, object instanceObject, object value) {
type.GetProperty(propertyName).SetValue(instanceObject, value);
}
static void GetPropertyValue(Type type, string propertyName, object instanceObject) {
Console.WriteLine($"Value of Property {propertyName}: {type.GetProperty(propertyName).GetValue(instanceObject, null)}");
}
}
public class Employee {
public int EmployeeId { get; set; }
public string EmployeeName { get; set; }
}
}
The output of the above code is
Value of Property EmployeeId: 1
Value of Property EmployeeName: Mark
In the above example we could see that the Employee properties values are set using Reflection by getting the type and property name. Similarly for fetching the property value we have used GetProperty() method of the Reflection class. By using this we can fetch the value of any property during the runtime.
|
[
{
"code": null,
"e": 1131,
"s": 1062,
"text": "We can make use of Reflection to fetch a property value dynamically."
},
{
"code": null,
"e": 1495,
"s": 1131,
"text": "Reflection provides objects (of type Type) that describe assemblies, modules and types. We can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties. If we use attributes in our code, reflection enables us to access them."
},
{
"code": null,
"e": 1677,
"s": 1495,
"text": "The System.Reflection namespace and System.Type class play an important role in .NET Reflection. These two works together and allows us to reflect over many other aspects of a type."
},
{
"code": null,
"e": 1688,
"s": 1677,
"text": " Live Demo"
},
{
"code": null,
"e": 2869,
"s": 1688,
"text": "using System;\nusing System.Text;\n namespace DemoApplication {\n public class Program {\n static void Main(string[] args) {\n var employeeType = typeof(Employee);\n var employee = Activator.CreateInstance(employeeType);\n SetPropertyValue(employeeType, \"EmployeeId\", employee, 1);\n SetPropertyValue(employeeType, \"EmployeeName\", employee, \"Mark\");\n GetPropertyValue(employeeType, \"EmployeeId\", employee);\n GetPropertyValue(employeeType, \"EmployeeName\", employee);\n Console.ReadLine();\n }\n static void SetPropertyValue(Type type, string propertyName, object instanceObject, object value) {\n type.GetProperty(propertyName).SetValue(instanceObject, value);\n }\n static void GetPropertyValue(Type type, string propertyName, object instanceObject) {\n Console.WriteLine($\"Value of Property {propertyName}: {type.GetProperty(propertyName).GetValue(instanceObject, null)}\");\n }\n }\n public class Employee {\n public int EmployeeId { get; set; }\n public string EmployeeName { get; set; }\n }\n }"
},
{
"code": null,
"e": 2901,
"s": 2869,
"text": "The output of the above code is"
},
{
"code": null,
"e": 2970,
"s": 2901,
"text": "Value of Property EmployeeId: 1\nValue of Property EmployeeName: Mark"
},
{
"code": null,
"e": 3278,
"s": 2970,
"text": "In the above example we could see that the Employee properties values are set using Reflection by getting the type and property name. Similarly for fetching the property value we have used GetProperty() method of the Reflection class. By using this we can fetch the value of any property during the runtime."
}
] |
JavaScript Number - toLocaleString()
|
This method converts a number object into a human readable string representing the number using the locale of the environment.
Its syntax is as follows −
number.toLocaleString()
Returns a human readable string representing the number using the locale of the environment.
Try the following example.
<html>
<head>
<title>JavaScript toLocaleString() Method </title>
</head>
<body>
<script type = "text/javascript">
var num = new Number(177.1234);
document.write( num.toLocaleString());
</script>
</body>
</html>
177.1234
25 Lectures
2.5 hours
Anadi Sharma
74 Lectures
10 hours
Lets Kode It
72 Lectures
4.5 hours
Frahaan Hussain
70 Lectures
4.5 hours
Frahaan Hussain
46 Lectures
6 hours
Eduonix Learning Solutions
88 Lectures
14 hours
Eduonix Learning Solutions
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2593,
"s": 2466,
"text": "This method converts a number object into a human readable string representing the number using the locale of the environment."
},
{
"code": null,
"e": 2620,
"s": 2593,
"text": "Its syntax is as follows −"
},
{
"code": null,
"e": 2645,
"s": 2620,
"text": "number.toLocaleString()\n"
},
{
"code": null,
"e": 2738,
"s": 2645,
"text": "Returns a human readable string representing the number using the locale of the environment."
},
{
"code": null,
"e": 2765,
"s": 2738,
"text": "Try the following example."
},
{
"code": null,
"e": 3038,
"s": 2765,
"text": "<html>\n <head>\n <title>JavaScript toLocaleString() Method </title>\n </head>\n \n <body> \n <script type = \"text/javascript\">\n var num = new Number(177.1234);\n document.write( num.toLocaleString()); \n </script> \n </body>\n</html>"
},
{
"code": null,
"e": 3048,
"s": 3038,
"text": "177.1234\n"
},
{
"code": null,
"e": 3083,
"s": 3048,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3097,
"s": 3083,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3131,
"s": 3097,
"text": "\n 74 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 3145,
"s": 3131,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3180,
"s": 3145,
"text": "\n 72 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3197,
"s": 3180,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3232,
"s": 3197,
"text": "\n 70 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3249,
"s": 3232,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3282,
"s": 3249,
"text": "\n 46 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3310,
"s": 3282,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3344,
"s": 3310,
"text": "\n 88 Lectures \n 14 hours \n"
},
{
"code": null,
"e": 3372,
"s": 3344,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3379,
"s": 3372,
"text": " Print"
},
{
"code": null,
"e": 3390,
"s": 3379,
"text": " Add Notes"
}
] |
Automate Tableau Data Sources refresh using Python | by Cristian Saavedra Desmoineaux | Towards Data Science
|
Suppose you want your Dashboards ready at the right moment when the data is available. In that case, you will find that using a Schedule Task is not enough because you don't know when the population process is going to finish!
The only missing piece is an automated process that refreshes the Dashboard after a trigger happens, like after the last step of an ETL is executed or when you are getting new files loaded into an Amazon S3 Bucket.
To solve these problems, I will explain how to refresh or update an existing Tableau Data Source and WorkBook using Python. I recommend checking this previous post to see other uses cases.
The following code shows you how to get the ID and execute Data Source or Workbook refresh.
If you don’t have Python installed, I recommend you to use Miniconda. You can see more details in this post.
The first you will need is install the Tableau Server Client (TSC) using pip as recommends the documentation at https://tableau.github.io/server-client-python/docs/#install-tsc
pip install tableauserverclientpip install tableauserverclient --upgrade
We are going to use a Personal Access Token or PAT to connect. The next step is going to Tableau Server at the right-up corner and select My Account Settings.
Scroll down and copy the Token Secret of the Personal Access Token
To simplify, I created the class TableauServerConnection with the variables:
server_url, full HTTP address like https://10ax.online.tableau.com/
token_name, It is the identification name of the Token made previously
token_secret. It is the secret text of the Token created yet
site. It is the site name. If you need to connect to the default, let empty.
Your connection will look like the following:
tsConn = TableauServerConnection('https://10ax.online.tableau.com/','APIToken','copyHereTheTokenSecret')
The next step is to connect to the Tableau Server and refresh an existing Data Source. To do that, You will need the ID. Because it is not easy to find It, I created the function getDataSourcesTableauServer that lists all the Data Sources using the previous connection.
I am going to use Python Pandas to search the ID, creating a Data Frame with the list returned by the function:
Then you can get the ID of filtering the Data Frame as following:
And then you can use refreshDataSourceTableauServer to refresh the Data Source by the ID like the following:
The next lines are the ones that do the magic. If you want to know more about what is doing, you can find information on the documentation page.
refresh datasource = server.datasources.get_by_id(datasource_id)refreshed_datasource = server.datasources.refresh(datasource)
In some cases, you have a WorkBooks connected to Data Sources and, at the same time, have his Data Source that needs to be refresh too.
Like the previous step, the WorkBook required the ID to execute a refresh. To facilitate the search of the ID, use the function getWorkBooksTableauServer in the same way as the previous step.
To refresh the WorkBook, use the refreshDataSourceTableauServer function by the ID like the following:
tableau.github.io
help.tableau.com
help.tableau.com
To finish, I am grateful to Carlos Lobera, who introduced me to Evan Slotnick, Anir Agarwal, and Elliott Stam, whos opened this door to automate the daily task for Tableau Server.
|
[
{
"code": null,
"e": 398,
"s": 171,
"text": "Suppose you want your Dashboards ready at the right moment when the data is available. In that case, you will find that using a Schedule Task is not enough because you don't know when the population process is going to finish!"
},
{
"code": null,
"e": 613,
"s": 398,
"text": "The only missing piece is an automated process that refreshes the Dashboard after a trigger happens, like after the last step of an ETL is executed or when you are getting new files loaded into an Amazon S3 Bucket."
},
{
"code": null,
"e": 802,
"s": 613,
"text": "To solve these problems, I will explain how to refresh or update an existing Tableau Data Source and WorkBook using Python. I recommend checking this previous post to see other uses cases."
},
{
"code": null,
"e": 894,
"s": 802,
"text": "The following code shows you how to get the ID and execute Data Source or Workbook refresh."
},
{
"code": null,
"e": 1003,
"s": 894,
"text": "If you don’t have Python installed, I recommend you to use Miniconda. You can see more details in this post."
},
{
"code": null,
"e": 1180,
"s": 1003,
"text": "The first you will need is install the Tableau Server Client (TSC) using pip as recommends the documentation at https://tableau.github.io/server-client-python/docs/#install-tsc"
},
{
"code": null,
"e": 1253,
"s": 1180,
"text": "pip install tableauserverclientpip install tableauserverclient --upgrade"
},
{
"code": null,
"e": 1412,
"s": 1253,
"text": "We are going to use a Personal Access Token or PAT to connect. The next step is going to Tableau Server at the right-up corner and select My Account Settings."
},
{
"code": null,
"e": 1479,
"s": 1412,
"text": "Scroll down and copy the Token Secret of the Personal Access Token"
},
{
"code": null,
"e": 1556,
"s": 1479,
"text": "To simplify, I created the class TableauServerConnection with the variables:"
},
{
"code": null,
"e": 1624,
"s": 1556,
"text": "server_url, full HTTP address like https://10ax.online.tableau.com/"
},
{
"code": null,
"e": 1695,
"s": 1624,
"text": "token_name, It is the identification name of the Token made previously"
},
{
"code": null,
"e": 1756,
"s": 1695,
"text": "token_secret. It is the secret text of the Token created yet"
},
{
"code": null,
"e": 1833,
"s": 1756,
"text": "site. It is the site name. If you need to connect to the default, let empty."
},
{
"code": null,
"e": 1879,
"s": 1833,
"text": "Your connection will look like the following:"
},
{
"code": null,
"e": 1984,
"s": 1879,
"text": "tsConn = TableauServerConnection('https://10ax.online.tableau.com/','APIToken','copyHereTheTokenSecret')"
},
{
"code": null,
"e": 2254,
"s": 1984,
"text": "The next step is to connect to the Tableau Server and refresh an existing Data Source. To do that, You will need the ID. Because it is not easy to find It, I created the function getDataSourcesTableauServer that lists all the Data Sources using the previous connection."
},
{
"code": null,
"e": 2366,
"s": 2254,
"text": "I am going to use Python Pandas to search the ID, creating a Data Frame with the list returned by the function:"
},
{
"code": null,
"e": 2432,
"s": 2366,
"text": "Then you can get the ID of filtering the Data Frame as following:"
},
{
"code": null,
"e": 2541,
"s": 2432,
"text": "And then you can use refreshDataSourceTableauServer to refresh the Data Source by the ID like the following:"
},
{
"code": null,
"e": 2686,
"s": 2541,
"text": "The next lines are the ones that do the magic. If you want to know more about what is doing, you can find information on the documentation page."
},
{
"code": null,
"e": 2812,
"s": 2686,
"text": "refresh datasource = server.datasources.get_by_id(datasource_id)refreshed_datasource = server.datasources.refresh(datasource)"
},
{
"code": null,
"e": 2948,
"s": 2812,
"text": "In some cases, you have a WorkBooks connected to Data Sources and, at the same time, have his Data Source that needs to be refresh too."
},
{
"code": null,
"e": 3140,
"s": 2948,
"text": "Like the previous step, the WorkBook required the ID to execute a refresh. To facilitate the search of the ID, use the function getWorkBooksTableauServer in the same way as the previous step."
},
{
"code": null,
"e": 3243,
"s": 3140,
"text": "To refresh the WorkBook, use the refreshDataSourceTableauServer function by the ID like the following:"
},
{
"code": null,
"e": 3261,
"s": 3243,
"text": "tableau.github.io"
},
{
"code": null,
"e": 3278,
"s": 3261,
"text": "help.tableau.com"
},
{
"code": null,
"e": 3295,
"s": 3278,
"text": "help.tableau.com"
}
] |
Tryit Editor v3.7
|
Tryit: width and height attributes
|
[] |
HSQLDB - Select Query
|
The SELECT command is used to fetch the record data from HSQLDB database. Here, you need to mention the required fields list in the Select statement.
Here is the generic syntax for Select query.
SELECT field1, field2,...fieldN table_name1, table_name2...
[WHERE Clause]
[OFFSET M ][LIMIT N]
You can fetch one or more fields in a single SELECT command.
You can fetch one or more fields in a single SELECT command.
You can specify star (*) in place of fields. In this case, SELECT will return all the fields.
You can specify star (*) in place of fields. In this case, SELECT will return all the fields.
You can specify any condition using WHERE clause.
You can specify any condition using WHERE clause.
You can specify an offset using OFFSET from where SELECT will start returning records. By default, offset is zero.
You can specify an offset using OFFSET from where SELECT will start returning records. By default, offset is zero.
You can limit the number of returns using LIMIT attribute.
You can limit the number of returns using LIMIT attribute.
Here is an example that fetches id, title, and author fields of all records from tutorials_tbl table. We can achieve this by using the SELECT statement. Following is the query for the example.
SELECT id, title, author FROM tutorials_tbl
After execution of the above query, you will receive the following output.
+------+----------------+-----------------+
| id | title | author |
+------+----------------+-----------------+
| 100 | Learn PHP | John Poul |
| 101 | Learn C | Yaswanth |
| 102 | Learn MySQL | Abdul S |
| 103 | Learn Excell | Bavya kanna |
| 104 | Learn JDB | Ajith kumar |
| 105 | Learn Junit | Sathya Murthi |
+------+----------------+-----------------+
Here is the JDBC program that will fetch id, title, and author fields of all records from tutorials_tbl table. Save the following code into the SelectQuery.java file.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class SelectQuery {
public static void main(String[] args) {
Connection con = null;
Statement stmt = null;
ResultSet result = null;
try {
Class.forName("org.hsqldb.jdbc.JDBCDriver");
con = DriverManager.getConnection(
"jdbc:hsqldb:hsql://localhost/testdb", "SA", "");
stmt = con.createStatement();
result = stmt.executeQuery(
"SELECT id, title, author FROM tutorials_tbl");
while(result.next()){
System.out.println(result.getInt("id")+" | "+
result.getString("title")+" | "+
result.getString("author"));
}
} catch (Exception e) {
e.printStackTrace(System.out);
}
}
}
You can start the database using the following command.
\>cd C:\hsqldb-2.3.4\hsqldb
hsqldb>java -classpath lib/hsqldb.jar org.hsqldb.server.Server --database.0
file:hsqldb/demodb --dbname.0 testdb
Compile and execute the above code using the following command.
\>javac SelectQuery.java
\>java SelectQuery
After execution of the above command, you will receive the following output −
100 | Learn PHP | John Poul
101 | Learn C | Yaswanth
102 | Learn MySQL | Abdul S
103 | Learn Excell | Bavya Kanna
104 | Learn JDB | Ajith kumar
105 | Learn Junit | Sathya Murthi
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2132,
"s": 1982,
"text": "The SELECT command is used to fetch the record data from HSQLDB database. Here, you need to mention the required fields list in the Select statement."
},
{
"code": null,
"e": 2177,
"s": 2132,
"text": "Here is the generic syntax for Select query."
},
{
"code": null,
"e": 2274,
"s": 2177,
"text": "SELECT field1, field2,...fieldN table_name1, table_name2...\n[WHERE Clause]\n[OFFSET M ][LIMIT N]\n"
},
{
"code": null,
"e": 2335,
"s": 2274,
"text": "You can fetch one or more fields in a single SELECT command."
},
{
"code": null,
"e": 2396,
"s": 2335,
"text": "You can fetch one or more fields in a single SELECT command."
},
{
"code": null,
"e": 2490,
"s": 2396,
"text": "You can specify star (*) in place of fields. In this case, SELECT will return all the fields."
},
{
"code": null,
"e": 2584,
"s": 2490,
"text": "You can specify star (*) in place of fields. In this case, SELECT will return all the fields."
},
{
"code": null,
"e": 2634,
"s": 2584,
"text": "You can specify any condition using WHERE clause."
},
{
"code": null,
"e": 2684,
"s": 2634,
"text": "You can specify any condition using WHERE clause."
},
{
"code": null,
"e": 2799,
"s": 2684,
"text": "You can specify an offset using OFFSET from where SELECT will start returning records. By default, offset is zero."
},
{
"code": null,
"e": 2914,
"s": 2799,
"text": "You can specify an offset using OFFSET from where SELECT will start returning records. By default, offset is zero."
},
{
"code": null,
"e": 2973,
"s": 2914,
"text": "You can limit the number of returns using LIMIT attribute."
},
{
"code": null,
"e": 3032,
"s": 2973,
"text": "You can limit the number of returns using LIMIT attribute."
},
{
"code": null,
"e": 3225,
"s": 3032,
"text": "Here is an example that fetches id, title, and author fields of all records from tutorials_tbl table. We can achieve this by using the SELECT statement. Following is the query for the example."
},
{
"code": null,
"e": 3270,
"s": 3225,
"text": "SELECT id, title, author FROM tutorials_tbl\n"
},
{
"code": null,
"e": 3345,
"s": 3270,
"text": "After execution of the above query, you will receive the following output."
},
{
"code": null,
"e": 3786,
"s": 3345,
"text": "+------+----------------+-----------------+\n| id | title | author |\n+------+----------------+-----------------+\n| 100 | Learn PHP | John Poul |\n| 101 | Learn C | Yaswanth |\n| 102 | Learn MySQL | Abdul S |\n| 103 | Learn Excell | Bavya kanna |\n| 104 | Learn JDB | Ajith kumar |\n| 105 | Learn Junit | Sathya Murthi |\n+------+----------------+-----------------+\n"
},
{
"code": null,
"e": 3953,
"s": 3786,
"text": "Here is the JDBC program that will fetch id, title, and author fields of all records from tutorials_tbl table. Save the following code into the SelectQuery.java file."
},
{
"code": null,
"e": 4833,
"s": 3953,
"text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.ResultSet;\nimport java.sql.Statement;\n\npublic class SelectQuery {\n \n public static void main(String[] args) {\n Connection con = null;\n Statement stmt = null;\n ResultSet result = null;\n \n try {\n Class.forName(\"org.hsqldb.jdbc.JDBCDriver\");\n con = DriverManager.getConnection(\n \"jdbc:hsqldb:hsql://localhost/testdb\", \"SA\", \"\");\n stmt = con.createStatement();\n result = stmt.executeQuery(\n \"SELECT id, title, author FROM tutorials_tbl\");\n \n while(result.next()){\n System.out.println(result.getInt(\"id\")+\" | \"+\n result.getString(\"title\")+\" | \"+\n result.getString(\"author\"));\n }\n } catch (Exception e) {\n e.printStackTrace(System.out);\n }\n }\n}"
},
{
"code": null,
"e": 4889,
"s": 4833,
"text": "You can start the database using the following command."
},
{
"code": null,
"e": 5031,
"s": 4889,
"text": "\\>cd C:\\hsqldb-2.3.4\\hsqldb\nhsqldb>java -classpath lib/hsqldb.jar org.hsqldb.server.Server --database.0\nfile:hsqldb/demodb --dbname.0 testdb\n"
},
{
"code": null,
"e": 5095,
"s": 5031,
"text": "Compile and execute the above code using the following command."
},
{
"code": null,
"e": 5140,
"s": 5095,
"text": "\\>javac SelectQuery.java\n\\>java SelectQuery\n"
},
{
"code": null,
"e": 5218,
"s": 5140,
"text": "After execution of the above command, you will receive the following output −"
},
{
"code": null,
"e": 5397,
"s": 5218,
"text": "100 | Learn PHP | John Poul\n101 | Learn C | Yaswanth\n102 | Learn MySQL | Abdul S\n103 | Learn Excell | Bavya Kanna\n104 | Learn JDB | Ajith kumar\n105 | Learn Junit | Sathya Murthi\n"
},
{
"code": null,
"e": 5404,
"s": 5397,
"text": " Print"
},
{
"code": null,
"e": 5415,
"s": 5404,
"text": " Add Notes"
}
] |
JavaFX | StackPane Class - GeeksforGeeks
|
13 Sep, 2018
StackPane class is a part of JavaFX. StackPane class lays out its children in form of a stack. The new node is placed on the top of the previous node in a StackPane. StackPane class inherits Pane Class.
Constructors of the class:
StackPane(): Creates a new empty StackPane.StackPane(Node... c): Creates a new StackPne with specified nodes.
StackPane(): Creates a new empty StackPane.
StackPane(Node... c): Creates a new StackPne with specified nodes.
Commonly Used Methods:
Below programs illustrate the use of StackPane Class:
Java Program to create a StackPane, add circle, label, rectangle and add it to the stage: In this program we are creating a Label named label, a Rectangle named rectangle and a Circle named circle. Then set the font of the StackPane using the setFont() function. Now set the fill of the rectangle and circle using the setFill() function. We will then create a StackPane named stack_pane and add rectangle, circle and label. Create a scene and add the stack_pane to the scene. Add this scene to the stage and call the show() function to display the final results.// Java Program to create a StackPane,// add circle, label, rectangle// and add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.scene.paint.*;import javafx.scene.canvas.*;import javafx.scene.text.*;import javafx.scene.Group;import javafx.scene.shape.*; public class StackPane_1 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle("StackPane"); // create a label Label label = new Label("this is StackPane example"); // set Font for label label.setFont(new Font(30)); // create a circle Circle circle = new Circle(100, 100, 70); // set fill for the circle circle.setFill(Color.RED); // create Rectangle Rectangle rectangle = new Rectangle(100, 100, 180, 160); // set fill for rectangle rectangle.setFill(Color.BLUE); // create a stack pane StackPane stack_pane = new StackPane(rectangle, circle, label); // create a scene Scene scene = new Scene(stack_pane, 400, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:Java Program to create a StackPane, add the circle, label, rectangle and then set the alignment of the StackPane and add it to the stage: In this program we are creating a Label named label, a Rectangle named rectangle and a Circle named circle. Then set the font of the StackPane using the setFont() function. Set fill of the rectangle and circle using the setFill() function. Now create a StackPane named stack_pane and add rectangle, circle, and label. Set the alignment of the stack_pane using setAlignment() function. Create a scene and add the stack_pane to the scene. Finally add this scene to the stage and call the show() function to display the results.// Java Program to create a StackPane, // add the circle, label, rectangle and// then set the alignment of the StackPane// and add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.geometry.*;import javafx.scene.paint.*;import javafx.scene.canvas.*;import javafx.scene.text.*;import javafx.scene.Group;import javafx.scene.shape.*; public class StackPane_2 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle("StackPane"); // create a label Label label = new Label("this is StackPane example"); // set Font for label label.setFont(new Font(30)); // create a circle Circle circle = new Circle(100, 100, 70); // set fill for the circle circle.setFill(Color.RED); // create Rectangle Rectangle rectangle = new Rectangle(100, 100, 180, 160); // set fill for rectangle rectangle.setFill(Color.BLUE); // create a stack pane StackPane stack_pane = new StackPane(rectangle, circle, label); // set alignement for the stack pane stack_pane.setAlignment(Pos.TOP_CENTER); // create a scene Scene scene = new Scene(stack_pane, 400, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:Note: The above programs might not run in an online IDE please use an offline compiler.Reference: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/layout/StackPane.htmlMy Personal Notes
arrow_drop_upSave
Java Program to create a StackPane, add circle, label, rectangle and add it to the stage: In this program we are creating a Label named label, a Rectangle named rectangle and a Circle named circle. Then set the font of the StackPane using the setFont() function. Now set the fill of the rectangle and circle using the setFill() function. We will then create a StackPane named stack_pane and add rectangle, circle and label. Create a scene and add the stack_pane to the scene. Add this scene to the stage and call the show() function to display the final results.// Java Program to create a StackPane,// add circle, label, rectangle// and add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.scene.paint.*;import javafx.scene.canvas.*;import javafx.scene.text.*;import javafx.scene.Group;import javafx.scene.shape.*; public class StackPane_1 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle("StackPane"); // create a label Label label = new Label("this is StackPane example"); // set Font for label label.setFont(new Font(30)); // create a circle Circle circle = new Circle(100, 100, 70); // set fill for the circle circle.setFill(Color.RED); // create Rectangle Rectangle rectangle = new Rectangle(100, 100, 180, 160); // set fill for rectangle rectangle.setFill(Color.BLUE); // create a stack pane StackPane stack_pane = new StackPane(rectangle, circle, label); // create a scene Scene scene = new Scene(stack_pane, 400, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:
// Java Program to create a StackPane,// add circle, label, rectangle// and add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.scene.paint.*;import javafx.scene.canvas.*;import javafx.scene.text.*;import javafx.scene.Group;import javafx.scene.shape.*; public class StackPane_1 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle("StackPane"); // create a label Label label = new Label("this is StackPane example"); // set Font for label label.setFont(new Font(30)); // create a circle Circle circle = new Circle(100, 100, 70); // set fill for the circle circle.setFill(Color.RED); // create Rectangle Rectangle rectangle = new Rectangle(100, 100, 180, 160); // set fill for rectangle rectangle.setFill(Color.BLUE); // create a stack pane StackPane stack_pane = new StackPane(rectangle, circle, label); // create a scene Scene scene = new Scene(stack_pane, 400, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}
Output:
Java Program to create a StackPane, add the circle, label, rectangle and then set the alignment of the StackPane and add it to the stage: In this program we are creating a Label named label, a Rectangle named rectangle and a Circle named circle. Then set the font of the StackPane using the setFont() function. Set fill of the rectangle and circle using the setFill() function. Now create a StackPane named stack_pane and add rectangle, circle, and label. Set the alignment of the stack_pane using setAlignment() function. Create a scene and add the stack_pane to the scene. Finally add this scene to the stage and call the show() function to display the results.// Java Program to create a StackPane, // add the circle, label, rectangle and// then set the alignment of the StackPane// and add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.geometry.*;import javafx.scene.paint.*;import javafx.scene.canvas.*;import javafx.scene.text.*;import javafx.scene.Group;import javafx.scene.shape.*; public class StackPane_2 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle("StackPane"); // create a label Label label = new Label("this is StackPane example"); // set Font for label label.setFont(new Font(30)); // create a circle Circle circle = new Circle(100, 100, 70); // set fill for the circle circle.setFill(Color.RED); // create Rectangle Rectangle rectangle = new Rectangle(100, 100, 180, 160); // set fill for rectangle rectangle.setFill(Color.BLUE); // create a stack pane StackPane stack_pane = new StackPane(rectangle, circle, label); // set alignement for the stack pane stack_pane.setAlignment(Pos.TOP_CENTER); // create a scene Scene scene = new Scene(stack_pane, 400, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:Note: The above programs might not run in an online IDE please use an offline compiler.Reference: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/layout/StackPane.htmlMy Personal Notes
arrow_drop_upSave
// Java Program to create a StackPane, // add the circle, label, rectangle and// then set the alignment of the StackPane// and add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.geometry.*;import javafx.scene.paint.*;import javafx.scene.canvas.*;import javafx.scene.text.*;import javafx.scene.Group;import javafx.scene.shape.*; public class StackPane_2 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle("StackPane"); // create a label Label label = new Label("this is StackPane example"); // set Font for label label.setFont(new Font(30)); // create a circle Circle circle = new Circle(100, 100, 70); // set fill for the circle circle.setFill(Color.RED); // create Rectangle Rectangle rectangle = new Rectangle(100, 100, 180, 160); // set fill for rectangle rectangle.setFill(Color.BLUE); // create a stack pane StackPane stack_pane = new StackPane(rectangle, circle, label); // set alignement for the stack pane stack_pane.setAlignment(Pos.TOP_CENTER); // create a scene Scene scene = new Scene(stack_pane, 400, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}
Output:
Note: The above programs might not run in an online IDE please use an offline compiler.
Reference: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/layout/StackPane.html
JavaFX
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Comparator Interface in Java with Examples
Internal Working of HashMap in Java
Strings in Java
|
[
{
"code": null,
"e": 25251,
"s": 25223,
"text": "\n13 Sep, 2018"
},
{
"code": null,
"e": 25454,
"s": 25251,
"text": "StackPane class is a part of JavaFX. StackPane class lays out its children in form of a stack. The new node is placed on the top of the previous node in a StackPane. StackPane class inherits Pane Class."
},
{
"code": null,
"e": 25481,
"s": 25454,
"text": "Constructors of the class:"
},
{
"code": null,
"e": 25591,
"s": 25481,
"text": "StackPane(): Creates a new empty StackPane.StackPane(Node... c): Creates a new StackPne with specified nodes."
},
{
"code": null,
"e": 25635,
"s": 25591,
"text": "StackPane(): Creates a new empty StackPane."
},
{
"code": null,
"e": 25702,
"s": 25635,
"text": "StackPane(Node... c): Creates a new StackPne with specified nodes."
},
{
"code": null,
"e": 25725,
"s": 25702,
"text": "Commonly Used Methods:"
},
{
"code": null,
"e": 25779,
"s": 25725,
"text": "Below programs illustrate the use of StackPane Class:"
},
{
"code": null,
"e": 30710,
"s": 25779,
"text": "Java Program to create a StackPane, add circle, label, rectangle and add it to the stage: In this program we are creating a Label named label, a Rectangle named rectangle and a Circle named circle. Then set the font of the StackPane using the setFont() function. Now set the fill of the rectangle and circle using the setFill() function. We will then create a StackPane named stack_pane and add rectangle, circle and label. Create a scene and add the stack_pane to the scene. Add this scene to the stage and call the show() function to display the final results.// Java Program to create a StackPane,// add circle, label, rectangle// and add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.scene.paint.*;import javafx.scene.canvas.*;import javafx.scene.text.*;import javafx.scene.Group;import javafx.scene.shape.*; public class StackPane_1 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle(\"StackPane\"); // create a label Label label = new Label(\"this is StackPane example\"); // set Font for label label.setFont(new Font(30)); // create a circle Circle circle = new Circle(100, 100, 70); // set fill for the circle circle.setFill(Color.RED); // create Rectangle Rectangle rectangle = new Rectangle(100, 100, 180, 160); // set fill for rectangle rectangle.setFill(Color.BLUE); // create a stack pane StackPane stack_pane = new StackPane(rectangle, circle, label); // create a scene Scene scene = new Scene(stack_pane, 400, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:Java Program to create a StackPane, add the circle, label, rectangle and then set the alignment of the StackPane and add it to the stage: In this program we are creating a Label named label, a Rectangle named rectangle and a Circle named circle. Then set the font of the StackPane using the setFont() function. Set fill of the rectangle and circle using the setFill() function. Now create a StackPane named stack_pane and add rectangle, circle, and label. Set the alignment of the stack_pane using setAlignment() function. Create a scene and add the stack_pane to the scene. Finally add this scene to the stage and call the show() function to display the results.// Java Program to create a StackPane, // add the circle, label, rectangle and// then set the alignment of the StackPane// and add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.geometry.*;import javafx.scene.paint.*;import javafx.scene.canvas.*;import javafx.scene.text.*;import javafx.scene.Group;import javafx.scene.shape.*; public class StackPane_2 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle(\"StackPane\"); // create a label Label label = new Label(\"this is StackPane example\"); // set Font for label label.setFont(new Font(30)); // create a circle Circle circle = new Circle(100, 100, 70); // set fill for the circle circle.setFill(Color.RED); // create Rectangle Rectangle rectangle = new Rectangle(100, 100, 180, 160); // set fill for rectangle rectangle.setFill(Color.BLUE); // create a stack pane StackPane stack_pane = new StackPane(rectangle, circle, label); // set alignement for the stack pane stack_pane.setAlignment(Pos.TOP_CENTER); // create a scene Scene scene = new Scene(stack_pane, 400, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:Note: The above programs might not run in an online IDE please use an offline compiler.Reference: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/layout/StackPane.htmlMy Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 32947,
"s": 30710,
"text": "Java Program to create a StackPane, add circle, label, rectangle and add it to the stage: In this program we are creating a Label named label, a Rectangle named rectangle and a Circle named circle. Then set the font of the StackPane using the setFont() function. Now set the fill of the rectangle and circle using the setFill() function. We will then create a StackPane named stack_pane and add rectangle, circle and label. Create a scene and add the stack_pane to the scene. Add this scene to the stage and call the show() function to display the final results.// Java Program to create a StackPane,// add circle, label, rectangle// and add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.scene.paint.*;import javafx.scene.canvas.*;import javafx.scene.text.*;import javafx.scene.Group;import javafx.scene.shape.*; public class StackPane_1 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle(\"StackPane\"); // create a label Label label = new Label(\"this is StackPane example\"); // set Font for label label.setFont(new Font(30)); // create a circle Circle circle = new Circle(100, 100, 70); // set fill for the circle circle.setFill(Color.RED); // create Rectangle Rectangle rectangle = new Rectangle(100, 100, 180, 160); // set fill for rectangle rectangle.setFill(Color.BLUE); // create a stack pane StackPane stack_pane = new StackPane(rectangle, circle, label); // create a scene Scene scene = new Scene(stack_pane, 400, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:"
},
{
"code": "// Java Program to create a StackPane,// add circle, label, rectangle// and add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.scene.paint.*;import javafx.scene.canvas.*;import javafx.scene.text.*;import javafx.scene.Group;import javafx.scene.shape.*; public class StackPane_1 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle(\"StackPane\"); // create a label Label label = new Label(\"this is StackPane example\"); // set Font for label label.setFont(new Font(30)); // create a circle Circle circle = new Circle(100, 100, 70); // set fill for the circle circle.setFill(Color.RED); // create Rectangle Rectangle rectangle = new Rectangle(100, 100, 180, 160); // set fill for rectangle rectangle.setFill(Color.BLUE); // create a stack pane StackPane stack_pane = new StackPane(rectangle, circle, label); // create a scene Scene scene = new Scene(stack_pane, 400, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}",
"e": 34615,
"s": 32947,
"text": null
},
{
"code": null,
"e": 34623,
"s": 34615,
"text": "Output:"
},
{
"code": null,
"e": 37318,
"s": 34623,
"text": "Java Program to create a StackPane, add the circle, label, rectangle and then set the alignment of the StackPane and add it to the stage: In this program we are creating a Label named label, a Rectangle named rectangle and a Circle named circle. Then set the font of the StackPane using the setFont() function. Set fill of the rectangle and circle using the setFill() function. Now create a StackPane named stack_pane and add rectangle, circle, and label. Set the alignment of the stack_pane using setAlignment() function. Create a scene and add the stack_pane to the scene. Finally add this scene to the stage and call the show() function to display the results.// Java Program to create a StackPane, // add the circle, label, rectangle and// then set the alignment of the StackPane// and add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.geometry.*;import javafx.scene.paint.*;import javafx.scene.canvas.*;import javafx.scene.text.*;import javafx.scene.Group;import javafx.scene.shape.*; public class StackPane_2 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle(\"StackPane\"); // create a label Label label = new Label(\"this is StackPane example\"); // set Font for label label.setFont(new Font(30)); // create a circle Circle circle = new Circle(100, 100, 70); // set fill for the circle circle.setFill(Color.RED); // create Rectangle Rectangle rectangle = new Rectangle(100, 100, 180, 160); // set fill for rectangle rectangle.setFill(Color.BLUE); // create a stack pane StackPane stack_pane = new StackPane(rectangle, circle, label); // set alignement for the stack pane stack_pane.setAlignment(Pos.TOP_CENTER); // create a scene Scene scene = new Scene(stack_pane, 400, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:Note: The above programs might not run in an online IDE please use an offline compiler.Reference: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/layout/StackPane.htmlMy Personal Notes\narrow_drop_upSave"
},
{
"code": "// Java Program to create a StackPane, // add the circle, label, rectangle and// then set the alignment of the StackPane// and add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.geometry.*;import javafx.scene.paint.*;import javafx.scene.canvas.*;import javafx.scene.text.*;import javafx.scene.Group;import javafx.scene.shape.*; public class StackPane_2 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle(\"StackPane\"); // create a label Label label = new Label(\"this is StackPane example\"); // set Font for label label.setFont(new Font(30)); // create a circle Circle circle = new Circle(100, 100, 70); // set fill for the circle circle.setFill(Color.RED); // create Rectangle Rectangle rectangle = new Rectangle(100, 100, 180, 160); // set fill for rectangle rectangle.setFill(Color.BLUE); // create a stack pane StackPane stack_pane = new StackPane(rectangle, circle, label); // set alignement for the stack pane stack_pane.setAlignment(Pos.TOP_CENTER); // create a scene Scene scene = new Scene(stack_pane, 400, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}",
"e": 39132,
"s": 37318,
"text": null
},
{
"code": null,
"e": 39140,
"s": 39132,
"text": "Output:"
},
{
"code": null,
"e": 39228,
"s": 39140,
"text": "Note: The above programs might not run in an online IDE please use an offline compiler."
},
{
"code": null,
"e": 39318,
"s": 39228,
"text": "Reference: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/layout/StackPane.html"
},
{
"code": null,
"e": 39325,
"s": 39318,
"text": "JavaFX"
},
{
"code": null,
"e": 39330,
"s": 39325,
"text": "Java"
},
{
"code": null,
"e": 39335,
"s": 39330,
"text": "Java"
},
{
"code": null,
"e": 39433,
"s": 39335,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 39448,
"s": 39433,
"text": "Stream In Java"
},
{
"code": null,
"e": 39469,
"s": 39448,
"text": "Constructors in Java"
},
{
"code": null,
"e": 39488,
"s": 39469,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 39518,
"s": 39488,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 39564,
"s": 39518,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 39581,
"s": 39564,
"text": "Generics in Java"
},
{
"code": null,
"e": 39602,
"s": 39581,
"text": "Introduction to Java"
},
{
"code": null,
"e": 39645,
"s": 39602,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 39681,
"s": 39645,
"text": "Internal Working of HashMap in Java"
}
] |
Python | Character Encoding - GeeksforGeeks
|
29 May, 2021
Finding the text which is having nonstandard character encoding is a very common step to perform in text processing. All the text would have been from utf-8 or ASCII encoding ideally but this might not be the case always. So, in such cases when the encoding is not known, such non-encoded text has to be detected and the be converted to a standard encoding. So, this step is important before processing the text further. Charade Installation : For performing the detection and conversion of encoding, charade – a Python library is required. This module can be simply installed using sudo easy_install charade or pip install charade. Let’s see the wrapper function around the charade module. Code : encoding.detect(string), to detect the encoding
Python3
# -*- coding: utf-8 -*- import charadedef detect(s): try: # check it in the charade list if isinstance(s, str): return charade.detect(s.encode()) # detecting the string else: return charade.detect(s) # in case of error # encode with 'utf -8' encoding except UnicodeDecodeError: return charade.detect(s.encode('utf-8'))
The detect functions will return 2 attributes :
Confidence : the probability of charade being correct.
Encoding : which encoding it is.
Code : encoding.convert(string) to convert the encoding.
Python3
# -*- coding: utf-8 -*-import charade def convert(s): # if in the charade instance if isinstance(s, str): s = s.encode() # retrieving the encoding information # from the detect() output encode = detect(s)['encoding'] if encode == 'utf-8': return s.decode() else: return s.decode(encoding)
Code : Example
Python3
# importing libraryimport encoding d1 = encoding.detect('geek')print ("d1 is encoded as : ", d1) d2 = encoding.detect('ascii')print ("d2 is encoded as : ", d2)
Output :
d1 is encoded as : (confidence': 0.505, 'encoding': 'utf-8')
d2 is encoded as : ('confidence': 1.0, 'encoding': 'ascii')
detect() : It is a charade.detect() wrapper. It encodes the strings and handles the UnicodeDecodeError exceptions. It expects a bytes object so therefore the string is encoded before trying to detect the encoding.convert() : It is a charade.convert() wrapper. It calls detect() first to get the encoding. Then, it returns a decoded string.
nidhi_biet
sumitgumber28
Natural-language-processing
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n29 May, 2021"
},
{
"code": null,
"e": 26285,
"s": 25537,
"text": "Finding the text which is having nonstandard character encoding is a very common step to perform in text processing. All the text would have been from utf-8 or ASCII encoding ideally but this might not be the case always. So, in such cases when the encoding is not known, such non-encoded text has to be detected and the be converted to a standard encoding. So, this step is important before processing the text further. Charade Installation : For performing the detection and conversion of encoding, charade – a Python library is required. This module can be simply installed using sudo easy_install charade or pip install charade. Let’s see the wrapper function around the charade module. Code : encoding.detect(string), to detect the encoding "
},
{
"code": null,
"e": 26293,
"s": 26285,
"text": "Python3"
},
{
"code": "# -*- coding: utf-8 -*- import charadedef detect(s): try: # check it in the charade list if isinstance(s, str): return charade.detect(s.encode()) # detecting the string else: return charade.detect(s) # in case of error # encode with 'utf -8' encoding except UnicodeDecodeError: return charade.detect(s.encode('utf-8'))",
"e": 26693,
"s": 26293,
"text": null
},
{
"code": null,
"e": 26743,
"s": 26693,
"text": "The detect functions will return 2 attributes : "
},
{
"code": null,
"e": 26834,
"s": 26743,
"text": "Confidence : the probability of charade being correct.\nEncoding : which encoding it is. "
},
{
"code": null,
"e": 26892,
"s": 26834,
"text": "Code : encoding.convert(string) to convert the encoding. "
},
{
"code": null,
"e": 26900,
"s": 26892,
"text": "Python3"
},
{
"code": "# -*- coding: utf-8 -*-import charade def convert(s): # if in the charade instance if isinstance(s, str): s = s.encode() # retrieving the encoding information # from the detect() output encode = detect(s)['encoding'] if encode == 'utf-8': return s.decode() else: return s.decode(encoding)",
"e": 27246,
"s": 26900,
"text": null
},
{
"code": null,
"e": 27263,
"s": 27246,
"text": "Code : Example "
},
{
"code": null,
"e": 27271,
"s": 27263,
"text": "Python3"
},
{
"code": "# importing libraryimport encoding d1 = encoding.detect('geek')print (\"d1 is encoded as : \", d1) d2 = encoding.detect('ascii')print (\"d2 is encoded as : \", d2)",
"e": 27435,
"s": 27271,
"text": null
},
{
"code": null,
"e": 27446,
"s": 27435,
"text": "Output : "
},
{
"code": null,
"e": 27567,
"s": 27446,
"text": "d1 is encoded as : (confidence': 0.505, 'encoding': 'utf-8')\nd2 is encoded as : ('confidence': 1.0, 'encoding': 'ascii')"
},
{
"code": null,
"e": 27908,
"s": 27567,
"text": "detect() : It is a charade.detect() wrapper. It encodes the strings and handles the UnicodeDecodeError exceptions. It expects a bytes object so therefore the string is encoded before trying to detect the encoding.convert() : It is a charade.convert() wrapper. It calls detect() first to get the encoding. Then, it returns a decoded string. "
},
{
"code": null,
"e": 27919,
"s": 27908,
"text": "nidhi_biet"
},
{
"code": null,
"e": 27933,
"s": 27919,
"text": "sumitgumber28"
},
{
"code": null,
"e": 27961,
"s": 27933,
"text": "Natural-language-processing"
},
{
"code": null,
"e": 27968,
"s": 27961,
"text": "Python"
},
{
"code": null,
"e": 28066,
"s": 27968,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28098,
"s": 28066,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28140,
"s": 28098,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28182,
"s": 28140,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28209,
"s": 28182,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28265,
"s": 28209,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28287,
"s": 28265,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28326,
"s": 28287,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 28357,
"s": 28326,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 28386,
"s": 28357,
"text": "Create a directory in Python"
}
] |
How to sort an ArrayList in Descending Order in Java - GeeksforGeeks
|
11 Dec, 2018
Given an unsorted ArrayList, the task is to sort this ArrayList in descending order in Java.
Examples:
Input: Unsorted ArrayList: [Geeks, For, ForGeeks, GeeksForGeeks, A computer portal]Output: Sorted ArrayList: [GeeksForGeeks, Geeks, ForGeeks, For, A computer portal]
Input: Unsorted ArrayList: [Geeks, For, ForGeeks]Output: Sorted ArrayList: [Geeks, ForGeeks, For]
Approach: An ArrayList can be Sorted by using the sort() method of the Collections Class in Java. This sort() method takes the collection to be sorted and Collections.reverseOrder() as the parameter and returns a Collection sorted in the Descending Order. Collections.reverseOrder() acts as the comparator in this method.
Syntax:
Collections.sort(ArrayList, Collections.reverseOrder());
Below is the implementation of the above approach:
// Java program to demonstrate// How to sort ArrayList in descending order import java.util.*; public class GFG { public static void main(String args[]) { // Get the ArrayList ArrayList<String> list = new ArrayList<String>(); // Populate the ArrayList list.add("Geeks"); list.add("For"); list.add("ForGeeks"); list.add("GeeksForGeeks"); list.add("A computer portal"); // Print the unsorted ArrayList System.out.println("Unsorted ArrayList: " + list); // Sorting ArrayList in descending Order // using Collection.sort() method // by passing Collections.reverseOrder() as comparator Collections.sort(list, Collections.reverseOrder()); // Print the sorted ArrayList System.out.println("Sorted ArrayList " + "in Descending order : " + list); }}
Unsorted ArrayList: [Geeks, For, ForGeeks, GeeksForGeeks, A computer portal]
Sorted ArrayList in Descending order : [GeeksForGeeks, Geeks, ForGeeks, For, A computer portal]
Java - util package
Java-ArrayList
Java-Collections
Java-List-Programs
Sorting Quiz
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Comparator Interface in Java with Examples
Internal Working of HashMap in Java
Strings in Java
|
[
{
"code": null,
"e": 25249,
"s": 25221,
"text": "\n11 Dec, 2018"
},
{
"code": null,
"e": 25342,
"s": 25249,
"text": "Given an unsorted ArrayList, the task is to sort this ArrayList in descending order in Java."
},
{
"code": null,
"e": 25352,
"s": 25342,
"text": "Examples:"
},
{
"code": null,
"e": 25518,
"s": 25352,
"text": "Input: Unsorted ArrayList: [Geeks, For, ForGeeks, GeeksForGeeks, A computer portal]Output: Sorted ArrayList: [GeeksForGeeks, Geeks, ForGeeks, For, A computer portal]"
},
{
"code": null,
"e": 25616,
"s": 25518,
"text": "Input: Unsorted ArrayList: [Geeks, For, ForGeeks]Output: Sorted ArrayList: [Geeks, ForGeeks, For]"
},
{
"code": null,
"e": 25938,
"s": 25616,
"text": "Approach: An ArrayList can be Sorted by using the sort() method of the Collections Class in Java. This sort() method takes the collection to be sorted and Collections.reverseOrder() as the parameter and returns a Collection sorted in the Descending Order. Collections.reverseOrder() acts as the comparator in this method."
},
{
"code": null,
"e": 25946,
"s": 25938,
"text": "Syntax:"
},
{
"code": null,
"e": 26003,
"s": 25946,
"text": "Collections.sort(ArrayList, Collections.reverseOrder());"
},
{
"code": null,
"e": 26054,
"s": 26003,
"text": "Below is the implementation of the above approach:"
},
{
"code": "// Java program to demonstrate// How to sort ArrayList in descending order import java.util.*; public class GFG { public static void main(String args[]) { // Get the ArrayList ArrayList<String> list = new ArrayList<String>(); // Populate the ArrayList list.add(\"Geeks\"); list.add(\"For\"); list.add(\"ForGeeks\"); list.add(\"GeeksForGeeks\"); list.add(\"A computer portal\"); // Print the unsorted ArrayList System.out.println(\"Unsorted ArrayList: \" + list); // Sorting ArrayList in descending Order // using Collection.sort() method // by passing Collections.reverseOrder() as comparator Collections.sort(list, Collections.reverseOrder()); // Print the sorted ArrayList System.out.println(\"Sorted ArrayList \" + \"in Descending order : \" + list); }}",
"e": 27017,
"s": 26054,
"text": null
},
{
"code": null,
"e": 27191,
"s": 27017,
"text": "Unsorted ArrayList: [Geeks, For, ForGeeks, GeeksForGeeks, A computer portal]\nSorted ArrayList in Descending order : [GeeksForGeeks, Geeks, ForGeeks, For, A computer portal]\n"
},
{
"code": null,
"e": 27211,
"s": 27191,
"text": "Java - util package"
},
{
"code": null,
"e": 27226,
"s": 27211,
"text": "Java-ArrayList"
},
{
"code": null,
"e": 27243,
"s": 27226,
"text": "Java-Collections"
},
{
"code": null,
"e": 27262,
"s": 27243,
"text": "Java-List-Programs"
},
{
"code": null,
"e": 27275,
"s": 27262,
"text": "Sorting Quiz"
},
{
"code": null,
"e": 27280,
"s": 27275,
"text": "Java"
},
{
"code": null,
"e": 27285,
"s": 27280,
"text": "Java"
},
{
"code": null,
"e": 27302,
"s": 27285,
"text": "Java-Collections"
},
{
"code": null,
"e": 27400,
"s": 27302,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27415,
"s": 27400,
"text": "Stream In Java"
},
{
"code": null,
"e": 27436,
"s": 27415,
"text": "Constructors in Java"
},
{
"code": null,
"e": 27455,
"s": 27436,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 27485,
"s": 27455,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 27531,
"s": 27485,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 27548,
"s": 27531,
"text": "Generics in Java"
},
{
"code": null,
"e": 27569,
"s": 27548,
"text": "Introduction to Java"
},
{
"code": null,
"e": 27612,
"s": 27569,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 27648,
"s": 27612,
"text": "Internal Working of HashMap in Java"
}
] |
Arrangement of the characters of a word such that all vowels are at odd places - GeeksforGeeks
|
07 May, 2021
Given a string ‘S’ containing vowels and consonants of lowercase English alphabets. The task is to find the number of ways in which the characters of the word can be arranged such that the vowels occupy only the odd positions.
Examples:
Input: geeks Output: 36 Input: publish Output: 1440
Approach:
First find the total no. of odd places and even places in the given word.Total number of even places = floor(word length/2) Total number of odd places = word length – total even placesLet’s consider the string “contribute” then there are 10 letters in the given word and there are 5 odd places, 5 even places, 4 vowels and 6 consonants.Let us mark these positions as under: (1) (2) (3) (4) (5) (6) (7) (8) (9) (10)Now, 4 vowels can be placed at any of the five places, marked 1, 3, 5, 7, 9. The number of ways of arranging the vowels = 5_P_4 = 5! = 120Also, the 6 consonants can be arranged at the remaining 6 positions. Number of ways of these arrangements = 6_P_6 = 6! = 720.Total number of ways = (120 x 720) = 86400
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find the number of ways// in which the characters of the word// can be arranged such that the vowels// occupy only the odd positions#include <bits/stdc++.h>using namespace std; // Function to return the// factorial of a numberint fact(int n){ int f = 1; for (int i = 2; i <= n; i++) { f = f * i; } return f;} // calculating nPrint npr(int n, int r){ return fact(n) / fact(n - r);} // Function to find the number of ways// in which the characters of the word// can be arranged such that the vowels// occupy only the odd positionsint countPermutations(string str){ // Get total even positions int even = floor(str.length() / 2); // Get total odd positions int odd = str.length() - even; int ways = 0; // Store frequency of each character of // the string int freq[26] = { 0 }; for (int i = 0; i < str.length(); i++) { ++freq[str[i] - 'a']; } // Count total number of vowels int nvowels = freq[0] + freq[4] + freq[8] + freq[14] + freq[20]; // Count total number of consonants int nconsonants = str.length() - nvowels; // Calculate the total number of ways ways = npr(odd, nvowels) * npr(nconsonants, nconsonants); return ways;} // Driver codeint main(){ string str = "geeks"; cout << countPermutations(str); return 0;}
// Java program to find the number of ways// in which the characters of the word// can be arranged such that the vowels// occupy only the odd positionsclass GFG{// Function to return the// factorial of a numberstatic int fact(int n){ int f = 1; for (int i = 2; i <= n; i++) { f = f * i; } return f;} // calculating nPrstatic int npr(int n, int r){ return fact(n) / fact(n - r);} // Function to find the number of ways// in which the characters of the word// can be arranged such that the vowels// occupy only the odd positionsstatic int countPermutations(String str){ // Get total even positions int even = (int)Math.floor((double)(str.length() / 2)); // Get total odd positions int odd = str.length() - even; int ways = 0; // Store frequency of each character of // the string int[] freq=new int[26]; for (int i = 0; i < str.length(); i++) { freq[(int)(str.charAt(i)-'a')]++; } // Count total number of vowels int nvowels= freq[0] + freq[4]+ freq[8] + freq[14]+ freq[20]; // Count total number of consonants int nconsonants= str.length() - nvowels; // Calculate the total number of ways ways = npr(odd, nvowels) * npr(nconsonants, nconsonants); return ways;} // Driver codepublic static void main(String[] args){ String str = "geeks"; System.out.println(countPermutations(str));}}// This code is contributed by mits
# Python3 program to find the number# of ways in which the characters# of the word can be arranged such# that the vowels occupy only the# odd positionsimport math # Function to return the factorial# of a numberdef fact(n): f = 1; for i in range(2, n + 1): f = f * i; return f; # calculating nPrdef npr(n, r): return fact(n) / fact(n - r); # Function to find the number of# ways in which the characters of# the word can be arranged such# that the vowels occupy only the# odd positionsdef countPermutations(str): # Get total even positions even = math.floor(len(str) / 2); # Get total odd positions odd = len(str) - even; ways = 0; # Store frequency of each # character of the string freq = [0] * 26; for i in range(len(str)): freq[ord(str[i]) - ord('a')] += 1; # Count total number of vowels nvowels = (freq[0] + freq[4] + freq[8] + freq[14] + freq[20]); # Count total number of consonants nconsonants = len(str) - nvowels; # Calculate the total number of ways ways = (npr(odd, nvowels) * npr(nconsonants, nconsonants)); return int(ways); # Driver codestr = "geeks"; print(countPermutations(str)); # This code is contributed by mits
// C# program to find the number of ways// in which the characters of the word// can be arranged such that the vowels// occupy only the odd positionsusing System;class GFG{// Function to return the// factorial of a numberstatic int fact(int n){ int f = 1; for (int i = 2; i <= n; i++) { f = f * i; } return f;} // calculating nPrstatic int npr(int n, int r){ return fact(n) / fact(n - r);} // Function to find the number of ways// in which the characters of the word// can be arranged such that the vowels// occupy only the odd positionsstatic int countPermutations(String str){ // Get total even positions int even = (int)Math.Floor((double)(str.Length / 2)); // Get total odd positions int odd = str.Length - even; int ways = 0; // Store frequency of each character of // the string int[] freq=new int[26]; for (int i = 0; i < str.Length; i++) { freq[(int)(str[i]-'a')]++; } // Count total number of vowels int nvowels= freq[0] + freq[4]+ freq[8] + freq[14]+ freq[20]; // Count total number of consonants int nconsonants= str.Length - nvowels; // Calculate the total number of ways ways = npr(odd, nvowels) * npr(nconsonants, nconsonants); return ways;} // Driver codestatic void Main(){ String str = "geeks"; Console.WriteLine(countPermutations(str));}}// This code is contributed by mits
<?php// PHP program to find the number// of ways in which the characters// of the word can be arranged such// that the vowels occupy only the// odd positions // Function to return the// factorial of a numberfunction fact($n){ $f = 1; for ($i = 2; $i <= $n; $i++) { $f = $f * $i; } return $f;} // calculating nPrfunction npr($n, $r){ return fact($n) / fact($n - $r);} // Function to find the number// of $ways in which the characters// of the word can be arranged such// that the vowels occupy only the// odd positionsfunction countPermutations($str){ // Get total even positions $even = floor(strlen($str)/ 2); // Get total odd positions $odd = strlen($str) - $even; $ways = 0; // Store $frequency of each // character of the string $freq = array_fill(0, 26, 0); for ($i = 0; $i < strlen($str); $i++) { ++$freq[ord($str[$i]) - ord('a')]; } // Count total number of vowels $nvowels= $freq[0] + $freq[4] + $freq[8] + $freq[14] + $freq[20]; // Count total number of consonants $nconsonants= strlen($str) - $nvowels; // Calculate the total number of ways $ways = npr($odd, $nvowels) * npr($nconsonants, $nconsonants); return $ways;} // Driver code$str = "geeks"; echo countPermutations($str); // This code is contributed by mits?>
<script>// Javascript program to find the number// of ways in which the characters// of the word can be arranged such// that the vowels occupy only the// odd positions // Function to return the// factorial of a numberfunction fact(n){ let f = 1; for (let i = 2; i <= n; i++) { f = f * i; } return f;} // calculating nPrfunction npr(n, r){ return fact(n) / fact(n - r);} // Function to find the number// of ways in which the characters// of the word can be arranged such// that the vowels occupy only the// odd positionsfunction countPermutations(str){ // Get total even positions let even = Math.floor(str.length/ 2); // Get total odd positions let odd = str.length - even; let ways = 0; // Store frequency of each // character of the string let freq = new Array(26).fill(0); for (let i = 0; i < str.length; i++) { ++freq[str.charCodeAt(i) - 'a'.charCodeAt(0)]; } // Count total number of vowels let nvowels= freq[0] + freq[4] + freq[8] + freq[14] + freq[20]; // Count total number of consonants let nconsonants= str.length - nvowels; // Calculate the total number of ways ways = npr(odd, nvowels) * npr(nconsonants, nconsonants); return ways;} // Driver codelet str = "geeks"; document.write(countPermutations(str)); // This code is contributed by gfgking</script>
36
Mithun Kumar
gfgking
factorial
permutation
vowel-consonant
Mathematical
Strings
Strings
Mathematical
permutation
factorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program to print prime numbers from 1 to N.
Segment Tree | Set 1 (Sum of given range)
Modular multiplicative inverse
Count all possible paths from top left to bottom right of a mXn matrix
Fizz Buzz Implementation
Write a program to reverse an array or string
Reverse a string in Java
Longest Common Subsequence | DP-4
Check for Balanced Brackets in an expression (well-formedness) using Stack
Python program to check if a string is palindrome or not
|
[
{
"code": null,
"e": 25937,
"s": 25909,
"text": "\n07 May, 2021"
},
{
"code": null,
"e": 26164,
"s": 25937,
"text": "Given a string ‘S’ containing vowels and consonants of lowercase English alphabets. The task is to find the number of ways in which the characters of the word can be arranged such that the vowels occupy only the odd positions."
},
{
"code": null,
"e": 26175,
"s": 26164,
"text": "Examples: "
},
{
"code": null,
"e": 26229,
"s": 26175,
"text": "Input: geeks Output: 36 Input: publish Output: 1440 "
},
{
"code": null,
"e": 26241,
"s": 26229,
"text": "Approach: "
},
{
"code": null,
"e": 26963,
"s": 26241,
"text": "First find the total no. of odd places and even places in the given word.Total number of even places = floor(word length/2) Total number of odd places = word length – total even placesLet’s consider the string “contribute” then there are 10 letters in the given word and there are 5 odd places, 5 even places, 4 vowels and 6 consonants.Let us mark these positions as under: (1) (2) (3) (4) (5) (6) (7) (8) (9) (10)Now, 4 vowels can be placed at any of the five places, marked 1, 3, 5, 7, 9. The number of ways of arranging the vowels = 5_P_4 = 5! = 120Also, the 6 consonants can be arranged at the remaining 6 positions. Number of ways of these arrangements = 6_P_6 = 6! = 720.Total number of ways = (120 x 720) = 86400 "
},
{
"code": null,
"e": 27016,
"s": 26963,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27020,
"s": 27016,
"text": "C++"
},
{
"code": null,
"e": 27025,
"s": 27020,
"text": "Java"
},
{
"code": null,
"e": 27033,
"s": 27025,
"text": "Python3"
},
{
"code": null,
"e": 27036,
"s": 27033,
"text": "C#"
},
{
"code": null,
"e": 27040,
"s": 27036,
"text": "PHP"
},
{
"code": null,
"e": 27051,
"s": 27040,
"text": "Javascript"
},
{
"code": "// C++ program to find the number of ways// in which the characters of the word// can be arranged such that the vowels// occupy only the odd positions#include <bits/stdc++.h>using namespace std; // Function to return the// factorial of a numberint fact(int n){ int f = 1; for (int i = 2; i <= n; i++) { f = f * i; } return f;} // calculating nPrint npr(int n, int r){ return fact(n) / fact(n - r);} // Function to find the number of ways// in which the characters of the word// can be arranged such that the vowels// occupy only the odd positionsint countPermutations(string str){ // Get total even positions int even = floor(str.length() / 2); // Get total odd positions int odd = str.length() - even; int ways = 0; // Store frequency of each character of // the string int freq[26] = { 0 }; for (int i = 0; i < str.length(); i++) { ++freq[str[i] - 'a']; } // Count total number of vowels int nvowels = freq[0] + freq[4] + freq[8] + freq[14] + freq[20]; // Count total number of consonants int nconsonants = str.length() - nvowels; // Calculate the total number of ways ways = npr(odd, nvowels) * npr(nconsonants, nconsonants); return ways;} // Driver codeint main(){ string str = \"geeks\"; cout << countPermutations(str); return 0;}",
"e": 28416,
"s": 27051,
"text": null
},
{
"code": "// Java program to find the number of ways// in which the characters of the word// can be arranged such that the vowels// occupy only the odd positionsclass GFG{// Function to return the// factorial of a numberstatic int fact(int n){ int f = 1; for (int i = 2; i <= n; i++) { f = f * i; } return f;} // calculating nPrstatic int npr(int n, int r){ return fact(n) / fact(n - r);} // Function to find the number of ways// in which the characters of the word// can be arranged such that the vowels// occupy only the odd positionsstatic int countPermutations(String str){ // Get total even positions int even = (int)Math.floor((double)(str.length() / 2)); // Get total odd positions int odd = str.length() - even; int ways = 0; // Store frequency of each character of // the string int[] freq=new int[26]; for (int i = 0; i < str.length(); i++) { freq[(int)(str.charAt(i)-'a')]++; } // Count total number of vowels int nvowels= freq[0] + freq[4]+ freq[8] + freq[14]+ freq[20]; // Count total number of consonants int nconsonants= str.length() - nvowels; // Calculate the total number of ways ways = npr(odd, nvowels) * npr(nconsonants, nconsonants); return ways;} // Driver codepublic static void main(String[] args){ String str = \"geeks\"; System.out.println(countPermutations(str));}}// This code is contributed by mits",
"e": 29843,
"s": 28416,
"text": null
},
{
"code": "# Python3 program to find the number# of ways in which the characters# of the word can be arranged such# that the vowels occupy only the# odd positionsimport math # Function to return the factorial# of a numberdef fact(n): f = 1; for i in range(2, n + 1): f = f * i; return f; # calculating nPrdef npr(n, r): return fact(n) / fact(n - r); # Function to find the number of# ways in which the characters of# the word can be arranged such# that the vowels occupy only the# odd positionsdef countPermutations(str): # Get total even positions even = math.floor(len(str) / 2); # Get total odd positions odd = len(str) - even; ways = 0; # Store frequency of each # character of the string freq = [0] * 26; for i in range(len(str)): freq[ord(str[i]) - ord('a')] += 1; # Count total number of vowels nvowels = (freq[0] + freq[4] + freq[8] + freq[14] + freq[20]); # Count total number of consonants nconsonants = len(str) - nvowels; # Calculate the total number of ways ways = (npr(odd, nvowels) * npr(nconsonants, nconsonants)); return int(ways); # Driver codestr = \"geeks\"; print(countPermutations(str)); # This code is contributed by mits",
"e": 31087,
"s": 29843,
"text": null
},
{
"code": "// C# program to find the number of ways// in which the characters of the word// can be arranged such that the vowels// occupy only the odd positionsusing System;class GFG{// Function to return the// factorial of a numberstatic int fact(int n){ int f = 1; for (int i = 2; i <= n; i++) { f = f * i; } return f;} // calculating nPrstatic int npr(int n, int r){ return fact(n) / fact(n - r);} // Function to find the number of ways// in which the characters of the word// can be arranged such that the vowels// occupy only the odd positionsstatic int countPermutations(String str){ // Get total even positions int even = (int)Math.Floor((double)(str.Length / 2)); // Get total odd positions int odd = str.Length - even; int ways = 0; // Store frequency of each character of // the string int[] freq=new int[26]; for (int i = 0; i < str.Length; i++) { freq[(int)(str[i]-'a')]++; } // Count total number of vowels int nvowels= freq[0] + freq[4]+ freq[8] + freq[14]+ freq[20]; // Count total number of consonants int nconsonants= str.Length - nvowels; // Calculate the total number of ways ways = npr(odd, nvowels) * npr(nconsonants, nconsonants); return ways;} // Driver codestatic void Main(){ String str = \"geeks\"; Console.WriteLine(countPermutations(str));}}// This code is contributed by mits",
"e": 32489,
"s": 31087,
"text": null
},
{
"code": "<?php// PHP program to find the number// of ways in which the characters// of the word can be arranged such// that the vowels occupy only the// odd positions // Function to return the// factorial of a numberfunction fact($n){ $f = 1; for ($i = 2; $i <= $n; $i++) { $f = $f * $i; } return $f;} // calculating nPrfunction npr($n, $r){ return fact($n) / fact($n - $r);} // Function to find the number// of $ways in which the characters// of the word can be arranged such// that the vowels occupy only the// odd positionsfunction countPermutations($str){ // Get total even positions $even = floor(strlen($str)/ 2); // Get total odd positions $odd = strlen($str) - $even; $ways = 0; // Store $frequency of each // character of the string $freq = array_fill(0, 26, 0); for ($i = 0; $i < strlen($str); $i++) { ++$freq[ord($str[$i]) - ord('a')]; } // Count total number of vowels $nvowels= $freq[0] + $freq[4] + $freq[8] + $freq[14] + $freq[20]; // Count total number of consonants $nconsonants= strlen($str) - $nvowels; // Calculate the total number of ways $ways = npr($odd, $nvowels) * npr($nconsonants, $nconsonants); return $ways;} // Driver code$str = \"geeks\"; echo countPermutations($str); // This code is contributed by mits?>",
"e": 33851,
"s": 32489,
"text": null
},
{
"code": "<script>// Javascript program to find the number// of ways in which the characters// of the word can be arranged such// that the vowels occupy only the// odd positions // Function to return the// factorial of a numberfunction fact(n){ let f = 1; for (let i = 2; i <= n; i++) { f = f * i; } return f;} // calculating nPrfunction npr(n, r){ return fact(n) / fact(n - r);} // Function to find the number// of ways in which the characters// of the word can be arranged such// that the vowels occupy only the// odd positionsfunction countPermutations(str){ // Get total even positions let even = Math.floor(str.length/ 2); // Get total odd positions let odd = str.length - even; let ways = 0; // Store frequency of each // character of the string let freq = new Array(26).fill(0); for (let i = 0; i < str.length; i++) { ++freq[str.charCodeAt(i) - 'a'.charCodeAt(0)]; } // Count total number of vowels let nvowels= freq[0] + freq[4] + freq[8] + freq[14] + freq[20]; // Count total number of consonants let nconsonants= str.length - nvowels; // Calculate the total number of ways ways = npr(odd, nvowels) * npr(nconsonants, nconsonants); return ways;} // Driver codelet str = \"geeks\"; document.write(countPermutations(str)); // This code is contributed by gfgking</script>",
"e": 35248,
"s": 33851,
"text": null
},
{
"code": null,
"e": 35251,
"s": 35248,
"text": "36"
},
{
"code": null,
"e": 35266,
"s": 35253,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 35274,
"s": 35266,
"text": "gfgking"
},
{
"code": null,
"e": 35284,
"s": 35274,
"text": "factorial"
},
{
"code": null,
"e": 35296,
"s": 35284,
"text": "permutation"
},
{
"code": null,
"e": 35312,
"s": 35296,
"text": "vowel-consonant"
},
{
"code": null,
"e": 35325,
"s": 35312,
"text": "Mathematical"
},
{
"code": null,
"e": 35333,
"s": 35325,
"text": "Strings"
},
{
"code": null,
"e": 35341,
"s": 35333,
"text": "Strings"
},
{
"code": null,
"e": 35354,
"s": 35341,
"text": "Mathematical"
},
{
"code": null,
"e": 35366,
"s": 35354,
"text": "permutation"
},
{
"code": null,
"e": 35376,
"s": 35366,
"text": "factorial"
},
{
"code": null,
"e": 35474,
"s": 35376,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35518,
"s": 35474,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 35560,
"s": 35518,
"text": "Segment Tree | Set 1 (Sum of given range)"
},
{
"code": null,
"e": 35591,
"s": 35560,
"text": "Modular multiplicative inverse"
},
{
"code": null,
"e": 35662,
"s": 35591,
"text": "Count all possible paths from top left to bottom right of a mXn matrix"
},
{
"code": null,
"e": 35687,
"s": 35662,
"text": "Fizz Buzz Implementation"
},
{
"code": null,
"e": 35733,
"s": 35687,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 35758,
"s": 35733,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 35792,
"s": 35758,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 35867,
"s": 35792,
"text": "Check for Balanced Brackets in an expression (well-formedness) using Stack"
}
] |
Multidimensional arrays in PHP - GeeksforGeeks
|
31 Jul, 2021
Multi-dimensional arrays are such type of arrays which stores an another array at each index instead of single element. In other words, define multi-dimensional arrays as array of arrays. As the name suggests, every element in this array can be an array and they can also hold other sub-arrays within. Arrays or sub-arrays in multidimensional arrays can be accessed using multiple dimensions.
Dimensions: Dimensions of multidimensional array indicates the number of indices needed to select an element. For a two dimensional array two indices to select an element.
Two dimensional array: It is the simplest form of a multidimensional array. It can be created using nested array. These type of arrays can be used to store any type of elements, but the index is always a number. By default, the index starts with zero.
Syntax:
array (
array (elements...),
array (elements...),
...
)
Example:
<?php // PHP program to create // multidimensional array // Creating multidimensional// array$myarray = array( // Default key for each will // start from 0 array("Ankit", "Ram", "Shyam"), array("Unnao", "Trichy", "Kanpur")); // Display the array informationprint_r($myarray);?>
Array
(
[0] => Array
(
[0] => Ankit
[1] => Ram
[2] => Shyam
)
[1] => Array
(
[0] => Unnao
[1] => Trichy
[2] => Kanpur
)
)
Two dimensional associative array: Al associative array is similar to indexed array but instead of linear storage (indexed storage), every value can be assigned with a user-defined key of string type.
Example:
<?php // PHP program to creating two // dimensional associative array$marks = array( // Ankit will act as key "Ankit" => array( // Subject and marks are // the key value pair "C" => 95, "DCO" => 85, "FOL" => 74, ), // Ram will act as key "Ram" => array( // Subject and marks are // the key value pair "C" => 78, "DCO" => 98, "FOL" => 46, ), // Anoop will act as key "Anoop" => array( // Subject and marks are // the key value pair "C" => 88, "DCO" => 46, "FOL" => 99, ),); echo "Display Marks: \n"; print_r($marks);?>
Display Marks:
Array
(
[Ankit] => Array
(
[C] => 95
[DCO] => 85
[FOL] => 74
)
[Ram] => Array
(
[C] => 78
[DCO] => 98
[FOL] => 46
)
[Anoop] => Array
(
[C] => 88
[DCO] => 46
[FOL] => 99
)
)
Three Dimensional Array: It is the form of multidimensional array. Initialization in Three-Dimensional array is same as that of Two-dimensional arrays. The difference is as the number of dimension increases so the number of nested braces will also increase.
Syntax:
array (
array (
array (elements...),
array (elements...),
...
),
array (
array (elements...),
array (elements...),
...
),
...
)
Example:
<?php // PHP program to creating three// dimensional array // Create three nested array$myarray = array( array( array(1, 2), array(3, 4), ), array( array(5, 6), array(7, 8), ),); // Display the array informationprint_r($myarray);?>
Array
(
[0] => Array
(
[0] => Array
(
[0] => 1
[1] => 2
)
[1] => Array
(
[0] => 3
[1] => 4
)
)
[1] => Array
(
[0] => Array
(
[0] => 5
[1] => 6
)
[1] => Array
(
[0] => 7
[1] => 8
)
)
)
Accessing multidimensional array elements: There are mainly two ways to access multidimensional array elements in PHP.
Elements can be accessed using dimensions as array_name[‘first dimension’][‘second dimension’].
Elements can be accessed using for loop.
Elements can be accessed using for each loop.
Example:
<?php // PHP code to create // multidimensional array // Creating multidimensional// associative array$marks = array( // Ankit will act as key "Ankit" => array( // Subject and marks are // the key value pair "C" => 95, "DCO" => 85, "FOL" => 74, ), // Ram will act as key "Ram" => array( // Subject and marks are // the key value pair "C" => 78, "DCO" => 98, "FOL" => 46, ), // Anoop will act as key "Anoop" => array( // Subject and marks are // the key value pair "C" => 88, "DCO" => 46, "FOL" => 99, ),); // Accessing the array element // using dimensions // It will display the marks of// Ankit in C subjectecho $marks['Ankit']['C'] . "\n"; // Accessing array elements using for each loopforeach($marks as $mark) { echo $mark['C']. " ".$mark['DCO']." ".$mark['FOL']."\n"; } ?>
95
95 85 74
78 98 46
88 46 99
PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.
PHP-array
Picked
PHP
PHP Programs
Technical Scripter
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 pass JavaScript variables to PHP ?
Split a comma delimited string into an array in PHP
Download file from URL using PHP
How to convert array to string in PHP ?
How to call PHP function on the click of a Button ?
How to pass JavaScript variables to PHP ?
Split a comma delimited string into an array in PHP
How to get parameters from a URL string in PHP?
|
[
{
"code": null,
"e": 25695,
"s": 25667,
"text": "\n31 Jul, 2021"
},
{
"code": null,
"e": 26088,
"s": 25695,
"text": "Multi-dimensional arrays are such type of arrays which stores an another array at each index instead of single element. In other words, define multi-dimensional arrays as array of arrays. As the name suggests, every element in this array can be an array and they can also hold other sub-arrays within. Arrays or sub-arrays in multidimensional arrays can be accessed using multiple dimensions."
},
{
"code": null,
"e": 26260,
"s": 26088,
"text": "Dimensions: Dimensions of multidimensional array indicates the number of indices needed to select an element. For a two dimensional array two indices to select an element."
},
{
"code": null,
"e": 26512,
"s": 26260,
"text": "Two dimensional array: It is the simplest form of a multidimensional array. It can be created using nested array. These type of arrays can be used to store any type of elements, but the index is always a number. By default, the index starts with zero."
},
{
"code": null,
"e": 26520,
"s": 26512,
"text": "Syntax:"
},
{
"code": null,
"e": 26588,
"s": 26520,
"text": "array (\n array (elements...),\n array (elements...),\n ...\n)"
},
{
"code": null,
"e": 26597,
"s": 26588,
"text": "Example:"
},
{
"code": "<?php // PHP program to create // multidimensional array // Creating multidimensional// array$myarray = array( // Default key for each will // start from 0 array(\"Ankit\", \"Ram\", \"Shyam\"), array(\"Unnao\", \"Trichy\", \"Kanpur\")); // Display the array informationprint_r($myarray);?>",
"e": 26900,
"s": 26597,
"text": null
},
{
"code": null,
"e": 27137,
"s": 26900,
"text": "Array\n(\n [0] => Array\n (\n [0] => Ankit\n [1] => Ram\n [2] => Shyam\n )\n\n [1] => Array\n (\n [0] => Unnao\n [1] => Trichy\n [2] => Kanpur\n )\n\n)\n"
},
{
"code": null,
"e": 27338,
"s": 27137,
"text": "Two dimensional associative array: Al associative array is similar to indexed array but instead of linear storage (indexed storage), every value can be assigned with a user-defined key of string type."
},
{
"code": null,
"e": 27347,
"s": 27338,
"text": "Example:"
},
{
"code": "<?php // PHP program to creating two // dimensional associative array$marks = array( // Ankit will act as key \"Ankit\" => array( // Subject and marks are // the key value pair \"C\" => 95, \"DCO\" => 85, \"FOL\" => 74, ), // Ram will act as key \"Ram\" => array( // Subject and marks are // the key value pair \"C\" => 78, \"DCO\" => 98, \"FOL\" => 46, ), // Anoop will act as key \"Anoop\" => array( // Subject and marks are // the key value pair \"C\" => 88, \"DCO\" => 46, \"FOL\" => 99, ),); echo \"Display Marks: \\n\"; print_r($marks);?>",
"e": 28056,
"s": 27347,
"text": null
},
{
"code": null,
"e": 28417,
"s": 28056,
"text": "Display Marks: \nArray\n(\n [Ankit] => Array\n (\n [C] => 95\n [DCO] => 85\n [FOL] => 74\n )\n\n [Ram] => Array\n (\n [C] => 78\n [DCO] => 98\n [FOL] => 46\n )\n\n [Anoop] => Array\n (\n [C] => 88\n [DCO] => 46\n [FOL] => 99\n )\n\n)\n"
},
{
"code": null,
"e": 28675,
"s": 28417,
"text": "Three Dimensional Array: It is the form of multidimensional array. Initialization in Three-Dimensional array is same as that of Two-dimensional arrays. The difference is as the number of dimension increases so the number of nested braces will also increase."
},
{
"code": null,
"e": 28683,
"s": 28675,
"text": "Syntax:"
},
{
"code": null,
"e": 28879,
"s": 28683,
"text": "array (\n array (\n array (elements...),\n array (elements...),\n ...\n ),\n array (\n array (elements...),\n array (elements...),\n ...\n ),\n ...\n)"
},
{
"code": null,
"e": 28888,
"s": 28879,
"text": "Example:"
},
{
"code": "<?php // PHP program to creating three// dimensional array // Create three nested array$myarray = array( array( array(1, 2), array(3, 4), ), array( array(5, 6), array(7, 8), ),); // Display the array informationprint_r($myarray);?>",
"e": 29167,
"s": 28888,
"text": null
},
{
"code": null,
"e": 29734,
"s": 29167,
"text": "Array\n(\n [0] => Array\n (\n [0] => Array\n (\n [0] => 1\n [1] => 2\n )\n\n [1] => Array\n (\n [0] => 3\n [1] => 4\n )\n\n )\n\n [1] => Array\n (\n [0] => Array\n (\n [0] => 5\n [1] => 6\n )\n\n [1] => Array\n (\n [0] => 7\n [1] => 8\n )\n\n )\n\n)\n"
},
{
"code": null,
"e": 29853,
"s": 29734,
"text": "Accessing multidimensional array elements: There are mainly two ways to access multidimensional array elements in PHP."
},
{
"code": null,
"e": 29949,
"s": 29853,
"text": "Elements can be accessed using dimensions as array_name[‘first dimension’][‘second dimension’]."
},
{
"code": null,
"e": 29990,
"s": 29949,
"text": "Elements can be accessed using for loop."
},
{
"code": null,
"e": 30036,
"s": 29990,
"text": "Elements can be accessed using for each loop."
},
{
"code": null,
"e": 30045,
"s": 30036,
"text": "Example:"
},
{
"code": "<?php // PHP code to create // multidimensional array // Creating multidimensional// associative array$marks = array( // Ankit will act as key \"Ankit\" => array( // Subject and marks are // the key value pair \"C\" => 95, \"DCO\" => 85, \"FOL\" => 74, ), // Ram will act as key \"Ram\" => array( // Subject and marks are // the key value pair \"C\" => 78, \"DCO\" => 98, \"FOL\" => 46, ), // Anoop will act as key \"Anoop\" => array( // Subject and marks are // the key value pair \"C\" => 88, \"DCO\" => 46, \"FOL\" => 99, ),); // Accessing the array element // using dimensions // It will display the marks of// Ankit in C subjectecho $marks['Ankit']['C'] . \"\\n\"; // Accessing array elements using for each loopforeach($marks as $mark) { echo $mark['C']. \" \".$mark['DCO'].\" \".$mark['FOL'].\"\\n\"; } ?>",
"e": 31033,
"s": 30045,
"text": null
},
{
"code": null,
"e": 31064,
"s": 31033,
"text": "95\n95 85 74\n78 98 46\n88 46 99\n"
},
{
"code": null,
"e": 31233,
"s": 31064,
"text": "PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples."
},
{
"code": null,
"e": 31243,
"s": 31233,
"text": "PHP-array"
},
{
"code": null,
"e": 31250,
"s": 31243,
"text": "Picked"
},
{
"code": null,
"e": 31254,
"s": 31250,
"text": "PHP"
},
{
"code": null,
"e": 31267,
"s": 31254,
"text": "PHP Programs"
},
{
"code": null,
"e": 31286,
"s": 31267,
"text": "Technical Scripter"
},
{
"code": null,
"e": 31303,
"s": 31286,
"text": "Web Technologies"
},
{
"code": null,
"e": 31307,
"s": 31303,
"text": "PHP"
},
{
"code": null,
"e": 31405,
"s": 31307,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31445,
"s": 31405,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 31490,
"s": 31445,
"text": "PHP | Converting string to Date and DateTime"
},
{
"code": null,
"e": 31532,
"s": 31490,
"text": "How to pass JavaScript variables to PHP ?"
},
{
"code": null,
"e": 31584,
"s": 31532,
"text": "Split a comma delimited string into an array in PHP"
},
{
"code": null,
"e": 31617,
"s": 31584,
"text": "Download file from URL using PHP"
},
{
"code": null,
"e": 31657,
"s": 31617,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 31709,
"s": 31657,
"text": "How to call PHP function on the click of a Button ?"
},
{
"code": null,
"e": 31751,
"s": 31709,
"text": "How to pass JavaScript variables to PHP ?"
},
{
"code": null,
"e": 31803,
"s": 31751,
"text": "Split a comma delimited string into an array in PHP"
}
] |
CSS | empty-cells Property - GeeksforGeeks
|
06 Sep, 2021
This property is used to specify whether to display the borders or not in the empty cells in a table.
Syntax:
empty-cells: show|hide|initial|inherit;
Default Value:
show
Property values:
show property: This property is used to display the borders on empty cells.
Syntax:empty-cell: show;
empty-cell: show;
Example:htmlhtml<!DOCTYPE html><html> <head> <title>empty-cell property</title> <style> table.geek { empty-cells: show; } td { text-align:center; } .gfg { font-size:40px; font-weight:bold; color:green; } .geeks { font-size:17px; } </style> </head> <body> <center> <div class = "gfg">GeeksforGeeks</div> <div class = "geeks">A computer science portal for geeks</div> <h2>empty-cells: show;</h2> <table class="geek" border="1"> <tr> <td>C Programming</td> <td>C++ Programming</td> </trA> <tr> <td>Java</td> <td></td> </tr> </table> </center> </body></html>
html
<!DOCTYPE html><html> <head> <title>empty-cell property</title> <style> table.geek { empty-cells: show; } td { text-align:center; } .gfg { font-size:40px; font-weight:bold; color:green; } .geeks { font-size:17px; } </style> </head> <body> <center> <div class = "gfg">GeeksforGeeks</div> <div class = "geeks">A computer science portal for geeks</div> <h2>empty-cells: show;</h2> <table class="geek" border="1"> <tr> <td>C Programming</td> <td>C++ Programming</td> </trA> <tr> <td>Java</td> <td></td> </tr> </table> </center> </body></html>
Output:
hide property: This property is used to hide the border in empty-cell in the table.
Syntax:empty-cell: hide;
empty-cell: hide;
Example:htmlhtml<!DOCTYPE html><html> <head> <title>empty-cell property</title> <style> table.geek { empty-cells: hide; } td { text-align:center; } .gfg { font-size:40px; font-weight:bold; color:green; } .geeks { font-size:17px; } </style> </head> <body> <center> <div class = "gfg">GeeksforGeeks</div> <div class = "geeks">A computer science portal for geeks</div> <h2>empty-cells: show;</h2> <table class="geek" border="1"> <tr> <td>C Programming</td> <td>C++ Programming</td> </trA> <tr> <td>Java</td> <td></td> </tr> </table> </center> </body></html>
html
<!DOCTYPE html><html> <head> <title>empty-cell property</title> <style> table.geek { empty-cells: hide; } td { text-align:center; } .gfg { font-size:40px; font-weight:bold; color:green; } .geeks { font-size:17px; } </style> </head> <body> <center> <div class = "gfg">GeeksforGeeks</div> <div class = "geeks">A computer science portal for geeks</div> <h2>empty-cells: show;</h2> <table class="geek" border="1"> <tr> <td>C Programming</td> <td>C++ Programming</td> </trA> <tr> <td>Java</td> <td></td> </tr> </table> </center> </body></html>
Output:
initial property: This property is used to set the default property.
Syntax:empty-cell: initial;
empty-cell: initial;
Example:htmlhtml<!DOCTYPE html><html> <head> <title>empty-cell property</title> <style> table.geek { empty-cells: initial; } td { text-align:center; } .gfg { font-size:40px; font-weight:bold; color:green; } .geeks { font-size:17px; } </style> </head> <body> <center> <div class = "gfg">GeeksforGeeks</div> <div class = "geeks">A computer science portal for geeks</div> <h2>empty-cells: show;</h2> <table class="geek" border="1"> <tr> <td>C Programming</td> <td>C++ Programming</td> </trA> <tr> <td>Java</td> <td></td> </tr> </table> </center> </body></html>
html
<!DOCTYPE html><html> <head> <title>empty-cell property</title> <style> table.geek { empty-cells: initial; } td { text-align:center; } .gfg { font-size:40px; font-weight:bold; color:green; } .geeks { font-size:17px; } </style> </head> <body> <center> <div class = "gfg">GeeksforGeeks</div> <div class = "geeks">A computer science portal for geeks</div> <h2>empty-cells: show;</h2> <table class="geek" border="1"> <tr> <td>C Programming</td> <td>C++ Programming</td> </trA> <tr> <td>Java</td> <td></td> </tr> </table> </center> </body></html>
Output:
inherit property: This property is used to inherit the property from its parent.
Syntax:empty-cell: inherit;
empty-cell: inherit;
Example:htmlhtml<!DOCTYPE html><html> <head> <title>empty-cell property</title> <style> table.geek { empty-cells: initial; } .g4g { empty-cells: inherit; } td { text-align:center; } .gfg { font-size:40px; font-weight:bold; color:green; } .geeks { font-size:17px; } </style> </head> <body> <center> <div class = "gfg">GeeksforGeeks</div> <div class = "geeks">A computer science portal for geeks</div> <h2>empty-cells: show;</h2> <table class="geek" border="1"> <tr> <td>C Programming</td> <td>Algorithm</td> </tr> <tr> <td></td> <td> <table class="g4g" border="1"> <tr> <td>DP</td> <td>Backtracking</td> </tr> <tr> <td>Sorting</td> <td></td> </tr> </table> </td> </tr> </table> </center> </body></html>
html
<!DOCTYPE html><html> <head> <title>empty-cell property</title> <style> table.geek { empty-cells: initial; } .g4g { empty-cells: inherit; } td { text-align:center; } .gfg { font-size:40px; font-weight:bold; color:green; } .geeks { font-size:17px; } </style> </head> <body> <center> <div class = "gfg">GeeksforGeeks</div> <div class = "geeks">A computer science portal for geeks</div> <h2>empty-cells: show;</h2> <table class="geek" border="1"> <tr> <td>C Programming</td> <td>Algorithm</td> </tr> <tr> <td></td> <td> <table class="g4g" border="1"> <tr> <td>DP</td> <td>Backtracking</td> </tr> <tr> <td>Sorting</td> <td></td> </tr> </table> </td> </tr> </table> </center> </body></html>
Output:
Supported Browsers: The browsers supported by CSS | empty-cells Property are listed below:
Google Chrome 1.0
Internet Esplorer 8.0
Firefox 1.0
Opera 4.0
Safari 1.2
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
hritikbhatnagar2182
CSS-Properties
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to update Node.js and NPM to next version ?
How to create footer to stay at the bottom of a Web page?
How to apply style to parent if it has child with CSS?
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to update Node.js and NPM to next version ?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
|
[
{
"code": null,
"e": 24979,
"s": 24951,
"text": "\n06 Sep, 2021"
},
{
"code": null,
"e": 25081,
"s": 24979,
"text": "This property is used to specify whether to display the borders or not in the empty cells in a table."
},
{
"code": null,
"e": 25089,
"s": 25081,
"text": "Syntax:"
},
{
"code": null,
"e": 25129,
"s": 25089,
"text": "empty-cells: show|hide|initial|inherit;"
},
{
"code": null,
"e": 25144,
"s": 25129,
"text": "Default Value:"
},
{
"code": null,
"e": 25149,
"s": 25144,
"text": "show"
},
{
"code": null,
"e": 25166,
"s": 25149,
"text": "Property values:"
},
{
"code": null,
"e": 25242,
"s": 25166,
"text": "show property: This property is used to display the borders on empty cells."
},
{
"code": null,
"e": 25267,
"s": 25242,
"text": "Syntax:empty-cell: show;"
},
{
"code": null,
"e": 25285,
"s": 25267,
"text": "empty-cell: show;"
},
{
"code": null,
"e": 26269,
"s": 25285,
"text": "Example:htmlhtml<!DOCTYPE html><html> <head> <title>empty-cell property</title> <style> table.geek { empty-cells: show; } td { text-align:center; } .gfg { font-size:40px; font-weight:bold; color:green; } .geeks { font-size:17px; } </style> </head> <body> <center> <div class = \"gfg\">GeeksforGeeks</div> <div class = \"geeks\">A computer science portal for geeks</div> <h2>empty-cells: show;</h2> <table class=\"geek\" border=\"1\"> <tr> <td>C Programming</td> <td>C++ Programming</td> </trA> <tr> <td>Java</td> <td></td> </tr> </table> </center> </body></html> "
},
{
"code": null,
"e": 26274,
"s": 26269,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title>empty-cell property</title> <style> table.geek { empty-cells: show; } td { text-align:center; } .gfg { font-size:40px; font-weight:bold; color:green; } .geeks { font-size:17px; } </style> </head> <body> <center> <div class = \"gfg\">GeeksforGeeks</div> <div class = \"geeks\">A computer science portal for geeks</div> <h2>empty-cells: show;</h2> <table class=\"geek\" border=\"1\"> <tr> <td>C Programming</td> <td>C++ Programming</td> </trA> <tr> <td>Java</td> <td></td> </tr> </table> </center> </body></html> ",
"e": 27242,
"s": 26274,
"text": null
},
{
"code": null,
"e": 27250,
"s": 27242,
"text": "Output:"
},
{
"code": null,
"e": 27334,
"s": 27250,
"text": "hide property: This property is used to hide the border in empty-cell in the table."
},
{
"code": null,
"e": 27359,
"s": 27334,
"text": "Syntax:empty-cell: hide;"
},
{
"code": null,
"e": 27377,
"s": 27359,
"text": "empty-cell: hide;"
},
{
"code": null,
"e": 28361,
"s": 27377,
"text": "Example:htmlhtml<!DOCTYPE html><html> <head> <title>empty-cell property</title> <style> table.geek { empty-cells: hide; } td { text-align:center; } .gfg { font-size:40px; font-weight:bold; color:green; } .geeks { font-size:17px; } </style> </head> <body> <center> <div class = \"gfg\">GeeksforGeeks</div> <div class = \"geeks\">A computer science portal for geeks</div> <h2>empty-cells: show;</h2> <table class=\"geek\" border=\"1\"> <tr> <td>C Programming</td> <td>C++ Programming</td> </trA> <tr> <td>Java</td> <td></td> </tr> </table> </center> </body></html> "
},
{
"code": null,
"e": 28366,
"s": 28361,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title>empty-cell property</title> <style> table.geek { empty-cells: hide; } td { text-align:center; } .gfg { font-size:40px; font-weight:bold; color:green; } .geeks { font-size:17px; } </style> </head> <body> <center> <div class = \"gfg\">GeeksforGeeks</div> <div class = \"geeks\">A computer science portal for geeks</div> <h2>empty-cells: show;</h2> <table class=\"geek\" border=\"1\"> <tr> <td>C Programming</td> <td>C++ Programming</td> </trA> <tr> <td>Java</td> <td></td> </tr> </table> </center> </body></html> ",
"e": 29334,
"s": 28366,
"text": null
},
{
"code": null,
"e": 29342,
"s": 29334,
"text": "Output:"
},
{
"code": null,
"e": 29411,
"s": 29342,
"text": "initial property: This property is used to set the default property."
},
{
"code": null,
"e": 29439,
"s": 29411,
"text": "Syntax:empty-cell: initial;"
},
{
"code": null,
"e": 29460,
"s": 29439,
"text": "empty-cell: initial;"
},
{
"code": null,
"e": 30447,
"s": 29460,
"text": "Example:htmlhtml<!DOCTYPE html><html> <head> <title>empty-cell property</title> <style> table.geek { empty-cells: initial; } td { text-align:center; } .gfg { font-size:40px; font-weight:bold; color:green; } .geeks { font-size:17px; } </style> </head> <body> <center> <div class = \"gfg\">GeeksforGeeks</div> <div class = \"geeks\">A computer science portal for geeks</div> <h2>empty-cells: show;</h2> <table class=\"geek\" border=\"1\"> <tr> <td>C Programming</td> <td>C++ Programming</td> </trA> <tr> <td>Java</td> <td></td> </tr> </table> </center> </body></html> "
},
{
"code": null,
"e": 30452,
"s": 30447,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title>empty-cell property</title> <style> table.geek { empty-cells: initial; } td { text-align:center; } .gfg { font-size:40px; font-weight:bold; color:green; } .geeks { font-size:17px; } </style> </head> <body> <center> <div class = \"gfg\">GeeksforGeeks</div> <div class = \"geeks\">A computer science portal for geeks</div> <h2>empty-cells: show;</h2> <table class=\"geek\" border=\"1\"> <tr> <td>C Programming</td> <td>C++ Programming</td> </trA> <tr> <td>Java</td> <td></td> </tr> </table> </center> </body></html> ",
"e": 31423,
"s": 30452,
"text": null
},
{
"code": null,
"e": 31431,
"s": 31423,
"text": "Output:"
},
{
"code": null,
"e": 31512,
"s": 31431,
"text": "inherit property: This property is used to inherit the property from its parent."
},
{
"code": null,
"e": 31540,
"s": 31512,
"text": "Syntax:empty-cell: inherit;"
},
{
"code": null,
"e": 31561,
"s": 31540,
"text": "empty-cell: inherit;"
},
{
"code": null,
"e": 33058,
"s": 31561,
"text": "Example:htmlhtml<!DOCTYPE html><html> <head> <title>empty-cell property</title> <style> table.geek { empty-cells: initial; } .g4g { empty-cells: inherit; } td { text-align:center; } .gfg { font-size:40px; font-weight:bold; color:green; } .geeks { font-size:17px; } </style> </head> <body> <center> <div class = \"gfg\">GeeksforGeeks</div> <div class = \"geeks\">A computer science portal for geeks</div> <h2>empty-cells: show;</h2> <table class=\"geek\" border=\"1\"> <tr> <td>C Programming</td> <td>Algorithm</td> </tr> <tr> <td></td> <td> <table class=\"g4g\" border=\"1\"> <tr> <td>DP</td> <td>Backtracking</td> </tr> <tr> <td>Sorting</td> <td></td> </tr> </table> </td> </tr> </table> </center> </body></html> "
},
{
"code": null,
"e": 33063,
"s": 33058,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title>empty-cell property</title> <style> table.geek { empty-cells: initial; } .g4g { empty-cells: inherit; } td { text-align:center; } .gfg { font-size:40px; font-weight:bold; color:green; } .geeks { font-size:17px; } </style> </head> <body> <center> <div class = \"gfg\">GeeksforGeeks</div> <div class = \"geeks\">A computer science portal for geeks</div> <h2>empty-cells: show;</h2> <table class=\"geek\" border=\"1\"> <tr> <td>C Programming</td> <td>Algorithm</td> </tr> <tr> <td></td> <td> <table class=\"g4g\" border=\"1\"> <tr> <td>DP</td> <td>Backtracking</td> </tr> <tr> <td>Sorting</td> <td></td> </tr> </table> </td> </tr> </table> </center> </body></html> ",
"e": 34544,
"s": 33063,
"text": null
},
{
"code": null,
"e": 34552,
"s": 34544,
"text": "Output:"
},
{
"code": null,
"e": 34643,
"s": 34552,
"text": "Supported Browsers: The browsers supported by CSS | empty-cells Property are listed below:"
},
{
"code": null,
"e": 34661,
"s": 34643,
"text": "Google Chrome 1.0"
},
{
"code": null,
"e": 34683,
"s": 34661,
"text": "Internet Esplorer 8.0"
},
{
"code": null,
"e": 34695,
"s": 34683,
"text": "Firefox 1.0"
},
{
"code": null,
"e": 34705,
"s": 34695,
"text": "Opera 4.0"
},
{
"code": null,
"e": 34716,
"s": 34705,
"text": "Safari 1.2"
},
{
"code": null,
"e": 34853,
"s": 34716,
"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": 34873,
"s": 34853,
"text": "hritikbhatnagar2182"
},
{
"code": null,
"e": 34888,
"s": 34873,
"text": "CSS-Properties"
},
{
"code": null,
"e": 34892,
"s": 34888,
"text": "CSS"
},
{
"code": null,
"e": 34897,
"s": 34892,
"text": "HTML"
},
{
"code": null,
"e": 34914,
"s": 34897,
"text": "Web Technologies"
},
{
"code": null,
"e": 34919,
"s": 34914,
"text": "HTML"
},
{
"code": null,
"e": 35017,
"s": 34919,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35067,
"s": 35017,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 35129,
"s": 35067,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 35177,
"s": 35129,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 35235,
"s": 35177,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 35290,
"s": 35235,
"text": "How to apply style to parent if it has child with CSS?"
},
{
"code": null,
"e": 35340,
"s": 35290,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 35402,
"s": 35340,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 35450,
"s": 35402,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 35510,
"s": 35450,
"text": "How to set the default value for an HTML <select> element ?"
}
] |
NumPy - Fibonacci Series using Binet Formula - GeeksforGeeks
|
03 Jun, 2020
All of us are familiar with Fibonacci Series. Each number in the sequence is the sum of the two numbers that precede it. So, the sequence goes: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34...... In this tutorial, we will implement the same using NumPy with the aid of Binet formula.
Binet Formula
‘n’ is the parameter which relates the first ‘n’ numbers of Fibonacci Series. In the first example we are going to findout first 10 numbers of Fibonacci Series (n = 10), after that we takes the parameter ‘n’ from user and produce the corresponding result.
NOTE : We are ignoring the first element(0) of Fibonacci Series
Example 1: To find first 10 Fibonacci numbers .
import numpy as np # We are creating an array contains n = 10 elements# for getting first 10 Fibonacci numbersa = np.arange(1, 11)lengthA = len(a) # splitting of terms for easinesssqrtFive = np.sqrt(5)alpha = (1 + sqrtFive) / 2beta = (1 - sqrtFive) / 2 # Implementation of formula# np.rint is used for rounding off to integerFn = np.rint(((alpha ** a) - (beta ** a)) / (sqrtFive))print("The first {} numbers of Fibonacci series are {} . ".format(lengthA, Fn))
Output :
The first 10 numbers of Fibonacci series are [ 1. 1. 2. 3. 5. 8. 13. 21. 34. 55.] .
Example 2 : To find first ‘n’ Fibonacci numbers ..
import numpy as np # We are creating an array contains n elements# for getting first 'n' Fibonacci numbersfNumber = int(input("Enter the value of n + 1'th number : "))a = np.arange(1, fNumber)length_a = len(a) # splitting of terms for easinesssqrt_five = np.sqrt(5)alpha = (1 + sqrt_five) / 2beta = (1 - sqrt_five) / 2 # Implementation of formula# np.rint is used for rounding off to integerFn = np.rint(((alpha ** a) - (beta ** a)) / (sqrt_five))print("The first {} numbers of Fibonacci series are {} . ".format(length_a, Fn))
Output :
# Here user input was 10
Enter the value of n+1'th number :10
The first 9 numbers of Fibonacci series are [ 1. 1. 2. 3. 5. 8. 13. 21. 34.] .
Python numpy-arrayManipulation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
|
[
{
"code": null,
"e": 26347,
"s": 26319,
"text": "\n03 Jun, 2020"
},
{
"code": null,
"e": 26617,
"s": 26347,
"text": "All of us are familiar with Fibonacci Series. Each number in the sequence is the sum of the two numbers that precede it. So, the sequence goes: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34...... In this tutorial, we will implement the same using NumPy with the aid of Binet formula."
},
{
"code": null,
"e": 26631,
"s": 26617,
"text": "Binet Formula"
},
{
"code": null,
"e": 26887,
"s": 26631,
"text": "‘n’ is the parameter which relates the first ‘n’ numbers of Fibonacci Series. In the first example we are going to findout first 10 numbers of Fibonacci Series (n = 10), after that we takes the parameter ‘n’ from user and produce the corresponding result."
},
{
"code": null,
"e": 26951,
"s": 26887,
"text": "NOTE : We are ignoring the first element(0) of Fibonacci Series"
},
{
"code": null,
"e": 26999,
"s": 26951,
"text": "Example 1: To find first 10 Fibonacci numbers ."
},
{
"code": "import numpy as np # We are creating an array contains n = 10 elements# for getting first 10 Fibonacci numbersa = np.arange(1, 11)lengthA = len(a) # splitting of terms for easinesssqrtFive = np.sqrt(5)alpha = (1 + sqrtFive) / 2beta = (1 - sqrtFive) / 2 # Implementation of formula# np.rint is used for rounding off to integerFn = np.rint(((alpha ** a) - (beta ** a)) / (sqrtFive))print(\"The first {} numbers of Fibonacci series are {} . \".format(lengthA, Fn))",
"e": 27463,
"s": 26999,
"text": null
},
{
"code": null,
"e": 27472,
"s": 27463,
"text": "Output :"
},
{
"code": null,
"e": 27556,
"s": 27472,
"text": "The first 10 numbers of Fibonacci series are [ 1. 1. 2. 3. 5. 8. 13. 21. 34. 55.] ."
},
{
"code": null,
"e": 27607,
"s": 27556,
"text": "Example 2 : To find first ‘n’ Fibonacci numbers .."
},
{
"code": "import numpy as np # We are creating an array contains n elements# for getting first 'n' Fibonacci numbersfNumber = int(input(\"Enter the value of n + 1'th number : \"))a = np.arange(1, fNumber)length_a = len(a) # splitting of terms for easinesssqrt_five = np.sqrt(5)alpha = (1 + sqrt_five) / 2beta = (1 - sqrt_five) / 2 # Implementation of formula# np.rint is used for rounding off to integerFn = np.rint(((alpha ** a) - (beta ** a)) / (sqrt_five))print(\"The first {} numbers of Fibonacci series are {} . \".format(length_a, Fn))",
"e": 28138,
"s": 27607,
"text": null
},
{
"code": null,
"e": 28147,
"s": 28138,
"text": "Output :"
},
{
"code": null,
"e": 28294,
"s": 28147,
"text": "# Here user input was 10\nEnter the value of n+1'th number :10\nThe first 9 numbers of Fibonacci series are [ 1. 1. 2. 3. 5. 8. 13. 21. 34.] . "
},
{
"code": null,
"e": 28325,
"s": 28294,
"text": "Python numpy-arrayManipulation"
},
{
"code": null,
"e": 28338,
"s": 28325,
"text": "Python-numpy"
},
{
"code": null,
"e": 28345,
"s": 28338,
"text": "Python"
},
{
"code": null,
"e": 28443,
"s": 28345,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28461,
"s": 28443,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28493,
"s": 28461,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28515,
"s": 28493,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28557,
"s": 28515,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28583,
"s": 28557,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28612,
"s": 28583,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 28656,
"s": 28612,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 28693,
"s": 28656,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 28735,
"s": 28693,
"text": "How To Convert Python Dictionary To JSON?"
}
] |
GATE | GATE-CS-2002 | Question 50 - GeeksforGeeks
|
05 Dec, 2018
Consider the following logic circuit whose inputs and function and output is f.
Given that
f1(dx, y, z) = ∑(0, 1, 3, 5),
f2(dx, y, z) = ∑(6, 7) and
f(dx, y, z) = ∑(1, 4, 5),
f3 is :(A) ∑(1, 4, 5)(B) ∑(6, 7)(C) ∑(0, 1, 3, 5)(D) None of theseAnswer: (A)Explanation: Function f will be:
f = ((f1f2)′(f3)')′ = (f1f2) + f3
Since AND of two expressions will contain the common terms and f1 and f2 don’t have any common term, so f1f2 is 0 and hence f = f3 = Σ(1,4,5).
Option (A) is correct.Quiz of this Question
GATE-CS-2002
GATE-GATE-CS-2002
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE MOCK 2017 | Question 24
GATE | GATE-CS-2006 | Question 47
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
|
[
{
"code": null,
"e": 25659,
"s": 25631,
"text": "\n05 Dec, 2018"
},
{
"code": null,
"e": 25739,
"s": 25659,
"text": "Consider the following logic circuit whose inputs and function and output is f."
},
{
"code": null,
"e": 25750,
"s": 25739,
"text": "Given that"
},
{
"code": null,
"e": 25833,
"s": 25750,
"text": "f1(dx, y, z) = ∑(0, 1, 3, 5),\nf2(dx, y, z) = ∑(6, 7) and\nf(dx, y, z) = ∑(1, 4, 5),"
},
{
"code": null,
"e": 25943,
"s": 25833,
"text": "f3 is :(A) ∑(1, 4, 5)(B) ∑(6, 7)(C) ∑(0, 1, 3, 5)(D) None of theseAnswer: (A)Explanation: Function f will be:"
},
{
"code": null,
"e": 25977,
"s": 25943,
"text": "f = ((f1f2)′(f3)')′ = (f1f2) + f3"
},
{
"code": null,
"e": 26120,
"s": 25977,
"text": "Since AND of two expressions will contain the common terms and f1 and f2 don’t have any common term, so f1f2 is 0 and hence f = f3 = Σ(1,4,5)."
},
{
"code": null,
"e": 26164,
"s": 26120,
"text": "Option (A) is correct.Quiz of this Question"
},
{
"code": null,
"e": 26177,
"s": 26164,
"text": "GATE-CS-2002"
},
{
"code": null,
"e": 26195,
"s": 26177,
"text": "GATE-GATE-CS-2002"
},
{
"code": null,
"e": 26200,
"s": 26195,
"text": "GATE"
},
{
"code": null,
"e": 26298,
"s": 26200,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26332,
"s": 26298,
"text": "GATE | Gate IT 2007 | Question 25"
},
{
"code": null,
"e": 26366,
"s": 26332,
"text": "GATE | GATE-CS-2001 | Question 39"
},
{
"code": null,
"e": 26400,
"s": 26366,
"text": "GATE | GATE-CS-2000 | Question 41"
},
{
"code": null,
"e": 26433,
"s": 26400,
"text": "GATE | GATE-CS-2005 | Question 6"
},
{
"code": null,
"e": 26469,
"s": 26433,
"text": "GATE | GATE MOCK 2017 | Question 21"
},
{
"code": null,
"e": 26505,
"s": 26469,
"text": "GATE | GATE MOCK 2017 | Question 24"
},
{
"code": null,
"e": 26539,
"s": 26505,
"text": "GATE | GATE-CS-2006 | Question 47"
},
{
"code": null,
"e": 26573,
"s": 26539,
"text": "GATE | Gate IT 2008 | Question 43"
},
{
"code": null,
"e": 26607,
"s": 26573,
"text": "GATE | GATE-CS-2009 | Question 38"
}
] |
PHP | array_reduce() Function - GeeksforGeeks
|
29 May, 2021
This inbuilt function of PHP is used to reduce the elements of an array into a single value that can be of float, integer or string value. The function uses a user-defined callback function to reduce the input array.
Syntax:
array_reduce($array, own_function, $initial)
Parameters: The function takes three arguments and are described below:
$array (mandatory): This is a mandatory parameter and refers to the original array from which we need to reduce.own_function (mandatory): This parameter is also mandatory and refers to the user-defined function that is used to hold the value of the $array$initial (optional): This parameter is optional and refers to the value to be sent to the function.
$array (mandatory): This is a mandatory parameter and refers to the original array from which we need to reduce.
own_function (mandatory): This parameter is also mandatory and refers to the user-defined function that is used to hold the value of the $array
$initial (optional): This parameter is optional and refers to the value to be sent to the function.
Return Value: This function returns the reduced result. It can be of any type int, float or string.
Examples:
Input : $array = (15, 120, 45, 78)
$initial = 25
own_function() takes two parameters and concatenates
them with "and" as a separator in between
Output : 25 and 15 and 120 and 45 and 78
Input : $array = array(2, 4, 5);
$initial = 1
own_function() takes two parameters
and multiplies them.
Output : 40
In this program, we will see how an array of integer elements is reduced to a single string value. We also passed the initial element of our choice.
PHP
<?php// PHP function to illustrate the use of array_reduce()function own_function($element1, $element2){ return $element1 . " and " . $element2;} $array = array(15, 120, 45, 78);print_r(array_reduce($array, "own_function", "Initial"));?>
Output:
Initial and 15 and 120 and 45 and 78
In the below program, the array_reduce reduces the given array to the product of all the elements of the array using the own_function().
PHP
<?php// PHP function to illustrate the use of array_reduce()function own_function($element1, $element2){ $element1 = $element1 * $element2; return $element1;} $array = array(2, 4, 5, 10, 100);print_r(array_reduce($array, "own_function", "2"));?>
Output:
80000
Reference: http://php.net/manual/en/function.array-reduce.php
sweetyty
PHP-array
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to Upload Image into Database and Display it using PHP ?
How to check whether an array is empty using PHP?
PHP | Converting string to Date and DateTime
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 25889,
"s": 25861,
"text": "\n29 May, 2021"
},
{
"code": null,
"e": 26106,
"s": 25889,
"text": "This inbuilt function of PHP is used to reduce the elements of an array into a single value that can be of float, integer or string value. The function uses a user-defined callback function to reduce the input array."
},
{
"code": null,
"e": 26115,
"s": 26106,
"text": "Syntax: "
},
{
"code": null,
"e": 26160,
"s": 26115,
"text": "array_reduce($array, own_function, $initial)"
},
{
"code": null,
"e": 26234,
"s": 26160,
"text": "Parameters: The function takes three arguments and are described below: "
},
{
"code": null,
"e": 26589,
"s": 26234,
"text": "$array (mandatory): This is a mandatory parameter and refers to the original array from which we need to reduce.own_function (mandatory): This parameter is also mandatory and refers to the user-defined function that is used to hold the value of the $array$initial (optional): This parameter is optional and refers to the value to be sent to the function."
},
{
"code": null,
"e": 26702,
"s": 26589,
"text": "$array (mandatory): This is a mandatory parameter and refers to the original array from which we need to reduce."
},
{
"code": null,
"e": 26846,
"s": 26702,
"text": "own_function (mandatory): This parameter is also mandatory and refers to the user-defined function that is used to hold the value of the $array"
},
{
"code": null,
"e": 26946,
"s": 26846,
"text": "$initial (optional): This parameter is optional and refers to the value to be sent to the function."
},
{
"code": null,
"e": 27046,
"s": 26946,
"text": "Return Value: This function returns the reduced result. It can be of any type int, float or string."
},
{
"code": null,
"e": 27058,
"s": 27046,
"text": "Examples: "
},
{
"code": null,
"e": 27409,
"s": 27058,
"text": "Input : $array = (15, 120, 45, 78)\n $initial = 25\n own_function() takes two parameters and concatenates \n them with \"and\" as a separator in between\nOutput : 25 and 15 and 120 and 45 and 78\n\nInput : $array = array(2, 4, 5);\n $initial = 1\n own_function() takes two parameters \n and multiplies them.\nOutput : 40"
},
{
"code": null,
"e": 27559,
"s": 27409,
"text": "In this program, we will see how an array of integer elements is reduced to a single string value. We also passed the initial element of our choice. "
},
{
"code": null,
"e": 27563,
"s": 27559,
"text": "PHP"
},
{
"code": "<?php// PHP function to illustrate the use of array_reduce()function own_function($element1, $element2){ return $element1 . \" and \" . $element2;} $array = array(15, 120, 45, 78);print_r(array_reduce($array, \"own_function\", \"Initial\"));?>",
"e": 27804,
"s": 27563,
"text": null
},
{
"code": null,
"e": 27813,
"s": 27804,
"text": "Output: "
},
{
"code": null,
"e": 27850,
"s": 27813,
"text": "Initial and 15 and 120 and 45 and 78"
},
{
"code": null,
"e": 27988,
"s": 27850,
"text": "In the below program, the array_reduce reduces the given array to the product of all the elements of the array using the own_function(). "
},
{
"code": null,
"e": 27992,
"s": 27988,
"text": "PHP"
},
{
"code": "<?php// PHP function to illustrate the use of array_reduce()function own_function($element1, $element2){ $element1 = $element1 * $element2; return $element1;} $array = array(2, 4, 5, 10, 100);print_r(array_reduce($array, \"own_function\", \"2\"));?>",
"e": 28244,
"s": 27992,
"text": null
},
{
"code": null,
"e": 28253,
"s": 28244,
"text": "Output: "
},
{
"code": null,
"e": 28259,
"s": 28253,
"text": "80000"
},
{
"code": null,
"e": 28322,
"s": 28259,
"text": "Reference: http://php.net/manual/en/function.array-reduce.php "
},
{
"code": null,
"e": 28331,
"s": 28322,
"text": "sweetyty"
},
{
"code": null,
"e": 28341,
"s": 28331,
"text": "PHP-array"
},
{
"code": null,
"e": 28354,
"s": 28341,
"text": "PHP-function"
},
{
"code": null,
"e": 28358,
"s": 28354,
"text": "PHP"
},
{
"code": null,
"e": 28375,
"s": 28358,
"text": "Web Technologies"
},
{
"code": null,
"e": 28379,
"s": 28375,
"text": "PHP"
},
{
"code": null,
"e": 28477,
"s": 28379,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28527,
"s": 28477,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 28567,
"s": 28527,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 28628,
"s": 28567,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 28678,
"s": 28628,
"text": "How to check whether an array is empty using PHP?"
},
{
"code": null,
"e": 28723,
"s": 28678,
"text": "PHP | Converting string to Date and DateTime"
},
{
"code": null,
"e": 28763,
"s": 28723,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28796,
"s": 28763,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28841,
"s": 28796,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28884,
"s": 28841,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
React.js | Uncontrolled Vs Controlled Inputs - GeeksforGeeks
|
29 Jan, 2021
In HTML, form elements such as <input>, <textarea>, <select>, etc typically maintain their own state and update it based on user input. In React, a mutable (changeable) state is usually kept in the state property of components. In React forms input value can be of two types according to your choice: uncontrolled and controlled values.Uncontrolled input: With uncontrolled input values, there is no updating or changing of any states. It maintains its own internal state, which basically means it remembers what you typed in the field. That value can be exploited by pulling it using the ref keyword whenever it needs to be used. In uncontrolled inputs, the value you submit is the value you get.
Now, Open your react project and edit the index.js file in the src folder:
src index.js:
Javascript
import React from 'react';import ReactDOM from 'react-dom';import NameForm from './NameForm'; ReactDOM.render( <React.StrictMode> <NameForm /> </React.StrictMode>, document.getElementById('root'));
Create a Component name NameForm.js in react project:
Now, Open your react project and edit the NameForm.js file in the src folder:
src NameForm.js:
javascript
import React,{Component} from 'react'; class NameForm extends React.Component { handleClick = () => { const name = this._name.value; alert('Hello ', name); } render() { return ( <div> <input type="text" ref= {inputValue => this._name = inputValue} placeholder="Enter your name" /> <button onClick={this.handleClick}> Done </button> </div> ); } } export default NameForm;
Input: Tanisha Output: Hello Tanisha (Display on the alert box)
Controlled input: In controlled inputs, there is at all times some sort of changes and amendments going on in the field, every single character entered and even something like a backspace would count as a change. The current value of the input field will be a prop of the class component (usually it will live in the state referred to by using this.state.varName.) as they don’t maintain their internal state. There will also be a callback function (like onChange, onClick, etc) that is necessary to handle the changes (in value) occurring in the input field, which makes them controllable. Now, Open your react project and edit the NameForm.js file in the src folder:src NameForm.js:
javascript
import React,{Component} from 'react'; class NameForm extends React.Component { constructor(props) { super(props); this.state = { name: '', }; } handleNameChange = (event) => { this.setState({ name: event.target.value }); }; render() { return ( <div> <input type="text" onChange= {this.handleNameChange} placeholder="Enter your name" /> <h1>{this.state.name}</h1> </div> ); }} export default NameForm;
Input: Tanisha Output: Tanisha (Displaying on the screen letter by letter as the user types)
Which one is better? It’s evident that controlled and uncontrolled form fields each have their individual benefits. You might need to use both or either depending on what the situation calls for. If you are making a simple form with little to no UI feedback and no need for instant validation (which means you only would validate and/or need the values when you submit), using uncontrolled inputs with refs is what you should go for. It would keep the source of truth in the DOM making it quicker and requiring lesser code. If you need more UI feedback and take into account every little change in the particular input field go for controlled input.
shubhamyadav4
react-js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to apply style to parent if it has child with CSS?
How to execute PHP code using command line ?
Difference Between PUT and PATCH Request
REST API (Introduction)
How to redirect to another page in ReactJS ?
|
[
{
"code": null,
"e": 26169,
"s": 26141,
"text": "\n29 Jan, 2021"
},
{
"code": null,
"e": 26868,
"s": 26169,
"text": "In HTML, form elements such as <input>, <textarea>, <select>, etc typically maintain their own state and update it based on user input. In React, a mutable (changeable) state is usually kept in the state property of components. In React forms input value can be of two types according to your choice: uncontrolled and controlled values.Uncontrolled input: With uncontrolled input values, there is no updating or changing of any states. It maintains its own internal state, which basically means it remembers what you typed in the field. That value can be exploited by pulling it using the ref keyword whenever it needs to be used. In uncontrolled inputs, the value you submit is the value you get. "
},
{
"code": null,
"e": 26943,
"s": 26868,
"text": "Now, Open your react project and edit the index.js file in the src folder:"
},
{
"code": null,
"e": 26957,
"s": 26943,
"text": "src index.js:"
},
{
"code": null,
"e": 26968,
"s": 26957,
"text": "Javascript"
},
{
"code": "import React from 'react';import ReactDOM from 'react-dom';import NameForm from './NameForm'; ReactDOM.render( <React.StrictMode> <NameForm /> </React.StrictMode>, document.getElementById('root'));",
"e": 27172,
"s": 26968,
"text": null
},
{
"code": null,
"e": 27226,
"s": 27172,
"text": "Create a Component name NameForm.js in react project:"
},
{
"code": null,
"e": 27304,
"s": 27226,
"text": "Now, Open your react project and edit the NameForm.js file in the src folder:"
},
{
"code": null,
"e": 27322,
"s": 27304,
"text": "src NameForm.js: "
},
{
"code": null,
"e": 27333,
"s": 27322,
"text": "javascript"
},
{
"code": "import React,{Component} from 'react'; class NameForm extends React.Component { handleClick = () => { const name = this._name.value; alert('Hello ', name); } render() { return ( <div> <input type=\"text\" ref= {inputValue => this._name = inputValue} placeholder=\"Enter your name\" /> <button onClick={this.handleClick}> Done </button> </div> ); } } export default NameForm;",
"e": 27839,
"s": 27333,
"text": null
},
{
"code": null,
"e": 27905,
"s": 27839,
"text": "Input: Tanisha Output: Hello Tanisha (Display on the alert box) "
},
{
"code": null,
"e": 28590,
"s": 27905,
"text": "Controlled input: In controlled inputs, there is at all times some sort of changes and amendments going on in the field, every single character entered and even something like a backspace would count as a change. The current value of the input field will be a prop of the class component (usually it will live in the state referred to by using this.state.varName.) as they don’t maintain their internal state. There will also be a callback function (like onChange, onClick, etc) that is necessary to handle the changes (in value) occurring in the input field, which makes them controllable. Now, Open your react project and edit the NameForm.js file in the src folder:src NameForm.js:"
},
{
"code": null,
"e": 28601,
"s": 28590,
"text": "javascript"
},
{
"code": "import React,{Component} from 'react'; class NameForm extends React.Component { constructor(props) { super(props); this.state = { name: '', }; } handleNameChange = (event) => { this.setState({ name: event.target.value }); }; render() { return ( <div> <input type=\"text\" onChange= {this.handleNameChange} placeholder=\"Enter your name\" /> <h1>{this.state.name}</h1> </div> ); }} export default NameForm;",
"e": 29181,
"s": 28601,
"text": null
},
{
"code": null,
"e": 29276,
"s": 29181,
"text": "Input: Tanisha Output: Tanisha (Displaying on the screen letter by letter as the user types) "
},
{
"code": null,
"e": 29927,
"s": 29276,
"text": "Which one is better? It’s evident that controlled and uncontrolled form fields each have their individual benefits. You might need to use both or either depending on what the situation calls for. If you are making a simple form with little to no UI feedback and no need for instant validation (which means you only would validate and/or need the values when you submit), using uncontrolled inputs with refs is what you should go for. It would keep the source of truth in the DOM making it quicker and requiring lesser code. If you need more UI feedback and take into account every little change in the particular input field go for controlled input. "
},
{
"code": null,
"e": 29941,
"s": 29927,
"text": "shubhamyadav4"
},
{
"code": null,
"e": 29950,
"s": 29941,
"text": "react-js"
},
{
"code": null,
"e": 29967,
"s": 29950,
"text": "Web Technologies"
},
{
"code": null,
"e": 30065,
"s": 29967,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30105,
"s": 30065,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 30150,
"s": 30105,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 30193,
"s": 30150,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 30254,
"s": 30193,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 30326,
"s": 30254,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 30381,
"s": 30326,
"text": "How to apply style to parent if it has child with CSS?"
},
{
"code": null,
"e": 30426,
"s": 30381,
"text": "How to execute PHP code using command line ?"
},
{
"code": null,
"e": 30467,
"s": 30426,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 30491,
"s": 30467,
"text": "REST API (Introduction)"
}
] |
TestNG - Group Test
|
Group test is a new innovative feature in TestNG, which doesn’t exist in JUnit framework. It permits you to dispatch methods into proper portions and perform sophisticated groupings of test methods.
Not only can you declare those methods that belong to groups, but you can also specify groups that contain other groups. Then, TestNG can be invoked and asked to include a certain set of groups (or regular expressions), while excluding another set.
Group tests provide maximum flexibility in how you partition your tests, and doesn't require you to recompile anything if you want to run two different sets of tests back to back.
Groups are specified in your testng.xml file using the <groups> tag. It can be found either under the <test> or <suite> tag. Groups specified in the <suite> tag apply to all the <test> tags underneath.
Now, let's take an example to see how group test works.
Create a java class to be tested, say, MessageUtil.java in /work/testng/src.
Create a java class to be tested, say, MessageUtil.java in /work/testng/src.
/*
* This class prints the given message on console.
*/
public class MessageUtil {
private String message;
// Constructor
// @param message to be printed
public MessageUtil(String message) {
this.message = message;
}
// prints the message
public String printMessage() {
System.out.println(message);
return message;
}
// add "tutorialspoint" to the message
public String salutationMessage() {
message = "tutorialspoint" + message;
System.out.println(message);
return message;
}
// add "www." to the message
public String exitMessage() {
message = "www." + message;
System.out.println(message);
return message;
}
}
Create a java test class, say, GroupTestExample.java in /work/testng/src.
Create a java test class, say, GroupTestExample.java in /work/testng/src.
Add test methods, testPrintMessage() and testSalutationMessage(), to your test class.
Add test methods, testPrintMessage() and testSalutationMessage(), to your test class.
Group the test method in two categories −
Check-in tests (checkintest) − These tests should be run before you submit new code. They should typically be fast and just make sure no basic functionality is broken.
Functional tests (functest) − These tests should cover all the functionalities of your software and be run at least once a day, although ideally you would want to run them continuously.
Group the test method in two categories −
Check-in tests (checkintest) − These tests should be run before you submit new code. They should typically be fast and just make sure no basic functionality is broken.
Check-in tests (checkintest) − These tests should be run before you submit new code. They should typically be fast and just make sure no basic functionality is broken.
Functional tests (functest) − These tests should cover all the functionalities of your software and be run at least once a day, although ideally you would want to run them continuously.
Functional tests (functest) − These tests should cover all the functionalities of your software and be run at least once a day, although ideally you would want to run them continuously.
Following are the contents of GroupTestExample.java.
import org.testng.Assert;
import org.testng.annotations.Test;
public class GroupTestExample {
String message = ".com";
MessageUtil messageUtil = new MessageUtil(message);
@Test(groups = { "functest", "checkintest" })
public void testPrintMessage() {
System.out.println("Inside testPrintMessage()");
message = ".com";
Assert.assertEquals(message, messageUtil.printMessage());
}
@Test(groups = { "checkintest" })
public void testSalutationMessage() {
System.out.println("Inside testSalutationMessage()");
message = "tutorialspoint" + ".com";
Assert.assertEquals(message, messageUtil.salutationMessage());
}
@Test(groups = { "functest" })
public void testingExitMessage() {
System.out.println("Inside testExitMessage()");
message = "www." + "tutorialspoint"+".com";
Assert.assertEquals(message, messageUtil.exitMessage());
}
}
Create testng.xml in /work/testng/src, to execute test case(s). Here, we would be executing only those tests, that belong to the group functest.
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name = "Suite1">
<test name = "test1">
<groups>
<run>
<include name = "functest" />
</run>
</groups>
<classes>
<class name = "GroupTestExample" />
</classes>
</test>
</suite>
Compile the MessageUtil, Test case classes using javac.
/work/testng/src$ javac MessageUtil.java GroupTestExample.java
Now, run the testng.xml, which will run only the method testPrintMessage(), as it belongs to the group functest.
/work/testng/src$ java org.testng.TestNG testng.xml
Verify the output. Only the method testPrintMessage() is executed.
Inside testPrintMessage()
.com
Inside testExitMessage()
www..com
===============================================
Suite1
Total tests run: 2, Failures: 1, Skips: 0
===============================================
Groups can also include other groups. These groups are called MetaGroups. For example, you might want to define a group all that includes checkintest and functest. Let's modify our testng.xml file as follows −
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name = "Suite1">
<test name = "test1">
<groups>
<define name = "all">
<include name = "functest"/>
<include name = "checkintest"/>
</define>
<run>
<include name = "all"/>
</run>
</groups>
<classes>
<class name = "GroupTestExample" />
</classes>
</test>
</suite>
Executing the above testng.xml will execute all the three tests and will give you the following result −
Inside testPrintMessage()
.com
Inside testSalutationMessage()
tutorialspoint.com
Inside testExitMessage()
www.tutorialspoint.com
===============================================
Suite1
Total tests run: 3, Failures: 0, Skips: 0
===============================================
You can ignore a group by using the <exclude> tag as shown below −
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name = "Suite1">
<test name = "test1">
<groups>
<define name = "all">
<exclude name = "functest"/>
<include name = "checkintest"/>
</define>
<run>
<include name = "all"/>
</run>
</groups>
<classes>
<class name = "GroupTestExample" />
</classes>
</test>
</suite>
38 Lectures
4.5 hours
Lets Kode It
15 Lectures
1.5 hours
Quaatso Learning
28 Lectures
3 hours
Dezlearn Education
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2259,
"s": 2060,
"text": "Group test is a new innovative feature in TestNG, which doesn’t exist in JUnit framework. It permits you to dispatch methods into proper portions and perform sophisticated groupings of test methods."
},
{
"code": null,
"e": 2508,
"s": 2259,
"text": "Not only can you declare those methods that belong to groups, but you can also specify groups that contain other groups. Then, TestNG can be invoked and asked to include a certain set of groups (or regular expressions), while excluding another set."
},
{
"code": null,
"e": 2688,
"s": 2508,
"text": "Group tests provide maximum flexibility in how you partition your tests, and doesn't require you to recompile anything if you want to run two different sets of tests back to back."
},
{
"code": null,
"e": 2890,
"s": 2688,
"text": "Groups are specified in your testng.xml file using the <groups> tag. It can be found either under the <test> or <suite> tag. Groups specified in the <suite> tag apply to all the <test> tags underneath."
},
{
"code": null,
"e": 2946,
"s": 2890,
"text": "Now, let's take an example to see how group test works."
},
{
"code": null,
"e": 3023,
"s": 2946,
"text": "Create a java class to be tested, say, MessageUtil.java in /work/testng/src."
},
{
"code": null,
"e": 3100,
"s": 3023,
"text": "Create a java class to be tested, say, MessageUtil.java in /work/testng/src."
},
{
"code": null,
"e": 3813,
"s": 3100,
"text": "/*\n* This class prints the given message on console.\n*/\npublic class MessageUtil {\n private String message;\n\n // Constructor\n // @param message to be printed\n public MessageUtil(String message) {\n this.message = message;\n }\n\n // prints the message\n public String printMessage() {\n System.out.println(message);\n return message;\n }\n\n // add \"tutorialspoint\" to the message\n public String salutationMessage() {\n message = \"tutorialspoint\" + message;\n System.out.println(message);\n return message;\n }\n\n // add \"www.\" to the message\n public String exitMessage() {\n message = \"www.\" + message;\n System.out.println(message);\n return message;\n }\n}"
},
{
"code": null,
"e": 3887,
"s": 3813,
"text": "Create a java test class, say, GroupTestExample.java in /work/testng/src."
},
{
"code": null,
"e": 3961,
"s": 3887,
"text": "Create a java test class, say, GroupTestExample.java in /work/testng/src."
},
{
"code": null,
"e": 4047,
"s": 3961,
"text": "Add test methods, testPrintMessage() and testSalutationMessage(), to your test class."
},
{
"code": null,
"e": 4133,
"s": 4047,
"text": "Add test methods, testPrintMessage() and testSalutationMessage(), to your test class."
},
{
"code": null,
"e": 4532,
"s": 4133,
"text": "Group the test method in two categories −\n\nCheck-in tests (checkintest) − These tests should be run before you submit new code. They should typically be fast and just make sure no basic functionality is broken.\nFunctional tests (functest) − These tests should cover all the functionalities of your software and be run at least once a day, although ideally you would want to run them continuously.\n\n"
},
{
"code": null,
"e": 4574,
"s": 4532,
"text": "Group the test method in two categories −"
},
{
"code": null,
"e": 4742,
"s": 4574,
"text": "Check-in tests (checkintest) − These tests should be run before you submit new code. They should typically be fast and just make sure no basic functionality is broken."
},
{
"code": null,
"e": 4910,
"s": 4742,
"text": "Check-in tests (checkintest) − These tests should be run before you submit new code. They should typically be fast and just make sure no basic functionality is broken."
},
{
"code": null,
"e": 5096,
"s": 4910,
"text": "Functional tests (functest) − These tests should cover all the functionalities of your software and be run at least once a day, although ideally you would want to run them continuously."
},
{
"code": null,
"e": 5282,
"s": 5096,
"text": "Functional tests (functest) − These tests should cover all the functionalities of your software and be run at least once a day, although ideally you would want to run them continuously."
},
{
"code": null,
"e": 5335,
"s": 5282,
"text": "Following are the contents of GroupTestExample.java."
},
{
"code": null,
"e": 6253,
"s": 5335,
"text": "import org.testng.Assert;\nimport org.testng.annotations.Test;\n\npublic class GroupTestExample {\n String message = \".com\";\n MessageUtil messageUtil = new MessageUtil(message);\n\n @Test(groups = { \"functest\", \"checkintest\" })\n\n public void testPrintMessage() {\n System.out.println(\"Inside testPrintMessage()\");\n message = \".com\";\n Assert.assertEquals(message, messageUtil.printMessage());\n }\n\n @Test(groups = { \"checkintest\" })\n\n public void testSalutationMessage() {\n System.out.println(\"Inside testSalutationMessage()\");\n message = \"tutorialspoint\" + \".com\";\n Assert.assertEquals(message, messageUtil.salutationMessage());\n }\n\n @Test(groups = { \"functest\" })\n\n public void testingExitMessage() {\n System.out.println(\"Inside testExitMessage()\");\n message = \"www.\" + \"tutorialspoint\"+\".com\";\n Assert.assertEquals(message, messageUtil.exitMessage());\n }\n}"
},
{
"code": null,
"e": 6398,
"s": 6253,
"text": "Create testng.xml in /work/testng/src, to execute test case(s). Here, we would be executing only those tests, that belong to the group functest."
},
{
"code": null,
"e": 6756,
"s": 6398,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<!DOCTYPE suite SYSTEM \"http://testng.org/testng-1.0.dtd\" >\n\n<suite name = \"Suite1\">\n <test name = \"test1\">\n\n <groups>\n <run>\n <include name = \"functest\" />\n </run>\n </groups>\n\n <classes>\n <class name = \"GroupTestExample\" />\n </classes>\n\n </test>\n</suite>"
},
{
"code": null,
"e": 6812,
"s": 6756,
"text": "Compile the MessageUtil, Test case classes using javac."
},
{
"code": null,
"e": 6876,
"s": 6812,
"text": "/work/testng/src$ javac MessageUtil.java GroupTestExample.java\n"
},
{
"code": null,
"e": 6989,
"s": 6876,
"text": "Now, run the testng.xml, which will run only the method testPrintMessage(), as it belongs to the group functest."
},
{
"code": null,
"e": 7042,
"s": 6989,
"text": "/work/testng/src$ java org.testng.TestNG testng.xml\n"
},
{
"code": null,
"e": 7109,
"s": 7042,
"text": "Verify the output. Only the method testPrintMessage() is executed."
},
{
"code": null,
"e": 7321,
"s": 7109,
"text": "Inside testPrintMessage()\n.com\nInside testExitMessage()\nwww..com\n\n===============================================\nSuite1\nTotal tests run: 2, Failures: 1, Skips: 0\n===============================================\n"
},
{
"code": null,
"e": 7532,
"s": 7321,
"text": "Groups can also include other groups. These groups are called MetaGroups. For example, you might want to define a group all that includes checkintest and functest. Let's modify our testng.xml file as follows −"
},
{
"code": null,
"e": 8021,
"s": 7532,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<!DOCTYPE suite SYSTEM \"http://testng.org/testng-1.0.dtd\" >\n<suite name = \"Suite1\">\n <test name = \"test1\">\n\n <groups>\n\n <define name = \"all\">\n <include name = \"functest\"/>\n <include name = \"checkintest\"/>\n </define>\n\n <run>\n <include name = \"all\"/>\n </run>\n\n </groups>\n\n <classes>\n <class name = \"GroupTestExample\" />\n </classes>\n\n </test>\n</suite>"
},
{
"code": null,
"e": 8126,
"s": 8021,
"text": "Executing the above testng.xml will execute all the three tests and will give you the following result −"
},
{
"code": null,
"e": 8402,
"s": 8126,
"text": "Inside testPrintMessage()\n.com\nInside testSalutationMessage()\ntutorialspoint.com\nInside testExitMessage()\nwww.tutorialspoint.com\n\n===============================================\nSuite1\nTotal tests run: 3, Failures: 0, Skips: 0\n===============================================\n"
},
{
"code": null,
"e": 8469,
"s": 8402,
"text": "You can ignore a group by using the <exclude> tag as shown below −"
},
{
"code": null,
"e": 8956,
"s": 8469,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<!DOCTYPE suite SYSTEM \"http://testng.org/testng-1.0.dtd\" >\n<suite name = \"Suite1\">\n <test name = \"test1\">\n\n <groups>\n <define name = \"all\">\n <exclude name = \"functest\"/>\n <include name = \"checkintest\"/>\n </define>\n\n <run>\n <include name = \"all\"/>\n </run>\n </groups>\n\n <classes>\n <class name = \"GroupTestExample\" />\n </classes>\n\n </test>\n</suite>"
},
{
"code": null,
"e": 8991,
"s": 8956,
"text": "\n 38 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 9005,
"s": 8991,
"text": " Lets Kode It"
},
{
"code": null,
"e": 9040,
"s": 9005,
"text": "\n 15 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 9058,
"s": 9040,
"text": " Quaatso Learning"
},
{
"code": null,
"e": 9091,
"s": 9058,
"text": "\n 28 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 9111,
"s": 9091,
"text": " Dezlearn Education"
},
{
"code": null,
"e": 9118,
"s": 9111,
"text": " Print"
},
{
"code": null,
"e": 9129,
"s": 9118,
"text": " Add Notes"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.