code-rag-bench/online-tutorials huggingface dataset:
C Program for Tower of Hanoi

16 Jun, 2022
Tower of Hanoi is a mathematical puzzle where we have three rods and n disks. The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules: 1) Only one disk can be moved at a time. 2) Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack. 3) No disk may be placed on top of a smaller disk. 
C
#include <stdio.h> // C recursive function to solve tower of hanoi puzzlevoid towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod){    if (n == 1)    {        printf("\n Move disk 1 from rod %c to rod %c", from_rod, to_rod);        return;    }    towerOfHanoi(n-1, from_rod, aux_rod, to_rod);    printf("\n Move disk %d from rod %c to rod %c", n, from_rod, to_rod);    towerOfHanoi(n-1, aux_rod, to_rod, from_rod);} int main(){    int n = 4; // Number of disks    towerOfHanoi(n, \'A\', \'C\', \'B\');  // A, B and C are names of rods    return 0;}
Output:
 Move disk 1 from rod A to rod B
 Move disk 2 from rod A to rod C
 Move disk 1 from rod B to rod C
 Move disk 3 from rod A to rod B
 Move disk 1 from rod C to rod A
 Move disk 2 from rod C to rod B
 Move disk 1 from rod A to rod B
 Move disk 4 from rod A to rod C
 Move disk 1 from rod B to rod C
 Move disk 2 from rod B to rod A
 Move disk 1 from rod C to rod A
 Move disk 3 from rod B to rod C
 Move disk 1 from rod A to rod B
 Move disk 2 from rod A to rod C
 Move disk 1 from rod B to rod C
Time Complexity: O(2n)
Auxiliary Space: O(n)
Please refer complete article on Program for Tower of Hanoi for more details!
chandramauliguptach
C Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Header files in C/C++ and its uses
C Program to read contents of Whole File
How to return multiple values from a function in C or C++?
C++ Program to check Prime Number
Producer Consumer Problem in C
C Program to Swap two Numbers
How to Append a Character to a String in C
C program to sort an array in ascending order
Program to find Prime Numbers Between given Interval
Set, Clear and Toggle a given bit of a number in C
Getting screen’s height and width using Tkinter | Python

14 Sep, 2021
Tkinter provides some methods with the help of which we can get the current screen height and width.Following methods can be used to decide height and width : 
winfo_screenheight() // Returns screen height in pixels

winfo_screenmmheight() // Returns screen height in mm

winfo_screenwidth() // Returns screen width in pixels

winfo_screenmmwidth() // Returns screen width in mm
  Code #1: Getting height and width in pixels.  
Python3
# importing tkinter modulefrom tkinter import * from tkinter.ttk import * # creating tkinter windowroot = Tk() # getting screen's height in pixelsheight = root.winfo_screenheight() # getting screen's width in pixelswidth = root.winfo_screenwidth() print("\n width x height = %d x %d (in pixels)\n" %(width, height))# infinite loopmainloop()
Output:  
  Code #2: Getting height and width in mm.  
Python3
# importing tkinter modulefrom tkinter import * from tkinter.ttk import * # creating tkinter windowroot = Tk() # getting screen's height in mmheight = root.winfo_screenmmheight() # getting screen's width in mmwidth = root.winfo_screenmmwidth() print("\n width x height = %d x %d (in mm)\n" %(width, height))# infinite loopmainloop()
Output:  
 
gopikumarkaushik9065
Python-gui
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Convert integer to string in Python
Python | os.path.join() method
Create a Pandas DataFrame from Lists
Data Structures | Heap | Question 12

28 Jun, 2021
The elements 32, 15, 20, 30, 12, 25, 16 are inserted one by one in the given order into a Max Heap. The resultant Max Heap is.
(A) a(B) b(C) c(D) dAnswer: (A)Explanation:
32, 15, 20, 30, 12, 25, 16 

After insertion of 32, 15 and 20
          32
        /    \
      15      20
 
After insertion of 30
          32
        /    \
      15      20
     /
    30
Max Heap property is violated, so 30 is swapped with 15
          32
        /    \
      30      20
     /
    15

After insertion of 12
          32
        /    \
      30      20
     /  \
    15  12

After insertion of 25
          32
        /    \
      30      20
     /  \     /
    15  12   25
Max Heap property is violated, so 25 is swapped with 20
          32
        /    \
      30      25
     /  \     /
    15  12   20


After insertion of 16
          32
        /    \
      30      25
     /  \     /  \
    15  12   20  16 

Quiz of this Question
Data Structures
Data Structures-Heap
Heap Quizzes
Data Structures
Data Structures
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to get the width of the Tkinter widget?

Tkinter widgets are supposed to be present in the Tkinter application window. All the widgets can be configured and customized by using predefined properties or functions.
To get the width of a widget in a Tkinter application, we can use winfo_width() method. It returns the width of the widget which can be printed later as the output.
#Import the required libraries
from tkinter import *

#Create an instance of Tkinter Frame
win = Tk()

#Set the geometry
win.geometry("700x350")

#Set the default color of the window
win.config(bg='#aad5df')

#Create a Label to display the text
label=Label(win, text= "Hello World!",font= ('Helvetica 18 bold'), background= 'white', foreground='purple1')
label.pack(pady = 50)

win.update()

#Return and print the width of label widget
width = label.winfo_width()
print("The width of the label is:", width, "pixels")

win.mainloop()
Running the above code will display a window that contains a Label widget.
When we compile the code, it will print the width of the label widget on the console.
The width of the label is: 148 pixels
wxPython - Dockable Windows

wxAui is an Advanced User Interface library incorporated in wxWidgets API. Wx.aui.AuiManager the central class in AUI framework.
AuiManager manages the panes associated with a particular frame using each panel’s information in wx.aui.AuiPanelInfo object. Let us learn about various properties of PanelInfo object control docking and floating behavior.
Putting dockable windows in the top level frame involves the following steps −
First, create an AuiManager object.
self.mgr = wx.aui.AuiManager(self)

Then, a panel with required controls is designed.
pnl = wx.Panel(self) 
pbox = wx.BoxSizer(wx.HORIZONTAL) 
text1 = wx.TextCtrl(pnl, -1, "Dockable", style = wx.NO_BORDER | wx.TE_MULTILINE) 
pbox.Add(text1, 1, flag = wx.EXPAND) 
pnl.SetSizer(pbox)
The following parameters of AuiPanelInfo are set.
Direction − Top, Bottom, Left, Right, or Center
Direction − Top, Bottom, Left, Right, or Center
Position − More than one pane can be placed inside a dockable region. Each is given a position number.
Position − More than one pane can be placed inside a dockable region. Each is given a position number.
Row − More than one pane appears in one row. Just like more than one toolbar appearing in the same row.
Row − More than one pane appears in one row. Just like more than one toolbar appearing in the same row.
Layer − Panes can be placed in layers.
Layer − Panes can be placed in layers.
Using this PanelInfo, the designed panel is added into the manager object.
info1 = wx.aui.AuiPaneInfo().Bottom() 
self.mgr.AddPane(pnl,info1)

Rest of the top level window may have other controls as usual.
The complete code is as follows −
import wx 
import wx.aui
  
class Mywin(wx.Frame):
  
   def __init__(self, parent, title): 
      super(Mywin, self).__init__(parent, title = title, size = (300,300)) 
		
      self.mgr = wx.aui.AuiManager(self)
		
      pnl = wx.Panel(self) 
      pbox = wx.BoxSizer(wx.HORIZONTAL)
      text1 = wx.TextCtrl(pnl, -1, "Dockable", style = wx.NO_BORDER | wx.TE_MULTILINE) 
      pbox.Add(text1, 1, flag = wx.EXPAND) 
      pnl.SetSizer(pbox) 
         
      info1 = wx.aui.AuiPaneInfo().Bottom() 
      self.mgr.AddPane(pnl, info1) 
      panel = wx.Panel(self) 
      text2 = wx.TextCtrl(panel, size = (300,200), style =  wx.NO_BORDER | wx.TE_MULTILINE) 
      box = wx.BoxSizer(wx.HORIZONTAL) 
      box.Add(text2, 1, flag = wx.EXPAND) 
         
      panel.SetSizerAndFit(box) 
      self.mgr.Update() 
		
      self.Bind(wx.EVT_CLOSE, self.OnClose) 
      self.Centre() 
      self.Show(True) 
		
   def OnClose(self, event): 
      self.mgr.UnInit() 
      self.Destroy() 
		
app = wx.App()
Mywin(None,"Dock Demo")  
app.MainLoop()
The above code produces the following output −
 Print
 Add Notes
 Bookmark this page
TypeScript - Union

TypeScript 1.4 gives programs the ability to combine one or two types. Union types are a powerful way to express a value that can be one of the several types. Two or more data types are combined using the pipe symbol (|) to denote a Union Type. In other words, a union type is written as a sequence of types separated by vertical bars.
Type1|Type2|Type3 

var val:string|number 
val = 12 
console.log("numeric value of val "+val) 
val = "This is a string" 
console.log("string value of val "+val)

In the above example, the variable’s type is union. It means that the variable can contain either a number or a string as its value.
On compiling, it will generate following JavaScript code.
//Generated by typescript 1.8.10
var val;
val = 12;
console.log("numeric value of val " + val);
val = "This is a string";
console.log("string value of val " + val);

Its output is as follows −
numeric value of val  12 
string value of val this is a string 

function disp(name:string|string[]) { 
   if(typeof name == "string") { 
      console.log(name) 
   } else { 
      var i; 
      
      for(i = 0;i<name.length;i++) { 
         console.log(name[i])
      } 
   } 
} 
disp("mark") 
console.log("Printing names array....") 
disp(["Mark","Tom","Mary","John"])

The function disp() can accept argument either of the type string or a string array.
On compiling, it will generate following JavaScript code.
//Generated by typescript 1.8.10
function disp(name) {
   if (typeof name == "string") {
      console.log(name);
   } else {
      var i;
      for (i = 0; i < name.length; i++) {
         console.log(name[i]);
      }
   }
}

disp("mark");
console.log("Printing names array....");
disp(["Mark", "Tom", "Mary", "John"]);

The output is as follows −
Mark 
Printing names array.... 
Mark 
Tom
Mary
John 

Union types can also be applied to arrays, properties and interfaces. The following illustrates the use of union type with an array.
var arr:number[]|string[]; 
var i:number; 
arr = [1,2,4] 
console.log("**numeric array**")  

for(i = 0;i<arr.length;i++) { 
   console.log(arr[i]) 
}  

arr = ["Mumbai","Pune","Delhi"] 
console.log("**string array**")  

for(i = 0;i<arr.length;i++) { 
   console.log(arr[i]) 
} 

The program declares an array. The array can represent either a numeric collection or a string collection.
On compiling, it will generate following JavaScript code.
//Generated by typescript 1.8.10
var arr;
var i;
arr = [1, 2, 4];
console.log("**numeric array**");

for (i = 0; i < arr.length; i++) {
   console.log(arr[i]);
}
arr = ["Mumbai", "Pune", "Delhi"];
console.log("**string array**");

for (i = 0; i < arr.length; i++) {
   console.log(arr[i]);
}

Its output is as follows −
**numeric array** 
1 
2 
4 
**string array** 
Mumbai 
Pune 
Delhi


    45 Lectures 
     4 hours 

 Antonio Papa

    41 Lectures 
     7 hours 

 Haider Malik

    60 Lectures 
     2.5 hours 

 Skillbakerystudios

    77 Lectures 
     8 hours 

 Sean Bradley

    77 Lectures 
     3.5 hours 

 TELCOMA Global

    19 Lectures 
     3 hours 

 Christopher Frewin
 Print
 Add Notes
 Bookmark this page
How can I do "cd" in Python?

You can change directory or cd in Python using the os module. It takes as input the relative/absolute path of the directory you want to switch to.
>>> import os
>>> os.chdir('my_folder')
How to create matrix and vector from CSV file in R ?

21 Apr, 2021
In this article, we will discuss how to convert CSV data into a matrix and a vector in R Programming Language. We will use read.csv() function to load the csv file:
Syntax: object=read.csv(path)
where, path is the location of a file present in our local system.
Matrix: Matrix is a two-dimensional data structure that contains rows and columns. It can hold multiple data types. We can convert csv file data into matrix by using the method called as.matrix()
Syntax:as.matrix(csv_file_object)
Vector: Vector is a one-dimensional data structure that can hold multiple datatypes. We can convert CSV data into a vector, By using as.vector()
Syntax: as.vector(csv_file_object)
CSV File Used:
Step 1: Create an object to CSV by reading the path
R
data=read.csv("C:/sravan/data.csv")print(data)
Output:
    Name       ID
1  sravan    7058
2  Jyothika  7059
Step 2: Convert the data into a matrix.
R
matrixdata = as.matrix(data)print(matrixdata)
Output:
    Name           ID
[1, ] "sravan"   "7058"
[2, ] " Jyothika" "7059"
Step 3: Convert the data into a vector
R
vectordata=as.vector(data)print(vectordata)
Output:
    Name       ID
1  sravan    7058
2  Jyothika  7059
Below is the full implementation:
R
# Read data from CSVdata=read.csv("C:/sravan/data.csv")  # Create a matrixmatrixdata=as.matrix(data)  # Create a vectorvectordata=as.vector(data)print(matrixdata)print(vectordata)
Output:
    Name           ID
[1, ] "sravan"   "7058"
[2, ] " Jyothika" "7059"
    Name       ID
1  sravan    7058
2  Jyothika  7059
Picked
R-CSV
R-Matrix
R-Vectors
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
LISP - Loops

There may be a situation, when you need to execute a block of code numbers of times. A loop statement allows us to execute a statement or group of statements multiple times and following is the general form of a loop statement in most of the programming languages.
LISP provides the following types of constructs to handle looping requirements. Click the following links to check their detail.
The loop construct is the simplest form of iteration provided by LISP. In its simplest form, it allows you to execute some statement(s) repeatedly until it finds a return statement.
The loop for construct allows you to implement a for-loop like iteration as most common in other languages.
The do construct is also used for performing iteration using LISP. It provides a structured form of iteration.
The dotimes construct allows looping for some fixed number of iterations.
The dolist construct allows iteration through each element of a list.
The block and return-from allows you to exit gracefully from any nested blocks in case of any error.
The block function allows you to create a named block with a body composed of zero or more statements. Syntax is −
(block block-name(
...
...
))

The return-from function takes a block name and an optional (the default is nil) return value.
The following example demonstrates this −
Create a new source code file named main.lisp and type the following code in it −
(defun demo-function (flag)
   (print 'entering-outer-block)
   
   (block outer-block
      (print 'entering-inner-block)
      (print (block inner-block

         (if flag
            (return-from outer-block 3)
            (return-from inner-block 5)
         )

         (print 'This-wil--not-be-printed))
      )

      (print 'left-inner-block)
      (print 'leaving-outer-block)
   t)
)
(demo-function t)
(terpri)
(demo-function nil)
When you click the Execute button, or type Ctrl+E, LISP executes it immediately and the result returned is −
ENTERING-OUTER-BLOCK 
ENTERING-INNER-BLOCK 

ENTERING-OUTER-BLOCK 
ENTERING-INNER-BLOCK 
5 
LEFT-INNER-BLOCK 
LEAVING-OUTER-BLOCK


    79 Lectures 
     7 hours 

 Arnold Higuit
 Print
 Add Notes
 Bookmark this page
Need help in deleting duplicate columns from a table in MySQL?

To delete duplicate columns, use DELETE with INNER JOIN. Following is the syntax −
delete tbl1 from yourTableName anyAliasName1
inner join yourTableName anyAliasName2
where
yourCondition1
and
yourCondition2
Let us create a table −
mysql> create table demo14
−> (
−> id int not null auto_increment primary key,
−> name varchar(30)
−> );
Query OK, 0 rows affected (1.89 sec)
Insert some records into the table with the help of insert command −
mysql> insert into demo14(name) values('John');
Query OK, 1 row affected (0.14 sec)

mysql> insert into demo14(name) values('David');
Query OK, 1 row affected (0.18 sec)

mysql> insert into demo14(name) values('David');
Query OK, 1 row affected (0.09 sec)

mysql> insert into demo14(name) values('Bob');
Query OK, 1 row affected (0.15 sec)

mysql> insert into demo14(name) values('John');
Query OK, 1 row affected (0.45 sec)

mysql> insert into demo14(name) values('Carol');
Query OK, 1 row affected (0.16 sec)
Display records from the table using select statement −
mysql> select *from demo14;
This will produce the following output −
+----+-------+
| id | name  |
+----+-------+
|  1 | John  |
|  2 | David |
|  3 | David |
|  4 | Bob   |
|  5 | John  |
|  6 | Carol |
+----+-------+
6 rows in set (0.00 sec)
Following is the query to delete duplicate columns from the table −
mysql> delete tbl1 from demo14 tbl1
−> inner join demo14 tbl2
−> where
−> tbl1.id < tbl2.id and
−> tbl1.name = tbl2.name
−> ;
Query OK, 2 rows affected (0.20 sec)
Display records from the table using select statement −
mysql> select *from demo14;
This will produce the following output −
+----+-------+
| id | name  |
+----+-------+
|  3 | David |
|  4 | Bob   |
|  5 | John  |
|  6 | Carol |
+----+-------+
4 rows in set (0.00 sec)
Private Variables in Python

In actual terms (practically), python doesn’t have anything called private member variable in Python. However, adding two underlines(__) at the beginning makes a variable or a method private is the convention used by most python code.
Let’s understand this concept through an example −
 Live Demo
class myClass:
   __privateVar = 27;
   def __privMeth(self):
      print("I'm inside class myClass")
   def hello(self):
      print("Private Variable value: ",myClass.__privateVar)
foo = myClass()
foo.hello()
foo.__privateMeth
In the above program, __privMeth is a private method and __privateVar is a private variable. Let’s see its output now −
Private Variable value: 27
Traceback (most recent call last):
   File "C:/Python/Python361/privateVar1.py", line 12, in <module>
   foo.__privateMeth
AttributeError: 'myClass' object has no attribute '__privateMeth'
From the above output, we can see that outside the class “myClass”, you cannot access the private method as well as the private variable. However, inside the class (myClass) we can access the private variables. In the hello() method, the __privateVar variable can be accessed (as shown above: “Private Variable value: 27”).
So from the above example, we can understand that all the variables and the methods inside the class are public by the method. When we declare data member as private it means they are accessible only side the class and are inaccessible outside the class. The technique of making a variable or method private is called data mangling. Any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classname__spam, where classname is the current class name with a leading underscore(s) stripped. This mangling is done without regard to the syntactic position of the identifier, as long as it occurs within the definition of a class.
Double underscore names are meant to avoid accidental overriding by a subclass instead.
How do I terminate a thread in C++11?

Here we will see, how to terminate the threads in C++11. The C++11 does not have direct method to terminate the threads.
The std::future<void> can be used to the thread, and it should exit when value in future is available. If we want to send a signal to the thread, but does not send the actual value, we can pass void type object.
To create one promise object, we have to follow this syntax −
std::promise<void> exitSignal;
Now fetch the associated future object from this created promise object in main function −
std::future<void> futureObj = exitSignal.get_future();
Now pass the main function while creating the thread, pass the future object −
std::thread th(&threadFunction, std::move(futureObj));
#include <thread>
#include <iostream>
#include <assert.h>
#include <chrono>
#include <future>
using namespace std;
void threadFunction(std::future<void> future){
   std::cout << "Starting the thread" << std::endl;
   while (future.wait_for(std::chrono::milliseconds(1)) == std::future_status::timeout){
      std::cout << "Executing the thread....." << std::endl;
      std::this_thread::sleep_for(std::chrono::milliseconds(500)); //wait for 500 milliseconds
   }
   std::cout << "Thread Terminated" << std::endl;
}
main(){
   std::promise<void> signal_exit; //create promise object
   std::future<void> future = signal_exit.get_future();//create future objects
   std::thread my_thread(&threadFunction, std::move(future)); //start thread, and move future
   std::this_thread::sleep_for(std::chrono::seconds(7)); //wait for 7 seconds
   std::cout << "Threads will be stopped soon...." << std::endl;
   signal_exit.set_value(); //set value into promise
   my_thread.join(); //join the thread with the main thread
   std::cout << "Doing task in main function" << std::endl;
}
Starting the thread
Executing the thread.....
Executing the thread.....
Executing the thread.....
Executing the thread.....
Executing the thread.....
Executing the thread.....
Executing the thread.....
Executing the thread.....
Executing the thread.....
Executing the thread.....
Executing the thread.....
Executing the thread.....
Executing the thread.....
Executing the thread.....
Threads will be stopped soon....
Thread Terminated
Doing task in main function
How to close active/current tab without closing the browser in Selenium-Python?

We can close the active/current tab without closing the browser in Selenium webdriver in Python. By default, Selenium has control over the parent window. Once another browser window is opened, we have to explicitly shift the control with the help of switch_to.window method.
The handle id of the browser window where we want to shift is passed as a parameter to that method. The method window_handles returns the list of all window handle ids of the opened browsers.
The method current_window_handle is used to hold the window handle id of the browser window in focus. To close only the active or current tab we have to use the close method.
parent = driver.window_handles[0]
chld = driver.window_handles[1]
driver.switch_to.window(chld)
driver.close()
Let us try to close active browser as shown in the below image −
from selenium import webdriver
#set chromodriver.exe path
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
driver.implicitly_wait(0.5)
#launch URL
driver.get("https://accounts.google.com/")
#identify element
m = driver.find_element_by_link_text("Help")
m.click()
#obtain parent window handle
p= driver.window_handles[0]
#obtain browser tab window
c = driver.window_handles[1]
#switch to tab browser
driver.switch_to.window(c)
print("Page title :")
print(driver.title)
#close browser tab window
driver.close()
#switch to parent window
driver.switch_to.window(p)
print("Current page title:")
print(driver.title)
#close browser parent window
driver.quit()
Count duplicates records in MySQL table?

You can use if() from MySQL to count duplicate records. The syntax is as follows −
SELECT yourColumnName, COUNT(*) AS anyVariableName, IF (
   COUNT(*)>1,"Duplicate Records", "Not Duplicate records") as anyVariableName FROM yourTableName group by yourColumnName;
To understand the above syntax, let us create a table. The query to create a table is as follows −
mysql> create table DuplicateRecords
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> Name varchar(30),
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (0.82 sec)
Insert some records in the table using insert command. The query is as follows −
mysql> insert into DuplicateRecords(Name) values('Carol');
Query OK, 1 row affected (0.81 sec)

mysql> insert into DuplicateRecords(Name) values('John');
Query OK, 1 row affected (0.17 sec)

mysql> insert into DuplicateRecords(Name) values('Sam');
Query OK, 1 row affected (0.19 sec)

mysql> insert into DuplicateRecords(Name) values('John');
Query OK, 1 row affected (0.17 sec)

mysql> insert into DuplicateRecords(Name) values('Sam');
Query OK, 1 row affected (0.11 sec)

mysql> insert into DuplicateRecords(Name) values('Sam');
Query OK, 1 row affected (0.20 sec)

mysql> insert into DuplicateRecords(Name) values('John');
Query OK, 1 row affected (0.12 sec)

mysql> insert into DuplicateRecords(Name) values('Carol');
Query OK, 1 row affected (0.14 sec)

mysql> insert into DuplicateRecords(Name) values('Carol');
Query OK, 1 row affected (0.10 sec)

mysql> insert into DuplicateRecords(Name) values('Mike');
Query OK, 1 row affected (0.14 sec)
Display all records from the table using select statement. The query is as follows −
mysql> select *from DuplicateRecords;
The following is the output −
+----+-------+
| Id | Name  |
+----+-------+
| 1 | Carol  |
| 2 | John   |
| 3 | Sam    |
| 4 | John   |
| 5 | Sam    |
| 6 | Sam    |
| 7 | John   |
| 8 | Carol  |
| 9 | Carol  |
| 10 | Mike  |
+----+-------+
10 rows in set (0.00 sec)
Here is the query to count the duplicate records from the table −
mysql> SELECT Name, COUNT(*) AS Repetition, IF (COUNT(*)>1,"Duplicate Records", "Not Duplicate records") as IsDuplicateRecordsOrNot
   -> from DuplicateRecords group by Name;
The following is the output −
+-------+------------+-------------------------+
| Name  | Repetition | IsDuplicateRecordsOrNot |
+-------+------------+-------------------------+
| Carol |          3 | Duplicate Records       |
| John  |          3 | Duplicate Records       |
| Sam   |          3 | Duplicate Records       |
| Mike  |          1 | Not Duplicate records   |
+-------+------------+-------------------------+
4 rows in set (0.00 sec)
What is the base class for all data types in C#.NET?

Object is the base class for all data types in C#. The Object Type is the ultimate base class for all data types in C# Common Type System (CTS). The object is an alias for System.Object class.
When a value type is converted to object type, it is called boxing and on the other hand, when an object type is converted to a value type, it is called unboxing.
The following is an example showing the usage of object data types −
using System;
using System.IO;

namespace Demo {
   class objectClass {
      public int x = 56;
   }

   class MyApplication {
      static void Main() {
         object obj;
         obj = 96;
         Console.WriteLine(obj);
         obj = new objectClass();
         objectClass newRef;
         newRef = (objectClass)obj;
         Console.WriteLine(newRef.x);
      }
   }  
}
What is Conditional Operator (?:) in JavaScript?

The conditional operator or ternary operator first evaluates an expression for a true or false value and then executes one of the two given statements depending upon the result of the evaluation.
You can try to run the following code to understand how Ternary Operator works in JavaScript −
<html>
   <body>
      <script>
         var a =10;
         var b =20;
         varlinebreak = "<br />";

         document.write ("((a > b) ? 100 : 200) => ");
         result =(a > b) ? 100 : 200;
         document.write(result);
         document.write(linebreak);

         document.write ("((a < b) ? 100 : 200) => ");
         result =(a < b) ? 100 : 200;
         document.write(result);
         document.write(linebreak);
      </script>
   </body>
</html>
Get value of an input box using Selenium (Python)

We can get the value of an input box with Selenium webdriver. The get_attribute() method is capable of obtaining the value we have entered in an input box. To get the value, we have to pass value as a parameter to the method.
First of all, we have to identify the input box with the help of any of the locators like id, class, name, css or xpath. Then we have to type some values inside it with the send_keys() method.
Let us consider the below input box where we shall enter some texts - Selenium Python and then fetch the value with get_attribute().
from selenium import webdriver
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
driver.implicitly_wait(0.5)
driver.get("https://www.google.com/")
#identify element
l= driver.find_element_by_name("q")
l.send_keys("q")
#get_attribute() to get value of input box
print("Value of input box: " + l.get_attribute('value'))
driver.close()
ReactJS - State Management API

As we learned earlier, React component maintains and expose it’s state through this.state of the component. React provides a single API to maintain state in the component. The API is this.setState(). It accepts either a JavaScript object or a function that returns a JavaScript object.
The signature of the setState API is as follows −
this.setState( { ... object ...} );

A simple example to set / update name is as follows −
this.setState( { name: 'John' } )

The signature of the setState with function is as follows −
this.setState( (state, props) => 
   ... function returning JavaScript object ... );

Here,
state refers the current state of the React component
state refers the current state of the React component
props refers the current properties of the React component.
props refers the current properties of the React component.
React recommends to use setState API with function as it works correctly in async environment. Instead of lambda function, normal JavaScript function can be used as well.
this.setState( function(state, props) { 
   return ... JavaScript object ... 
}

A simple example to update the amount using function is as follows −
this.setState( (state, props) => ({ 
   amount: this.state.amount + this.props.additionaAmount 
})

React state should not be modified directly through this.state member variable and updating the state through member variable does not re-render the component.
A special feature of React state API is that it will be merged with the existing state instead of replacing the state. For example, we can update any one of the state fields at a time instead of updating the whole object. This feature gives the developer the flexibility to easily handle the state data.
A special feature of React state API is that it will be merged with the existing state instead of replacing the state. For example, we can update any one of the state fields at a time instead of updating the whole object. This feature gives the developer the flexibility to easily handle the state data.
For example, let us consider that the internal state contains a student record.
{ 
   name: 'John', age: 16 
}

We can update only the age using setState API, which will automatically merge the new object with the existing student record object.
this.setState( (state, props) => ({ 
   age: 18 
});


    20 Lectures 
     1.5 hours 

 Anadi Sharma

    60 Lectures 
     4.5 hours 

 Skillbakerystudios

    165 Lectures 
     13 hours 

 Paul Carlo Tordecilla

    63 Lectures 
     9.5 hours 

 TELCOMA Global

    17 Lectures 
     2 hours 

 Mohd Raqif Warsi
 Print
 Add Notes
 Bookmark this page
Building a row from a dictionary in PySpark - GeeksforGeeks

18 Jul, 2021
In this article, we will discuss how to build a row from the dictionary in PySpark
For doing this, we will pass the dictionary to the Row() method.
Syntax:
Syntax: Row(dict)
Example 1: Build a row with key-value pair (Dictionary) as arguments.
Here, we are going to pass the Row with Dictionary 
Syntax: Row({‘Key’:”value”, ‘Key’:”value”,’Key’:”value”})
Python3
# import Rowfrom pyspark.sql import Row  # dictdic = {'First_name':"Sravan",        'Last_name':"Kumar",       'address':"hyderabad"}  # create a row with three values# as dictionary.row = Row(dic)  # display rowprint(row)
Output:
<Row({‘First_name’: ‘Sravan’, ‘Last_name’: ‘Kumar’, ‘address’: ‘hyderabad’})>
Example 2: Python program to build two Rows with dictionary.
Syntax: Row(dict, dict)
Code:
Python3
# import Rowfrom pyspark.sql import Row  dic_1 = {'First_name':"Sravan",          'Last_name':"Kumar",         'address':"hyderabad"}  dic_2 = {'First_name':"Bobby",         'Last_name':"Gottumukkala",         'address':"Ponnur"}  # create two rows with# three values as dictionary.row = [Row(dic_1),       Row(dic_2)]# display rowprint(row)
Output:
[<Row({‘First_name’: ‘Sravan’, ‘Last_name’: ‘Kumar’, ‘address’: ‘hyderabad’})>,
 <Row({‘First_name’: ‘Bobby’, ‘Last_name’: ‘Gottumukkala’, ‘address’: ‘Ponnur’})>]
Picked
Python-Pyspark
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python Classes and Objects
Create a directory in Python
Python | os.path.join() method
Python | Pandas dataframe.groupby()
Python | Get unique values from a list
Predefined Identifier __func__ in C - GeeksforGeeks

24 Sep, 2021
Before we start discussing about __func__, let us write some code snippet and anticipate the output: 
C
#include <stdio.h> int main(){   printf("%s",__func__);   return 0;}
Will it compile error due to not defining variable __func__ ? Well, as you would have guessed so far, it won’t give any compile error and it’d print main! 
C language standard (i.e. C99 and C11) defines a predefined identifier as follows in clause 6.4.2.2:
“The identifier __func__ shall be implicitly declared by the translator as if, immediately following the opening brace of each function definition, the declarationstatic const char __func__[] = “function-name”;appeared, where function-name is the name of the lexically-enclosing function.“
It means that C compiler implicitly adds __func__ in every function so that it can be used in that function to get the function name. To understand it better, let us write this code: 
C
#include <stdio.h>void foo(void){   printf("%s",__func__);}void bar(void){   printf("%s",__func__);} int main(){   foo();   bar();   return 0;}
And it’ll give output as foobar. A use case of this predefined identifier could be logging the output of a big program where a programmer can use __func__ to get the current function instead of mentioning the complete function name explicitly. Now what happens if we define one more variable of name __func__ 
C
#include <stdio.h> int __func__ = 10;int  main(){   printf("%d",__func__);   return 0;}
Since C standard says compiler implicitly defines __func__ for each function as the function-name, we should not defined __func__ at the first place. You might get error but C standard says “undefined behavior” if someone explicitly defines __func__ .
Just to finish the discussion on Predefined Identifier __func__, let us mention Predefined Macros as well (such as __FILE__ and __LINE__ etc.) Basically, C standard clause 6.10.8 mentions several predefined macros out of which __FILE__ and __LINE__ are of relevance here. 
It’s worthwhile to see the output of the following code snippet: 
C
#include <stdio.h> int main(){   printf("In file:%s, function:%s() and line:%d",__FILE__,__func__,__LINE__);    return 0;}
Instead of explaining the output, we will leave this to you to guess and understand the role of __FILE__ and __LINE__!Please do Like/Tweet/G+1 if you find the above useful. Also, please do leave us comment for further clarification or info. We would love to help and learn  
avsadityavardhan
chhabradhanvi
C-Library
Articles
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Service-Oriented Architecture
Const keyword in C++
Amazon’s most frequently asked interview questions | Set 2
What's the difference between Scripting and Programming Languages?
Advantages and Disadvantages of Linked List
Arrays in C/C++
Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
std::sort() in C++ STL
Bitwise Operators in C/C++
Multidimensional Arrays in C / C++
Program for longest common directory path in Python

In this tutorial, we are going to write a program that finds the longest common path from the given list of paths. Let's see an example to understand the problem statement more clearly.
paths = ['home/tutorialspoint/python', 'home/tutorialspoint/c', 'home/tutorialspoint/javascript',
'home/tutorialspoint/react', 'home/tutorialspoint/django']
/home/tutorialspoint/
We can solve the problem using os module very easily. Let's see the steps to solve the
Import the os module.
Initialize the list of paths to find the longest common path.
Find the common prefix of all paths using os.path.commonprefix(paths) and store it in variable.
And extract the directory from the common prefix using os.path.dirname(common_prefix).
 Live Demo
# importing the os module
import os
# initializing the paths
paths = ['home/tutorialspoint/python', 'home/tutorialspoint/c', 'home/tutorials
point/javascript', 'home/tutorialspoint/react', 'home/tutorialspoint/django']
# finding the common prefix
common_prefix = os.path.commonprefix(paths)
# extracting the directory from the common prefix
longest_common_directory = os.path.dirname(common_prefix)
# printing the long common path
print(longest_common_directory)
If you run the above code, then you will get the following result.
home/tutorialspoint
If you have any queries regarding the tutorial, mention them in the comment section.
Add packages to Anaconda environment in Python

There are multiple ways by which we can add packages to our existing anaconda environment.
Method 1 − One common approach is to use the “Anaconda Navigator” to add packages to our anaconda environment. Once “Ananconda Navigator” is opened, home page will look something like −
Go to Environments tab just below the Home tab and from there we can check what all packages are installed and what is not.
It is very easy to install any package through anaconda navigator, simply search the required package, select package and click on apply to install it. Let's suppose tensorflow packages are not installed in your computer, I can simply search the required package(like tensorflow), select it and click on apply to install it.
Method 2 − Another way of installing packages is by the use of terminal or an Anaconda Prompt −
conda install opencv
Above command will install OpenCV package into your current environment.
To install specific a specific version of a opencv package −
conda install opencv-3.4.2
We can install multiple packages at once, such as OpenCV and tensorflow −
conda install opencv tensorflow
Note − It is recommended to install all required packages at once so that all of the dependencies are installed at once.
To install a specific package such as opencv into your existing environment “myenv”(in case you have a virtual environment to install project specific packages).
conda install –name myenv opencv
Method 3 − If the package is not available in our conda environment or through anaconda navigator, we can find and install the package with another package manager like pip.
We can install pip in our existing conda environment by simply giving the command −
conda install pip
And your screen will be shown an output something like −
Now if you want to install any particular package, through pip in conda environment, we can do it like −
Above we have installed opencv package through pip in conda environment.
We can use the anaconda prompt, to list all of the packages in the active environment −
conda list
Uri.EscapeDataString(String) Method in C#

The Uri.EscapeDataString() method in C# converts a string to its escaped representation.
Following is the syntax −
public static string EscapeDataString (string str);
Above, the string str is the string to escape.
Let us now see an example to implement the Uri.EscapeDataString() method −
using System;
public class Demo {
   public static void Main(){
      string URI1 = "https://www.tutorialspoint.com/index.htm";
      Console.WriteLine("URI = "+URI1);
      string URI2 = "https://www.tutorialspoint.com/";
      Console.WriteLine("URI = "+URI2);
      Console.WriteLine("\nEscaped string (URI1) = "+Uri.EscapeDataString(URI1));
      Console.WriteLine("Escaped string (URI2) = "+Uri.EscapeDataString(URI2));
   }
}
This will produce the following output −
URI = https://www.tutorialspoint.com/index.htm URI = https://www.tutorialspoint.com/
Escaped string (URI1) = https%3A%2F%2Fwww.tutorialspoint.com%2Findex.htm
Escaped string (URI2) = https%3A%2F%2Fwww.tutorialspoint.com%2F
How to append data into a CSV file using PowerShell?

To append the data into CSV file you need to use –Append parameter while exporting to the CSV file.
In the below example, we have created a CSV file
$outfile = "C:\temp\Outfile.csv"
$newcsv = {} | Select "EMP_Name","EMP_ID","CITY" | Export-Csv $outfile
$csvfile = Import-Csv $outfile
$csvfile.Emp_Name = "Charles"
$csvfile.EMP_ID = "2000"
$csvfile.CITY = "New York"
$csvfile | Export-CSV
$outfile Import-Csv $outfile
Now we need to append the below data to the existing file. So first we will import the csv file into a variable called $csvfile
$csvfile = Import-Csv $outfile
$csvfile.Emp_Name = "James"
$csvfile.EMP_ID = "2500"
$csvfile.CITY = "Scotland"
Once data is inserted into a variable, we will append data with –Append parameter.
$csvfile | Export-CSV $outfile –Append
Check the output:
Import-Csv $outfile
EMP_Name    EMP_ID     CITY
--------    ------     ----
Charles     2000       New York
James       2500       Scotland
Express.js – app.use() Method

The app.use() method mounts or puts the specified middleware functions at the specified path. This middleware function will be executed only when the base of the requested path matches the defined path.
app.use([path], callback, [callback])
path − This is the path for which the middleware function is invoked. A path can be a string, path pattern, a regular expression or an array of all these.
path − This is the path for which the middleware function is invoked. A path can be a string, path pattern, a regular expression or an array of all these.
callback − These are the middleware functions or a series of middleware functions that acts like a middleware except that these callbacks can invoke next (route).
callback − These are the middleware functions or a series of middleware functions that acts like a middleware except that these callbacks can invoke next (route).
Create a file with the name "appUse.js" and copy the following code snippet. After creating the file, use the command "node appUse.js" to run this code.
// app.use() Method Demo Example

// Importing the express module
const express = require('express');

// Initializing the express and port number
var app = express();

// Initializing the router from express
var router = express.Router();
var PORT = 3000;

// This method will call the next() middleware
app.use('/api', function (req, res, next) {
   console.log('Time for main function: %d', Date.now())
   next();
})

// Will be called after the middleware
app.get('/api', function (req, res) {
   console.log('Time for middleware function: %d', Date.now())
   res.send('Welcome to Tutorials Point')
})

// App listening on the below port
app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});
Now, hit the following Endpoint with a GET request
http://localhost:3000/api

C:\home\node>> node appUse.js
Server listening on PORT 3000
Time for main function: 1627490133904
Time for middleware function: 1627490133905
Let’s take a look at one more example.
// app.use() Method Demo Example

// Importing the express module
const express = require('express');

// Initializing the express and port number
var app = express();

// Initializing the router from express
var router = express.Router();
var PORT = 3000;

// This method will call the next() middleware
app.use('/', function (req, res, next) {
   console.log('Middleware will not be called')
})

// Will be called after the middleware
app.get('/api', function (req, res) {
   console.log('Time for middleware function: %d', Date.now())
   res.send('Welcome to Tutorials Point')
})

// App listening on the below port
app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});
Now, hit the following Endpoint with a GET request
http://localhost:3000/api

C:\home\node>> node appUse.js
Server listening on PORT 3000
Middleware will not be called
Implementation of sleep (system call) in OS - GeeksforGeeks

15 Dec, 2021
In this article, we are going to learn about sleep (system call) in operating systems. In the computer science field, a system call is a mechanism that provides the interface between a process and the operating system. In simple terms, it is basically a method in which a computer program requests a service from the kernel of the operating system.
What is sleep in the operating system?Sleep is a computer program and when you call this method, then it sets the process to wait until the specified amount of time proceeds, then goes and finds some other process to run. The sleep system call is used to take a time value as a parameter, specifying the minimum amount of time that the process is to sleep before resuming execution.
Syntax –
 sleep(time);
Methods used : 
sleep() –  This method is used to sleep a thread for a specified amount of time.
start() – This method is used to create a separate call stack for the thread.
run() – This method is used if the thread was constructed using a separate Runnable object. Otherwise this method does nothing and returns.
Example 1 – 
Java
class TestSleep extends Thread{  public void run(){   for(int i=1;i<5;i++){     try{Thread.sleep(300);}catch(InterruptedException e){System.out.println(e);}     System.out.println(i);   }  }  public static void main(String args[]){   TestSleep t1=new TestSleep();   TestSleep t2=new TestSleep();       t1.start();   t2.start();  } }   
Output –
Note - In the above example you can notice that at a time only one thread has been executed and if 
       you sleep a thread for thespecified time,the thread shedular picks up another thread and 
       so on.
Points to remember while using the Tread.sleep() :
Whenever you use this method, it will pause the current thread execution.
Interrupted Exception will be thrown when any other thread interrupts when the thread is sleeping.
anikaseth98
surindertarika1234
Picked
Operating Systems
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Memory Management in Operating System
File Allocation Methods
Logical and Physical Address in Operating System
Difference between Internal and External fragmentation
Process Table and Process Control Block (PCB)
File Access Methods in Operating System
Memory Hierarchy Design and its Characteristics
File Systems in Operating System
States of a Process in Operating Systems
Introduction of Process Management