code-rag-bench/online-tutorials huggingface dataset:
VBScript - Syntax

Let us write a VBScript to print out "Hello World".
<html>
   <body>
      <script language = "vbscript" type = "text/vbscript">
         document.write("Hello World!")
      </script>
   </body>
</html>
In the above example, we called a function document.write, which writes a string into the HTML document. This function can be used to write text, HTML or both. So, above code will display following result −
Hello World!

VBScript ignores spaces, tabs, and newlines that appear within VBScript programs. One can use spaces, tabs, and newlines freely within the program, so you are free to format and indent your programs in a neat and consistent way that makes the code easy to read and understand.
VBScript is based on Microsoft's Visual Basic. Unlike JavaScript, no statement terminators such as semicolon is used to terminate a particular statement.
Colons are used when two or more lines of VBScript ought to be written in a single line. Hence, in VBScript, Colons act as a line separator.
<script language = "vbscript" type = "text/vbscript">
   var1 = 10 : var2 = 20
</script>

When a statement in VBScript is lengthy and if user wishes to break it into multiple lines, then the user has to use underscore "_". This improves the readability of the code. The following example illustrates how to work with multiple lines.
<script language = "vbscript" type = "text/vbscript">
   var1 = 10 
   var2 = 20
   Sum = var1 + var2  
   document.write("The Sum of two numbers"&_"var1 and var2 is " & Sum)
</script>
The following list shows the reserved words in VBScript. These reserved words SHOULD NOT be used as a constant or variable or any other identifier names.
VBScript is a case-insensitive language. This means that language keywords, variables, function names and any other identifiers need NOT be typed with a consistent capitalization of letters. So identifiers int_counter, INT_Counter and INT_COUNTER have the same meaning within VBScript.
Comments are used to document the program logic and the user information with which other programmers can seamlessly work on the same code in future. It can include information such as developed by, modified by and it can also include incorporated logic. Comments are ignored by the interpreter while execution. Comments in VBScript are denoted by two methods.
1. Any statement that starts with a Single Quote (‘) is treated as comment.
Following is the example −
<script language = "vbscript" type = "text/vbscript">
   <!—
      ' This Script is invoked after successful login
      ' Written by : TutorialsPoint
      ' Return Value : True / False
   //- >
</script>
2. Any statement that starts with the keyword “REM”.
Following is the example −
<script language = "vbscript" type = "text/vbscript">
   <!—
      REM This Script is written to Validate the Entered Input
      REM Modified by  : Tutorials point/user2
   //- >
</script>

    63 Lectures 
     4 hours 

 Frahaan Hussain
 Print
 Add Notes
 Bookmark this page
XML - WhiteSpaces

In this chapter, we will discuss whitespace handling in XML documents. Whitespace is a collection of spaces, tabs, and newlines. They are generally used to make a document more readable.
XML document contains two types of whitespaces - Significant Whitespace and Insignificant Whitespace. Both are explained below with examples.
A significant Whitespace occurs within the element which contains text and markup present together. For example −
<name>TanmayPatil</name>
and
<name>Tanmay Patil</name>
The above two elements are different because of the space between Tanmay and Patil. Any program reading this element in an XML file is obliged to maintain the distinction.
Insignificant whitespace means the space where only element content is allowed. For example −
<address.category = "residence">
<address....category = "..residence">
The above examples are same. Here, the space is represented by dots (.). In the above
example, the space between address and category is insignificant.
A special attribute named xml:space may be attached to an element. This indicates that whitespace should not be removed for that element by the application. You can set this attribute to default or preserve as shown in the following example −
<!ATTLIST address  xml:space (default|preserve) 'preserve'>

Where,
The value default signals that the default whitespace processing modes of an application are acceptable for this element.
The value default signals that the default whitespace processing modes of an application are acceptable for this element.
The value preserve indicates the application to preserve all the whitespaces.
The value preserve indicates the application to preserve all the whitespaces.

    84 Lectures 
     6 hours 

 Frahaan Hussain

    29 Lectures 
     2 hours 

 YouAccel

    27 Lectures 
     1 hours 

 Jordan Stanchev

    16 Lectures 
     2 hours 

 Simon Sez IT
 Print
 Add Notes
 Bookmark this page
How to subtract one polynomial to another using NumPy in Python? - GeeksforGeeks

29 Aug, 2020
In this article, let’s discuss how to subtract one polynomial to another. Two polynomials are given as input and the result is the subtraction of two polynomials.
The polynomial p(x) = C3 x2 + C2 x + C1  is represented in NumPy as : ( C1, C2, C3 ) { the coefficients (constants)}.
Let take two polynomials p(x) and q(x) then subtract these to get r(x) = p(x) – q(x) as a result of subtraction of two input polynomials.
If p(x) = A3 x2 + A2 x + A1 
and
q(x) = B3 x2 + B2 x + B1 

then result is 
r(x) = p(x) - q(x) i.e;
r(x) = (A3 - B3) x2 + (A2 - B2) x + (A1 - B1) 

and output is 
( (A1 - B1), (A2 - B2), (A3 - B3) ).

In NumPy, it can be solved using the polysub() method. This function helps to find the difference of two polynomials and then returning the result as a polynomial
Below is the implementation with some examples :
Example 1:  Using  polysub()
Python3
# importing packageimport numpy  # define the polynomials# p(x) = 5(x**2) + (-2)x +5px = (5,-2,5)  # q(x) = 2(x**2) + (-5)x +2qx = (2,-5,2)  # subtract the polynomialsrx = numpy.polynomial.polynomial.polysub(px,qx)  # print the resultant polynomialprint(rx)
Output :
[ 3.  3.  3.]
Example 2: sub_with_decimals
Python3
# importing packageimport numpy  # define the polynomials# p(x) = 2.2px = (0,0,2.2)  # q(x) = 9.8(x**2) + 4qx = (9.8,0,4)  # subtract the polynomialsrx = numpy.polynomial.polynomial.polysub(px,qx)  # print the resultant polynomialprint(rx)
Output :
[-9.8  0.  -1.8]

Example 3:  #eval_then_sub
Python3
# importing packageimport numpy  # define the polynomials# p(x) = (5/3)xpx = (0,5/3,0)  # q(x) = (-7/4)(x**2) + (9/5)qx = (-7/4,0,9/5)  # subtract the polynomialsrx = numpy.polynomial.polynomial.polysub(px,qx)  # print the resultant polynomialprint(rx)
Output :
[ 1.75        1.66666667 -1.8       ]       

Python numpy-Mathematical Function
Python-numpy
Python
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
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Defaultdict in Python
Python | Get unique values from a list
Create a directory in Python
Python | Pandas dataframe.groupby()
Python | Ways to change keys in dictionary - GeeksforGeeks

28 Feb, 2019
Given a dictionary, the task is to change the key based on the requirement. Let’s see different methods we can do this task.
Method #1 : Using naive method
# Python code to demonstrate# changing keys of dictionary# using naive method  # inititialising dictionaryini_dict = {'nikhil': 1, 'vashu' : 5,            'manjeet' : 10, 'akshat' : 15}  # printing initial jsonprint ("initial 1st dictionary", ini_dict)  # changing keys of dictionaryini_dict['akash'] = ini_dict['akshat']del ini_dict['akshat']    # printing final resultprint ("final dictionary", str(ini_dict))
initial 1st dictionary {‘akshat’: 15, ‘nikhil’: 1, ‘manjeet’: 10, ‘vashu’: 5}final dictionary {‘akash’: 15, ‘nikhil’: 1, ‘manjeet’: 10, ‘vashu’: 5}
 Method #2: Using pop()
# Python code to demonstrate# changing keys of dictionary# using pop() method  # inititialising dictionaryini_dict = {'nikhil': 1, 'vashu' : 5,             'manjeet' : 10, 'akshat' : 15}  # printing initial jsonprint ("initial 1st dictionary", ini_dict)  # changing keys of dictionaryini_dict['akash'] = ini_dict.pop('akshat')  # printing final resultprint ("final dictionary", str(ini_dict))
initial 1st dictionary {‘akshat’: 15, ‘manjeet’: 10, ‘vashu’: 5, ‘nikhil’: 1}final dictionary {‘akash’: 15, ‘manjeet’: 10, ‘vashu’: 5, ‘nikhil’: 1}
 Method #3: Using zip()
Suppose we want to change all keys of dictionary.
# Python code to demonstrate# changing all keys of dictionary# corresponding to list using zip()  # inititialising dictionaryini_dict = {'nikhil': 1, 'vashu' : 5,             'manjeet' : 10, 'akshat' : 15}  # initialising listini_list = ['a', 'b', 'c', 'd']  # printing initial jsonprint ("initial 1st dictionary", ini_dict)  # changing keys of dictionaryfinal_dict = dict(zip(ini_list, list(ini_dict.values())))  # printing final resultprint ("final dictionary", str(final_dict))
initial 1st dictionary {‘akshat’: 15, ‘manjeet’: 10, ‘vashu’: 5, ‘nikhil’: 1}final dictionary {‘c’: 5, ‘d’: 1, ‘a’: 15, ‘b’: 10}
Marketing
Python dictionary-programs
python-dict
Python
Python Programs
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Python program to convert a list to string
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python program to check whether a number is Prime or not
Python | Convert a list to dictionary
Difference between Class and Structure in C# - GeeksforGeeks

18 May, 2020
A class is a user-defined blueprint or prototype from which objects are created. Basically, a class combines the fields and methods(member function which defines actions) into a single unit.
Example:
// C# program to illustrate the// concept of classusing System;  // Class Declarationpublic class Author {      // Data members of class    public string name;    public string language;    public int article_no;    public int improv_no;      // Method of class    public void Details(string name, string language,                        int article_no, int improv_no)    {        this.name = name;        this.language = language;        this.article_no = article_no;        this.improv_no = improv_no;          Console.WriteLine("The name of the author is :  " + name                          + "\nThe name of language is : " + language                          + "\nTotal number of article published  "                           + article_no + "\nTotal number of Improvements:"                          +" done by author is : " + improv_no);    }      // Main Method    public static void Main(String[] args)    {          // Creating object        Author obj = new Author();          // Calling method of class        // using class object        obj.Details("Ankita", "C#", 80, 50);    }}
The name of the author is :  Ankita
The name of language is : C#
Total number of article published  80
Total number of Improvements: done by author is : 50

A structure is a collection of variables of different data types under a single unit. It is almost similar to a class because both are user-defined data types and both hold a bunch of different data types.
Example:
// C# program to illustrate the// concept of structureusing System;  // Defining structurepublic struct Car{      // Declaring different data types    public string Brand;    public string Model;    public string Color;}  class GFG {      // Main Method    static void Main(string[] args)    {          // Declare c1 of type Car        // no need to create an         // instance using 'new' keyword        Car c1;          // c1's data        c1.Brand = "Bugatti";        c1.Model = "Bugatti Veyron EB 16.4";        c1.Color = "Gray";          // Displaying the values        Console.WriteLine("Name of brand: " + c1.Brand +                           "\nModel name: " + c1.Model +                           "\nColor of car: " + c1.Color);    }}
Name of brand: Bugatti
Model name: Bugatti Veyron EB 16.4
Color of car: Gray

zeuss
CSharp-OOP
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Dictionary with examples
Destructors in C#
C# | Delegates
Extension Method in C#
C# | String.IndexOf( ) Method | Set - 1
Introduction to .NET Framework
C# | Abstract Classes
C# | Data Types
HashSet in C# with Examples
Top 50 C# Interview Questions & Answers
java.lang.reflect.Field.getType() Method Example

The java.lang.reflect.Field.getType() method returns a Class object that identifies the declared type for the field represented by this Field object.
Following is the declaration for java.lang.reflect.Field.getType() method.
public Class<?> getType()

a Class object identifying the declared type of the field represented by this object.
The following example shows the usage of java.lang.reflect.Field.getType() method.
package com.tutorialspoint;

import java.lang.reflect.Field;

public class FieldDemo {

   public static void main(String[] args) throws NoSuchFieldException, 
      SecurityException, IllegalArgumentException, IllegalAccessException {
          
      Field field = SampleClass.class.getField("sampleField");
      System.out.println(field.getType());
   }
}

class SampleClass {
   public static long sampleField = 5;
}
Let us compile and run the above program, this will produce the following result −
long

 Print
 Add Notes
 Bookmark this page
Python | Pandas Series.ffill()

13 Feb, 2019
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index.
Pandas Series.ffill() function is synonym for forward fill. This function is used t fill the missing values in the given series object using forward fill method.
Syntax: Series.ffill(axis=None, inplace=False, limit=None, downcast=None)
Parameter :axis : {0 or ‘index’}inplace : If True, fill in place.limit : If method is specified, this is the maximum number of consecutive NaN values to forward/backward filldowncast : dict, default is None
Returns : filled : Series
Example #1: Use Series.ffill() function to fill out the missing values in the given series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', None, 'Rio'])  # Create the Indexsr.index = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5']   # set the indexsr.index = index_  # Print the seriesprint(sr)
Output :
Now we will use Series.ffill() function to fill out the missing values in the given series object.
# fill the missing valuesresult = sr.ffill()  # Print the resultprint(result)
Output :As we can see in the output, the Series.ffill() function has successfully filled out the missing values in the given series object. Example #2 : Use Series.ffill() function to fill out the missing values in the given series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series([100, None, None, 18, 65, None, 32, 10, 5, 24, None])  # Create the Indexindex_ = pd.date_range('2010-10-09', periods = 11, freq ='M')  # set the indexsr.index = index_  # Print the seriesprint(sr)
Output :
Now we will use Series.ffill() function to fill out the missing values in the given series object.
# fill the missing valuesresult = sr.ffill()  # Print the resultprint(result)
Output :As we can see in the output, the Series.ffill() function has successfully filled out the missing values in the given series object.
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Create a directory in Python
Python – Product of two Dictionary Keys

17 Dec, 2019
Sometimes, while working with dictionaries, we might have utility problem in which we need to perform elementary operation among the common keys of dictionaries. This can be extended to any operation to be performed. Let’s discuss product of like key values and ways to solve it in this article.
Method #1 : Using dictionary comprehension + keys()The combination of above two can be used to perform this particular task. This is just a shorthand to the longer method of loops and can be used to perform this task in one line.
# Python3 code to demonstrate working of# Dictionary Keys Product# Using dictionary comprehension + keys()  # Initialize dictionariestest_dict1 = {'gfg' : 6, 'is' : 4, 'best' : 7}test_dict2 = {'gfg' : 10, 'is' : 6, 'best' : 10}  # printing original dictionaries print("The original dictionary 1 : " + str(test_dict1))print("The original dictionary 2 : " + str(test_dict2))  # Using dictionary comprehension + keys()# Dictionary Keys Productres = {key: test_dict2[key] * test_dict1.get(key, 0)                        for key in test_dict2.keys()}  # printing result print("The product dictionary is : " + str(res))
The original dictionary 1 : {'best': 7, 'is': 4, 'gfg': 6}
The original dictionary 2 : {'best': 10, 'is': 6, 'gfg': 10}
The product dictionary is : {'best': 70, 'is': 24, 'gfg': 60}

 
Method #2 : Using Counter() + “*” operatorThe combination of above method can be used to perform this particular task. In this, the Counter function converts the dictionary in the form in which the minus operator can perform the task of multiplication.
# Python3 code to demonstrate working of# Dictionary Keys Product# Using Counter() + "*" operatorfrom collections import Counter  # Initialize dictionariestest_dict1 = {'gfg' : 6, 'is' : 4, 'best' : 7}test_dict2 = {'gfg' : 10, 'is' : 6, 'best' : 10}  # printing original dictionaries print("The original dictionary 1 : " + str(test_dict1))print("The original dictionary 2 : " + str(test_dict2))  # Using Counter() + "*" operator# Dictionary Keys Producttemp1 = Counter(test_dict1)temp2 = Counter(test_dict2)res = Counter({key : temp1[key] * temp2[key] for key in temp1})  # printing result print("The product dictionary is : " + str(dict(res)))
The original dictionary 1 : {'best': 7, 'is': 4, 'gfg': 6}
The original dictionary 2 : {'best': 10, 'is': 6, 'gfg': 10}
The product dictionary is : {'best': 70, 'is': 24, 'gfg': 60}

Python dictionary-programs
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
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
SQL Query to Create Table With a Primary Key

13 Sep, 2021
A primary key uniquely identifies each row table. It must contain unique and non-NULL values. A table can have only one primary key, which may consist of single or multiple fields. When multiple fields are used as a primary key, they are called composite keys.
To create a Primary key in the table, we have to use a keyword; “PRIMARY KEY ( )”
Query:
CREATE TABLE `Employee` ( `Emp_ID` VARCHAR(20) NOT NULL ,`Name` VARCHAR(50) NOT NULL ,  
`Age` INT NOT NULL ,`Phone_No` VARCHAR(10) NOT NULL ,`Address` VARCHAR(100) NOT NULL ,
 PRIMARY KEY (`Emp_ID`));
To view whether “Emp_ID” is the primary key or not we use Describe command to view the structure of the Table.
DESCRIBE is used to describe something. Since in database we have tables, that’s why we use DESCRIBE or DESC(both are same) command to describe the structure of a table.
Query:
DESCRIBE Employee;
Or 
DESC Employee;
Output:
Now, to create a PRIMARY KEY constraint on any column when the table already exists (NO EARLIER PRIMARY KEY DEFINED), use the following SQL Syntax:
ALTER TABLE [Table_Name] ADD PRIMARY KEY (ID);
Query:
ALTER TABLE Employee ADD PRIMARY KEY (Phone_No);
Output:
If any earlier primary key is defined, then there will be errors like;
Output:
This error is because; Only one primary key can exist. So, we have to first delete the initial PRIMARY KEY to create a new PRIMARY KEY.
 
1. To create PRIMARY KEY on multiple columns:
Query:
CREATE TABLE `Employee` ( `Emp_ID` VARCHAR(20) NOT NULL ,
                      `Name` VARCHAR(50) NOT NULL ,  
                      `Age` INT NOT NULL ,  
                      `Phone_No` VARCHAR(10) NOT NULL ,
                      `Address` VARCHAR(100) NOT NULL ,
                      PRIMARY KEY (`Emp_ID`,`Name`));
Output:
2. Add Multiple Primary Keys when Table already existing
Query:
ALTER TABLE Employee
 ADD CONSTRAINT PK_CUSTID PRIMARY KEY (Emp_ID, NAME);
 DESC Employee;
Output:
Blogathon-2021
Picked
SQL-Query
Blogathon
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Import JSON Data into SQL Server?
SQL Query to Convert Datetime to Date
Python program to convert XML to Dictionary
Scrape LinkedIn Using Selenium And Beautiful Soup in Python
How to toggle password visibility in forms using Bootstrap-icons ?
SQL | DDL, DQL, DML, DCL and TCL Commands
SQL | Join (Inner, Left, Right and Full Joins)
SQL | WITH clause
How to find Nth highest salary from a table
CTE in SQL
Take Matrix input from user in Python

30 Dec, 2020
Matrix is nothing but a rectangular arrangement of data or numbers. In other words, it is a rectangular array of data or numbers. The horizontal entries in a matrix are called as ‘rows’ while the vertical entries are called as ‘columns’. If a matrix has r number of rows and c number of columns then the order of matrix is given by r x c. Each entries in a matrix can be integer values, or floating values, or even it can be complex numbers.
Examples:
// 3 x 4 matrix
     1 2 3 4
M =  4 5 6 7
     6 7 8 9

// 2 x 3 matrix in Python
A = ( [ 2, 5, 7 ],
      [ 4, 7, 9 ] )

// 3 x 4 matrix in Python where entries are floating numbers
B = ( [ 1.0, 3.5, 5.4, 7.9 ],
      [ 9.0, 2.5, 4.2, 3.6 ],
      [ 1.5, 3.2, 1.6, 6.5 ] )
In Python, we can take a user input matrix in different ways. Some of the methods for user input matrix in Python are shown below:
Code #1:
# A basic code for matrix input from user  R = int(input("Enter the number of rows:"))C = int(input("Enter the number of columns:"))  # Initialize matrixmatrix = []print("Enter the entries rowwise:")  # For user inputfor i in range(R):          # A for loop for row entries    a =[]    for j in range(C):      # A for loop for column entries         a.append(int(input()))    matrix.append(a)  # For printing the matrixfor i in range(R):    for j in range(C):        print(matrix[i][j], end = " ")    print()
Output:
Enter the number of rows:2
Enter the number of columns:3
Enter the entries rowwise:
1
2
3
4
5
6

1 2 3 
4 5 6 

One liner:
# one-liner logic to take input for rows and columnsmat = [[int(input()) for x in range (C)] for y in range(R)]
 Code #2: Using map() function and Numpy.
In Python, there exists a popular library called NumPy. This library is a fundamental library for any scientific computation. It is also used for multidimensional arrays and as we know matrix is a rectangular array, we will use this library for user input matrix.
import numpy as np  R = int(input("Enter the number of rows:"))C = int(input("Enter the number of columns:"))    print("Enter the entries in a single line (separated by space): ")  # User input of entries in a # single line separated by spaceentries = list(map(int, input().split()))  # For printing the matrixmatrix = np.array(entries).reshape(R, C)print(matrix)
Output:
Enter the number of rows:2
Enter the number of columns:2
Enter the entries in a single line separated by space: 1 2 3 1 
[[1 2]
 [3 1]]
mkumarchaudhary06
Picked
Python matrix-program
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
How to Maintain Insertion Order of the Elements in Java HashMap?

04 Jan, 2021
When elements get from the HashMap due to hashing the order they inserted is not maintained while retrieval. We can achieve the given task using LinkedHashMap. The LinkedHashMap class implements a doubly-linked list so that it can traverse through all the elements.
Example:
Input : HashMapInput = {c=6, a=1, b=2}
Output: HashMapPrint = {c=6, a=1, b=2}

Input : HashMapInput = {"first"=1, "second"=3}
Output: HashMapPrint = {"first"=1, "second"=3}
Syntax:
public LinkedHashMap(Map m)
It creates an object of the LinkedHashMap class with the same mappings specified in the original Map object.
Order Not Maintain Here: HashMap Implementation:
Java
// Java Program to maintain insertion order// of the elements in HashMap  // Using HashMap (Order not maintain)import java.io.*;import java.util.*;class GFG {      public static void main(String args[])    {          // creating a hashmap        HashMap<String, String> hm = new HashMap<>();          // putting elements        hm.put("01", "aaaaaaa");        hm.put("03", "bbbbbbb");        hm.put("04", "zzzzzzz");        hm.put("02", "kkkkkkk");          System.out.println("Iterate over original HashMap");                // printing hashmap        for (Map.Entry<String, String> entry :             hm.entrySet()) {            System.out.println(entry.getKey() + " => "                               + ": " + entry.getValue());        }    }}
Iterate over original HashMap
01 => : aaaaaaa
02 => : kkkkkkk
03 => : bbbbbbb
04 => : zzzzzzz
Here, the original insertion order of HashMap is [01, 03, 04, 02], but the output is different [01, 02, 03, 04]. It did not maintain the original insertion order of the elements.
Order Maintain Here: LinkedHashMap implementation
Java
// Java Program to maintain insertion order// of the elements in HashMap  // LinkedHashMapimport java.io.*;import java.util.*;class GFG {      public static void main(String args[])    {          // creating a hashmap        HashMap<String, String> hm = new LinkedHashMap<>();          // putting elements        hm.put("01", "aaaaaaa");        hm.put("03", "bbbbbbb");        hm.put("04", "zzzzzzz");        hm.put("02", "kkkkkkk");          // printing LinkedHashMap        System.out.println("Iterate over LinkedHashMap");        for (Map.Entry<String, String> entry :             hm.entrySet()) {            System.out.println(entry.getKey() + " => "                               + ": " + entry.getValue());        }    }}
Iterate over LinkedHashMap
01 => : aaaaaaa
03 => : bbbbbbb
04 => : zzzzzzz
02 => : kkkkkkk
Java-LinkedHashMap
Picked
Java
Java Programs
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
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
Factory method design pattern in Java
Java Program to Remove Duplicate Elements From the Array
Python – Sort Dictionary key and values List

02 Jun, 2020
Sometimes, while working with Python dictionaries, we can have a problem in which we need to perform the sorting of it, wrt keys, but also can have a variation in which we need to perform a sort on its values list as well. Let’s discuss certain way in which this task can be performed.
Input : test_dict = {‘c’: [3], ‘b’: [12, 10], ‘a’: [19, 4]}Output : {‘a’: [4, 19], ‘b’: [10, 12], ‘c’: [3]}
Input : test_dict = {‘c’: [10, 34, 3]}Output : {‘c’: [3, 10, 34]}
Method #1 : Using sorted() + loopThe combination of above functions can be used to solve this problem. In this, we initially sort all the values of keys, and then perform the keys sorting after that, in brute manner.
# Python3 code to demonstrate working of # Sort Dictionary key and values List# Using loop + dictionary comprehension  # initializing dictionarytest_dict = {'gfg': [7, 6, 3],              'is': [2, 10, 3],              'best': [19, 4]}  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # Sort Dictionary key and values List# Using loop + dictionary comprehensionres = dict()for key in sorted(test_dict):    res[key] = sorted(test_dict[key])  # printing result print("The sorted dictionary : " + str(res)) 
The original dictionary is : {‘gfg’: [7, 6, 3], ‘is’: [2, 10, 3], ‘best’: [19, 4]}The sorted dictionary : {‘best’: [4, 19], ‘gfg’: [3, 6, 7], ‘is’: [2, 3, 10]}
 
Method #2: Using dictionary comprehension + sorted()The combination of above functions can be used to solve this problem. In this, we perform the task of dual sorting inside dictionary comprehension construct.
# Python3 code to demonstrate working of # Sort Dictionary key and values List# Using dictionary comprehension + sorted()  # initializing dictionarytest_dict = {'gfg': [7, 6, 3],              'is': [2, 10, 3],              'best': [19, 4]}  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # Sort Dictionary key and values List# Using dictionary comprehension + sorted()res = {key : sorted(test_dict[key]) for key in sorted(test_dict)}  # printing result print("The sorted dictionary : " + str(res)) 
The original dictionary is : {‘gfg’: [7, 6, 3], ‘is’: [2, 10, 3], ‘best’: [19, 4]}The sorted dictionary : {‘best’: [4, 19], ‘gfg’: [3, 6, 7], ‘is’: [2, 3, 10]}
Python dictionary-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 ?
Python Classes and Objects
Python | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
Macro Processor

06 Oct, 2020
A Macro instruction is the notational convenience for the programmer. For every occurrence of macro the whole macro body or macro block of statements gets expanded in the main source code. Thus Macro instructions make writing code more convenient. 
Salient features of Macro Processor: 
Macro represents a group of commonly used statements in the source programming language.
Macro Processor replaces each macro instruction with the corresponding group of source language statements. This is known as the expansion of macros.
Using Macro instructions programmer can leave the mechanical details to be handled by the macro processor.
Macro Processor designs are not directly related to the computer architecture on which it runs.
Macro Processor involves definition, invocation, and expansion.
Macro Definition and Expansion: 

Line                 Label                 Opcode                 Operand
  
5                    COPY                  START                  0
10                   RDBUFF                MACRO                  &INDEV, &BUFADR
15                   
.
.
90
95                                         MEND

Line 10: RDBUFF (Read Buffer) in the Label part is the name of the Macro or definition of the Macro. &INDEV and &BUFADR are the parameters present in the Operand part. Each parameter begins with the character &. 
Line 15 – Line 90: From Line 15 to Line 90 Macro Body is present. Macro directives are the statements that make up the body of the macro definition. 
Line 95: MEND is the assembler directive that means the end of the macro definition.  
Macro Invocation: 

Line                 Label                 Opcode                 Operand
  
180                  FIRST                 STL                    RETADR
190                  CLOOP                 RDBUFF                 F1, BUFFER
15                   
.
.
255                                         END                    FIRST

Line 190: RDBUFF is the Macro invocation or Macro Call that gives the name of the macro instruction being invoked and F1, BUFFER are the arguments to be used in expanding the macro. The statement that form the expansion of a macro are generated each time the macro is invoked. 
PanchajanyaSarkar
Computer Organization & Architecture
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Direct Access Media (DMA) Controller in Computer Architecture
Architecture of 8085 microprocessor
Control Characters
Pin diagram of 8086 microprocessor
I2C Communication Protocol
Computer Organization and Architecture | Pipelining | Set 2 (Dependencies and Data Hazard)
Difference between SRAM and DRAM
Difference between Hardwired and Micro-programmed Control Unit | Set 2
Cache Coherence
Difference between RISC and CISC processor | Set 2
Selenium Webdriver - Double Click

Selenium can perform mouse movements, key press, hovering on an element, double click, drag and drop actions, and so on with the help of the ActionsChains class. The method double_click performs double-click on an element.
The syntax for using the double click is as follows:
double_click(e=None)

Here, e is the element to be double-clicked. If None is mentioned, the click is performed on the present mouse position. We have to add the statement from selenium.webdriver import ActionChains to work with the ActionChains class.
Let us perform the double click on the below element −
In the above image, it is seen that on double clicking the Double Click me! button, an alert box gets generated.
The code implementation for using the double click is as follows −
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.alert import Alert
driver = webdriver.Chrome(executable_path='../drivers/chromedriver')
#implicit wait time
driver.implicitly_wait(5)
#url launch
driver.get("http://www.uitestpractice.com/Students/Actions")
#identify element
s = driver.find_element_by_name("dblClick")
#object of ActionChains
a = ActionChains(driver)
#right click then perform
a.double_click(s).perform()
#switch to alert
alrt = Alert(driver)
# get alert text
print(alrt.text)
#accept alert
alrt.accept()
#driver quit
driver.quit()
The output shows the message - Process with exit code 0 meaning that the above Python code executed successfully. Also, the Alert text - Double Clicked! gets printed in the console. The Alert got generated by double clicking the Double Click me! button.

    46 Lectures 
     5.5 hours 

 Aditya Dua

    296 Lectures 
     146 hours 

 Arun Motoori

    411 Lectures 
     38.5 hours 

 In28Minutes Official

    22 Lectures 
     7 hours 

 Arun Motoori

    118 Lectures 
     17 hours 

 Arun Motoori

    278 Lectures 
     38.5 hours 

 Lets Kode It
 Print
 Add Notes
 Bookmark this page
How to get the complete screenshot of a page in Selenium with python?

We can get the complete screenshot of a page in Selenium. While
executing any test cases, we might encounter failures. To keep track of the failures
we capture a screenshot of the web page where the error exists.
In a test case, there may be failure for reasons listed below −
If the assertion does not pass.
If there are sync issues between our application and Selenium.
If there are timeout issues.
If an alert appears in between.
If the element cannot be identified with the locators.
If the actual and final results are not matching.
For capturing the screenshot, save_screenshot() method is available. This method
takes the full page screenshot.
driver.save_screenshot("screenshot_t.png")
In the arguments, we have to provide the screenshot file name along with the
extension of .png. If anything else is used as extension, a warning message will be
thrown and the image cannot be viewed.
The screenshot gets saved in the same path of the program.
Code Implementation for full page screenshot.
from selenium import webdriver
#browser exposes an executable file
#Through Selenium test we will invoke the executable file which will then
#invoke actual browser
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
# to maximize the browser window
driver.maximize_window()
#get method to launch the URL
driver.get("https://www.tutorialspoint.com/index.htm")
#to refresh the browser
driver.refresh()
#to get the screenshot of complete page
driver.save_screenshot("screenshot_tutorialspoint.png")
#to close the browser
driver.close()
Can we throw an Unchecked Exception from a static block in java?

A static block is a block of code with a static keyword. In general, these are used to initialize the static members. JVM executes static blocks before the main method at the time of class loading.
 Live Demo
public class MyClass {
   static{
      System.out.println("Hello this is a static block");
   }
   public static void main(String args[]){
      System.out.println("This is main method");
   }
}
Hello this is a static block
This is main method
Just like any other method in Java when an exception occurs in static block you can handle it using try-catch pair.
 Live Demo
import java.io.File;
import java.util.Scanner;
public class ThrowingExceptions{
   static String path = "D://sample.txt";
   static {
      try {
         Scanner sc = new Scanner(new File(path));
         StringBuffer sb = new StringBuffer();
         sb.append(sc.nextLine());
         String data = sb.toString();
         System.out.println(data);
      } catch(Exception ex) {
         System.out.println("");
      }
   }
   public static void main(String args[]) {
   }
}
This is a sample fileThis is main method
Whenever you throw a checked exception you need to handle it in the current method or, you can throw (postpone) it to the calling method.
You cannot use throws keyword with a static block, and more over a static block is invoked at compile time (at the time of class loading) no method invokes it.
Herefore, if you throw an exception using the throw keyword in a static block you must wrap it within try-catch blocks else a compile time error will be generated.
 Live Demo
import java.io.FileNotFoundException;
public class ThrowingExceptions{
   static String path = "D://sample.txt";
   static {
      FileNotFoundException ex = new FileNotFoundException();
      throw ex;
   }
   public static void main(String args[]) {
   }
}
ThrowingExceptions.java:4: error: initializer must be able to complete normally
      static {
      ^
ThrowingExceptions.java:6: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
      throw ex;
      ^
2 errors
Convert an integer to a hex string in C++

In this program we will see how to convert an integer to hex string. To convert an integer into hexadecimal string we can follow mathematical steps. But in this case we have solved this problem using simple trick.
In C / C++ there is a format specifier %X. It prints the value of some variable into hexadecimal form. We have used this format specifier to convert number into a string by using sprintf() function.
Input: An integer number 255
Output: FF
Step 1:Take a number from the user
Step 2: Make a string after converting number using %X format specifier
Step 3: Print the result.
Step 4: End
 Live Demo
#include<iostream>
using namespace std;
main() {
   int n;
   char hex_string[20];
   cout << "Enter a number: ";
   cin >> n;
   sprintf(hex_string, "%X", n); //convert number to hex
   cout << hex_string;
}
Enter a number: 250
FA
How to restart a remote system using PowerShell?

To restart the remote computer, you need to use the Restart-Computer command provided by the computer name. For example,
Restart-Computer -ComputerName Test1-Win2k12
The above command will restart computer Test1-Win2k12 automatically and if you have multiple remote computers to restart then you can provide multiple computers separated with comma (,).For example,
Restart-Computer -ComputerName Test1-Win2k12, Test2-Win2k12
Restart signal will be sent to both the computers at a time in the above example.
You can also use the Pipeline to restart remote computers. For example,
"Test1-Win2k12","Test2-Win2k12" | Restart-Computer -Verbose
OR
(Get-Content C:\Servers.txt) | Restart-Computer -Verbose

Few servers have dependencies on the other servers so main servers need to restart first. For
example, AD and Exchange servers. If you are giving both the servers in the same command line then
both servers will reboot at the same time and this is what we don't need it. To overcome this solution, you need to pass each server one at a time, write a few steps for server post-reboot checklist, and then move on to the next server. You can add servers to the array or text file and then pass a single value through foreach loop and the steps for the post-reboot checklist and move on to
the next server.
People often confuse with the - Wait parameter in the Restart-Computer cmdlet that - Wait parameter will reboot one server at a time after the server post-reboot checklist completes but - Wait parameter only performs the three major checklists like WinRM, WMI and PowerShell connectivity check on the remote computer for each computer specified in the cmdlet after server comes up but it can't hold the execution of servers reboot.
Restart-Computer shoots reboot command on all the computers and - Wait parameter does the checks on each computer the specified tests and even if the remote computer failed in checks, servers will reboot.
When anyone is logged on to the remote server(s), PowerShell failed to restart the remote server
and throws the below error message.
PS C:\Users\Administrator> Restart-Computer test1-win2k12 –Verbose
VERBOSE: Performing the operation "Enable the Remote shutdown access rights
and restart the computer." on target "test1-win2k12".
Restart-Computer : Failed to restart the computer test1-win2k12 with the
following error message:
The system shutdown cannot be initiated because there are other users logged
on to thecomputer.
At line:1 char:1+ Restart-Computer test1-win2k12 -Verbose+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (test1-win2k12:String) [Restart-
Computer], InvalidOperationException
+ FullyQualifiedErrorId :
RestartcomputerFailed,Microsoft.PowerShell.Commands.RestartComputerCommand
To restart the computer forcefully, you need to use -Force parameter.
Restart-Computer Test1-Win2k12 -Force
How to change the order of bars in bar chart in R?

This can be done by setting the levels of the variable in the order we want.
> data <- data.frame(Class=c("Highschool","Highschool","Graduate","Graduate",
"Graduate","Graduate","Masters","Masters","Masters","PhD"))
Setting the levels in decreasing order
> data <- within(data,
Class <- factor(Class,
levels=names(sort(table(Class),
decreasing=TRUE))))
> library(ggplot2)
> ggplot(data, aes(x = Class)) + geom_bar()
Setting the levels in increasing order
> data <- within(data,
Class <- factor(Class,
levels=names(sort(table(Class),
decreasing=TRUE))))
> ggplot(data, aes(x = Class)) + geom_bar()
String slicing in C# to rotate a string

Let’s say our string is −
var str = "welcome";
Use the substring() method and the following, if you want to rotate only some characters. Here, we are rotating only 2 characters −
var res = str.Substring(1, str.Length - 1) + str.Substring(0, 2);
The following is the complete code −
 Live Demo
using System;

public class Program {
   public static void Main() {
      var str = "welcome";

      Console.WriteLine("Original String = "+str);
      var res = str.Substring(1, str.Length - 1) + str.Substring(0, 2);

      Console.WriteLine("Rotating two characters in the String: "+res);
   }
}
Original String = welcome
Rotating two characters in the String: elcomewe
Error Bar plots from a Data Frame using Matplotlib in Python | by Kalyan Keesara | Towards Data Science

I recently had to compare the performance of a few approaches/algorithms for a report and I chose error bars to summarize the results. If you have a similar task at hand, save yourself some time with this article.
Error bar charts are a great way to represent the variability in your data. In simpler words, they give an intuitive idea of how far the data could be from the reported value (or mean in most cases).
This could typically be done by using:
Standard Deviation
Confidence Interval (preferably 95)
If your report needs to make a comment on the precision (or reproducibility) of the displayed result, error bar charts are a must in my personal opinion. I have also come across a few reports using it to present tolerances in suitable cases.
But of course, be sure that you have the right audience that can interpret your fancy visualizations.
For the sake of simplicity, I have created a sample data using a random number generator on Excel. You can use mean() and std() functions to quickly calculate the mean and standard deviation of your data.
Import Matplotlib and use the errorbar() function from Matplotlib. It offers a fairly decent level of customization for the plot.
import pandas as pd ## for handling the dataframeimport matplotlib.pyplot as plt ## for visualizationdf = pd.read_excel("Sample_error_charts.xlsx")## read the Dataframe##Plotplt.errorbar( df['Model'], df['Mean'], yerr=df['SD'], fmt='o', color='Black', elinewidth=3,capthick=3,errorevery=1, alpha=1, ms=4, capsize = 5)plt.bar(df['Model'], df['Mean'],tick_label = df['Model'])##Bar plotplt.xlabel('Model') ## Label on X axisplt.ylabel('Average Performance') ##Label on Y axis
Make sure to tweak the capsize and thickness to suit your graph.
I have picked Standard deviation here in the example but you can use confidence Intervals or standard error as well, depending on what suits your overall narrative. Get yourself thoroughly acquainted with basic descriptive statistics and it would all make more sense immediately on what to pick.
How to sort an ArrayList in Descending Order in Java

To sort an ArrayList, you need to use the Collections.sort() method. This sorts in ascending order, but if you want to sort the ArrayList in descending order, use the Collections.reverseOrder() method as well. This gets included as a parameter −
Collections.sort(myList, Collections.reverseOrder());
Following is the code to sort an ArrayList in descending order in Java −
 Live Demo
import java.util.ArrayList;
import java.util.Collections;
public class Demo {
   public static void main(String args[]) {
      ArrayList<Integer> myList = new ArrayList<Integer>();
      myList.add(30);
      myList.add(99);
      myList.add(12);
      myList.add(23);
      myList.add(8);
      myList.add(94);
      myList.add(78);
      myList.add(87);
      System.out.println("Points\n"+ myList);
      Collections.sort(myList,Collections.reverseOrder());
      System.out.println("Points (descending order)\n"+ myList);
   }
}
Points
[30, 99, 12, 23, 8, 94, 78, 87]
Points (descending order)
[99, 94, 87, 78, 30, 23, 12, 8]
Let us see another example wherein we will sort string values in descending order −
 Live Demo
import java.util.ArrayList;
import java.util.Collections;
public class Demo {
   public static void main(String args[]) {
      ArrayList<String> myList = new ArrayList<String>();
      myList.add("Jack");
      myList.add("Katie");
      myList.add("Amy");
      myList.add("Tom");
      myList.add("David");
      myList.add("Arnold");
      myList.add("Steve");
      myList.add("Tim");
      System.out.println("Names\n"+ myList);
      Collections.sort(myList,Collections.reverseOrder());
      System.out.println("Names (descending order)\n"+ myList);
   }
}
Names
[Jack, Katie, Amy, Tom, David, Arnold, Steve, Tim]
Names (descending order)
[Tom, Tim, Steve, Katie, Jack, David, Arnold, Amy]