code-rag-bench/online-tutorials huggingface dataset:
Extract IP address from file using Python - GeeksforGeeks

10 Feb, 2022
Let us see how to extract IP addresses from a file using Python. 
Algorithm :  
Import the re module for regular expression.
Open the file using the open() function.
Read all the lines in the file and store them in a list.
Declare the pattern for IP addresses. The regex pattern is :  
r'(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'
For every element of the list search for the pattern using the search() function, store the IP addresses in a list.
Display the list containing the IP addresses.
The file to be processed is test.txt :  
test.txt
 
python3
# importing the moduleimport re  # opening and reading the file with open('C:/Users/user/Desktop/New Text Document.txt') as fh:   fstring = fh.readlines()  # declaring the regex pattern for IP addressespattern = re.compile(r'(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})')  # initializing the list objectlst=[]  # extracting the IP addressesfor line in fstring:   lst.append(pattern.search(line)[0])  # displaying the extracted IP addressesprint(lst)
Output :
The above Python program displays any kind of IP addresses present in the file. We can also display the valid IP addresses.
Rules for a valid IP Address : 
The numbers should be in a range of 0-255
It should consist of 4 cells separated by ‘.’
The regular expression for valid IP addresses is : 
((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)
 
Explanation of Regular Expression used for valid IP:
Since we cannot use 0-255 range in regular expression we divide the same in 3 groups:
25[0-5] – represents numbers from 250 to 255
2[0-4][0-9] – represents numbers from 200 to 249
[01]?[0-9][0-9]?- represents numbers from 0 to 199
The file to be processed is test2.txt :  
test2.txt 
 
python3
# importing the moduleimport re  # opening and reading the filewith open('test2.txt') as fh:  string = fh.readlines()    # declaring the regex pattern for IP addresses pattern =re.compile('''((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)''')  # initializing the list objectsvalid =[]invalid=[]  # extracting the IP addressesfor line in string:    line = line.rstrip()    result = pattern.search(line)      # valid IP addresses    if result:      valid.append(line)      # invalid IP addresses      else:      invalid.append(line)  # displaying the IP addressesprint("Valid IPs")print(valid)print("Invalid IPs")print(invalid)
Output :
prudvikristipati
gabaa406
saurabh1990aror
reenadevi98412200
Python Regex-programs
python-regex
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
How to set the width and height of an image using HTML ? - GeeksforGeeks

14 Sep, 2020
The height and width of an image can be set using height and width attribute. The height and width can be set in terms of pixels.
The <img> height attribute is used to set the height of the image in pixels. The <img> width attribute is used to set the width of the image in pixels.
Example 1: In this example, we will set the width and height of an image.
HTML
<!DOCTYPE html> <html>   <head>     <title>         How to specify the width and         height of an image using HTML?    </title> </head>   <body>     <h1 style="color:green;">GeeksforGeeks</h1>       <h2>        How to specify the width and         height of an image using HTML?    </h2>       <img src= "https://media.geeksforgeeks.org/wp-content/uploads/20190506164011/logo3.png"        alt="GeeksforGeeks logo" width="300" height="300"> </body>   </html>
Output:
Example 2: In this example, we will not assign width and height value so the image will display with its original height and width.
HTML
<!DOCTYPE html> <html>   <head>     <title>         How to specify the width and         height of an image using HTML?    </title> </head>   <body>     <h1 style="color:green;">GeeksforGeeks</h1>       <h2>        How to specify the width and         height of an image using HTML?    </h2>       <img src= "https://media.geeksforgeeks.org/wp-content/uploads/20190506164011/logo3.png"        alt="GeeksforGeeks logo" width="" height=""> </body>   </html>
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
CSS-Misc
HTML-Misc
CSS
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to apply style to parent if it has child with CSS?
Types of CSS (Cascading Style Sheet)
How to position a div at the bottom of its container using CSS?
Design a web page using HTML and CSS
How to set space between the flexbox ?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
REST API (Introduction)
How to Insert Form Data into Database using PHP ?
Types of CSS (Cascading Style Sheet)
map vs unordered_map in C++ - GeeksforGeeks

11 May, 2022
Pre-requisite : std::map, std::unordered_mapWhen it comes to efficiency, there is a huge difference between maps and unordered maps. We must know the internal working of both to decide which one is to be used.
Difference : 
                  | map             | unordered_map
---------------------------------------------------------
Ordering        | increasing  order   | no ordering
                | (by default)        |

Implementation  | Self balancing BST  | Hash Table
                | like Red-Black Tree |  

search time     | log(n)              | O(1) -> Average 
                |                     | O(n) -> Worst Case

Insertion time  | log(n) + Rebalance  | Same as search
                      
Deletion time   | log(n) + Rebalance  | Same as search


Use std::map when 
You need ordered data.
You would have to print/access the data (in sorted order).
You need predecessor/successor of elements.
See advantages of BST over Hash Table for more cases.
CPP
// CPP program to demonstrate use of std::map#include <bits/stdc++.h>  int main(){    // Ordered map    std::map<int, int> order;      // Mapping values to keys    order[5] = 10;    order[3] = 5;    order[20] = 100;    order[1] = 1;      // Iterating the map and     // printing ordered values    for (auto i = order.begin(); i          != order.end(); i++) {        std::cout << i->first                   << " : "                   << i->second << '\n';    }}
1 : 1
3 : 5
5 : 10
20 : 100


Use std::unordered_map when 
You need to keep count of some data (Example – strings) and no ordering is required.
You need single element access i.e. no traversal.
CPP
// CPP program to demonstrate use of// std::unordered_map#include <bits/stdc++.h>  int main(){    // Unordered map    std::unordered_map<int, int> order;      // Mapping values to keys    order[5] = 10;    order[3] = 5;    order[20] = 100;    order[1] = 1;      // Iterating the map and     // printing unordered values    for (auto i = order.begin();          i != order.end(); i++)    {        std::cout << i->first                   << " : "                   << i->second << '\n';    }}
1 : 1
20 : 100
5 : 10
3 : 5


shubhamgupta2956
cpp-map
cpp-unordered_map
STL
C++
Difference Between
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Inheritance in C++
C++ Classes and Objects
Bitwise Operators in C/C++
Virtual Function in C++
Constructors in C++
Difference between BFS and DFS
Class method vs Static method in Python
Differences between TCP and UDP
Difference between var, let and const keywords in JavaScript
Differences between IPv4 and IPv6
PyQt5 Label - Setting color to shadow - GeeksforGeeks

10 May, 2020
In this article we will see how we can set shadow color to the label, when we create a shadow to the label it is by default of black color although we can its color.
In order to set color to the shadow of label with the help of setColor method
Syntax : shadow.setColor(color_object)Here shadow is the QGraphicsDropShadowEffect object
Argument : It takes color object as argument example Qt.green
Return : None
Below is the implementation
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys    class Window(QMainWindow):      def __init__(self):        super().__init__()          # setting background color of window        # self.setStyleSheet("background-color : black;")          # setting title        self.setWindowTitle("Python ")          # setting geometry        self.setGeometry(100, 100, 600, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()      # method for widgets    def UiComponents(self):          # creating label        label = QLabel("Label", self)          # setting alignment        label.setAlignment(Qt.AlignCenter)          # setting geometry to the label        label.setGeometry(200, 100, 150, 60)          # setting border        label.setStyleSheet("border : 8px solid black")          # creating a QGraphicsDropShadowEffect object        shadow = QGraphicsDropShadowEffect()          # setting blur radius        shadow.setBlurRadius(20)          # setting border color        shadow.setColor(Qt.green)          # adding shadow to the label        label.setGraphicsEffect(shadow)              # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python PyQt5-Label
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
Python - Wildcard Substring search - GeeksforGeeks

22 Apr, 2020
Sometimes, while working with Python Strings, we have problem in which, we need to search for substring, but have some of characters missing and we need to find the match. This can have application in many domains. Lets discuss certain ways in which this task can be performed.
Method #1 : Using re.search()This is one of the way in which this task can be performed. In this, we feed the regex compile with the substring and search for it using main string in search().
# Python3 code to demonstrate working of # Wildcard Substring search# Using re.search()import re      # initializing stringtest_str = 'geeksforgeeks is best for geeks'  # printing original stringprint("The original string is : " + str(test_str))  # initializing Substringsub_str = '..st'  # Wildcard Substring search# Using re.search()temp = re.compile(sub_str) res = temp.search(test_str)  # printing result print("The substring match is : " + str(res.group(0))) 
The original string is : geeksforgeeks is best for geeks                                                                
The substring match is : best     

 
Method #2 : Using re.finditer()This is yet another way to solve this problem. In this, we can also extract the position of match if required.
# Python3 code to demonstrate working of # Wildcard Substring search# Using re.finditer()import re      # initializing stringtest_str = 'geeksforgeeks is best for geeks'  # printing original stringprint("The original string is : " + str(test_str))  # initializing Substringsub_str = '..st'  # Wildcard Substring search# Using re.finditer()temp = re.compile(sub_str) res = temp.search(test_str)  # printing result print("The substring match is : " + str(res.group(0))) 
The original string is : geeksforgeeks is best for geeks                                                                
The substring match is : best     

Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
Mean and Median of a matrix in C++

In this problem, we are given a 2D array of size n*n. Our task is to create a program that will print the mean and median of the matrix in C++.
Mean is the average of the date set. In a matrix mean is the average of all elements of the matrix.
Mean = (sum of all elements of the matrix)/(number of elements of the matrix)
Median is the middlemost element of the sorted data set. For this, we will have to sort the elements of the matrix.
Median is calculated as,
If n is odd, median = matrix[n/2][n/2]
If n is even, median = ((matrix[(n-2)/2][n-1])+(matrix[n/2][0]))/2
Program to illustrate the working of our solution
 Live Demo
#include <iostream>
using namespace std;
const int N = 4;
int calcMean(int Matrix[][N]) {
   int sum = 0;
   for (int i=0; i<N; i++)
      for (int j=0; j<N; j++)
         sum += Matrix[i][j];
      return (int)sum/(N*N);
   }
   int calcMedian(int Matrix[][N]) {
      if (N % 2 != 0)
         return Matrix[N/2][N/2];
      if (N%2 == 0)
         return (Matrix[(N-2)/2][N-1] + Matrix[N/2][0])/2;
}
int main() {
   int Matrix[N][N]= {
      {5, 10, 15, 20},
      {25, 30, 35, 40},
      {45, 50, 55, 60},
      {65, 70, 75, 80}};
   cout<<"Mean of the matrix: "<<calcMean(Matrix)<<endl;
   cout<<"Median of the matrix : "<<calcMedian(Matrix)<<endl;
   return 0;
}
Mean of the matrix: 42
Median of the matrix : 42
Go - Loops

There may be a situation, when you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on.
Programming languages provide various control structures that allow for more complicated execution paths.
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 −
Go programming language provides the following types of loop to handle looping requirements.
It executes a sequence of statements multiple times and abbreviates the code that manages the loop variable.
These are one or multiple loops inside any for loop.
Loop control statements change an execution from its normal sequence. When an execution leaves its scope, all automatic objects that were created in that scope are destroyed.
Go supports the following control statements −
It terminates a for loop or switch statement and transfers execution to the statement immediately following the for loop or switch.
It causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.
It transfers control to the labeled statement.
A loop becomes an infinite loop if its condition never becomes false. The for loop is traditionally used for this purpose. Since none of the three expressions that form the for loop are required, you can make an endless loop by leaving the conditional expression empty or by passing true to it.
package main

import "fmt"

func main() {
   for true  {
       fmt.Printf("This loop will run forever.\n");
   }
}
When the conditional expression is absent, it is assumed to be true. You may have an initialization and increment expression, but C programmers more commonly use the for(;;) construct to signify an infinite loop.
Note − You can terminate an infinite loop by pressing Ctrl + C keys.

    64 Lectures 
     6.5 hours 

 Ridhi Arora

    20 Lectures 
     2.5 hours 

 Asif Hussain

    22 Lectures 
     4 hours 

 Dilip Padmanabhan

    48 Lectures 
     6 hours 

 Arnab Chakraborty

    7 Lectures 
     1 hours 

 Aditya Kulkarni

    44 Lectures 
     3 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
How to add the JDBC MySQL driver to an Eclipse project?

To add the JDBC MySQL driver to an Eclipse project, you need to follow the below steps.
The first step is as follows:
Step1: Create a dynamic web project with some name in Eclipse.
Step2: After pressing the Dynamic Web Project, a new window will open. Now give the project name. The screenshot is as follows:
After clicking the Finish button, you will get a project structure. The screenshot is as follows:
Therefore, I have a project name JDBCJarFiles and in WEB-INF, there is a lib folder. You can add JDBC jar files in lib folder. Now, paste the jar files here. The screenshot is as follows:
Now create a Java class to test if it connects to the database or not. First create a class and give class name and click the finish button. The following is the screenshot:
After clicking the finish button, you will get a window like this.
After that write the following code to test the Database connection. Here, we have database name ‘test’, username=’root’ and password is ‘123456’.
The Java code is as follows:
import java.sql.Connection;
import java.sql.DriverManager;
public class JdbcConnectionDemo {
   public static void main(String[] args) {
      String JdbcURL = "jdbc:mysql://localhost:3306/test?useSSL=false";
      String Username = "root";
      String password = "123456";
      Connection con = null;
      try {
         System.out.println("Connecting to database..............."+JdbcURL);
         con=DriverManager.getConnection(JdbcURL, Username, password);
         System.out.println("Connection is successful!!!!!!");
      }
      catch(Exception e) {
         e.printStackTrace();
      }
   }
}
The screenshot of code is as follows:
The following is the output:
Connecting to database...............jdbc:mysql://localhost:3306/test?useSSL=false
Connection is successful!!!!!!
The snapshot of sample output:
8051 Program to Add two 8 Bit numbers

Intel 8051 is an 8-bit microcontroller. It has many powerful instructions and IO accessing techniques. In this section, we will see one of the simplest program using 8051.
Here we will add two8-bit numbers using this microcontroller. The register A(Accumulator) is used as one operand in the operations. There are seven registers R0 – R7 in different register banks. We can use any of them as the second operand.
We are taking two number 5FH and D8H at location 20H and 21H, After adding them, the result will be stored at location 30H and 31H.  
MOVR0,#20H;set source address 20H to R0
MOVR1,#30H;set destination address 30H to R1
MOVA,@R0; take the value from source to register A
MOVR5,A; Move the value from A to R5
MOVR4,#00H; Clear register R4 to store carry
INCR0; Point to the next location
MOVA,@R0; take the value from source to register A
ADDA,R5;Add R5 with A and store to register A
JNC SAVE
INCR4; Increment R4 to get carry
MOVB,R4;Get carry to register B
MOV@R1,B; Store the carry first
INCR1; Increase R1 to point to the next address
SAVE:   MOV@R1,A;Store the result  
HALT:   SJMP HALT ;Stop the program
So by adding 5FH + D8H, the result will be 137H. The 01H will be stored at 30H, and 37 is stored at 31H.
H2 Database - Show

SHOW is a command used to display the list of Schemas, Tables, or Columns of the table.
Following is the generic syntax of the SHOW command.
SHOW { SCHEMAS | TABLES [ FROM schemaName ] | 
COLUMNS FROM tableName [ FROM schemaName ] } 

The following command can be used to get the list of tables in the current database.
SHOW TABLES; 
The above command produces the following output.

    14 Lectures 
     1 hours 

 Mahesh Kumar

    100 Lectures 
     9.5 hours 

 Hari Om Singh

    108 Lectures 
     8 hours 

 Pavan Lalwani

    10 Lectures 
     1 hours 

 Deepti Trivedi

    20 Lectures 
     2 hours 

 Deepti Trivedi

    14 Lectures 
     1 hours 

 Deepti Trivedi
 Print
 Add Notes
 Bookmark this page
Dart Programming - Switch Case Statement

The switch statement evaluates an expression, matches the expression’s value to a case clause and executes the statements associated with that case.
Following is the syntax.
switch(variable_expression) { 
   case constant_expr1: { 
      // statements; 
   } 
   break; 
  
   case constant_expr2: { 
      //statements; 
   } 
   break; 
      
   default: { 
      //statements;  
   }
   break; 
} 

The value of the variable_expression is tested against all cases in the switch. If the variable matches one of the cases, the corresponding code block is executed. If no case expression matches the value of the variable_expression, the code within the default block is associated.
The following rules apply to a switch statement −
There can be any number of case statements within a switch.
The case statements can include only constants. It cannot be a variable or an expression.
The data type of the variable_expression and the constant expression must match.
Unless you put a break after each block of code, the execution flows into the next block.
The case expression must be unique.
The default block is optional.
The flow diagram of the switch...case statement is as follows −
void main() { 
   var grade = "A"; 
   switch(grade) { 
      case "A": {  print("Excellent"); } 
      break; 
     
      case "B": {  print("Good"); } 
      break; 
     
      case "C": {  print("Fair"); } 
      break; 
     
      case "D": {  print("Poor"); } 
      break; 
     
      default: { print("Invalid choice"); } 
      break; 
   } 
}  
The example verifies the value of the variable grade against the set of constants (A, B, C, D, and E) and executes the corresponding blocks. If the value in the variable doesn’t match any of the constants mentioned above, the default block will be executed.
The following output is displayed on successful execution on the above code.
Excellent


    44 Lectures 
     4.5 hours 

 Sriyank Siddhartha

    34 Lectures 
     4 hours 

 Sriyank Siddhartha

    69 Lectures 
     4 hours 

 Frahaan Hussain

    117 Lectures 
     10 hours 

 Frahaan Hussain

    22 Lectures 
     1.5 hours 

 Pranjal Srivastava

    34 Lectures 
     3 hours 

 Pranjal Srivastava
 Print
 Add Notes
 Bookmark this page
Get index of given element in array field in MongoDB?

You can use $indexOfArray operator for this. Let us create a collection with documents −
>db.getIndexDemo.insertOne({"InstructorName":"Chris","InstructorSubject":["MongoDB","MySQL","Java","C++"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cbd5251de8cc557214c0df8")
}
Display all documents from a collection with the help of find() method −
> db.getIndexDemo.find().pretty();
This will produce the following output −
{
   "_id" : ObjectId("5cbd5251de8cc557214c0df8"),
   "InstructorName" : "Chris",
   "InstructorSubject" : [
      "MongoDB",
      "MySQL",
      "Java",
      "C++"
   ]
}
Following is the query to get index of given element in an array field in MongoDB −
> db.getIndexDemo.aggregate( [ { "$project": { "matchedIndex": { "$indexOfArray": [ "$InstructorSubject", "MongoDB" ] } } } ] );
This will produce the following output −
{ "_id" : ObjectId("5cbd5251de8cc557214c0df8"), "matchedIndex" : 0 }
Following is the query to get index of another element in array field in MongoDB −
> db.getIndexDemo.aggregate( [ { "$project": { "matchedIndex": { "$indexOfArray": [ "$InstructorSubject", "C++" ] } } } ] );
This will produce the following output −
{ "_id" : ObjectId("5cbd5251de8cc557214c0df8"), "matchedIndex" : 3 }
NOTE -
As we know, in most of the languages array index starts from 0,
the first element of the array will have 0 index and last element
will have (n-1) index, where n is the number of elements of the array.
How to control recursion in Get-ChildItem in PowerShell?

When –Depth parameter is used along with Get-ChildItem, it controls the recursion of displaying the subfolders and their contents. For example, if –Depth parameter is set to 1 then it will display only the content of the parent folder and immediate subfolders but not the subfolders of the subfolders.
When you specify –Depth parameter, no need to add –Recursion parameter. It will automatically set the depth level.
Get-ChildItem D:\Temp\ -Depth 1
PS C:\WINDOWS\system32> Get-ChildItem D:\Temp\ -Depth 1
    Directory: D:\Temp
Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-----       13-12-2019     09:52                GPO_backup
d-----       24-11-2018     11:31                LGPO
-a----       07-05-2018     23:00            301 cars.xml
-a----       29-12-2017     15:16           4526 healthcheck.html
-a----       29-12-2017     15:16           4526 healthcheck1.html
-a----       08-12-2017     10:24          48362 servicereport.html
-a----       08-12-2017     10:24          48362 servicereport1.html
-a----       08-12-2017     10:16            393 style.css
-a----       08-12-2017     11:29           7974 Test.xlsx
-a----       25-10-2017     08:13            104 testcsv.csv
-a----       12-12-2017     23:04           1034 testhtmoutput.html
    Directory: D:\Temp\GPO_backup
Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-----       24-11-2018     11:34                {C9C3DB4C-2E51-4201-B3C3-7C0F1ACECBE9}
    Directory: D:\Temp\LGPO
Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----       01-06-2017     03:22         410088 LGPO.exe
-a----       01-06-2017     02:25         638115 LGPO.pdf
In the above example, -Depth value is set to 1, so it displays only its subfolders (D:\Temp\LGPO, D:\Temp\GPO_Backup) and their contents.
When you set the –Depth value to 2, the output will be.
Directory: D:\Temp\GPO_backup
Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-----       24-11-2018     11:34                {C9C3DB4C-2E51-4201-B3C3-7C0F1ACECBE9}
    Directory: D:\Temp\GPO_backup\{C9C3DB4C-2E51-4201-B3C3-7C0F1ACECBE9}
Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-----       24-11-2018     11:34                DomainSysvol
-a----       24-11-2018     11:34           6215 Backup.xml
-a----       24-11-2018     11:34            602 Bkupinfo.xml
    Directory: D:\Temp\LGPO
Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----       01-06-2017     03:22         410088 LGPO.exe
-a----       01-06-2017     02:25         638115 LGPO.pdf
As you can see in above example, additional level (D:\Temp\GPO_backup\{C9C3DB4C-2E51-4201-B3C3-7C0F1ACECBE9}) has been added.
How to enable and disable submit button using jQuery?

To enable and disable submit button, use the jQuery prop() method. You can try to run the following code to enable and disable submit button using jQuery −
Live Demo
<!DOCTYPE html>
<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script>
    $(document).ready(function() {
      $('#register').click(function() {
        $(this).prop('disabled',true);
        $("#content").show();

        setTimeout(function(){
          $('#register').prop('disabled', false);
        },3000);

     });
   });
</script>
</head>
<body>

  <div id="btnregister" name="registerbtn">
    <input type="submit" value="Click me!" id="register" name="register"/>
  </div>

  <div style="display:none;" id="content">
    The above button disables for 3 seconds, on clicking.                
  </div>

</body>
</html>
Fix ERROR 1064 (42000) while creating a database in MySQL?

The ERROR 1064 (42000) mainly occurs when the syntax isn’t set correctly i.e. error in applying the backtick symbol or while creating a database without them can also create an error, if you will use hyphen in the name, for example, Demo-Table will result in ERROR 1064 (42000).
To remove the error, you need to use backtick around the database name properly or use
nothing. Following is the syntax wherein we haven’t used the backtick. This works correctly −
create database yourDatabaseName;
Since adding hyhen to the database name will result in an error. Let us implement it while creating the database name −
mysql> create database customer-tracker;
This will produce the following error since we used hyphen in the database name, which isn’t acceptable −
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use near '-tracker' at line 1
Still, we can fix the hyphen in the database name by surrounding the name with backtick symbol −
mysql> create database `customer-tracker`;
This will produce the following output −
Query OK, 1 row affected (0.21 sec)
Now database is created successfully.
C# Methods

A method is a block of code which only runs when it is called.
You can pass data, known as parameters, into a method.
Methods are used to perform certain actions, and they are also known as functions.
Why use methods? To reuse code: define the code once, and use 
it many times.
A method is defined 
with the name of the method, followed by parentheses (). C# 
provides some pre-defined methods, which you already are familiar with, such as Main(), but you can also create your own methods to perform certain actions:
Create a method inside the Program class:
class Program
{
  static void MyMethod() 
  {
    // code to be executed
  }
} 

MyMethod() is the name of the method
static means that the method belongs to the Program class and not an object of the Program class. You will learn more about objects and how to access methods through objects later in this tutorial.
void means that this method does not have a 
return value. You will learn more about return values later in this chapter
Note: In C#, it is good practice to start with an uppercase letter when naming methods, as it makes the code easier to read.
To call (execute) a method, write the method's name followed by two 
parentheses () and a semicolon;
In the following example, MyMethod() is used to print a text (the action), when it is called:
Inside Main(), call the 
myMethod() method:
static void MyMethod() 
{
  Console.WriteLine("I just got executed!");
}

static void Main(string[] args)
{
  MyMethod();
}

// Outputs "I just got executed!"
 


Try it Yourself »

A method can be called multiple times:
static void MyMethod() 
{
  Console.WriteLine("I just got executed!");
}

static void Main(string[] args)
{
  MyMethod();
  MyMethod();
  MyMethod();
}

// I just got executed!
// I just got executed!
// I just got executed!
 
 
 


Try it Yourself »

Create a method named MyMethod and call it inside Main().
static void () 
{
  Console.WriteLine("I just got executed!");
}

static void Main(string[] args)
{

}

Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
Java Examples - Print Collection

How to print a collection ?
Following example how to print a collection by using tMap.keySet(), tMap.values() and tMap.firstKey() methods of Java Util class.
import java.util.*;

public class TreeExample{
   public static void main(String[] args) {
      System.out.println("Tree Map Example!\n");
      TreeMap <Integer, String>tMap = new TreeMap<Integer, String>();
      tMap.put(1, "Sunday");
      tMap.put(2, "Monday");
      tMap.put(3, "Tuesday");
      tMap.put(4, "Wednesday");
      tMap.put(5, "Thursday");
      tMap.put(6, "Friday");
      tMap.put(7, "Saturday");
      System.out.println("Keys of tree map: " + tMap.keySet());
      System.out.println("Values of tree map: " + tMap.values());
      System.out.println("Key: 5 value: " + tMap.get(5)+ "\n");
      System.out.println(
         "First key: " + tMap.firstKey() + " Value: " + tMap.get(tMap.firstKey()) + "\n");
      System.out.println(
         "Last key: " + tMap.lastKey() + " Value: "+ tMap.get(tMap.lastKey()) + "\n");
      System.out.println("Removing first data: " + tMap.remove(tMap.firstKey()));
      System.out.println("Now the tree map Keys: " + tMap.keySet());
      System.out.println("Now the tree map contain: " + tMap.values() + "\n");
      System.out.println("Removing last data: " + tMap.remove(tMap.lastKey()));
      System.out.println("Now the tree map Keys: " + tMap.keySet());
      System.out.println("Now the tree map contain: " + tMap.values());
   }
}
The above code sample will produce the following result.
C:\collection>javac TreeExample.java

C:\collection>java TreeExample
Tree Map Example!

Keys of tree map: [1, 2, 3, 4, 5, 6, 7]
Values of tree map: [Sunday, Monday, Tuesday, Wednesday, 
Thursday, Friday, Saturday]
Key: 5 value: Thursday

First key: 1 Value: Sunday

Last key: 7 Value: Saturday

Removing first data: Sunday
Now the tree map Keys: [2, 3, 4, 5, 6, 7]
Now the tree map contain: [Monday, Tuesday, Wednesday,
Thursday, Friday, Saturday]

Removing last data: Saturday
Now the tree map Keys: [2, 3, 4, 5, 6]
Now the tree map contain: [Monday, Tuesday, Wednesday,
Thursday, Friday]

C:\collection>

 Print
 Add Notes
 Bookmark this page
PyQt5 QSpinBox – Setting value

03 May, 2020
In this article we will see how we can set value to the spin box. By default its value is 0 although user can change it any time. In order to change its value programmatically we will use setValue method
Syntax : spin.setValue(n)
Argument : It takes integer as argument
Return : None
Below is the implementation
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys    class Window(QMainWindow):      def __init__(self):        super().__init__()          # setting title        self.setWindowTitle("Python ")          # setting geometry        self.setGeometry(100, 100, 600, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()      # method for widgets    def UiComponents(self):          # creating spin box        self.spin = QSpinBox(self)          # setting geometry to spin box        self.spin.setGeometry(100, 100, 100, 40)          # setting value to the spin box        self.spin.setValue(20)    # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  window.show()  # start the appsys.exit(App.exec())
Output :
Python PyQt-SpinBox
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Java Connection setTransactionIsolation() method with example

In a database system where more than one transaction is being executed simultaneously and in parallel, the property of isolation states that all the transactions will be carried out and executed as if it is the only transaction in the system. No transaction will affect the existence of any other transaction.
JDBC provides support 5 transaction isolation levels through Connection interface.
TRANSACTION_NONE: It is represented by integer value 0 does not support transactions.
TRANSACTION_READ_COMMITTED: It is represented by integer value 2 supports transactions allowing Non-Repeatable Reads and, Phantom Reads.
TRANSACTION_READ_UNCOMMITTED: It is represented by integer value 1 supports transactions allowing Dirty Reads, Non-Repeatable Reads and, Phantom Reads.
TRANSACTION_REPEATABLE_READ: It is represented by integer value 4 supports transactions allowing only Phantom Reads.
TRANSACTION_SERIALIZABLE: It is represented by integer value 8 supports transactions without allowing Dirty Reads, Non-Repeatable Reads and, Phantom Reads.
The setTransactionIsolation() method of the Connection interface is used to change the transaction isolation level for the current connection.
This method accepts an integer value representing one of the 5 transaction isolation levels.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Connection_setTransactionIsolation {
   public static void main(String args[]) throws SQLException {
      //Registering the Driver
      DriverManager.registerDriver(new com.mysql.jdbc.Driver());
      //Getting the connection
      String url = "jdbc:mysql://localhost/mydatabase";
      Connection con = DriverManager.getConnection(url, "root", "password");
      System.out.println("Connection established......");
      //Retrieving the transaction isolation level
      con.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
      int transactionIsoltionLevel = con.getTransactionIsolation();
      System.out.println("Transaction isolation level of the underlying
         database is: "+transactionIsoltionLevel);
   }
}
Connection established......
Transaction isolation level of the underlying database is: 1
Python – Inner Nested Value List Mean in Dictionary

14 May, 2020
Sometimes, while working with Python Dictionaries, we can have a problem in which we need to extract the mean of nested value lists in dictionary. This problem can have application in many domains including web development and competitive programming. Lets discuss certain ways in which this task can be performed.
Method #1 : Using mean() + loopThe combination of above functions provide the brute way to solve this problem. In this, we perform the task of finding mean using inbuilt mean() library and iterate for nesting using loop.
# Python3 code to demonstrate working of # Inner Nested Value List Mean in Dictionary# Using mean() + loopfrom statistics import mean  # initializing dictionarytest_dict = {'Gfg' : {'a' : [1, 5, 6, 7], 'b' : [6, 7, 8, 9]}, 'is' : {'best' :[2, 8, 9, 0]}}  # printing original dictionaryprint("The original dictionary : " + str(test_dict))  # Inner Nested Value List Mean in Dictionary# Using mean() + loopfor sub in test_dict.values():    for key in sub:        sub[key] = mean(sub[key])  # printing result print("The modified dictionary : " + str(test_dict)) 
The original dictionary : {‘Gfg’: {‘a’: [1, 5, 6, 7], ‘b’: [6, 7, 8, 9]}, ‘is’: {‘best’: [2, 8, 9, 0]}}The modified dictionary : {‘Gfg’: {‘a’: 4.75, ‘b’: 7.5}, ‘is’: {‘best’: 4.75}}
 
Method #2 : Using dictionary comprehension + mean()This is yet another way to solve this problem. In this, we perform similar task as above method. But difference is that in compact way and as one-liner.
# Python3 code to demonstrate working of # Inner Nested Value List Mean in Dictionary# Using dictionary comprehension + mean()from statistics import mean  # initializing dictionarytest_dict = {'Gfg' : {'a' : [1, 5, 6, 7], 'b' : [6, 7, 8, 9]}, 'is' : {'best' :[2, 8, 9, 0]}}  # printing original dictionaryprint("The original dictionary : " + str(test_dict))  # Inner Nested Value List Mean in Dictionary# Using dictionary comprehension + mean()res = {idx: {key: mean(idx) for key, idx in j.items()} for idx, j in test_dict.items()}  # printing result print("The modified dictionary : " + str(res)) 
The original dictionary : {‘Gfg’: {‘a’: [1, 5, 6, 7], ‘b’: [6, 7, 8, 9]}, ‘is’: {‘best’: [2, 8, 9, 0]}}The modified dictionary : {‘Gfg’: {‘a’: 4.75, ‘b’: 7.5}, ‘is’: {‘best’: 4.75}}
Python dictionary-programs
Python-nested-dictionary
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Repeat String till K

29 Jan, 2022
Sometimes, while working with strings, we might encounter a use case in which we need to repeat our string to the size of K, even though the last string might not be complete, but has to stop as the size of string becomes K. The problem of repeating string K times, is comparatively simpler than this problem. Let’s discuss way outs we can perform to solve this problem. Method #1 : Using list slicing and // operatorThis task can be performed using the above tools. In this we just multiply the string till it becomes greater than or equal to K, and then just omit the slice of extra string using the list slicing method. 
Python3
# Python3 code to demonstrate# Repeat string till K# using list slicing and // operator # initializing stringtest_string = "GeeksforGeeks" # initializing KK = 30 # printing original stringprint("The original string : " + str(test_string)) # using list slicing and // operator# Repeat string till Kres = (test_string * (K//len(test_string)+ 1))[:K] # print resultprint("String after performing repetition : " + res)
The original string : GeeksforGeeks
String after performing repeatition : GeeksforGeeksGeeksforGeeksGeek
 
 Method #2 : Using divmod() + list slicingThe division applied in the above method can be substituted in this method with the divmod function, which improves code readability with the cost of 40% of performance degradation. 
Python3
# Python3 code to demonstrate# Repeat string till K# using divmod() + list slicing # initializing stringtest_string = "GeeksforGeeks" # initializing KK = 30 # printing original stringprint("The original string : " + str(test_string)) # using divmod() + list slicing# Repeat string till Kdiv, mod = divmod(K, len(test_string))res = test_string * div + test_string[:mod] # print resultprint("String after performing repetition : " + res)
The original string : GeeksforGeeks
String after performing repeatition : GeeksforGeeksGeeksforGeeksGeek
 
saurabh1990aror
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
D3.js csv() Function

18 Aug, 2020
The d3.csv() function in D3.js is a part of the request API that returns a request for the file of type CSV at the specified URL. The mime type is text/CSV.
Syntax:
d3.csv(url[[, row], callback])
Parameters:
url: It is the URL of the file that is to be fetched.
callback: It is the function that is to be performed after the file is fetched.
Return Value: It returns a request for the file of type text/csv.CSV
Example 1: Fetching a file named sample.csv which is stored in the same location where the index.html is present. Please create the sample.csv file if not created already. Data of the CSV file is given as a comment in the code below. 
HTML
<!DOCTYPE html><html lang="en">  <head>    <meta charset="UTF-8">    <meta name="viewport" path1tent=        "width=device-width,initial-scale=1.0"></head>  <body>    <script src=        "https://d3js.org/d3.v4.min.js">    </script>      <script>        // Sample.csv file data         // should be like this          // year, population        // 2006, 40        // 2008, 45        // 2010, 48        // 2012, 51        // 2014, 53        // 2016, 57        // 2017, 62          // Fetch file        d3.csv("sample.csv", (d) => {            console.log(d)        })    </script></body>  </html>
Output:
Example 2:
HTML
<!DOCTYPE html><html lang="en">  <head>    <meta charset="UTF-8">    <meta name="viewport" path1tent=        "width=device-width,initial-scale=1.0"></head>  <body>    <script src=        "https://d3js.org/d3.v4.min.js">    </script>      <script>          // Fake json request        d3.csv("https://jsonplaceholder.typicode.com/todos/1",         (d) => {            console.log(d)        })    </script></body>  </html>
Output:
D3.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Roadmap to Learn JavaScript For Beginners
Difference Between PUT and PATCH Request
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Setting Precision in Python Using Decimal Module

01 Oct, 2020
The decimal module in Python can be used to set the precise value of a number. The default value of the Decimal module is up to 28 significant figures. However, it can be changed using getcontext().prec method.
The below program demonstrates the use of decimal module by computing the square root of 2 numbers up to the default the number of places.
Python3
# Import required modulesimport decimal    # Create decimal objectob1 = decimal.Decimal(5).sqrt()  ob2 = decimal.Decimal(7).sqrt()  # Display value  print(ob1)print(ob2)
2.236067977499789696409173669
2.645751311064590590501615754


We can set the precision up to n significant figure. The decimal.getcontext().prec has to be declared in the global scope such that all the decimal objects can have n significant figures.
Python3
# Import required moduleimport decimal  # Set precision to a fixed value decimal.getcontext().prec = 6    # Create Decimal objectob1 = decimal.Decimal(5).sqrt()  ob2 = decimal.Decimal(7).sqrt()  # Display value up to 6 significant figuresprint(ob1)print(ob2)
2.23607
2.64575


python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Spring - Annotation Based Configuration

Starting from Spring 2.5 it became possible to configure the dependency injection using annotations. So instead of using XML to describe a bean wiring, you can move the bean configuration into the component class itself by using annotations on the relevant class, method, or field declaration.
Annotation injection is performed before XML injection. Thus, the latter configuration will override the former for properties wired through both approaches.
Annotation wiring is not turned on in the Spring container by default. So, before we can use annotation-based wiring, we will need to enable it in our Spring configuration file. So consider the following configuration file in case you want to use any annotation in your Spring application.
<?xml version = "1.0" encoding = "UTF-8"?>

<beans xmlns = "http://www.springframework.org/schema/beans"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xmlns:context = "http://www.springframework.org/schema/context"
   xsi:schemaLocation = "http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context-3.0.xsd">

   <context:annotation-config/>
   <!-- bean definitions go here -->

</beans>
Once <context:annotation-config/> is configured, you can start annotating your code to indicate that Spring should automatically wire values into properties, methods, and constructors. Let us look at a few important annotations to understand how they work −
The @Required annotation applies to bean property setter methods.
The @Autowired annotation can apply to bean property setter methods, non-setter methods, constructor and properties.
The @Qualifier annotation along with @Autowired can be used to remove the confusion by specifiying which exact bean will be wired.
Spring supports JSR-250 based annotations which include @Resource, @PostConstruct and @PreDestroy annotations.