code-rag-bench/online-tutorials huggingface dataset:
HTML | DOM createTextNode() Method - GeeksforGeeks

19 Apr, 2021
The createTextNode() method is used to create a TextNode which contains element node and a text node. It is used to provide text to an element. This method contains the text values as parameter which is of string type.Syntax:  
document.createTextNode( text )
Parameters: This method accepts single parameter text which is mandatory. It is used to specify the text of text node.Example:  
html
<!DOCTYPE html><html>    <head>        <title>DOM createTextNode() Method</title>        <style>            h1, h2 {                color:green;                font-weight:bold;            }            body {                text-align:center;            }        </style>    </head>    <body>        <h1>GeeksForGeels</h1>        <h2>DOM createTextNode() Method</h2>        <button onclick="geeks()">Submit</button>        <script>            function geeks() {                var x =                    document.createTextNode("GeeksForGeeks");                document.body.appendChild(x);            }        </script>    </body></html>                   
Output: 
Before Clicking on Button:
After Clicking on Button: 
Supported Browsers: The browser supported by DOM createTextNode() Method  are listed below:  
Google Chrome
Internet Explorer
Firefox
Opera
Safari
 
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
hritikbhatnagar2182
HTML-DOM
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to update Node.js and NPM to next version ?
How to create footer to stay at the bottom of a Web page?
How to apply style to parent if it has child with CSS?
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to update Node.js and NPM to next version ?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
Python - Measuring Variance

In statistics, variance is a measure of how far a value in a data set lies from the mean value. In other words, it indicates how dispersed the values are.
It is measured by using standard deviation. The other method commonly used is skewness.
Both of these are calculated by using functions available in pandas library. 
Standard deviation is square root of variance. variance is the average of squared difference of values in a data set from the mean value. In python we calculate this value
by using the function std() from pandas library.
import pandas as pd

#Create a Dictionary of series
d = {'Name':pd.Series(['Tom','James','Ricky','Vin','Steve','Smith','Jack',
   'Lee','Chanchal','Gasper','Naviya','Andres']),
   'Age':pd.Series([25,26,25,23,30,25,23,34,40,30,25,46]),
   'Rating':pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8,3.78,2.98,4.80,4.10,3.65])}

#Create a DataFrame
df = pd.DataFrame(d)

# Calculate the standard deviation
print df.std()
Its output is as follows −
Age       7.265527
Rating    0.661628
dtype: float64
It used to determine whether the data is symmetric or skewed. If the index is between -1 and 1, then the distribution is symmetric. If the index is no more than -1 
then it is skewed to the left and if it is at least 1, then it is skewed to the right
import pandas as pd

#Create a Dictionary of series
d = {'Name':pd.Series(['Tom','James','Ricky','Vin','Steve','Smith','Jack',
   'Lee','Chanchal','Gasper','Naviya','Andres']),
   'Age':pd.Series([25,26,25,23,30,25,23,34,40,30,25,46]),
   'Rating':pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8,3.78,2.98,4.80,4.10,3.65])}

#Create a DataFrame
df = pd.DataFrame(d)
print df.skew()
Its output is as follows −
Age       1.443490
Rating   -0.153629
dtype: float64
So the distribution of age rating is symmetric while the distribution of age is skewed to the right.

    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
HTML | canvas getImageData() Method - GeeksforGeeks

19 Oct, 2021
The getImageData() method is used to copy the pixel data for the specified rectangle on a canvas.There are 4 pieces of information for every pixel in an ImageData object i.e. the RGBA values:  
R denotes the red color. It ranges from 0 to 255.
G denotes the green color. It ranges from 0 to 255.
B denotes the blue color. It ranges from 0 to 255.
A denotes the alpha channel. It also ranges from 0 to 255 i.e. 0 is transparent and 255 is fully visible
Syntax:  
context.getImageData(x, y, width, height);
Parameter Values:  
x: It is used to specify the x coordinate (in pixels) of the upper-left corner from where the copy to be started.
y: It is used to specify the x coordinate (in pixels) of the upper-left corner from where the copy to be started.
width: It is the width of the rectangular area to be copied.
height: It is the height of the rectangular area to be copied.
Example:  
html
<!DOCTYPE html><html> <body>     <h3 style="color:green; "> GeeksforGeeks</h3>    <h3 style="color:green; "> GetImageData() Method</h3>    <canvas id="gfgCanvas"            width="300"            height="300"            style="border:1px solid ;">    </canvas>     <script>        var gfg = document.getElementById("gfgCanvas");        var context = gfg.getContext("2d");        context.fillStyle = "green";        context.fillRect(55, 50, 200, 100);         function putImage() {            // getImageData is used to copy the pixels            var imageData = context.getImageData(55, 50, 200, 100);            context.putImageData(imageData, 55, 170);        }    </script>    <br>    <button onclick="putImage()">GetImageData</button> </body> </html>
Output: Before click:  
After click:  
Supported Browsers:  
Chrome
Mozilla Firefox
Internet Explorer 9.0
Opera
Safari
 
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
surinderdawra388
HTML-Methods
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
HTML Cheat Sheet - A Basic Guide to HTML
How to Insert Form Data into Database using PHP ?
Types of CSS (Cascading Style Sheet)
How to position a div at the bottom of its container using CSS?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Can an interface extend multiple interfaces in Java?


Yes, we can do it. An interface can extend multiple interfaces in Java.
interface A {
   public void test();
   public void test1();
}
interface B {
   public void test();
   public void test2();
}
interface C extends A,B {
   public void test3();
}
class D implements C {
   public void test() {
      System.out.println("Testing\n");
   }
   public void test1() {
      System.out.println("Testing1\n");
   }
   public void test2() {
      System.out.println("Testing2\n");
   }
   public void test3() {
      System.out.println("Testing3");
   }
}
public class Main {
   public static void main(String[] args) {
      D d=new D();
      d.test();
      d.test1();
      d.test2();
      d.test3();
   }
 }
Testing

Testing1

Testing2

Testing3
Which methods are supported by Get-ChildItem in PowerShell?

There are methods or functions which are useful for directories and file operations.
Methods for the directory.
TypeName: System.IO.DirectoryInfo

Name                      MemberType
----                      ----------
Create                    Method
CreateObjRef              Method
CreateSubdirectory        Method
Delete                    Method
EnumerateDirectories      Method
EnumerateFiles            Method
EnumerateFileSystemInfos  Method
Equals                    Method
GetAccessControl          Method
GetDirectories            Method
GetFiles                  Method
GetFileSystemInfos        Method
GetHashCode               Method
GetLifetimeService        Method
GetObjectData             Method
GetType                   Method
InitializeLifetimeService Method
MoveTo                    Method
Refresh                   Method
SetAccessControl          Method
ToString                  Method
Methods for Files.
TypeName: System.IO.FileInfo

Name                      MemberType
----                      ----------
AppendText                Method
CopyTo                    Method
Create                    Method
CreateObjRef              Method
CreateText                Method
Decrypt                   Method
Delete                    Method
Encrypt                   Method
Equals                    Method
GetAccessControl          Method
GetHashCode               Method
GetLifetimeService        Method
GetObjectData             Method
GetType                   Method
InitializeLifetimeService Method
MoveTo                    Method
Open                      Method
OpenRead                  Method
OpenText                  Method
OpenWrite                 Method
Refresh                   Method
Replace                   Method
SetAccessControl          Method
ToString                  Method
How to check whether a checkbox is checked in JavaScript?

To check whether a checkbox is checked, try to run the following code. It returns true if the checkbox is checked, else false −
Live Demo
<html>
   <head>
      <script>
         function myFunction(){
            var result = document.getElementById("check").checked;
            alert(result);
         }
      </script>
   </head>
   <body>
      <label><input id="check" type="checkbox" >One</label><br>
      <button onclick="myFunction()">Check value</button>
   </body>
</html>
Convert decimal fraction to binary number in C++

In this tutorial, we will be discussing a program to convert decimal fraction to a binary number.
For this we will be provided with a decimal fraction and integer ‘k’. Our task is to convert the given decimal fraction into its binary equivalent upto the given ‘k’ digits of decimal precision.
 Live Demo
#include<bits/stdc++.h>
using namespace std;
//converting decimal to binary number
string convert_tobinary(double num, int k_prec) {
   string binary = "";
   //getting the integer part
   int Integral = num;
   //getting the fractional part
   double fractional = num - Integral;
   //converting integer to binary
   while (Integral) {
      int rem = Integral % 2;
      binary.push_back(rem +'0');
      Integral /= 2;
   }
   //reversing the string to get the
   //required binary number
   reverse(binary.begin(),binary.end());
   binary.push_back('.');
   //converting fraction to binary
   while (k_prec--) {
      fractional *= 2;
      int fract_bit = fractional;
      if (fract_bit == 1) {
         fractional -= fract_bit;
         binary.push_back(1 + '0');
      } else
      binary.push_back(0 + '0');
   }
   return binary;
}
int main() {
   double n = 4.47;
   int k = 3;
   cout << convert_tobinary(n, k) << "\n";
   n = 6.986 , k = 5;
   cout << convert_tobinary(n, k);
   return 0;
}
100.011
110.11111
RequireJS - NodeJS

The Node adapter can be used along with the implementation of Require and Node's search path. If there is no module configuration used by RequireJS, you can use the existing Node based modules without changing them. You can install the node packages in the node_modules directory of project by using the npm command.
Node will load modules only from the local disk and config options such as map, packages, paths, etc. will be applied only when module is loaded by RequireJS.
You can install the Node adapter by using the following command which will install the latest release files −
npm install requirejs

You can install the Node in the following ways as well −
You can download the r.js from this link and keep it in your project folder.
You can download the r.js from this link and keep it in your project folder.
Obtain the source from r.js repository or install it through node dist.js. 
Obtain the source from r.js repository or install it through node dist.js. 
To use the node, you need to have require('requirejs') and move the require function in the configuration to the top level main.js file.
For instance −
var requirejs = require('requirejs');

requirejs.config({
   //load the mode modules to top level JS file 
   //by passing the top level main.js require function to requirejs
   nodeRequire: require
});

requirejs(['name1', 'name2'],
   function (name1, name2) {
      //by using requirejs config, name1 and name2 are loaded
      //node's require loads the module, if they did not find these
   }
);
You can make code module work with RequireJS and Node, without requiring users of library, and then use the amdefine package to accomplish this work.
For instance −
if (typeof define !== 'function') {
   var define = require('amdefine')(module);
}

define(function(require) {
   var myval = require('dependency');

   //The returned value from the function can be used 
   //as module which is visible to Node.
   return function () {};
});
Node module uses the RequireJS optimizer as an optimize method by using the function call instead of using the command line tool.
For instance −
var requirejs = require('requirejs');

var config = {
   baseUrl: '../directory/scripts',
   name: 'main',
   out: '../build/main-built.js'
};

requirejs.optimize(config, function (buildResponse) {

   //The text output of the modules specify by using buildResponse 
   //and loads the built file for the contents
   //get the optimized file contents by using config.out 
   var contents = fs.readFileSync(config.out, 'utf8');
}, function(err) {
   //code for optimization err callback
});
 Print
 Add Notes
 Bookmark this page
C program to store even, odd and prime numbers into separate files

A file is a physical storage location on disk and a directory is a logical path which is used to organise the files. A file exists within a directory.
The three operations that we can perform on file are as follows −
Open a file.
Process file (read, write, modify).
Save and close file.
Following is the C program to store even, odd and prime numbers into separate files −
 Live Demo
#include <stdio.h>
#include <stdlib.h>
/* Function declarations */
int even(const int num);
int prime(const int num);
int main(){
   FILE * fptrinput,
   * fptreven,
   * fptrodd,
   * fptrprime;
   int num, success;
   fptrinput = fopen("numbers.txt", "r");
   fptreven = fopen("even-numbers.txt" , "w");
   fptrodd = fopen("odd-numbers.txt" , "w");
   fptrprime= fopen("prime-numbers.txt", "w");
   if(fptrinput == NULL || fptreven == NULL || fptrodd == NULL || fptrprime == NULL){
      /* Unable to open file hence exit */
      printf("Unable to open file.\n");
      exit(EXIT_FAILURE);
   }
   /* File open success message */
   printf("File opened successfully. Reading integers from file. \n\n");
   // Read an integer and store read status in success.
   while (fscanf(fptrinput, "%d", &num) != -1){
      if (prime(num))
         fprintf(fptrprime, "%d\n", num);
      else if (even(num))
         fprintf(fptreven, "%d\n", num);
      else
         fprintf(fptrodd, "%d\n", num);

   }
   fclose(fptrinput);
   fclose(fptreven);
   fclose(fptrodd);
   fclose(fptrprime);
   printf("Data written successfully.");
   return 0;
}
int even(const int num){
   return !(num & 1);
}
int prime(const int num){
   int i;
   if (num < 0)
      return 0;
   for ( i=2; i<=num/2; i++ ) {
      if (num % i == 0) {
         return 0;
      }
   }
   return 1;
}
When the above program is executed, it produces the following result −
File opened successfully. Reading integers from file.
Data written successfully.
Given below is an explanation for the program used to store even, odd and prime numbers into separate files −
Input file:
numbers.txt file contains: 1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17
Which is open in read mode (already exists file)
Separated even, odd and prime numbers in separate file after execution
even-numbers.txt contains: 4 6 8 10 12 14 16
odd-numbers.txt contains: 9 15
prime-numbers.txt contains: 1 2 3 5 7 11 13 17
How to use the directory class in C#?

The Directory class in C# is used to manipulate the directory structure. It has methods to create, move, remove directories.
The following are some of the methods of the Directory class.
Let us learn about the usage of GetFiles() method in Directory class. It displays all the files in the specified directory.
using System;
using System.IO;
class Program {
   static void Main() {
      // Get all files in the D directory
      string[] arr = Directory.GetFiles(@"D:\");
      Console.WriteLine("Files:");
      foreach (string n in arr) {
         Console.WriteLine(n);
      }
   }
}
Adding Text on Image using Python - PIL - GeeksforGeeks

15 Sep, 2021
In Python to open an image, image editing, saving that image in different formats one additional library called Python Imaging Library (PIL). Using this PIL we can do so many operations on images like create a new Image, edit an existing image, rotate an image, etc. For adding text we have to follow the given approach.
Approach
Import module
Open targeted image
Add text property using image object
Show that edited Image
Save that image
Syntax: obj.text( (x,y), Text, font, fill)
Parameters: 
(x, y): This X and Y denotes the starting position(in pixels)/coordinate of adding the text on an image.
Text: A Text or message that we want to add to the Image.
Font: specific font type and font size that you want to give to the text.
Fill: Fill is for to give the Font color to your text.
Other than these we required some module from PIL to perform this task. We need ImageDraw that can add 2D graphics ( shapes, text) to an image. Also, we required the ImageFont module to add custom font style and font size. Given below is the Implementation of add text to an image. 
Image Used:
Example 1: Add a simple text to an image. ( without custom Font style)
Python3
# Importing the PIL libraryfrom PIL import Imagefrom PIL import ImageDraw # Open an Imageimg = Image.open('car.png') # Call draw Method to add 2D graphics in an imageI1 = ImageDraw.Draw(img) # Add Text to an imageI1.text((28, 36), "nice Car", fill=(255, 0, 0)) # Display edited imageimg.show() # Save the edited imageimg.save("car2.png")
Output:
Here You can see that we successfully add text to an image but it not properly visible so we can add the Font parameter to give a custom style.
Example 2: Add a simple text to an image. ( With custom Font style)
Python3
# Importing the PIL libraryfrom PIL import Imagefrom PIL import ImageDrawfrom PIL import ImageFont # Open an Imageimg = Image.open('car.png') # Call draw Method to add 2D graphics in an imageI1 = ImageDraw.Draw(img) # Custom font style and font sizemyFont = ImageFont.truetype('FreeMono.ttf', 65) # Add Text to an imageI1.text((10, 10), "Nice Car", font=myFont, fill =(255, 0, 0)) # Display edited imageimg.show() # Save the edited imageimg.save("car2.png")
Output:
kapoorsagar226
akshaysingh98088
Picked
Python-pil
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Selecting rows in pandas DataFrame based on conditions
Python | os.path.join() method
Defaultdict in Python
Create a directory in Python
Python | Get unique values from a list
Python | Pandas dataframe.groupby()
What is the difference between Read() and ReadLine() methods in C#?

The Read() reads the next characters from the standard input stream. If a key is pressed on the console, then it would close.
int a = Console.Read()
Console.WriteLine(a);
It reads the next line of characters from the standard input stream.
 Live Demo
using System;
class Program {
   static void Main() {

      int x = 10;
      Console.WriteLine(x);
      Console.Write("\nPress any key to continue... ");
      Console.ReadLine();

   }
}
10
Press any key to continue...
SQL Tryit Editor v1.6

SELECT Employees.LastName, COUNT(Orders.OrderID) AS NumberOfOrders
FROM Orders
INNER JOIN Employees ON Orders.EmployeeID = Employees.EmployeeID
WHERE LastName = 'Davolio' OR LastName = 'Fuller'
GROUP BY LastName
HAVING COUNT(Orders.OrderID) > 25;
​
Edit the SQL Statement, and click "Run SQL" to see the result.
This SQL-Statement is not supported in the WebSQL Database.
The example still works, because it uses a modified version of SQL.
Your browser does not support WebSQL.
Your are now using a light-version of the Try-SQL Editor, with a read-only Database.
If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time.
Our Try-SQL Editor uses WebSQL to demonstrate SQL.
A Database-object is created in your browser, for testing purposes.
You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button.
WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object.
WebSQL is supported in Chrome, Safari, Opera, and Edge(79).
If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
Java try Keyword

❮ Java Keywords

If an error occur, use try...catch to catch the error and execute some code to handle it:
try {
  int[] myNumbers = {1, 2, 3};
  System.out.println(myNumbers[10]);
} catch (Exception e) {
  System.out.println("Something went wrong.");
}


Try it Yourself »

The try keyword creates a try...catch statement.
The try statement allows you to define a block of code to be 
tested for errors while it is being executed.
The catch statement allows you to define a block of code to 
be executed, if an error occurs in the try block.
Read more about exceptions in our Java Try..Catch Tutorial.

❮ Java Keywords

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.
PyQt5 - How to get percentage of Progress Bar ? - GeeksforGeeks

22 Apr, 2020
In this article we will see how to get the percentage value of progress bar, we can set the percentage of progress bar using setValue method. In order to get the percentage value we use text method which will return the integer that indicates the percentage.
Syntax : bar.text()
Argument : It takes no argument.
Return : It return integer.
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 progress bar        bar = QProgressBar(self)          # setting geometry to progress bar        bar.setGeometry(200, 150, 200, 30)          # set value to progress bar        bar.setValue(70)          # getting percentage value        p_value = bar.text()          # creating label to print percentage        label = QLabel("percentage = " + str(p_value), self)          # moving the label        label.move(200, 200)          # setting alignment to centre        bar.setAlignment(Qt.AlignCenter)    # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Read a file line by line in Python
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
Reading and Writing to text files in Python
*args and **kwargs in Python
Convert integer to string in Python
Python | Get a google map image of specified location using Google Static Maps API

31 May, 2019
Google Static Maps API lets embed a Google Maps image on the web page without requiring JavaScript or any dynamic page loading. The Google Static Maps API service creates the map based on URL parameters sent through a standard HTTP request and returns the map as an image one can display on the web page.
To use this service, one must need an API key, get it form here .
Note: One need to create billing account on google then only can use Google APIs.
Modules needed :
import requests
Below is the implementation :
# Python program to get a google map # image of specified location using # Google Static Maps API  # importing required modulesimport requests  # Enter your api key hereapi_key = "_your_api_key_"  # url variable store urlurl = "https://maps.googleapis.com/maps/api/staticmap?"  # center defines the center of the map,# equidistant from all edges of the map. center = "Dehradun"  # zoom defines the zoom# level of the mapzoom = 10  # get method of requests module# return response objectr = requests.get(url + "center =" + center + "&zoom =" +                   str(zoom) + "&size = 400x400&key =" +                             api_key + "sensor = false")  # wb mode is stand for write binary modef = open('address of the file location ', 'wb')  # r.content gives content,# in this case gives imagef.write(r.content)  # close method of file object# save and close the filef.close()
Output :
Note : For checking whether the API key is properly working or not, store r.content in .txt file, inspite of saving as .png file. If the API key is invalid, API will return this error message instead of image “The Google Maps API server rejected your request. The provided API key is invalid “. 
Following list shows the approximate level of detail one can expect to see at each zoom level :
1 : World
5 : Landmass/continent
10 : City
15 : Streets
20 : Buildings

shubham_singh
python-utility
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python – Rearrange dictionary for consecutive value-keys

10 Sep, 2021
Sometimes, while working with Python dictionaries, we can have a problem in which we need to rearrange dictionary keys so as a value is followed by same key in dictionary. This problem can have application in competitive programming algorithms and Graph problems. Let’s discuss certain ways in which this task can be performed. 
Input : test_dict = {1 : 2, 3 : 2, 2 : 3} Output : {1: 2, 2: 3, 3: 2}Input : test_dict = {1 : 2} Output : {1 : 2}  
Method #1 : Using loop + keys() The combination of above functions can be used to solve this problem. In this, we extract the dictionary keys using keys() and iterate till we find value succeeded by equal key. 
Python3
# Python3 code to demonstrate working of# Rearrange dictionary for consecutive value-keys# Using loop + keys() # initializing dictionarytest_dict = {1 : 3, 4 : 5, 3 : 4, 5 : 6} # printing original dictionaryprint("The original dictionary : " + str(test_dict)) # Rearrange dictionary for consecutive value-keys# Using loop + keys()temp = list(test_dict.keys())[0]res = {}while len(test_dict) > len(res):    res[temp] = temp = test_dict[temp] # printing resultprint("The rearranged dictionary : " + str(res))
The original dictionary : {1: 3, 4: 5, 3: 4, 5: 6}
The rearranged dictionary : {1: 3, 3: 4, 4: 5, 5: 6}
 
 Method #2 : Using dictionary comprehension + accumulate() The combination of above functions can be used to solve this problem. In this, we perform the task fo pairing using accumulate and rearrange new dictionary using dictionary comprehension. 
Python3
# Python3 code to demonstrate working of# Rearrange dictionary for consecutive value-keys# Using dictionary comprehension + accumulate()from itertools import accumulate # initializing dictionarytest_dict = {1 : 3, 4 : 5, 3 : 4, 5 : 6} # printing original dictionaryprint("The original dictionary : " + str(test_dict)) # Rearrange dictionary for consecutive value-keys# Using dictionary comprehension + accumulate()res = {key : test_dict[key] for key in accumulate(test_dict,                              lambda key, x :test_dict[key])} # printing resultprint("The rearranged dictionary : " + str(res))
The original dictionary : {1: 3, 4: 5, 3: 4, 5: 6}
The rearranged dictionary : {1: 3, 3: 4, 4: 5, 5: 6}
 
adnanirshad158
Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Pattern pattern() method in Java with Examples

30 Jul, 2019
The pattern() method of the Pattern class in Java is used to get the regular expression which is compiled to create this pattern. We use a regular expression to create the pattern and this method used to get the same source expression.
Syntax:
public String pattern()

Parameters: This method does not accepts anything as parameter.
Return Value: This method returns the pattern’s source regular expression.
Below programs illustrate the pattern() method:Program 1:
// Java program to demonstrate// Pattern.pattern() method  import java.util.regex.*;  public class GFG {    public static void main(String[] args)    {          // create a REGEX String        String REGEX = "(.*)(for)(.*)?";          // create the string        // in which you want to search        String actualString            = "code of Machine";          // create pattern        Pattern pattern1 = Pattern.compile(REGEX);          // find the regular expressio of pattern        String RegularExpression = pattern1.pattern();          System.out.println("Pattern's RegularExpression = "                           + RegularExpression);    }}
Pattern's RegularExpression = (.*)(for)(.*)?

Program 2:
// Java program to demonstrate// Pattern.compile method  import java.util.regex.*;  public class GFG {    public static void main(String[] args)    {          // create a REGEX String        String REGEX = "(.*)(ee)(.*)?";          // create the string        // in which you want to search        String actualString            = "geeks";          // create pattern        Pattern pattern1 = Pattern.compile(REGEX);          // find the regular expressio of pattern        String RegularExpression = pattern1.pattern();          System.out.println("Pattern's RegularExpression = "                           + RegularExpression);    }}
Pattern's RegularExpression = (.*)(ee)(.*)?

References:https://docs.oracle.com/javase/10/docs/api/java/util/regex/Pattern.html#pattern()
Akanksha_Rai
Java 8
Java-Functions
Java-Pattern
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java
LocalDate getDayOfWeek() method in Java

28 Nov, 2018
The getDayOfWeek() method of LocalDate class in Java gets the day-of-week field, which is an enum DayOfWeek.
Syntax:
public DayOfWeek getDayOfWeek()

Parameter: This method does not accepts any parameter.
Return Value: The function returns the day of the week and not null.
Below programs illustrate the getDayOfWeek() method of LocalDate in Java:
Program 1:
// Program to illustrate the getDayOfWeek() method  import java.util.*;import java.time.*;  public class GfG {    public static void main(String[] args)    {        // Parses the date        LocalDate dt = LocalDate.parse("2018-11-27");          // Prints the day        System.out.println(dt.getDayOfWeek());    }}
TUESDAY

Program 2:
// Program to illustrate the getDayOfWeek() method  import java.util.*;import java.time.*;  public class GfG {    public static void main(String[] args)    {        // Parses the date        LocalDate dt = LocalDate.parse("2018-01-09");          // Prints the day        System.out.println(dt.getDayOfWeek());    }}
TUESDAY

Reference: https://docs.oracle.com/javase/10/docs/api/java/time/LocalDate.html#getDayOfWeek()
Java-Functions
Java-LocalDate
Java-time package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Collections in Java
Stream In Java
Multidimensional Arrays in Java
Singleton Class in Java
Set in Java
Top Down Integration Testing

Top-down integration testing is an integration testing technique used in order to simulate the behaviour of the lower-level modules that are not yet integrated. Stubs are the modules that act as temporary replacement for a called module and give the same output as that of the actual product.
The replacement for the 'called' modules is known as 'Stubs' and is also used when the software needs to interact with an external system.
The above diagrams clearly states that Modules 1, 2 and 3 are available for integration, whereas, below modules are still under development that cannot be integrated at this point of time. Hence, Stubs are used to test the modules. The order of Integration will be:
1,2
1,3
2,Stub 1
2,Stub 2
3,Stub 3
3,Stub 4
+ Firstly, the integration between the modules 1,2 and 3
+ Test the integration between the module 2 and stub 1,stub 2
+ Test the integration between the module 3 and stub 3,stub 4
Python MySQL – Insert into Table

06 Mar, 2020
MySQL is a Relational Database Management System (RDBMS) whereas the structured Query Language (SQL) is the language used for handling the RDBMS using commands i.e Creating, Inserting, Updating and Deleting the data from the databases. SQL commands are case insensitive i.e CREATE and create signify the same command.
Note: Before we insert data into our database, we need to create a table. In order to do so, refer to Python: MySQL Create Table.
You can insert one row or multiple rows at once. The connector code is required to connect the commands to the particular database.
Connector query
# Enter the server name in host# followed by your user and# password along with the database # name provided by you.  import mysql.connector    mydb = mysql.connector.connect(  host = "localhost",  user = "username",  password = "password",  database = "database_name")   mycursor = mydb.cursor()
Now, the Insert into Query can be written as follows:
Example: Let’s suppose the record looks like this –
sql = "INSERT INTO Student (Name, Roll_no) VALUES (%s, %s)"val = ("Ram", "85")  mycursor.execute(sql, val)mydb.commit()  print(mycursor.rowcount, "details inserted")  # disconnecting from servermydb.close()
Output:
1 details inserted
To insert multiple values at once, executemany() method is used. This method iterates through the sequence of parameters, passing the current parameter to the execute method.
Example:
sql = "INSERT INTO Student (Name, Roll_no) VALUES (%s, %s)"val = [("Akash", "98"),       ("Neel", "23"),       ("Rohan", "43"),       ("Amit", "87"),       ("Anil", "45"),        ("Megha", "55"),        ("Sita", "95")]  mycursor.executemany(sql, val)mydb.commit()  print(mycursor.rowcount, "details inserted")  # disconnecting from servermydb.close()
Output:
7 details inserted
Note:
The cursor() is used in order to iterate through the rows.
Without the command mydb.commit() the changes will not be saved.
Python-mySQL
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Iterate over a list in Python
Read JSON file using Python
Python map() function
How to iterate through Excel rows in Python?
Enumerate() in Python
Adding new column to existing DataFrame in Pandas
Python OOPs Concepts
Different ways to create Pandas Dataframe
How to get column names in Pandas dataframe
Stack in Python
How to catch FloatingPointError Exception in Python?

FloatingPointError is raised by floating point operations that result in errors, when floating point exception control (fpectl) is turned on. Enabling fpectl requires an interpreter compiled with the --with-fpectl flag.
The given code is rewritten as follows to handle the exception and find its type.
import sys
import math
import fpectl
try:
print 'Control off:', math.exp(700)
fpectl.turnon_sigfpe()
print 'Control on:', math.exp(1000)
except Exception as e:
print e
print sys.exc_type

Control off: 1.01423205474e+304
Control on: in math_1
<type 'exceptions.FloatingPointError'>
Python Program to Flatten a Nested List using Recursion

When it is required to flatten a given nested list using recursion technique, simple indexing, and the ‘isinstance’ method can be used along with recursion.
The recursion computes output of small bits of the bigger problem, and combines these bits to give the solution to the bigger problem.
Below is a demonstration for the same −
 Live Demo
def flatten_list(my_list):
   if my_list == []:
      return my_list
   if isinstance(my_list[0], list):
      return flatten_list(my_list[0]) + flatten_list(my_list[1:])
   return my_list[:1] + flatten_list(my_list[1:])
my_list = [[1,2],[3,4], [90, 11], [56, 78], [[34,56]]]
print("The list is :")
print(my_list)
print("The list after flattening is : ")
print(flatten_list(my_list))
The list is :
[[1, 2], [3, 4], [90, 11], [56, 78], [[34, 56]]]
The list after flattening is :
[1, 2, 3, 4, 90, 11, 56, 78, 34, 56]
A method named ‘flatten_list’ is defined, that takes a list as parameter.
It checks to see the data type of the first element in the list.
If it matches to a list, then, the first element along with the second element to last element is concatenated and displayed.
This results in a nested list being flattened.
Otherwise, the first element is left out, and the list is first reversed and the normal list is combined, and returned as output.
Outside the function, a nested list is defined, and is displayed on the console.
The method is called by passing the list as parameter.
The output is displayed on the console.
How to deal with reusable components in Selenium Java?

We can deal with reusable components in Selenium Java with the help of inheritance concept. It is a parent child relationship where the child class inherits the properties and methods of the parent class.
For Parent class.
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Baseclass {
   public void login() throws IOException {
      Properties prop = new Properties();
      //Reading values from property file
      FileInputStream ips = new FileInputStream(
      "C:\\Users\\ghs6kor\\eclipse- workspace\\Inheritance\\config.properties");
      prop.load(ips);
      System.setProperty("webdriver.gecko.driver",             "C:\\Users\\ghs6kor\\Desktop\\Java\\geckodriver.exe");
      WebDriver driver = new FirefoxDriver();
      driver.get(prop.getProperty("url"));
   }
}
For Child class.
import java.io.IOException;
public class Child extends Baseclass {
   public static void main(String[] args) throws IOException {
      // TODO Auto-generated method stub
      Child c = new Child();
      c.login();
      c.testinheritance();
   }
   public void testinheritance() {
      // parent class method used in child class
      login();
      System.out.println("Test Inheritance");
   }
}
Python - Calculate the count of column values of a Pandas DataFrame

To calculate the count of column values, use the count() method. At first, import the required Pandas library −
import pandas as pd
Create a DataFrame with two columns −
dataFrame1 = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Audi', 'Tesla', 'Bentley', 'Jaguar'],
      "Units": [100, 150, 110, 80, 110, 90]
   }
)
Finding count of "Units" column values using the count() function −
print"Count of values of Units column from DataFrame1 = ",dataFrame1['Units'].count()

In the same way, we have calculated the count from the 2nd DataFrame.
Following is the complete code −
import pandas as pd

# Create DataFrame1
dataFrame1 = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Audi', 'Tesla', 'Bentley', 'Jaguar'],
      "Units": [100, 150, 110, 80, 110, 90]
   }
)

print"DataFrame1 ...\n",dataFrame1

# Finding count of values of a specific column
print"Count of values of Units column from DataFrame1 = ",dataFrame1['Units'].count()

# Create DataFrame2
dataFrame2 = pd.DataFrame(
   {
      "Product": ['TV', 'PenDrive', 'HeadPhone', 'EarPhone', 'HDD'],
      "Price": [8000, 500, 3000, 1500, 3000]
   }
)

print"\nDataFrame2 ...\n",dataFrame2

# Finding count of values of all the column
print"\nCount of column values from DataFrame2 = \n",dataFrame2.count()


This will produce the following output −
DataFrame1 ...
       Car   Units
0      BMW    100
1    Lexus    150
2     Audi    110
3    Tesla     80
4  Bentley    110
5   Jaguar     90
Count of values of Units column from DataFrame1 = 6

DataFrame2 ...
    Price   Product
0   8000    TV
1    500    PenDrive
2   3000    HeadPhone
3   1500    EarPhone
4   3000    HDD

Count of column values from DataFrame2 =
Price     5
Product   5
dtype: int64
Bootstrap table-condensed class

Using the .table-condensed class, row padding is cut in half to condense the table. as seen in the following example. This is useful if you want any denser information.
You can try to run the following code to implement table-condensed class in Bootstrap −
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Table</title>
      <meta name = "viewport" content = "width = device-width, initial-scale = 1">
      <link rel = "stylesheet" href = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
   </head>
   <body>
      <table class = "table table-condensed table-hover table-bordered table-striped">
         <caption>Footballer Rank</caption>
         <thead>
            <tr>
               <th>Footballer</th>
               <th>Rank</th>
               <th>Country</th>
            </tr>
         </thead>
         <tbody>
            <tr>
               <td>Messi</td>
               <td>1</td>
               <td>Argentina</td>
            </tr>
            <tr>
               <td>Neymar</td>
               <td>2</td>
               <td>Brazil</td>
            </tr>
            <tr>
               <td>Ronaldo</td>
               <td>3</td>
               <td>Portugal</td>
            </tr>
         </tbody>
      </table>
   </body>
</html>
How to define character constants in C#?

Character literals are enclosed in single quotes. For example, 'x' and can be stored in a simple variable of char type. A character literal can be a plain character (such as 'x'), an escape sequence (such as '\t'), or a universal character (such as '\u02C0').
Let us see an example how to define a character constant in C# −
using System;

namespace Demo {
   class Program {
      static void Main(string[] args) {
         Console.WriteLine("Welcome!\t\n\n");
         Console.WriteLine("This is it!");
         Console.ReadLine();
      }
   }
}
Above, we have used the \n and \t constants that are new-line and horizontal tab constants −
Console.WriteLine("Welcome!\t\n\n");
Console.WriteLine("This is it!");
How to match pattern over multiple lines in Python?

The re.DOTALL flag tells python to make the ‘.’ special character match all characters, including newline characters.
import re
paragraph = \
'''
   This is a paragraph.
   It has multiple lines.
'''
match = re.search(r'<p>.*</p>', paragraph, re.DOTALL)
print match.group(0)
Output
This is a paragraph.
It has multiple lines.
Sum of even numbers up to using recursive function in JavaScript

We have to write a recursive function that takes in a number n and returns the sum of all even
numbers up to n.
Let’s write the code for this function −
const recursiveEvenSum = (num, sum = 0) => {
   num = num % 2 === 0 ? num : num - 1;
   if(num){
      return recursiveEvenSum(num - 2, sum+num);
   }
   return sum;
};
console.log(recursiveEvenSum(12));
console.log(recursiveEvenSum(122));
console.log(recursiveEvenSum(23));
console.log(recursiveEvenSum(10));
console.log(recursiveEvenSum(19));
The output in the console will be −
42
3782
132
30
90
How to change the Title of the console using PowerShell command?

For various reasons, you need to change the title of the PowerShell console. Like the title to describe the script. For example, System Information or Service Information.
To change the PowerShell Console Title use the “WindowsTitle” property in RawUI. It is just a temporary change. When you close the console and open it again, the title will be set to the default.
$host.UI.RawUI.WindowTitle = "System Information"
Now the title of the PowerShell console is changed to “System Information”.
You can also supply variable value to this parameter.
$Title = "System Information"
$host.UI.RawUI.WindowTitle = $Title
Place k elements such that minimum distance is maximized in C++

In this problem, we are given an array of n points that lie on the same line. Our task is to place k elements of the array in such a way that the minimum distance between them is maximized.
Let’s take an example to understand the problem,
Input − array = {}
Output −
To solve this problem, we will find have to find the maximum possible minimum distance. For such a problem first, we need to sort the given array and then do a binary search until we get the solution at mid.
Program to show the implementation of our solution,
 Live Demo
#include <bits/stdc++.h>
using namespace std;
bool canGenerateResult(int mid, int arr[], int n, int k) {
   int pos = arr[0];
   int elements = 1;
   for (int i=1; i<n; i++){
      if (arr[i] - pos >= mid){
         pos = arr[i];
         elements++;
         if (elements == k)
         return true;
      }
   }
   return 0;
}
int maxMinDist(int arr[], int n, int k) {
   sort(arr,arr+n);
   int res = -1;
   int left = arr[0], right = arr[n-1];
   while (left < right){
      int mid = (left + right)/2;
      if (canGenerateResult(mid, arr, n, k)){
         res = max(res, mid);
         left = mid + 1;
      }
      else
         right = mid;
   }
   return res;
}
int main() {
   int arr[] = {3, 5, 6, 9, 1, 8};
   int n = sizeof(arr)/sizeof(arr[0]);
   int k = 3;
   cout<<"The maximized minimum distance is : "<<maxMinDist(arr, n, k);
   return 0;
}
The maximized minimum distance is : 4