code-rag-bench/online-tutorials huggingface dataset:
Matcher appendReplacement() method in Java with Examples

The java.util.regex.Matcher class represents an engine that performs various match operations. There is no constructor for this class, you can create/obtain an object of this class using the matches() method of the class java.util.regex.Pattern.
The appendReplacement() method of this (Matcher) class accepts a StringBuffer object and a String (replacement string) as parameters and, appends the input data to the StringBuffer object, replacing the matched content with the replacement string.
Internally, this method reads each character from the input string and appends the String buffer, whenever a match occurs it appends the replacement string instead of matched content part of the string to the buffer and, proceeds from the next position of the matched substring.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class appendReplacementExample {
   public static void main(String[] args) {
      String str = "<p>This <b>is</b> an <b>example</b>HTML <b>script</b>.</p>";
      //Regular expression to match contents of the bold tags
      String regex = "<b>(\\S+)</b>";
      System.out.println("Input string: \n"+str);
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Matching the compiled pattern in the String
      Matcher matcher = pattern.matcher(str);
      //Creating an empty string buffer
      StringBuffer sb = new StringBuffer();
      while (matcher.find()) {
         matcher.appendReplacement(sb, "BoldData");
      }
      matcher.appendTail(sb);
      System.out.println("Contents of the StringBuffer: \n"+ sb.toString() );
   }
}
Input string:
<p>This <b>is</b> an <b>example</b> HTML <b>script</b>.</p>
Contents of the StringBuffer:
This BoldData an BoldData HTML BoldData.
<p>This BoldData an BoldData HTML BoldData.</p>
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class appendReplacementExample {
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter input text: ");
      String input = sc.nextLine();
      String regex = "[#$&+=@|<>-]";
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Creating a Matcher object
      Matcher matcher = pattern.matcher(input);
      int count =0;
      StringBuffer buffer = new StringBuffer();
      System.out.println("Removing the special character form the given string");
      while(matcher.find()) {
         count++;
         matcher.appendReplacement(buffer, "");
      }
      matcher.appendTail(buffer);
      //Retrieving Pattern used
      System.out.println("The are special characters occurred "+count+" times in the given text");
      System.out.println("Text after removing all of them \n"+buffer.toString());
   }
}
Enter input text:
Hello# how$ are& yo|u welco<me to> Tut-oria@ls@po-in#t.
Removing the special character form the given string
The are special characters occurred 11 times in the given text
Text after removing all of them
Hello how are you welcome to Tutorialspoint.
Else without IF and L-Value Required Error in C - GeeksforGeeks

08 Jan, 2019
This error is shown if we write anything in between if and else clause.
Example:
#include <stdio.h>  void main(){    int a;      if (a == 2)        a++;      // due to this line, we will    // get error as misplaced else.    printf("value of a is", a);      else printf("value of a is not equal to 2 ");}
Output:
prog.c: In function 'main':
prog.c:15:5: error: 'else' without a previous 'if'
     else printf("value of a is not equal to 2 ");
     ^

This error occurs when we put constants on left hand side of = operator and variables on right hand side of it.
Example:
#include <stdio.h>  void main(){    int a;    10 = a;}
Output:
prog.c: In function 'main':
prog.c:6:5: error: lvalue required as left operand of assignment
  10 = a;
     ^

Example 2: At line number 12, it will show an error L-value because arr++ means arr=arr+1.Now that is what their is difference in normal variable and array. If we write a=a+1 (where a is normal variable), compiler will know its job and their will be no error but when you write arr=arr+1 (where arr is name of an array) then, compiler will think arr contain address and how we can change address. Therefore it will take arr as address and left side will be constant, hence it will show error as L-value required.
#include <stdio.h>  void main(){    int arr[5];    int i;    for (i = 0; i < 5; i++) {        printf("Enter number: ");        scanf("%d", arr);        arr++;    }}
Output:
prog.c: In function 'main':
prog.c:10:6: error: lvalue required as increment operand
   arr++;
      ^

C Language
C Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
Multithreading in C
Exception Handling in C++
'this' pointer in C++
Arrow operator -> in C/C++ with Examples
Strings in C
Arrow operator -> in C/C++ with Examples
C Program to read contents of Whole File
UDP Server-Client implementation in C
Header files in C/C++ and its uses
unordered_set size() function in C++ STL

28 Jun, 2022
The unordered_set::size() method is a builtin function in C++ STL which is used to return the number of elements in the unordered_set container. Syntax:
unordered_set_name.size()
Parameter: It does not accepts any parameter. Return Value: The function returns the number of elements in the container. Below programs illustrate the unordered_set::size() function: Program 1: 
CPP
// C++ program to illustrate the// unordered_set.size() function#include <iostream>#include <unordered_set> using namespace std; int main(){     unordered_set<int> arr1 = { 1, 2, 3, 4, 5 };     // prints the size of arr1    cout << "size of arr1:" << arr1.size();     // prints the element    cout << "\nThe elements are: ";    for (auto it = arr1.begin(); it != arr1.end(); it++)        cout << *it << " ";     return 0;}
size of arr1:5
The elements are: 5 1 2 3 4
Program 2: 
CPP
// C++ program to illustrate the// unordered_set::size() function// when container is empty#include <iostream>#include <unordered_set> using namespace std; int main(){     unordered_set<int> arr2 = {};     // prints the size    cout << "Size of arr2 : " << arr2.size();     return 0;}
Size of arr2 : 0
Time complexity: O(1)
utkarshgupta110092
CPP-Functions
cpp-unordered_set
cpp-unordered_set-functions
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bitwise Operators in C/C++
Priority Queue in C++ Standard Template Library (STL)
vector erase() and clear() in C++
Substring in C++
Object Oriented Programming in C++
Inheritance in C++
The C++ Standard Template Library (STL)
C++ Classes and Objects
Sorting a vector in C++
2D Vector In C++ With User Defined Size
SQL – SELECT NULL

17 Jun, 2021
The word NULL is used to describe a missing value in SQL. In a table, a NULL value is a value in a field that appears to be empty. A field with a NULL value is the same as one that has no value. It’s important to grasp the difference between a NULL value and a zero value or a field of spaces.
There are two possibilities:
Where SQL is NULL
Syntax: 
SELECT  *
FROM TABLANAME
WHERE COLUMNNAME IS NULL;
Where SQL is NOT NULL
Syntax:  
SELECT *
FROM TABLANAME
WHERE COLUMNNAME IS NOT NULL;
NOT NULL denotes that the column must always consider an explicit value of the specified data type. We did not use NOT NULL in two columns, which means these columns may be NULL.  A field with a NULL value was left blank during the record creation process.
Example: 
Here, we will first create a database named “geeks” then we will create a table “department” in that database. After, that we will execute our query on that table.
CREATE DATABASE geeks;
USE geeks;
CREATE TABLE [dbo].[department](
[ID] [int] NULL,
[SALARY] [int] NULL,
[NAME] [varchar](20) NULL
)
GO
INSERT INTO [dbo].[department] ( ID, SALARY, NAME) VALUES  ( 1, 34000, 'Neha')  
INSERT INTO [dbo].[department]( ID,  NAME) VALUES  ( 2,  'Hema')
INSERT INTO [dbo].[department]( ID, SALARY, NAME) VALUES  ( 3, 36000, 'Jaya' )
INSERT INTO [dbo].[department] ( ID,  NAME)VALUES  ( 4,  'Priya' )
INSERT INTO [dbo].[department]( ID, SALARY, NAME) VALUES  ( 5, 34000, 'Ketan' ))
GO
This is our data inside the table:
SELECT * FROM department;
Select where SQL is NULL:
SELECT * FROM department WHERE salary IS NULL;
Output:
Select where SQL is NOT NULL:
SELECT * FROM department WHERE salary IS NOT NULL;
Output:
surinderdawra388
Picked
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
Window functions in SQL
What is Temporary Table in SQL?
SQL using Python
SQL | Sub queries in From Clause
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
RANK() Function in SQL Server
SQL Query to Convert VARCHAR to INT
SQL Query to Compare Two Dates
SQL Query to Insert Multiple Rows
How to Write Data to Text File in Excel VBA?

29 Oct, 2021
This VBA Program reads an Excel Range (Sales Data) and write to a Text file (Sales.txt)
Excel VBA code to read data from an Excel file (Sales Data – Range “A1:E26”).  Need two “For loop” for rows and columns. Write each value with a comma in the text file till the end of columns (write without comma only the last column value). Do the above step until reach the end of rows. 
Sales Data in Excel: 5 columns and 25 rows
Sales Data
VBA code to create a text file as below
Declaring Variables :  
'Variable declarations
Dim myFileName As String, rng As Range, cellVal As Variant, row As Integer, col As Integer
Initialize variables:myFileName: The file name with the full path of the output text filerng: Excel range to read data from an excel.
myFileName: The file name with the full path of the output text file
rng: Excel range to read data from an excel.
'Full path of the text file
myFileName = "D:\Excel\WriteText\sales.txt"
'Data range need to write on text file
Set rng = ActiveSheet.Range("A1:E26")
Open the output text file and assign a variable “#1”
'Open text file
Open myFileName For Output As #1
‘Nested loop to iterate both rows and columns of a given range eg: “A1:E26” [5 columns and 26 rows]
'Number of Rows
For row = 1 To rng.Rows.Count
   'Number of Columns
   For col = 1 To rng.Columns.Count
Assign the value to variable cellVal 
cellVal = rng.Cells(row, col).Value
Write cellVal with comma.  If the col is equal to the last column of a row.  write-only value without the comma.
'write cellVal on text file
    If col = rng.Columns.Count Then
        Write #1, cellVal 
    Else
        Write #1, cellVal, 
    End If
Close both for loops
   Next col
Next row
Close the file
Close #1
Step 1: Add a shape (Create Text File) to your worksheet 
Step 2: Right-click on “Create a Text file” and “Assign Macro..”
Step 3: Select MacroToCreateTextFile
Step 4: Save your excel file as “Excel Macro-Enabled Workbook”  *.xlsm
Step 5: Click “Create Text file”
Excel-VBA
Picked
Excel
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Delete Blank Columns in Excel?
How to Normalize Data in Excel?
How to Get Length of Array in Excel VBA?
How to Find the Last Used Row and Column in Excel VBA?
How to make a 3 Axis Graph using Excel?
How to Use Solver in Excel?
Introduction to Excel Spreadsheet
Macros in Excel
How to Show Percentages in Stacked Column Chart in Excel?
How to Create a Macro in Excel?
How to scale an Image in ImageView to keep the aspect ratio in Android?

This example demonstrates how to scale an Image in ImageView to keep the aspect ratio in Android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity">
   <ImageView
      android:id="@+id/my_image"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent"
      android:layout_centerInParent="true"
      android:adjustViewBounds="true"
      android:scaleType="fitXY"
      tools:ignore="MissingConstraints" />
</androidx.constraintlayout.widget.ConstraintLayout>
Step 3 − Add the following code to src/MainActivity.java
package com.app.sample;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      ImageView my_image = (ImageView) findViewById(R.id.my_image);
      my_image.setBackgroundResource(R.drawable.flower);
   }
}
Step 4 − Add the following code to Manifests/AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.app.sample">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
         <activity android:name=".MainActivity">
            <intent-filter>
               <action android:name="android.intent.action.MAIN" />
               <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
         </activity>
   </application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
Click here to download the project code.
LTRIM() Function in SQL Server

16 Dec, 2020
LTRIM() function helps to return remove all the space characters found on the left-hand side of the string.
Syntax :
LTRIM(string, [trim_string])
Parameter :
string – The string from which the leading space character would be removed.
trim_string – It is an optional parameter that specifies the characters to be removed from the given string.
Returns :The function will return the string after removing all left-hand side space characters.
Applicable to the following versions of SQL Server :
SQL Server 2017
SQL Server 2016
SQL Server 2014
SQL Server 2012
SQL Server 2008 R2
SQL Server 2008
SQL Server 2005
Example 1 :The basic usage of the LTRIM() function.
SELECT LTRIM('       GeeksforGeeks');
Output :
GeeksforGeeks
Example 2 :Using LTRIM() function with a variable.
DECLARE @str VARCHAR(50)
SET @str = '     Have a nice time ahead!!'
SELECT LTRIM(@str);
Output :
Have a nice time ahead!!
Example-3 :Use of “trim_space” in LTRIM() function.
SELECT LTRIM (‘000325400’, ‘0’);
Output :
325400
DBMS-SQL
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
Window functions in SQL
What is Temporary Table in SQL?
SQL | Sub queries in From Clause
SQL using Python
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
RANK() Function in SQL Server
SQL Query to Convert VARCHAR to INT
SQL Query to Compare Two Dates
How to Write a SQL Query For a Specific Date Range and Date Time?
Difference between Natural join and Inner Join in SQL

31 Aug, 2021
Prerequisite – Join (Inner, Left, Right and Full Joins) 1. Natural Join : Natural Join joins two tables based on same attribute name and datatypes. The resulting table will contain all the attributes of both the table but keep only one copy of each common column. 
Example: Consider the two tables given below: 
Student Table  
Marks Table  
Consider the given query 
SELECT * 
FROM Student NATURAL JOIN Marks;
Output: 
 
2. Inner Join : Inner Join joins two table on the basis of the column which is explicitly specified in the ON clause. The resulting table will contain all the attributes from both the tables including common column also. 
Example: Consider the above two tables and the query is given below: 
SELECT * 
FROM student S INNER JOIN Marks M ON S.Roll_No = M.Roll_No; 
Output : 
 
Difference between Natural JOIN and INNER JOIN in SQL : 
The Natural Joins are not supported in the SQL Server Management Studio also knowns as Microsoft SQL Server.
iamsamyak
DBMS-Join
DBMS
Difference Between
GATE CS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Change Contrast in OpenCV using C++?

Changing brightness and contrast are frequent editing effect in image processing.Here, we will learn how to change the contrast of images. Contrast controls the sharpness of the image. Higher the contrast the sharper the image, lower the contrast the smother the image.
Changing the contrast means increasing the weight of the pixels. More the contrast, sharper the image is. To change the contrast, multiply the pixel values with some constant. For example, if multiply all the pixel values of an image by 2, then the pixel's value will be doubled, and the image will look sharper.
The following program demonstrates how to change the contrast of an image in OpenCV.
#include<iostream>
#include<opencv2/highgui/highgui.hpp>
using namespace cv;
using namespace std;
int main() {
   Mat original;//Declaring a matrix to load the original image//
   Mat contrast;//Declaring a matrix to load the image after changing the brightness//
   namedWindow("Original");//Declaring window to show the original image//
   namedWindow("Contrast");//Declaring window for edited image//
   original = imread("mountain.jpg");//loading the image
   original.convertTo(contrast, -1, 2, 0);//changing contrast//
   imshow("Original", original);//showing original image//
   imshow("Contrast", contrast);//showing edited image//
   waitKey(0);//wait for keystroke//
   return(0);
}
Java Program to convert LocalDate to java.util.Date in UTC

Set the LocalDate to the current date −
LocalDate date = LocalDate.now();
Convert to java.util.Date in UTC −
Date.from(date.atStartOfDay().toInstant(ZoneOffset.UTC))
 Live Demo
import java.time.LocalDate;
import java.time.ZoneOffset;
import java.util.Date;
public class Demo {
   public static void main(String[] args) {
      LocalDate date = LocalDate.now();
      System.out.println("Date = "+date);
      System.out.println("Date (UTC) = "+Date.from(date.atStartOfDay().toInstant(ZoneOffset.UTC)));
   }
}
Date = 2019-04-19
Date (UTC) = Fri Apr 19 05:30:00 IST 2019
Recursive Program for Binary to Decimal in C++

We are given a string containing a binary number. The goal is to find the equivalent decimal number using the recursive method.
A binary number can be converted to decimal using following method-:
Traverse from LSB to MSB and multiply each with power of 2i Where 0<=i<=no. of digits and all previous results to it.
Input − binStr[] = "110010"
Output − Equivalent Decimal of given binary: 50
Explanation−If we convert 110010 to decimal then number will be:-
= 0*20 +1*21+0*22+0*23+1*24+1*25
= 0+2+0+0+16+32
= 50
Input − binStr[] = "0011"
Output − Equivalent Decimal of given binary: 3
Explanation − If we convert 110010 to decimal then number will be:-
= 1*20+1*21 +0*22 +0*23
= 1+2+0+0
= 3
In this approach we are using the recursive function bintoDecimal(strBin,length) which takes input string and its length and for each character convert it to decimal and multiply it with 2i . Add previous results to it.
Take the input string strBin[] containing a binary number.
Take the input string strBin[] containing a binary number.
Calculate its length using strlen(strBin).
Calculate its length using strlen(strBin).
Function bintoDecimal(strBin,length) takes input and returns the number calculated using a recursive approach.
Function bintoDecimal(strBin,length) takes input and returns the number calculated using a recursive approach.
If we are at last characterwhich is LSB, then return its decimal as it will be the same. (multiplied with 1 i.e 20 )
If we are at last characterwhich is LSB, then return its decimal as it will be the same. (multiplied with 1 i.e 20 )
Otherwise set temp=binary[i]-'0'. Its decimal value.
Otherwise set temp=binary[i]-'0'. Its decimal value.
Now multiply temp with 2len-i-1 using temp<<len-i-1.
Now multiply temp with 2len-i-1 using temp<<len-i-1.
Add the result of other digits to temp using temp=temp+bintoDecimal(binary,len,i+1).
Add the result of other digits to temp using temp=temp+bintoDecimal(binary,len,i+1).
At the end of recursion return temp.
At the end of recursion return temp.
Print the calculated decimal in main.
Print the calculated decimal in main.
#include<bits/stdc++.h>
using namespace std;
int bintoDecimal(char binary[],int len, int i=0){
   if (i == len-1)
   return (binary[i] - '0');

   int temp=binary[i]-'0';
   temp=temp<<len-i-1;
   temp=temp+bintoDecimal(binary,len,i+1);
   return (temp);
}
int main(){
   char strBin[] = "11010";
   int length=strlen(strBin);
   cout <<"Equivalent Decimal of given binary: "<<bintoDecimal(strBin,length) << endl;
   return 0;
}
If we run the above code it will generate the following Output
Equivalent Decimal of given binary: 26
RSA Cipher Encryption

In this chapter, we will focus on different implementation of RSA cipher encryption and the functions involved for the same. You can refer or include this python file for implementing RSA cipher algorithm implementation.
The modules included for the encryption algorithm are as follows −
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA512, SHA384, SHA256, SHA, MD5
from Crypto import Random
from base64 import b64encode, b64decode
hash = "SHA-256"
We have initialized the hash value as SHA-256 for better security purpose. We will use a function to generate new keys or a pair of public and private key using the following code.
def newkeys(keysize):
   random_generator = Random.new().read
   key = RSA.generate(keysize, random_generator)
   private, public = key, key.publickey()
   return public, private
def importKey(externKey):
   return RSA.importKey(externKey)

For encryption, the following function is used which follows the RSA algorithm −
def encrypt(message, pub_key):
   cipher = PKCS1_OAEP.new(pub_key)
   return cipher.encrypt(message)

Two parameters are mandatory: message and pub_key which refers to Public key. A public key is used for encryption and private key is used for decryption.
The complete program for encryption procedure is mentioned below −
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA512, SHA384, SHA256, SHA, MD5
from Crypto import Random
from base64 import b64encode, b64decode
hash = "SHA-256"

def newkeys(keysize):
   random_generator = Random.new().read
   key = RSA.generate(keysize, random_generator)
   private, public = key, key.publickey()
   return public, private

def importKey(externKey):
   return RSA.importKey(externKey)

def getpublickey(priv_key):
   return priv_key.publickey()

def encrypt(message, pub_key):
   cipher = PKCS1_OAEP.new(pub_key)
   return cipher.encrypt(message)

    10 Lectures 
     2 hours 

 Total Seminars

    10 Lectures 
     2 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
The __index metamethod in Lua Programming

Whenever we try to access a field that hasn’t been declared in a table in Lua, the answer we get is nil. While this is true, but the reason for it is that when such access happens, the interpreter triggers a search for an __index metamethod and if it doesn’t find any method named __index, then we get nil as an answer; else we will get whatever the value of the field is set in the __index metamethod.
We can explicitly put in the __index method in a table and provide it the named values that we want it to return instead of nil.
Let’s consider an example. We will create several tables describing windows. Each table will describe several parameters like size, height, width of the window; and we will also have a default constructor to create a table which is initially empty and all the fields are not-set.
 Live Demo
Window = {}
Window.prototype = {x=0, y=0, width=50, height=70, }
Window.mt = {}
function Window.new (o)
   setmetatable(o, Window.mt)
   return o
end
w = Window.new{x=10, y=20}
print(w.x)
print(w.width)
print(w.height)
In the above example, we are trying to print the value of three different fields of the Window, the x, the width, and the height. We know that when we create a new object using the constructor, we pass the value of x, so x will not be nil, but since we didn’t tell Lua about the values of the width and height of the window object w, we will get nil.
10
nil
nil
Now, we can explicitly create a __index method in the above code to tell the interpreter that we need it to return our value instead of nil, in case it doesn’t find the field in the table.
Consider the example shown below −
 Live Demo
Window = {}
Window.prototype = {x=0, y=0, width=50, height=70, }
Window.mt = {}
function Window.new (o)
   setmetatable(o, Window.mt)
   return o
end
Window.mt.__index = function (table, key)
   return Window.prototype[key]
end
w = Window.new{x=10, y=20}
print(w.x)
print(w.width)
print(w.height)
10
50
70
Hide and Unhide The Window in Tkinter – Python

04 Jul, 2021
Prerequisite: Tkinter
Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter is the fastest and easiest way to create GUI applications. Creating a GUI using Tkinter is an easy task.
In this article, we will discuss how to hide and unhide the window in Tkinter Using Python.
Functions used:
Toplevel() is used to launch the second window
Syntax:
toplevel = Toplevel(root, bg, fg, bd, height, width, font, ..)
deiconify() is used to show or unhide the window
Syntax:
deiconify()
withdraw() is used to hide the window
Syntax:
withdraw()
Approach:
Import module
Create a normal window
Add buttons to perform hide and unhide actions
Now create one more window
Execute code
Program:
Python3
# Import Libraryfrom tkinter import * # Create Objectroot = Tk() # Set titleroot.title("Main Window") # Set Geometryroot.geometry("200x200") # Open New Windowdef launch():    global second    second = Toplevel()    second.title("Child Window")    second.geometry("400x400") # Show the windowdef show():    second.deiconify() # Hide the windowdef hide():    second.withdraw() # Add ButtonsButton(root, text="launch Window", command=launch).pack(pady=10)Button(root, text="Show", command=show).pack(pady=10)Button(root, text="Hide", command=hide).pack(pady=10) # Execute Tkinterroot.mainloop()
Output:
simmytarika5
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
tcpdump Command in Linux with Examples

03 Jun, 2020
tcpdump is a packet sniffing and packet analyzing tool for a System Administrator to troubleshoot connectivity issues in Linux. It is used to capture, filter, and analyze network traffic such as TCP/IP packets going through your system. It is many times used as a security tool as well. It saves the captured information in a pcap file, these pcap files can then be opened through Wireshark or through the command tool itself.
Many Operating Systems have tcpdump command pre-installed but to install it, use the following commands.
For RedHat based linux OS
yum install tcpdump
For Ubuntu/Debian OS
apt install tcpdump
1. To capture the packets of current network interface
sudo tcpdump
This will capture the packets from the current interface of the network through which the system is connected to the internet.
2. To capture packets from a specific network interface
sudo tcpdump -i wlo1
This command will now capture the packets from wlo1 network interface.
3. To capture specific number of packets
sudo tcpdump -c 4 -i wlo1
This command will capture only 4 packets from the wlo1 interface.
4. To print captured packages in ASCII format
sudo tcpdump -A -i wlo1
This command will now print the captured packets from wlo1 to ASCII value.
5. To display all available interfaces
sudo tcpdump -D
This command will display all the interfaces that are available in the system.
6. To display packets in HEX and ASCII values
sudo tcpdump -XX -i wlo1
This command will now print the packages captured from the wlo1 interface in the HEX and ASCII values.
7. To save captured packets into a file
sudo tcpdump -w captured_packets.pcap -i wlo1
This command will now output all the captures packets in a file named as captured_packets.pcap.
8. To read captured packets from a file
sudo tcpdump -r captured_packets.pcap
This command will now read the captured packets from the captured_packets.pcap file.
9. To capture packets with ip address
sudo tcpdump -n -i wlo1
This command will now capture the packets with IP addresses.
10. To capture only TCP packets
sudo tcpdump -i wlo1 tcp
This command will now capture only TCP packets from wlo1.
linux-command
Linux-networking-commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ZIP command in Linux with examples
tar command in Linux with examples
curl command in Linux with Examples
SORT command in Linux/Unix with examples
Conditional Statements | Shell Script
TCP Server-Client implementation in C
Tail command in Linux with examples
Docker - COPY Instruction
scp command in Linux with Examples
UDP Server-Client implementation in C
Difference between Procedural and Non-Procedural language

28 May, 2019
Procedural Language:In procedural languages, the program code is written as a sequence of instructions. User has to specify “what to do” and also “how to do” (step by step procedure). These instructions are executed in the sequential order. These instructions are written to solve specific problems.
Examples of Procedural languages:
FORTRAN, COBOL, ALGOL, BASIC, C and Pascal.
Non-Procedural Language:In the non-procedural languages, the user has to specify only “what to do” and not “how to do”. It is also known as an applicative or functional language. It involves the development of the functions from other functions to construct more complex functions.
Examples of Non-Procedural languages:
SQL, PROLOG, LISP.
Difference between Procedural and Non-Procedural language:
Difference Between
Programming Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
time.Nanoseconds() Function in Golang With Examples

21 Apr, 2020
In Go language, time packages supplies functionality for determining as well as viewing time. The Nanoseconds() function in Go language is used to find the duration of time in form of an integer nanosecond count. Moreover, this function is defined under the time package. Here, you need to import the “time” package in order to use these functions.
Syntax:
func (d Duration) Nanoseconds() int64

Here, d is the duration of time.
Return Value: It returns the duration value as int64.
Example 1:
// Golang program to illustrate the usage of// Nanoseconds() function  // Including main packagepackage main  // Importing fmt and timeimport (    "fmt"    "time")  // Calling mainfunc main() {      // Defining duration     // of Nanoseconds method    nano, _ := time.ParseDuration("8s")      // Prints duration as int64    fmt.Printf("Only %d nanoseconds of"+     " task is remaining.", nano.Nanoseconds())}
Output:
Only 8000000000 nanoseconds of task is remaining.

Example 2:
// Golang program to illustrate the usage of// Nanoseconds() function  // Including main packagepackage main  // Importing fmt and timeimport (    "fmt"    "time")  // Calling mainfunc main() {      // Defining duration of Nanoseconds method    nano, _ := time.ParseDuration("56m7855s576567576ms")      // Prints duration as int64    fmt.Printf("Only %d nanoseconds of task"+       " is remaining.", nano.Nanoseconds())}
Output:
Only 587782576000000 nanoseconds of task is remaining.

GoLang-time
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Go
Golang Maps
How to Split a String in Golang?
Interfaces in Golang
Slices in Golang
Different Ways to Find the Type of Variable in Golang
How to Parse JSON in Golang?
How to Trim a String in Golang?
How to compare times in Golang?
Inheritance in GoLang
SQL | Remove Duplicates without Distinct

06 Apr, 2020
DISTINCT is useful in certain circumstances, but it has drawback that it can increase load on the query engine to perform the sort (since it needs to compare the result set to itself to remove duplicates)
Below are alternate solutions :
1. Remove Duplicates Using Row_Number.
WITH CTE (Col1, Col2, Col3, DuplicateCount)
AS
(
  SELECT Col1, Col2, Col3,
  ROW_NUMBER() OVER(PARTITION BY Col1, Col2,
       Col3 ORDER BY Col1) AS DuplicateCount
  FROM MyTable
) SELECT * from CTE Where DuplicateCount = 1
2.Remove Duplicates using self JoinYourTable
emp_name   emp_address  sex  matial_status  
uuuu       eee          m    s
iiii       iii          f    s
uuuu       eee          m    s
SELECT emp_name, emp_address, sex, marital_status
from YourTable a
WHERE NOT EXISTS (select 1 
         from YourTable b
         where b.emp_name = a.emp_name and
               b.emp_address = a.emp_address and
               b.sex = a.sex and
               b.create_date >= a.create_date)
3. Remove Duplicates using group ByThe idea is to group according to all columns to be selected in output. For example, if we wish to print unique values of “FirstName, LastName and MobileNo”, we can simply group by all three of these.
SELECT FirstName, LastName, MobileNo
FROM  CUSTOMER
GROUP BY FirstName, LastName, MobileNo;

Subha Saha
SQL-basics
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to check if a character in a string is a letter in Python?

You can use the isalpha() method from string class. It checks if a string consists only of alphabets. You can also use it to check if a character is an alphabet or not. For example, if you want to check if char at 5th index is letter or not,
>>> s = "Hello people"
>>> s[4].isalpha()
True
You can also check whole strings, if they are alphabetic or not. For example,
>>> s = "Hello people"
>>> s.isalpha()
False
>>> "Hello".isalpha()
True
Python Program to Split the array and add the first part to the end

26 Apr, 2020
There is a given an array and split it from a specified position, and move the first part of array add to the end.
Examples:
Input : arr[] = {12, 10, 5, 6, 52, 36}
            k = 2
Output : arr[] = {5, 6, 52, 36, 12, 10}
Explanation : Split from index 2 and first 
part {12, 10} add to the end .

Input : arr[] = {3, 1, 2}
           k = 1
Output : arr[] = {1, 2, 3}
Explanation : Split from index 1 and first
part add to the end.

# Python program to split array and move first# part to end.  def splitArr(arr, n, k):     for i in range(0, k):         x = arr[0]        for j in range(0, n-1):            arr[j] = arr[j + 1]                  arr[n-1] = x            # mainarr = [12, 10, 5, 6, 52, 36]n = len(arr)position = 2  splitArr(arr, n, position)  for i in range(0, n):     print(arr[i], end = ' ')  # Code Contributed by Mohit Gupta_OMG <(0_o)>   
5 6 52 36 12 10

Please refer complete article on Split the array and add the first part to the end for more details!Another Solution :
# Python program to split array and move first# part to end.  def splitArr(a, n, k):    b = a[:k]   return (a[k::]+b[::])            # mainarr = [12, 10, 5, 6, 52, 36]n = len(arr)position = 2arr = splitArr(arr, n, position)for i in range(0, n):     print(arr[i], end = ' ')
5 6 52 36 12 10

ishagup14
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python program to add two numbers
Python Program for factorial of a number
Python program to find second largest number in a list
Iterate over characters of a string in Python
Python | Convert set into a list
Appending to list in Python dictionary
Python | Convert a list into a tuple
Add a key:value pair to dictionary in Python
Python | Check if a variable is string
Python Program for Bubble Sort
Rename function in C/C++

The C library function int rename(const char *old_filename, const char *new_filename) causes the filename referred to by old_filename to be changed to new_filename
Following is the declaration for rename() function.
int rename(const char *old_filename, const char *new_filename)
The parameters are old_filename − This is the C string containing the name of the file to be renamed and/or moved, new_filename − This is the C string containing the new name for the file.
On success, zero is returned. On error, -1 is returned, and errno is set appropriately.
#include <stdio.h>
int main () {
   int ret;
   char oldname[] = "file.txt";
   char newname[] = "newfile.txt";
   ret = rename(oldname, newname);
   if(ret == 0) {
      printf("File renamed successfully");
   } else {
      printf("Error: unable to rename the file");
   }
   return(0);
}
Let us assume we have a text file file.txt, having some content. So, we are going to rename this file, using the above program. Let us compile and run the above program to produce the following message and the file will be renamed to newfile.txt file.
File renamed successfully
How to check if String is empty in Java?

The isEmpty() method of the String class returns true if the length of the current string is 0.
Live Demo
import java.lang.*;
public class StringDemo {
   public static void main(String[] args) {
      String str = "tutorialspoint";

      //prints length of string
      System.out.println("length of string = " + str.length());

      //checks if the string is empty or not
      System.out.println("is this string empty? = " + str.isEmpty());
   }
}
length of string = 14
is this string empty? = false
How to display column values as CSV in MySQL?

To display column values as CSV, use GROUP_CONCAT().
Let us first create a table −
mysql> create table DemoTable786 (
   StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   StudentName varchar(100)
)  
AUTO_INCREMENT=101;
Query OK, 0 rows affected (0.70 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable786(StudentName) values('Chris');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable786(StudentName) values('Robert');
Query OK, 1 row affected (0.24 sec)
mysql> insert into DemoTable786(StudentName) values('Mike');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable786(StudentName) values('Sam');
Query OK, 1 row affected (0.12 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable786;
This will produce the following output -
+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
| 101       | Chris       |
| 102       | Robert      |
| 103       | Mike        |
| 104       | Sam         |
+-----------+-------------+
4 rows in set (0.00 sec)
Following is the query to select columns as CSV in MySQL −
mysql> select group_concat(StudentId),group_concat(StudentName) from DemoTable786;
This will produce the following output -
+-------------------------+---------------------------+
| group_concat(StudentId) | group_concat(StudentName) |
+-------------------------+---------------------------+
| 101,102,103,104         | Chris,Robert,Mike,Sam     |
+-------------------------+---------------------------+
1 row in set (0.00 sec)
Sqoop - Import All Tables

This chapter describes how to import all the tables from the RDBMS database server to the HDFS. Each table data is stored in a separate directory and the directory name is same as the table name.
The following syntax is used to import all tables.
$ sqoop import-all-tables (generic-args) (import-args) 
$ sqoop-import-all-tables (generic-args) (import-args)
Let us take an example of importing all tables from the userdb database. The list of tables that the database userdb contains is as follows.
 +--------------------+
 |      Tables        |
 +--------------------+
 |      emp           |
 |      emp_add       |
 |      emp_contact   |
 +--------------------+

The following command is used to import all the tables from the userdb database.
$ sqoop import-all-tables \
--connect jdbc:mysql://localhost/userdb \
--username root
Note − If you are using the import-all-tables, it is mandatory that every table in that database must have a primary key field.
The following command is used to verify all the table data to the userdb database in HDFS.
$ $HADOOP_HOME/bin/hadoop fs -ls
It will show you the list of table names in userdb database as directories.
drwxr-xr-x - hadoop supergroup 0 2014-12-22 22:50 _sqoop
drwxr-xr-x - hadoop supergroup 0 2014-12-23 01:46 emp
drwxr-xr-x - hadoop supergroup 0 2014-12-23 01:50 emp_add
drwxr-xr-x - hadoop supergroup 0 2014-12-23 01:52 emp_contact


    50 Lectures 
     4 hours 

 Navdeep Kaur
 Print
 Add Notes
 Bookmark this page
Finding a specific item in subdocument with MongoDB?

To get a specific item in a sudocument, use the dot(.) notation. Let us create a collection with documents −
> db.demo81.insertOne({"StudentDetails":[{"StudentName":"Carol","StudentSubject":"Java"},{ "StudentName" : "David", "StudentSubject" : "MongoDB" }]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2bf6ec71bf0181ecc4229d")
}
> db.demo81.insertOne({"StudentDetails":[{"StudentName":"Mike","StudentSubject":"Python"},{ "StudentName" : "David", "StudentSubject" : "C" }]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2bf70471bf0181ecc4229e")
}
> db.demo81.insertOne({"StudentDetails":[{"StudentName":"Jace","StudentSubject":"C++"},{    "StudentName" : "John", "StudentSubject" : "MySQL" }]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2bf72071bf0181ecc4229f")
}
Display all documents from a collection with the help of find() method −
> db.demo81.find();
This will produce the following output −
{
   "_id" : ObjectId("5e2bf6ec71bf0181ecc4229d"), "StudentDetails" : [
      { "StudentName" : "Carol", "StudentSubject" : "Java" },
      {"StudentName" : "David", "StudentSubject" : "MongoDB" }
   ]
}
{
   "_id" : ObjectId("5e2bf70471bf0181ecc4229e"), "StudentDetails" : [
      { "StudentName" : "Mike", "StudentSubject" : "Python" },
      { "StudentName" : "David", "StudentSubject" : "C" }
   ]
}
{
   "_id" : ObjectId("5e2bf72071bf0181ecc4229f"), "StudentDetails" : [
      { "StudentName" : "Jace", "StudentSubject" : "C++" },
      { "StudentName" : "John", "StudentSubject" : "MySQL" }
   ] 
}
Following is the query to find item in a subdocument with MongoDB −
> db.demo81.find({"StudentDetails.StudentSubject":"MongoDB"});
This will produce the following output −
{ "_id" : ObjectId("5e2bf6ec71bf0181ecc4229d"), "StudentDetails" : [ { "StudentName" : "Carol", "StudentSubject" : "Java" }, { "StudentName" : "David", "StudentSubject" : "MongoDB" } ] }
How to check if a div is visible using jQuery?

You can use .is(‘:visible’) selects all elements that are visible.
<html>
<head>
<title>divvisible</title>
   <script src="../../Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
   <script type="text/javascript">
      $(document).ready(function () {
         $("button").click(function () {
            var dim = $('#div1').is(":visible");
            if (dim == false) {
               $('#div1').css({ "display": "block", "color": "red" });
            }
         });
      });
   </script>
</head>
<body>
<div id="div1" style="display:none">
<p>Div is visible</p>
</div>
   <button type="button" id="btn" onclick="click()">Click Here</button><br />
</body>
</html>
Python - Extract range of Consecutive Similar elements ranges from string list - GeeksforGeeks

01 Oct, 2020
Given a list, extract range of consecutive similar elements.
Input : test_list = [2, 3, 3, 3, 8, 8] Output : [(2, 0, 0), (3, 1, 3), (8, 4, 5)] Explanation : 2 occurs from 0th to 0th index, 3 from 1st to 3rd index.
Input : test_list = [3, 3, 3] Output : [(3, 0, 3)] Explanation : 3 from 0th to 3rd index. 
Approach: Using loop
This is a brute way to tackle this problem. In this, we loop for each element and get a similar element range. These are traced and appended in list accordingly with elements.
Python3
# Python3 code to demonstrate working of # Consecutive Similar elements ranges# Using loop  # initializing listtest_list = [2, 3, 3, 3, 8, 8, 6, 7, 7]  # printing original listprint("The original list is : " + str(test_list))  res = []idx = 0while idx < (len(test_list)):    strt_pos = idx    val = test_list[idx]          # getting last pos.    while (idx < len(test_list) and test_list[idx] == val):         idx += 1    end_pos = idx - 1          # appending in format [ele, strt_pos, end_pos]    res.append((val, strt_pos, end_pos))  # printing result print("Elements with range : " + str(res))
Output:
The original list is : [2, 3, 3, 3, 8, 8, 6, 7, 7]Elements with range : [(2, 0, 0), (3, 1, 3), (8, 4, 5), (6, 6, 6), (7, 7, 8)]
Python list-programs
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary