code-rag-bench/online-tutorials huggingface dataset:
Assign ids to each unique value in a Python list

While using Python dictionary we may need to identify each element of the dictionary uniquely. For that we have to assign unique IDs to each of the element in the dictionary. In this article we will see how to assign the same unique Id to an element if it is repeated in a Python dictionary.
The enumerate function expands a given dictionary by adding a counter to each element of the dictionary. Then we apply the OrderedDict.fromkeys() which will extract the same value of the counter from the dictionary hence eliminating the duplicates values of IDs.
 Live Demo
from collections import OrderedDict

Alist = ['Mon','Tue','Wed','Mon',5,3,3]
print("The given list : ",Alist)

# Assigning ids to values
list_ids = [{v: k for k, v in enumerate(
   OrderedDict.fromkeys(Alist))}
      [n] for n in Alist]

# The result
print("The list of ids : ",list_ids)
Running the above code gives us the following result −
The given list : ['Mon', 'Tue', 'Wed', 'Mon', 5, 3, 3]
The list of ids : [0, 1, 2, 0, 3, 4, 4]
In this method we use the defaultdict function which will assign a new key only to the new elements. Then we use the lambda function to loop through the new list of unique Ids.
 Live Demo
from collections import defaultdict
# Given List
Alist = ['Mon','Tue','Wed','Mon',5,3,3]
print("The given list : ",Alist)

# Assigning ids to values
d_dict = defaultdict(lambda: len(d_dict))
list_ids= [d_dict[n] for n in Alist]
# Print ids of the dictionary
print("The list of ids : ", list_ids)
Running the above code gives us the following result −
The given list : ['Mon', 'Tue', 'Wed', 'Mon', 5, 3, 3]
The list of ids : [0, 1, 2, 0, 3, 4, 4]
How to find the index of an object available in a list in Python?

If you only want the first index of the object, you can simply use the index method on the list. It accepts the object whose position you require. Note that if element is not found in the list, this will throw an error that needs to be handled using try .. expect.  
my_list = [2, 1, 3, 8, 5]
print(my_list.index(3))
This will give the output −
2
If you want to print all occurrences of the object, you should use enumerate instead.
my_list = [2, 3, 1, -4, -1, -4]
elem = -4
print([i for i, j in enumerate(my_list) if j == elem])
This will give the output −
[3, 5]
What is the purpose of Program.cs file in C# ASP.NET Core project?

ASP.NET Core web application is actually a console project which starts executing
from the entry point public static void Main() in Program class where we can create a
host for the web application.
public class Program{
   public static void Main(string[] args){
      BuildWebHost(args).Run();
   }
   public static IWebHost BuildWebHost(string[] args) =>
   WebHost.CreateDefaultBuilder(args)
   .UseStartup<startup>()
   .Build();
}
The WebHost is a static class which can be used for creating an instance of IWebHost and IWebHostBuilder with pre-configured defaults.
The CreateDefaultBuilder() method creates a new instance of WebHostBuilder with pre-configured defaults. Internally,
it configures Kestrel, IISIntegration and other configurations. The following is
CreateDefaultBuilder() method.
Sets the “Content Root” to be the current directory
Allows Command Line args to be pushed into your configuration object
Adds both appsettings.json and appsettings.{Environment}.json to be loaded
into the configuration object
Adds environment variables to the configuration object
If in Development, allows the loading of secrets.
Adds Console/Debug loggers
Tells the app to use Kestrel and to load Kestrel configuration from the loaded
config
Adds Routing
Adds IIS Integration
When we want to host our application into iis we need to add UseIISIntegration() method specifies the IIS as the external web server.
UseStartup<startup>() method specifies the Startup class to be used by the web host. we can also specify our custom class in place of startup.
Build() method returns an instance of IWebHost and Run() starts web application till it stops.
Underscore.js _.uniqueId() Function - GeeksforGeeks

15 Oct, 2020
Underscore.js is a JavaScript library that provides a lot of useful functions that help in the programming in a big way like the map, filter, invoke, etc even without using any built-in objects.
The _.uniqueId() function is an inbuilt function in Underscore.js library of JavaScript which is used to generate a globally unique id for the client-side models or the DOM elements which requires one. When a prefix is passed as an argument to this method, the id generated will be appended to it.
Syntax:
_.uniqueId( prefix )

Parameters: It accepts a single parameter as mentioned above and described below:
prefix: It is the prefix that would be appended to the id It is am optional parameter.
Return Value: This method returns a globally unique id.
Example 1:
HTML
<!DOCTYPE html><html>  <head>    <script src="https://unpkg.com/underscore@1.11.0/underscore-min.js">    </script></head>  <body>    <script type="text/javascript">          // Using _.uniqueId() method         // with its parameter        console.log(_.uniqueId('gfG_'));        console.log(_.uniqueId('Geeks_'));        console.log(_.uniqueId('CS_'));    </script></body>  </html>
Output:
gfG_1
Geeks_2
CS_3
Example 2:
HTML
<!DOCTYPE html><html>  <head>    <script src="https://unpkg.com/underscore@1.11.0/underscore-min.js">    </script></head>  <body>    <script type="text/javascript">          // Using a loop        for (i = 3; i < 100; i *= 2) {              // Calling uniqueId method            // without any parameter               console.log(_.uniqueId());        }    </script></body>  </html>
Output:
1
2
3
4
5
6

JavaScript - Underscore.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Convert a string to an integer in JavaScript
How to calculate the number of days between two dates in javascript?
Differences between Functional Components and Class Components in React
Difference between var, let and const keywords in JavaScript
File uploading in React.js
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
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?
How to right align the text in a ComboBox in Java

To right align the text in a JComboBox, use the following:
ComponentOrientation.RIGHT_TO_LEFT
The following is an example to right align the text in a ComboBox:
import java.awt.Component;
import java.awt.ComponentOrientation;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JList;
public class SwingDemo extends JFrame {
   public SwingDemo() {
      JComboBox<String> combo = new JComboBox<String>();
      combo.setRenderer(new MyListCellRenderer());
      combo.addItem("One");
      combo.addItem("Two");
      combo.addItem("Three");
      combo.addItem("Four");
      combo.addItem("Five");
      getContentPane().add(combo, "North");
      setSize(600, 400);
      setDefaultCloseOperation(EXIT_ON_CLOSE);
   }
   public static void main(String[] args) {
      new SwingDemo().setVisible(true);
   }
}
class MyListCellRenderer extends DefaultListCellRenderer {
   @Override
   public Component getListCellRendererComponent(
      JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
      Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
      c.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
      return c;
   }
}
MySQL query to fetch specific records matched from an array (comma separated values)

To fetch records from comma separated values, use MySQL FIND_IN_SET(). Let us first create a table −
mysql> create table DemoTable1548
   -> (
   -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> StudentName varchar(20),
   -> ArrayListOfMarks varchar(100)
   -> );
Query OK, 0 rows affected (0.88 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1548(StudentName,ArrayListOfMarks) values('Chris','56,78,90,87');
Query OK, 1 row affected (0.29 sec)
mysql> insert into DemoTable1548(StudentName,ArrayListOfMarks) values('Bob','90,78,65');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable1548(StudentName,ArrayListOfMarks) values('David','91,34,56,78,87');
Query OK, 1 row affected (0.16 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1548;
This will produce the following output −
+-----------+-------------+------------------+
| StudentId | StudentName | ArrayListOfMarks |
+-----------+-------------+------------------+
|         1 | Chris       |    56,78,90,87   |
|         2 | Bob         |       90,78,65   |
|         3 | David       | 91,34,56,78,87   |
+-----------+-------------+------------------+
3 rows in set (0.00 sec)
Here is the query to fetch specific records matching from comma separated values −
mysql> select * from DemoTable1548 where find_in_set('87',ArrayListOfMarks);
This will produce the following output −
+-----------+-------------+------------------+
| StudentId | StudentName | ArrayListOfMarks |
+-----------+-------------+------------------+
|         1 | Chris       |    56,78,90,87   |
|         3 | David       | 91,34,56,78,87   |
+-----------+-------------+------------------+
2 rows in set (0.00 sec)
C++ Algorithm Library - any_of() Function

The C++ function std::algorithm::any_of() Returns true if predicate returns true for any of the elements in the range of first to last. If range is empty then also true is returned otherwise it returns false.
Following is the declaration for std::algorithm::any_of() function form std::algorithm header.
template <class InputIterator, class UnaryPredicate>
bool any_of (InputIterator first, InputIterator last, UnaryPredicate pred);

first − Input iterators to the initial positions in a sequence.
first − Input iterators to the initial positions in a sequence.
last − Input iterators to the final positions in a sequence.
last − Input iterators to the final positions in a sequence.
pred − An unary predicate function that accepts an element and returns a bool.
pred − An unary predicate function that accepts an element and returns a bool.
Returns true if predicate returns true for any of the elements in the range or if the range is empty otherwise returns false.
Throws exception if either predicate or an operation on an iterator throws exception.
Please note that invalid parameters cause undefined behavior.
Linear in the distance between first and last.
The following example shows the usage of std::algorithm::any_of() function.
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

bool is_odd(int n) {
   return (n % 2 != 0);
}

int main(void) {
   vector<int> v = {2, 4, 6, 8, 11};
   bool result;

   result = any_of(v.begin(), v.end(), is_odd);

   if (result == true)
      cout << "Vector contains at least one odd number." << endl;

   v[4] = 10;

   result = any_of(v.begin(), v.end(), is_odd);

   if (result == false)
      cout << "Vector contains all even number." << endl;

   return 0;
}
Let us compile and run the above program, this will produce the following result −
Vector contains at least one odd number.
Vector contains all even number.

 Print
 Add Notes
 Bookmark this page
Tree Diameter in C++

Suppose we have an undirected tree; we have to find its diameter − the number of edges in the longest path in that tree is the diameter of that tree. Here tree is given as an edge list where edges[i] = [u, v] is a bidirectional edge between nodes u and v. Each node has labels in the set {0, 1, ..., edges.length}. So if the graph is like −
The output will be 4.
To solve this, we will follow these steps −
Define a map l
define a method called dfs(). this will take v, an array called visited, the graph and c. It will work as follows −
visited[v] := true, set ans := 0
for i in range 0 to size of graph[v]if visited[graph[v, i]] is false, thenans := max of ans, dfs(graph[v, i], visited, graph, c + 1)
if visited[graph[v, i]] is false, thenans := max of ans, dfs(graph[v, i], visited, graph, c + 1)
ans := max of ans, dfs(graph[v, i], visited, graph, c + 1)
if c > best, then best := c and node := v
set visited[v] := false
return max of c and ans
In the main method, it will take the edge list e
n := size of e, make an array called graph of size n + 1
for i in range 0 to n – 1insert e[i, 1] into graph[e[i, 0]] and insert e[i, 0] into graph[e[i, 1]]
insert e[i, 1] into graph[e[i, 0]] and insert e[i, 0] into graph[e[i, 1]]
make two arrays visited, and visited2 array of size n + 1, set best := 0 and node := 0
call dfs(0, visited, graph)
return dfs(node, visited2, graph)
Let us see the following implementation to get a better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
#define pb push_back
class Solution {
public:
   map <int ,int > l;
   int best;
   int node;
   int dfs(int v, bool* visited, vector <int> graph[], int c = 0){
      visited[v] = true;
      int ans = 0;
      for(int i = 0; i < graph[v].size(); i++){
         if(!visited[graph[v][i]])ans = max(ans,dfs(graph[v][i], visited, graph, c+1));
      }
      if(c > best){
         best = c;
         node = v ;
      }
      visited[v] = false;
      return max(c,ans);
   }
   int treeDiameter(vector<vector<int>>& e) {
      int n = e.size();
      vector <int> graph[n+1];
      for(int i = 0; i < n; i++){
         graph[e[i][0]].pb(e[i][1]);
         graph[e[i][1]].pb(e[i][0]);
      }
      bool* visited = new bool[n+1]();
      best = 0;
      node = 0;
      dfs(0, visited, graph);
      bool* visited2 = new bool[n+1]();
      return dfs(node, visited2, graph);
   }
};
main(){
   vector<vector<int>> v = {{0,1},{1,2},{2,3},{1,4},{4,5}};
   Solution ob;
   cout <<ob.treeDiameter(v);
}
[[0,1],[1,2],[2,3],[1,4],[4,5]]
4
How do I write a Latex formula in the legend of a plot using Matplotlib inside a .py file?

LaTeX is a typesetting language for producing scientific documents. We use a very small part of the language for writing mathematical notation. Jupyter notebook recognizes LaTeX code written in markdown cells and renders the symbols in the browser using the MathJax JavaScript library.
To write a LaTeX formula in the legend of a plot, we can take the following steps −
Create data points for x.
Create data points for x.
Create data point for y, i.e., y=sin(x).
Create data point for y, i.e., y=sin(x).
Plot the curve x and y with LaTex representation.
Plot the curve x and y with LaTex representation.
To activate the label, use the legend() method.
To activate the label, use the legend() method.
To display the figure, use the show() method.
To display the figure, use the show() method.
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
x = np.linspace(1, 10, 1000)
y = np.sin(x)
plt.plot(x, y, label=r'$\sin (x)$', c="red", lw=2)
plt.legend()
plt.show()
Put a little more complex equation in the label, for example, label=r'αiπ+1=0'
Now, look at the legend at the top-right corner of the plot.
How Can we use MySQL DISTINCT clause with WHERE and LIMIT clause?

By using the WHERE clause with a DISTINCT clause in MySQL queries, we are putting a condition on the basis of which MySQL returns the unique rows of the result set. By using the LIMIT clause with a DISTINCT clause in MySQL queries, we are actually providing a perimeter to the server about a maximum number of unique rows of the result set to be returned.
We can use WHERE and LIMIT clause with DISTINCT as follows on the table named ‘testing’ −
mysql> Select * from testing;
+------+---------+---------+
| id   | fname   | Lname   |
+------+---------+---------+
|  200 | Raman   | Kumar   |
|  201 | Sahil   | Bhalla  |
|  202 | Gaurav  | NULL    |
|  203 | Aarav   | NULL    |
|  204 | Harshit | Khurana |
|  205 | Rahul   | NULL    |
|  206 | Piyush  | Kohli   |
|  207 | Lovkesh | NULL    |
|  208 | Gaurav  | Kumar   |
|  209 | Raman  | Kumar    |
+------+---------+---------+
10 rows in set (0.00 sec)

mysql> Select DISTINCT Lname from testing where Lname IS NOT NULL limit 3;
+---------+
| Lname   |
+---------+
| Kumar   |
| Bhalla  |
| Khurana |
+---------+
3 rows in set (0.00 sec)
Rust - HelloWorld Example

This chapter explains the basic syntax of Rust language through a HelloWorld example.
Create a HelloWorld-App folder and navigate to that folder on terminal
Create a HelloWorld-App folder and navigate to that folder on terminal
C:\Users\Admin>mkdir HelloWorld-App
C:\Users\Admin>cd HelloWorld-App
C:\Users\Admin\HelloWorld-App>

To create a Rust file, execute the following command −
To create a Rust file, execute the following command −
C:\Users\Admin\HelloWorld-App>notepad Hello.rs

Rust program files have an extension .rs. The above command creates an empty file Hello.rs and opens it in NOTEpad. Add the code given below to this file −
fn
main(){
   println!("Rust says Hello to TutorialsPoint !!");
}
The above program defines a function main fn main(). The fn keyword is used to define a function. The main() is a predefined function that acts as an entry point to the program. println! is a predefined macro in Rust. It is used to print a string (here Hello) to the console. Macro calls are always marked with an exclamation mark – !.
Compile the Hello.rs file using rustc.
Compile the Hello.rs file using rustc.
C:\Users\Admin\HelloWorld-App>rustc Hello.rs

Upon successful compilation of the program, an executable file (file_name.exe) is generated. To verify if the .exe file is generated, execute the following command.
C:\Users\Admin\HelloWorld-App>dir
//lists the files in folder
Hello.exe
Hello.pdb
Hello.rs

Execute the Hello.exe file and verify the output.
Rust provides a powerful macro system that allows meta-programming. As you have seen in the previous example, macros look like functions, except that their name ends with a bang(!), but instead of generating a function call, macros are expanded into source code that gets compiled with the rest of the program. Therefore, they provide more runtime features to a program unlike functions. Macros are an extended version of functions.
println!(); // prints just a newline
println!("hello ");//prints hello
println!("format {} arguments", "some"); //prints format some arguments

Comments are a way to improve the readability of a program. Comments can be used to include additional information about a program like author of the code, hints about a function/ construct, etc. The compiler ignores comments.
Rust supports the following types of comments −
Single-line comments ( // ) − Any text between a // and the end of a line is treated as a comment
Single-line comments ( // ) − Any text between a // and the end of a line is treated as a comment
Multi-line comments (/* */) − These comments may span multiple lines.
Multi-line comments (/* */) − These comments may span multiple lines.
//this is single line comment

/* This is a
   Multi-line comment
*/

Rust programs can be executed online through Tutorialspoint Coding Ground. Write the HelloWorld program in the Editor tab and click Execute to view result.

    45 Lectures 
     4.5 hours 

 Stone River ELearning

    10 Lectures 
     33 mins

 Ken Burke
 Print
 Add Notes
 Bookmark this page
Difference between Struct and Enum in C/C++ with Examples

01 Jun, 2022
Structure in C++
A structure is a user-defined data type in C/C++. A structure creates a data type that can be used to group items of possibly different types into a single type. The ‘struct’ keyword is used to create a structure. 
Syntax:
struct structureName{
    member1;
    member2;
    member3;
    .
    .
    .
    memberN;
};
Below is the implementation:
C++
#include<stdio.h> struct Point{int x, y;}; int main(){struct Point p1 = {0, 1}; // Accessing members of point p1p1.x = 10;printf ("x = %d, y = %d", p1.x, p1.y); return 0;}
x = 10, y = 1
Structures in C++ can contain two types of members:  
Data Member: These members are normal C++ variables. We can create a structure with variables of different data types in C++.
Member Functions: These members are normal C++ functions. Along with variables, we can also include functions inside a structure declaration.
Enum in C++
Enum is the short name for enumeration. It is a user-defined data type. It is used to define a list of options that can be selected. Once, enum is declared we cannot change its value, the compiler will throw an error. Two enumerations cannot share the same names.
enum enumName{
    member1;
    member2;
    member3;
    .
    .
    .
    memberN;
};
Below is the implementation:
C++
#include <bits/stdc++.h>using namespace std; // Defining enum Yearenum year {    Jan,    Feb,    Mar,    Apr,    May,    Jun,    Jul,    Aug,    Sep,    Oct,    Nov,    Dec}; // Driver Codeint main(){    int i;     // Traversing the enum year    for (i = Jan; i <= Dec; i++)        cout << i << endl;     return 0;}
0
1
2
3
4
5
6
7
8
9
10
11

Difference between Struct and Enum
Struct only contains parameterized constructors and no destructors. 
The compiler does not generate a default constructor for a struct.
jayanth_mkv
C-Struct-Union-Enum
C Language
C++
Difference Between
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Unordered Sets in C++ Standard Template Library
What is the purpose of a function prototype?
Operators in C / C++
Exception Handling in C++
Smart Pointers in C++ and How to Use Them
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)
unordered_map in C++ STL
Python – Extract K length substrings

30 Jan, 2020
There are many problems in which we require to get all K length substrings of a string. This particular utility is very popular in competitive programming and having shorthands to solve this problems can always be handy. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using list comprehension + string slicingThe combination of list comprehension and string slicing can be used to perform this particular task. This is just brute force method to perform this task.
# Python3 code to demonstrate working of# Extract K length substrings# Using list comprehension + string slicing  # initializing string test_str = "Geeks"  # printing original string print("The original string is : " + str(test_str))  # initializing K K = 3  # Extract K length substrings# Using list comprehension + string slicingres = [test_str[i: j] for i in range(len(test_str)) for j in range(i + 1, len(test_str) + 1) if len(test_str[i:j]) == K]  # printing result print("All K length substrings of string are : " + str(res))
The original string is : Geeks
All K length substrings of string are : ['Gee', 'eek', 'eks']

 
Method #2 : Using itertools.combinations()This particular task can also be performed using the inbuilt function of combinations, which helps to get all K length the possible combinations i.e the substrings from a string.
# Python3 code to demonstrate working of# Extract K length substrings# Using itertools.combinations()from itertools import combinations  # initializing string test_str = "Geeks"  # printing original string print("The original string is : " + str(test_str))  # initializing K K = 3  # Extract K length substrings# Using itertools.combinations()res = [test_str[x:y] for x, y in combinations(range(len(test_str) + 1), r = 2) if len(test_str[x:y]) == K ]  # printing result print("All K length substrings of string are : " + str(res))
The original string is : Geeks
All K length substrings of string are : ['Gee', 'eek', 'eks']

Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL | DROP, TRUNCATE

09 Jan, 2019
DROP
DROP is used to delete a whole database or just a table.The DROP statement destroys the objects like an existing database, table, index, or view.A DROP statement in SQL removes a component from a relational database management system (RDBMS).Syntax:
DROP object object_name

Examples:
DROP TABLE table_name;
table_name: Name of the table to be deleted.

DROP DATABASE database_name;
database_name: Name of the database to be deleted.

TRUNCATE
TRUNCATE statement is a Data Definition Language (DDL) operation that is used to mark the extents of a table for deallocation (empty for reuse). The result of this operation quickly removes all data from a table, typically bypassing a number of integrity enforcing mechanisms. It was officially introduced in the SQL:2008 standard.The TRUNCATE TABLE mytable statement is logically (though not physically) equivalent to the DELETE FROM mytable statement (without a WHERE clause).Syntax:
TRUNCATE TABLE  table_name;
table_name: Name of the table to be truncated.
DATABASE name - student_data

DROP vs TRUNCATE
Truncate is normally ultra-fast and its ideal for deleting data from a temporary table.
Truncate preserves the structure of the table for future use, unlike drop table where the table is deleted with its full structure.
Table or Database deletion using DROP statement cannot be rolled back, so it must be used wisely.
Queries
To delete the whole databaseDROP DATABASE student_data; 
After running the above query whole database will be deleted.
DROP DATABASE student_data; 

After running the above query whole database will be deleted.
To truncate Student_details table from student_data database.TRUNCATE TABLE Student_details;
After running the above query Student_details table will be truncated, i.e, the data will be deleted but the structure will remain in the memory for further operations.
TRUNCATE TABLE Student_details;

After running the above query Student_details table will be truncated, i.e, the data will be deleted but the structure will remain in the memory for further operations.
References:
https://en.wikipedia.org/wiki/Truncate_(SQL)
https://en.wikipedia.org/wiki/Data_definition_language#DROP_statement
This article is contributed by Pratik Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
SQL-Clauses-Operators
Articles
DBMS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove Duplicate/Repeated words from String

25 Oct, 2021
Java
import java.io.*; class GFG {  public static void main(String[] args) {                 System.out.println("Enter The String : ");        String str = "geeksforgeeks";        StringBuffer sb = new StringBuffer();        str.chars().distinct().forEach(c -> sb.append((char) c));        String DuplicateString = sb.toString();        System.out.println("String after duplicates removed :"+DuplicateString);    }}
Given a string, we have to remove all duplicate/repeated words from the string.Examples: 
Input: str = “Geeks for Geeks A Computer Science portal for Geeks” Output: Geeks for A Computer Science portal Explanation: here ‘Geeks’ and ‘for’ are duplicate so these words are removed from the string   Input: “Publish your own articles on GeeksforGeeks and share your knowledge with the world” Output: Publish your own articles on GeeksforGeeks and share knowledge with the world Explanation: here ‘your’ is the duplicate word so that word is removed from string 
 
We create an empty hash table. Then split given string around spaces. For every word, we first check if it is in hash table or not. If not found in hash table, we print it and store in the hash table.To split given string into words, we use stringstream in C++. 
CPP
// C++ program to remove duplicate// word from string#include <bits/stdc++.h>using namespace std; void removeDupWord(string str){    // Used to split string around spaces.    istringstream ss(str);     // To store individual visited words    unordered_set<string> hsh;     // Traverse through all words    do    {        string word;        ss >> word;         // If current word is not seen before.        while (hsh.find(word) == hsh.end()) {            cout << word << " ";            hsh.insert(word);        }     } while (ss);} // Driver functionint main(){    string str = "Geeks for Geeks A Computer"                " Science portal for Geeks";    removeDupWord(str);    return 0;}
Geeks for A Computer Science portal
 
Remove Duplicate/Repeated words from String | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersRemove Duplicate/Repeated words from String | 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 / 2:51•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=dX8WiwMO5PU" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
VishwashBhardwaj
palashtrivedi007
cpp-string
cpp-stringstream
cpp-unordered_set
C++ Programs
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to create slider to map a range of values in JavaScript ?

13 Jul, 2020
The task is to map a range of values to another range of values like map (0-100) to (100-10000000) in JavaScript. There are two approaches that are discussed below.
Approach 1: Use the logarithmic scale to map the range. In this example, first the log value of the range is calculated and then the scale is calculated using the difference of log values of target scale to the difference of start scale. Then use the exponentiation to map the range for a particular number.
Example: This example implements the above approach.
<!DOCTYPE HTML><html>  <body style="text-align:center;">    <h1>GeeksForGeeks</h1>          <p id="GFG_UP"></p>          <button onclick="myGFG()">        Click Here    </button>          <p id="GFG_DOWN"></p>    <script>        var up = document.getElementById("GFG_UP");        var val = 50;        up.innerHTML = "Click on the button to map"            + " the value(0-100) to a range from "            + "100 to 10, 000, 000<br> Val - " + val;                  var down = document.getElementById("GFG_DOWN");                  function Slider(pos) {            var minM = 0;            var maxM = 100;            var minV = Math.log(100);            var maxV = Math.log(10000000);            var scal = (maxV - minV) / (maxM - minM);            return Math.exp(minV + scal * (pos - minM));        }        function myGFG() {            down.innerHTML = "The value for "                 + val + " is " + Slider(val);        }    </script></body>  </html>
Output:
Approach 2: This example also maps the value from one range to another but uses a different formula.
Example: This example implements the above approach.
<!DOCTYPE HTML><html>  <body style="text-align:center;">    <h1>GeeksForGeeks</h1>      <p id="GFG_UP"></p>          <button onclick="myGFG()">        Click Here    </button>          <p id="GFG_DOWN"></p>          <script>        var up = document.getElementById("GFG_UP");        var val = 50;        up.innerHTML = "Click on the button to map"            + " the value(0-100) to a range from "            + "100 to 10, 000, 000<br> Val - " + val;          var down = document.getElementById("GFG_DOWN");        function Slider(pos) {            return Math.floor(-900 + 1000 *                     Math.exp(pos / 10.857255959));        }        function myGFG() {            down.innerHTML = "The value for "             + val + " is " + Slider(val);        }    </script></body>  </html>
Output:
javascript-math
JavaScript
Web Technologies
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
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Hide or show elements in HTML using display property
Difference Between PUT and PATCH Request
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 ?
JavaScript string.codePointAt() Method - GeeksforGeeks

05 Oct, 2021
Below is the example of the string.codePointAt() Method.
Example:<script>     a = "gfg"      b = a.codePointAt(1);       document.write(b + "<br>") </script> 
<script>     a = "gfg"      b = a.codePointAt(1);       document.write(b + "<br>") </script> 
Output:102
102
The string.codePointAt() is an inbuilt method in JavaScript which is used to return a non-negative integer value i.e, code point value of the specified element of the given string.List of code point values of different elements:
Syntax:
string.codePointAt(A)
Parameters: It accepts a parameter which shows the index of an element in the string. Index starts form zero (0).
Return Values: It returns the code point value of the element which is denoted by a parameter in the string. It returns undefined if there is no element present at the specified location i.e, at “A”th index.
JavaScript code to show the working of string.codePointAt() method:Code #1:
<script>      // Taking a string "gfg"    a = "gfg"      // Pointing each elements of the string    b = a.codePointAt(0);    c = a.codePointAt(1);    d = a.codePointAt(2);      // Printing the code point value of each element    document.write(b + "<br>")    document.write(c + "<br>")    document.write(d)  </script>
Output:
103
102
103
Code #2:
<script>      // Taking a string "gfg"    a = "gfg"      // Pointing 4th index of the string    // index starts from 0    b = a.codePointAt(3);      // Printing the code point value    document.write(b + "<br>")  </script>
Output:
undefined
Note: Output is undefined because in “gfg” there is no element at 4th index.
Supported Browsers:
Google Chrome 41 and above
Edge 12 and above
Firefox 29 and above
Opera 28 and above
Safari 10 and above
ysachin2314
JavaScript-Methods
javascript-string
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
Solidity - Function Modifiers

Function Modifiers are used to modify the behaviour of a function. For example to add a prerequisite to a function.
First we create a modifier with or without parameter.
contract Owner {
   modifier onlyOwner {
      require(msg.sender == owner);
      _;
   }
   modifier costs(uint price) {
      if (msg.value >= price) {
         _;
      }
   }
}
The function body is inserted where the special symbol "_;" appears in the definition of a modifier. So if condition of modifier is satisfied while calling this function, the function is executed and otherwise, an exception is thrown.
See the example below −
pragma solidity ^0.5.0;

contract Owner {
   address owner;
   constructor() public {
      owner = msg.sender;
   }
   modifier onlyOwner {
      require(msg.sender == owner);
      _;
   }
   modifier costs(uint price) {
      if (msg.value >= price) {
         _;
      }
   }
}
contract Register is Owner {
   mapping (address => bool) registeredAddresses;
   uint price;
   constructor(uint initialPrice) public { price = initialPrice; }
   
   function register() public payable costs(price) {
      registeredAddresses[msg.sender] = true;
   }
   function changePrice(uint _price) public onlyOwner {
      price = _price;
   }
}

    38 Lectures 
     4.5 hours 

 Abhilash Nelson

    62 Lectures 
     8.5 hours 

 Frahaan Hussain

    31 Lectures 
     3.5 hours 

 Swapnil Kole
 Print
 Add Notes
 Bookmark this page
Area and Perimeter of a circle in PL/SQL

04 Jul, 2018
Prerequisite – PL/SQL introductionIn PL/SQL code groups of commands are arranged within a block. A block group related declarations or statements. In declare part, we declare variables and between begin and end part, we perform the operations.
Given the radius of a circle and the task is to find the area and perimeter of the circle.Examples:
Input: 3
Output: Area = 28.26
        Perimeter = 18.84

Input: 7
Output: Area = 153.86
        Perimeter = 43.96

Formula for area and perimeter of circle:Area:
pi * radius * radius 
Perimeter:
2 * pi * radius
where pi = 3.14
Below is the required implementation:
--Find the area and perimeter of circleDECLARE       -- Variables to store area and perimeter    area   NUMBER(6, 2)  ;      perimeter   NUMBER(6, 2)  ;           --Assigning the value of radius     radius NUMBER(1) := 3;           --Constant value of  PI     pi CONSTANT NUMBER(3, 2) := 3.14;       BEGIN           --Formula for area and perimeter of a circle         area := pi * radius * radius;         perimeter := 2 * pi * radius;        dbms_output.Put_line('Area = ' || area);         dbms_output.Put_line(' Perimeter = ' || perimeter);   END; 
Output:
Area = 28.26
Perimeter = 18.84

SQL-PL/SQL
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Program to display keys with same values in a dictionary List

11 Dec, 2020
Given a list with all dictionary elements, the task is to write a Python program to extract keys having similar values across all dictionaries.
Examples:
Input : test_list = [{“Gfg”: 5, “is” : 8, “best” : 0}, {“Gfg”: 5, “is” : 1, “best” : 0}, {“Gfg”: 5, “is” : 0, “best” : 0}] Output : [‘Gfg’, ‘best’] Explanation : All Gfg values are 5 and best has 0 as all its values in all dictionaries.
Input : test_list = [{“Gfg”: 5, “is” : 8, “best” : 1}, {“Gfg”: 5, “is” : 1, “best” : 0}, {“Gfg”: 5, “is” : 0, “best” : 0}] Output : [‘Gfg’] Explanation : All Gfg values are 5.  
Method 1 : Using keys() and loop
In this, we iterate through all the elements in the list using loop and extract keys using keys(). For each key, each dictionary’s key is compared, if found similar, key is added to result.
Python3
# initializing Matrixtest_list = [{"Gfg": 5, "is": 8, "best": 0},             {"Gfg": 5, "is": 1, "best": 0},             {"Gfg": 5, "is": 0, "best": 0}]  # printing original listprint("The original list is : " + str(test_list))  # getting keyskeys = list(test_list[0].keys())  res = []# iterating each dictionary for similar key's valuefor key in keys:    flag = 1    for ele in test_list:          # checking for similar values        if test_list[0][key] != ele[key]:            flag = 0            break      if flag:        res.append(key)  # printing resultprint("Similar values keys : " + str(res))
Output:
The original list is : [{‘Gfg’: 5, ‘is’: 8, ‘best’: 0}, {‘Gfg’: 5, ‘is’: 1, ‘best’: 0}, {‘Gfg’: 5, ‘is’: 0, ‘best’: 0}]
Similar values keys : [‘Gfg’, ‘best’]
Method 2 : Using all(), loop and keys()
In this, inner loop is avoided and replaced by all() which checks for all the keys having similar values and then the key is extracted.
Python3
# initializing Matrixtest_list = [{"Gfg": 5, "is": 8, "best": 0},             {"Gfg": 5, "is": 1, "best": 0},             {"Gfg": 5, "is": 0, "best": 0}]  # printing original listprint("The original list is : " + str(test_list))  # getting keyskeys = list(test_list[0].keys())  res = []  # iterating each dictionary for similar key's valuefor key in keys:      # using all to check all keys with similar values    flag = all(test_list[0][key] == ele[key] for ele in test_list)      if flag:        res.append(key)  # printing resultprint("Similar values keys : " + str(res))
Output:
The original list is : [{‘Gfg’: 5, ‘is’: 8, ‘best’: 0}, {‘Gfg’: 5, ‘is’: 1, ‘best’: 0}, {‘Gfg’: 5, ‘is’: 0, ‘best’: 0}]
Similar values keys : [‘Gfg’, ‘best’]
Python dictionary-programs
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Java Program to Print Multiplication Table for Any Number

19 Jan, 2021
Given a number n as input, we need to print its table, where N>0.
Example
Input 1 :- N = 7
Output  :- 
     7 * 1 = 7
    7 * 2 = 14
    7 * 3 = 21
    7 * 4 = 28
    7 * 5 = 35
    7 * 6 = 42
    7 * 7 = 49
    7 * 8 = 56
    7 * 9 = 63
    7 * 10 = 70
Two ways are shown to Print Multiplication Table for any Number:
Using for loop for printing the multiplication table upto 10.Using while loop for printing the multiplication table upto the given range.
Using for loop for printing the multiplication table upto 10.
Using while loop for printing the multiplication table upto the given range.
Method 1: Generating Multiplication Table using for loop upto 10
Java
// Java Program to print the multiplication table of the// number N.  class GFG {    public static void main(String[] args)    {        // number n for which we have to print the        // multiplication table.        int N = 7;          // looping from 1 to 10 to print the multiplication        // table of the number.        // using for loop        for (int i = 1; i <= 10; i++) {            // printing the N*i,ie ith multiple of N.            System.out.println(N + " * " + i + " = "                               + N * i);        }    }}
7 * 1 = 7
7 * 2 = 14
7 * 3 = 21
7 * 4 = 28
7 * 5 = 35
7 * 6 = 42
7 * 7 = 49
7 * 8 = 56
7 * 9 = 63
7 * 10 = 70
Method 2:- Generating Multiplication Table using while loop upto any given range
Java
// Java Program to print the multiplication table of// number N using while loop  class GFG {    public static void main(String[] args)    {        // number n for which we have to print the        // multiplication table.        int N = 7;          int range = 18;          // looping from 1 to range to print the        // multiplication table of the number.        int i = 1;          // using while loop        while (i <= range) {              // printing the N*i,ie ith multiple of N.            System.out.println(N + " * " + i + " = "                               + N * i);            i++;        }    }}
7 * 1 = 7
7 * 2 = 14
7 * 3 = 21
7 * 4 = 28
7 * 5 = 35
7 * 6 = 42
7 * 7 = 49
7 * 8 = 56
7 * 9 = 63
7 * 10 = 70
7 * 11 = 77
7 * 12 = 84
7 * 13 = 91
7 * 14 = 98
7 * 15 = 105
7 * 16 = 112
7 * 17 = 119
7 * 18 = 126
Picked
Technical Scripter 2020
Java
Java Programs
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
\leq - Tex Command

\leq - Used to draw less than or equal to symbol.
{ \leq }
\leq command is used to draw less than or equal to symbol.

\leq

≤



\leq

≤


\leq

    14 Lectures 
     52 mins

 Ashraf Said

    11 Lectures 
     1 hours 

 Ashraf Said

    9 Lectures 
     1 hours 

 Emenwa Global, Ejike IfeanyiChukwu

    29 Lectures 
     2.5 hours 

 Mohammad Nauman

    14 Lectures 
     1 hours 

 Daniel Stern

    15 Lectures 
     47 mins

 Nishant Kumar
 Print
 Add Notes
 Bookmark this page
Among id, name, xpath and css, which locator should be used?

Each of the locators has some significance. If the page contains unique
attribute values, we should use them first. However if there are no unique elements, we should use css selector as it is more effective in terms of speed.
Css also has a drawback that we cannot traverse from child to parent node which means we cannot travel backward. But xpath allows this feature. Xpath is the most common locator in Selenium and performs traversal through DOM elements and attributes to identify an object.
An xpath is represented by two ways namely ‘/ ‘and ‘// ‘. A forward single slash means absolute path. Here xpath traverses direct from parent to child in DOM. Thus in absolute xpath we have to travel from the root node to the target.
Syntax − 
driver.findElement(By.xpath("/html/body/div/input")).
A double forward ‘// ‘slash means relative path. Here xpath finds the matching element in every corner of DOM. It doesn't have a particular beginning point.
Syntax −
driver.findElement(By.xpath("//input[@name=’Tutorial’]")).
It is always recommended to use relative xpath rather than absolute xpath. In absolute xpath, we need to specify from the root to the desired element so if any of the attributes and its value get changed in between, then our xpath will no longer be correct.
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class TextMatch {
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",    "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url = " https://www.tutorialspoint.com/questions/index.php";
      driver.get(url);
      driver.manage().window().maximize();
      driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
      //identifying element with xpath
      driver.findElement(By.xpath("//input[@class=’gsc-input’]")).click();
      driver.close();
   }
}
Java program to find the 2nd smallest number in an array

To find the 2nd smallest element of the given array, first of all, sort the array.
Compare the first two elements of the array
If the first element is greater than the second swap them.
Then, compare 2nd and 3rd elements if the second element is greater than the 3rd swap them.
Repeat this till the end of the array.
After sorting an array print the 2nd element of the array.
Live Demo
public class SmallestNumberInAnArray {
   public static void main(String args[]){
      int temp, size;
      int array[] = {10, 20, 25, 63, 96, 57};
      size = array.length;

      for(int i = 0; i<size; i++ ){
         for(int j = i+1; j<size; j++){
            if(array[i]>array[j]){
               temp = array[i];
               array[i] = array[j];
               array[j] = temp;
            }
         }
      }
      System.out.println("2nd Smallest element of the array is:: "+array[0]);
   }
}
The 2nd Smallest element of the array is:: 10
You can also sort the elements of the given array using the sort method of the java.util.Arrays class then, print the 2nd element of the array.
Live Demo
import java.util.Arrays;
public class LargestNumberSample {
   public static void main(String args[]){
      int array[] = {10, 20, 25, 63, 96, 57};
      int size = array.length;
      Arrays.sort(array);
      System.out.println("sorted Array ::"+Arrays.toString(array));
      int res = array[1];
      System.out.println("2nd smallest element is ::"+res);
   }
}
sorted Array ::[10, 20, 25, 57, 63, 96]
largest element is ::20