code-rag-bench/online-tutorials huggingface dataset:
HTML <select> size Attribute

The size attribute of the <select> element is used to set the number of visible list items from a drop-down list. A scrollbar would get added if the size is set more than 1.
Following is the syntax−
<select size="num">
Above, num is the count of the visible list items in the drop-down list.
Let us now see an example to implement the size attribute of the <select> element−
 Live Demo
<!DOCTYPE html>
<html>
<body>
<h1>Candidate Profile</h1>
<p>Following are the details to be submitted by the candidate:</p>
<h2>Educational Qualification</h2>
<form action="">
<section>
<h3>Graduation</h3>
<select size = "2">
   <option value="bca">BCA</option>
   <option value="bcom">B.COM</option>
   <option value="btech">B.TECH</option>
   <option value="btech">B.SC</option>
</select>
</section>
<section>
<h3>Postgraduation</h3>
<select size="2">
   <option value="mca">MCA</option>
   <option value="mcom">M.COM</option>
   <option value="mtech">M.TECH</option>
   <option value="msc">M.Sc</option>
</select>
</section><br>
<input type="submit" value="Next">
</form>
</body>
</html>
In the above example, we have set two drop-down lists−
<section>
<h3>Graduation</h3>
<select size = "2">
   <option value="bca">BCA</option>
   <option value="bcom">B.COM</option>
   <option value="btech">B.TECH</option>
   <option value="btech">B.SC</option>
</select>
</section>
<section>
<h3>Postgraduation</h3>
<select size="2">
   <option value="mca">MCA</option>
   <option value="mcom">M.COM</option>
   <option value="mtech">M.TECH</option>
   <option value="msc">M.Sc</option>
</select>
</section>
We have set two drop-down lists above with the size attribute that allows to set the number of visible list items−
<select size="2">
How to touch all the  files recursively using Python?

To touch all the  files recursively, you need to walk the directory tree using os.walk and add touch all the files in it using os.utime(path_to_file). 
import os
# Recursively walk the tree
for root, dirs, files in os.walk(path):
    for file in files:
        # Set utime to current time
        os.utime(os.path.join(root, file))
In Python 3.4+, you can directly use the pathlib module to touch files. 
from pathlib import Path
import os
# Recursively walk the tree
for root, dirs, files in os.walk(path):
    for file in files:
        Path(os.path.join(root, file)).touch()
How to get free size of internal/external memory in Android App?

This example demonstrates how do I get the free size of internal/external memory in android app.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:padding="16dp"
   android:orientation="vertical" >
   <TextView
      android:id="@+id/textView"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:textSize="24sp"
      android:textStyle="bold" />
</LinearLayout>
Step 3 − Add the following code to src/MainActivity.java
import android.os.Bundle;
import android.os.Environment;
import android.os.StatFs;
import android.util.Log;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
   TextView textView;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      textView = findViewById(R.id.textView);
      StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
      long bytesAvailable;
      bytesAvailable = stat.getBlockSizeLong() * stat.getAvailableBlocksLong();
      long megAvailable = bytesAvailable / (1024 * 1024);
      textView.setText("Available Internal/External free Space: " + megAvailable + "MB");
   }
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="app.com.sample">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
Java Examples - Deleting a character

How to remove a particular character from a string ?
Following example shows how to remove a character from a particular position from a string with the help of removeCharAt(string,position) method.
public class Main {
   public static void main(String args[]) {
      String str = "this is Java";
      System.out.println(removeCharAt(str, 3));
   }
   public static String removeCharAt(String s, int pos) {
      return s.substring(0, pos) + s.substring(pos + 1);
   }
}
The above code sample will produce the following result.
thi is Java

 Print
 Add Notes
 Bookmark this page
fmt.Sprint() Function in Golang With Examples

05 May, 2020
In Go language, fmt package implements formatted I/O with functions analogous to C’s printf() and scanf() function. The fmt.Sprint() function in Go language formats using the default formats for its operands and returns the resulting string. Here spaces are added between operands when any string is not used as a constant variable. Moreover, this function is defined under the fmt package. Here, you need to import the “fmt” package in order to use these functions.
Syntax:
func Sprint(a ...interface{}) string

Here, “a ...interface{}” contains some strings including specified constant variables.
Returns: It returns the resulting string.
Example 1:
// Golang program to illustrate the usage of// fmt.Sprint() function  // Including the main packagepackage main  // Importing fmt, io and osimport (    "fmt"    "io"    "os")  // Calling mainfunc main() {      // Declaring some const variables    const name, dept = "GeeksforGeeks", "CS"      // Calling Sprint() function    s := fmt.Sprint(name, " is a ", dept, " Portal.\n")      // Calling WriteString() function to write the    // contents of the string "s" to "os.Stdout"    io.WriteString(os.Stdout, s)  }
Output:
GeeksforGeeks is a CS Portal.

Example 2:
// Golang program to illustrate the usage of// fmt.Sprint() function  // Including the main packagepackage main  // Importing fmt, io and osimport (    "fmt"    "io"    "os")  // Calling mainfunc main() {      // Declaring some const variables    const num1, num2, num3 = 5, 10, 15      // Calling Sprint() function    s := fmt.Sprint(num1, num2, num3)      // Calling WriteString() function to write the    // contents of the string "s" to "os.Stdout"    io.WriteString(os.Stdout, s)  }
Output:
5 10 15

In the above code, it can be seen that the function Sprint() is not using any space still space can be seen in the output between the numbers because the function itself added the spaces because not a single string is used as the constant variable.
Example 3:
// Golang program to illustrate the usage of// fmt.Sprint() function  // Including the main packagepackage main  // Importing fmt, io and osimport (    "fmt"    "io"    "os")  // Calling mainfunc main() {      // Declaring some const variables    const str1, str2, str3 = "a", "b", "c"      // Calling Sprint() function    s := fmt.Sprint(str1, str2, str3)      // Calling WriteString() function to write the    // contents of the string "s" to "os.Stdout"    io.WriteString(os.Stdout, s)  }
Output:
abc

In the above code, it can be seen that the function Sprint() is not using any space and also spaces can not be seen in the output in between two alphabets this is because strings are used in the constant variables.
Golang-fmt
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Initialize dictionary with multiple keys

02 Aug, 2019
Sometimes, while working with dictionaries, we might have a problem in which we need to initialize the dictionary with more than one keys with same value. This application requirement can be in domains of web development in which we might want to declare and initialize at the same time. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using loopWe can have a loop which performs this particular task. But this just partially solves our problem of multiple addition but the dictionary has to be declared beforehand for this.
# Python3 code to demonstrate working of# Initialize dictionary with multiple keys# Using loop  # declare dictionarytest_dict = {}  # printing original dictionaryprint("The original dictionary : " +  str(test_dict))  # Initialize keys test_keys = ['gfg', 'is', 'best']  # Using loop# Initialize dictionary with multiple keysfor keys in test_keys:    test_dict[keys] = 4  # printing result print("Dictionary after updating multiple key-value : " + str(test_dict))
The original dictionary : {}Dictionary after updating multiple key-value : {‘is’: 4, ‘gfg’: 4, ‘best’: 4}
 
Method #2 : Using fromkeys()This function is used to actually perform both task of multiple assignment and declaration with a single statement. We also use * operator to pack the values together into a dictionary.
# Python3 code to demonstrate working of# Initialize dictionary with multiple keys# Using fromkeys()  # Initialize keys test_keys = ['gfg', 'is', 'best']  # Using fromkeys()# Initialize dictionary with multiple keysres ={ **dict.fromkeys(test_keys, 4)}   # printing result print("Dictionary after Initializing multiple key-value : " + str(res))
Dictionary after Initializing multiple key-value : {‘gfg’: 4, ‘is’: 4, ‘best’: 4}
Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Matplotlib.pyplot.plot() function in Python

05 Jun, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. There are various plots which can be used in Pyplot are Line Plot, Contour, Histogram, Scatter, 3D Plot, etc.
The plot() function in pyplot module of matplotlib library is used to make a 2D hexagonal binning plot of points x, y.
Syntax: matplotlib.pyplot.plot(\*args, scalex=True, scaley=True, data=None, \*\*kwargs)
Parameters: This method accept the following parameters that are described below:
x, y: These parameter are the horizontal and vertical coordinates of the data points. x values are optional.
fmt: This parameter is an optional parameter and it contains the string value.
data: This parameter is an optional parameter and it is an object with labelled data.
Returns: This returns the following:
lines : This returns the list of Line2D objects representing the plotted data.
Below examples illustrate the matplotlib.pyplot.plot() function in matplotlib.pyplot:
Example 1:
# Implementation of matplotlib function       import matplotlib.pyplot as plt import numpy as np     plt.plot([1, 2, 3]) plt.title('matplotlib.pyplot.plot() example 1') plt.draw() plt.show() 
Output:
Example 2:
# Implementation of matplotlib function     import matplotlib.pyplot as plt import numpy as np     # Fixing random state for reproducibility np.random.seed(19680801)     # create random data xdata = np.random.random([2, 10])     # split the data into two parts xdata1 = xdata[0, :] xdata2 = xdata[1, :]     # sort the data so it makes clean curves xdata1.sort() xdata2.sort()     # create some y data points ydata1 = xdata1 ** 2ydata2 = 1 - xdata2 ** 3    # plot the data plt.plot(xdata1, ydata1, color ='tab:blue') plt.plot(xdata2, ydata2, color ='tab:orange')         # set the limits plt.xlim([0, 1]) plt.ylim([0, 1])   plt.title('matplotlib.pyplot.plot() example 2')     # display the plot plt.show()
Output:
Matplotlib Pyplot-class
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Capturing INSERT Timestamp in Table SQL Server

17 Feb, 2021
While inserting data in tables, sometimes we need to capture insert timestamp in the table. There is a very simple way that we could use to capture the timestamp of the inserted rows in the table.
Capture the timestamp of the inserted rows in the table with DEFAULT constraint in SQL Server.
Use DEFAULT constraint while creating the table:
Syntax:
CREATE TABLE TableName (ColumName INT, ColumnDateTime DATETIME DEFAULT CURRENT_TIMESTAMP)
GO
Example:
Let’s create a table named ‘GeekTab’.
CREATE TABLE GeekTab (ID INT, InDtTm DATETIME DEFAULT CURRENT_TIMESTAMP) ;
GO
Let’s insert few values in the table.
INSERT INTO GeekTab (ID) VALUES (1),  (2) ; 
GO
INSERT INTO GeekTab (ID)VALUES (3), (4) ; 
GO
Now, let’s select the value from the table.
SELECT * FROM GeekTab ;
GO
Output:
Conclusion:
When we select the value from the table GeekTab, we could see that it is having the current timestamp in the table in InDtTm column. This is because the column InDtTm was created with DATETIME DEFAULT CURRENT_TIMESTAMP.
Scenario-based example:
Let us suppose we have table “EmployeeTab”, whenever a new employee joins the company, a new record is inserted in the table:
CREATE TABLE EmployeeTab (Name varchar(100), ID INT, Location varchar(100),
InDtTm DATETIME DEFAULT CURRENT_TIMESTAMP); 
SELECT  Name, ID, Location FROM EmployeeTab ;
To get the insert date and time for each entry as ‘JoinDate’ below query could be used:
SELECT  Name, ID, Location, InDtTm as JoinDate FROM EmployeeTab ;
Note: There is one exception while using this feature and that if anyone inserts the explicit value inside the column ColumnDateTime, the column would have the newly inserted value and not the default value. 
DBMS-SQL
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to change the color of active links with CSS

Use the :active class to change the color of active links. Possible values could be any color name in any valid format. 
You can try to run the following code to implement the color of an active link −
<html>
   <head>
      <style>
         a:active {
            color: #FF00CC
         }
      </style>
   </head>
   <body>
      <a href = "">My Link</a>
   </body>
</html>
Cumulative sum of a column in Pandas - Python - GeeksforGeeks

26 Jul, 2020
Cumulative sum of a column in Pandas can be easily calculated with the use of a pre-defined function cumsum().  
Syntax:  cumsum(axis=None, skipna=True, *args, **kwargs)Parameters: axis: {index (0), columns (1)} skipna: Exclude NA/null values. If an entire row/column is NA, the result will be NAReturns: Cumulative sum of the column
Example 1:  
Python3
import pandas as pdimport numpy as np  # Create a dataframedf1 = pd.DataFrame({"A":[2, 3, 8, 14],                    "B":[1, 2, 4, 3],                    "C":[5, 3, 9,2]})   # Computing sum over Index axisprint(df1.cumsum(axis = 0))
Output:  
    A   B   C
0   2   1   5
1   5   3   8
2  13   7  17
3  27  10  19

Example 2:  
Python3
import pandas as pdimport numpy as np  # Create a dataframedf1 = pd.DataFrame({"A":[None, 3, 8, 14],                    "B":[1, None, 4, 3],                    "C":[5, 3, 9,None]})   # Computing sum over Index axisprint(df1.cumsum(axis = 0, skipna = True))
Output:  
      A    B     C
0   NaN  1.0   5.0
1   3.0  NaN   8.0
2  11.0  5.0  17.0
3  25.0  8.0   NaN

Example 3:  
Python3
import pandas as pdimport numpy as np  # Create a dataframedf1 = pd.DataFrame({"A":[2, 3, 8, 14],                    "B":[1, 2, 4, 3],                    "C":[5, 3, 9,2]})   # Computing sum over Index axisprint(df1.cumsum(axis = 1))
Output:  
    A   B   C
0   2   3   8
1   3   5   8
2   8  12  21
3  14  17  19

 
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python OOPs Concepts
How to Install PIP on Windows ?
Bar Plot in Matplotlib
Defaultdict in Python
Python Classes and Objects
Deque in Python
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python - Ways to remove duplicates from list
Class method vs Static method in Python
How to get selected option using Selenium WebDriver with Java?

We can get a selected option in a dropdown in Selenium webdriver. The method getFirstSelectedOption() returns the selected option in the dropdown. Once the option is fetched we can apply getText() method to fetch the text.
Let us consider the below dropdown Continents get its selected item−
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.support.ui.Select

public class SelecedItem{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver","C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String u =" https://www.tutorialspoint.com/selenium/selenium_automation_practice.htm"driver.get(u);
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      // identify element
      WebElement t=driver.findElement(By.xpath("//*[@name='continents']"));
      //Select class for dropdown
      Select select = new Select(t);
      // select an item with text visible
      select.selectByVisibleText("Australia");
      // get selected option with getFirstSelectedOption() with its text
      WebElement o = select.getFirstSelectedOption();
      String selectedoption = o.getText();
      System.out.println("Selected element: " + selectedoption);
      driver.close();
   }
}
Bootstrap Badges and Labels

Badges are numerical indicators of how many items are associated with a link:
The numbers (5, 10, and 2) are the badges.
Use the .badge class within <span> elements to create badges:
Badges can also be used inside other elements, such as buttons:
The following example shows how to add badges to buttons:
Labels are used to provide additional information about something:
Use the .label class,  followed by 
one of the six contextual classes .label-default, .label-primary, .label-success, 
.label-info, .label-warning or .label-danger, within 
a <span> element to create 
a label:
The following example shows all contextual label classes:
After the "Comments" text, use a span element to make a badge with the number two inside.
<button>Comments </button>

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

Following example will showcase fetching an HTML from the web using a url and then find its data.
String url = "http://www.google.com";
Document document = Jsoup.connect(url).get();

Where
document − document object represents the HTML DOM.
document − document object represents the HTML DOM.
Jsoup − main class to connect the url and get the HTML String.
Jsoup − main class to connect the url and get the HTML String.
url − url of the html page to load.
url − url of the html page to load.
The connect(url) method makes a connection to the url and get() method return the html of the requested url.
Create the following java program using any editor of your choice in say C:/> jsoup.
JsoupTester.java
import java.io.IOException;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

public class JsoupTester {
   public static void main(String[] args) throws IOException {
   
      String url = "http://www.google.com";
      Document document = Jsoup.connect(url).get();
      System.out.println(document.title());
   }
}
Compile the class using javac compiler as follows:
C:\jsoup>javac JsoupTester.java

Now run the JsoupTester to see the result.
C:\jsoup>java JsoupTester

See the result.
Google

 Print
 Add Notes
 Bookmark this page
How to access HTTP Cookie in Node.js ? - GeeksforGeeks

17 Feb, 2021
Cookies are small data that are stored on a client-side and sent to the client along with server requests. With the help of the cookie-parser module, we can do set the cookies as well as get the cookies. 
Create a project folder and run the following command from the root directory of the project:
npm init -y
This command will ask for the name of the module. Keep pressing enter until the end of the options. This will create an empty npm module with a package.json file. We will now install all the required dependencies using the below command:
npm install express cookie-parser
We are using express to create a server and cookie-parser is the library which will help us in working with cookies easily. Let’s create a file called index.js and write the code to create a server with two routes to set and get the cookies as given in the code below:
Filename: index.js
Javascript
// Requiring modulesvar express = require('express');var cookieParser = require('cookie-parser');var app = express();  // cookieParser middlewareapp.use(cookieParser());  // Route for setting the cookiesapp.get('/setcookie', function (req, res) {        // Setting a cookie with key 'my_cookie'   // and value 'geeksforgeeks'  res.cookie('my_cookie', 'geeksforgeeks');  res.send('Cookies added');})  // Route for getting all the cookiesapp.get('/getcookie', function (req, res) {    res.send(req.cookies);})  // Server listens to port 3000 app.listen(3000, (err) => {    if (err) throw err;    console.log('server running on port 3000');});
Here we have a route /setcookie which is used to set a cookie with key my_cookie and the value as geeksforgeeks. We can alter these keys and values to be anything as per requirement. Another route is /getcookie which is used to get all the cookies and show them on the webpage. At the end of the code, we are listening to 3000 port for our server to be able to run.
Run the index.js file using the following command:
node index.js
This will run the server as shown in the image above. We can check cookies by visiting localhost:3000/setcookie.
This will show a message as cookies are added. We can check the cookies by visiting localhost:3000/getcookie.
Now we can see that our cookies are added to the cookies object as shown above.
mridulmanochagfg
NodeJS-Questions
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between dependencies, devDependencies and peerDependencies
Mongoose find() Function
How to connect Node.js with React.js ?
Mongoose Populate() Method
Node.js Export Module
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
How to swap or exchange objects in Java?

Java uses call by value while passing parameters to a function. To swap objects, we need to use their wrappers. See the example below −
 Live Demo
public class Tester{
   public static void main(String[] args) {
      A a = new A();
      A b = new A();

      a.value = 1;
      b.value = 2;

      //swap using objects
      swap(a,b);
      System.out.println(a.value +", " + b.value);

      Wrapper wA = new Wrapper(a);
      Wrapper wB = new Wrapper(b);

      //swap using wrapper of objects
      swap(wA,wB);
      System.out.println(wA.a.value +", " + wB.a.value);
   }

   public static void swap(A a, A b){
      A temp = a;
      a = b;
      b = temp;
   }

   public static void swap(Wrapper wA, Wrapper wB){
      A temp = wA.a;
      wA.a = wB.a;
      wB.a = temp;
   }
}
class A {
   public int value;
}
class Wrapper {
   A a;
   Wrapper(A a){ this.a = a;}
}
1, 2
2, 1
TCS Placement Paper | Email Writing Question 9 - GeeksforGeeks

21 May, 2019
Pre-requisite: Procedure to E-mail WritingThis is a TCS model placement email-writing question. It covers the important directions along with a sample solution to the question.
Directions:
Use all the phrases given.Minimum words should be 70 otherwise your email cannot be validated.Addressing and signing should be done as in the question given.Common grammatical rules, punctuation should be according to standard English.You can use your own phrases along with the phrases given.
Use all the phrases given.
Minimum words should be 70 otherwise your email cannot be validated.
Addressing and signing should be done as in the question given.
Common grammatical rules, punctuation should be according to standard English.
You can use your own phrases along with the phrases given.
Question:You are a part of the corporate communication team in your company. The working time period is revised as 8:30 am to 5:00 pm. Using the following phrases, write an email with a minimum of 70 words and a maximum of 100 words to the employees in your company informing the same.
Phrases:
by 30 minutes to avoid traffic - effect from next week - lunch duration-
revised working time - reduced by 15 minutes-free breakfast-office will start earlier -
till the end of rainy season - will be in effect.

Solution – Sample E-mail:
Dear All,
We henceforth announce a revision in the work timings as 8:30 AM to 5:00 PM, i.e., an increase in office hours by 30 minutes to avoid traffic that is to take effect from next week.With the commencement of the office 30 minutes earlier, the lunch session will be reduced by 15 minutes, with a reduction in the timings of breakfast. The office will start earlier till the end of the rainy season and all other timings will stay in effect till the traffic issues are dealt with.
Thanks and regards,Lead – Corporate Communication.
Note: You can write your own versions of e-mail keeping in mind the points needed to be taken care of while an e-mail. Refer Procedure to E-mail Writing.
interview-preparation
placement preparation
TCS
Placements
TCS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 20 Puzzles Commonly Asked During SDE Interviews
Codenation Recruitment Process
Problem on HCF and LCM
Must Do Questions for Companies like TCS, CTS, HCL, IBM ...
How to Prepare for HR Interviews
Work and Wages
C program to reverse the content of the file and print it
Interview Preparation
Progressions (AP, GP, HP)
Permutation and Combination
How to update the windows host file entry using PowerShell?

Let say you want to update the host file particular entry, we have the below host file in our local computer.
Get-Content $env:windir\system32\drivers\etc\hosts
# For example:
#
#      102.54.94.97     rhino.acme.com          # source server
#       38.25.63.10     x.acme.com              # x client host

# localhost name resolution is handled within DNS itself.
#       127.0.0.1       localhost
#       ::1             localhost
8.8.8.8   Google.com
We need to update the google.com entry to IP address 4.4.4.4.
$hostfile = "$env:windir\system32\drivers\etc\hosts"
$file = Get-Content $hostfile
$newfile = $file -replace "8.8.8.8   Google.com","4.4.4.4   Google.com"
Set-Content -Value $newfile -Path $hostfile -Force
Once you check the host file again, a new entry will be displayed.
To update the host file on the remote computer, just change the $hostfile variable location and the rest content will be the same.
$hostfile = "\\RemoteServer\C$\Windows\system32\drivers\etc\hosts"
How to change auto increment number in MySQL?

The auto_increment is a default property that automatically increments the newly added record
by 1. The starting number can be changed with the help of the alter command.
First, a table is created with the help of the insert command. This is given as follows −
mysql> CREATE table AutoIncrementTable
-> (
-> id int auto_increment,
-> name varchar(200),
-> Primary key(id)
-> );
Query OK, 0 rows affected (0.70 sec)
After creating the table, records are inserted into the table with the help of the insert command
This is given as follows −
mysql> INSERT into AutoIncrementTable(name) values('Carol');
Query OK, 1 row affected (0.19 sec)

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

mysql> INSERT into AutoIncrementTable(name) values('John');
Query OK, 1 row affected (0.18 sec)
Now, the records in the table can be seen with the help of the select command. This is given as
follows −
mysql> SELECT * from AutoIncrementTable;

The output obtained from the above query is given below −
+----+-------+
| id | name  |
+----+-------+
| 1  | Carol |
| 2  | Bob   |
| 3  | John  |
+----+-------+
3 rows in set (0.00 sec)
Now, three records have been inserted in the table and the id is incremented by 1 each time.
Now the Auto Increment is changed so that the id of the next record starts from 1000.
The syntax to change the auto_increment is given as follows.
alter table yourTableName auto_increment=startingNumber;

The above syntax is used to change the auto_increment by 1000. This is shown below −
mysql> alter table AutoIncrementTable auto_increment = 1000;
Query OK, 0 rows affected (0.16 sec)
Records: 0 Duplicates: 0 Warnings: 0
After successfully changing the auto_increment, more recors are inserted into the table. This is
shown below −
mysql> INSERT into AutoIncrementTable(name) values('Taylor');
Query OK, 1 row affected (0.12 sec)

mysql> INSERT into AutoIncrementTable(name) values('Sam');
Query OK, 1 row affected (0.17 sec)
Now, the table records are viewed using the select statement. It can be seen that the 4th record
number starts from 1000.
mysql> SELECT * from AutoIncrementTable;

The following is the output
+------+--------+
| id   | name   |
+------+--------+
| 1    | Carol  |
| 2    | Bob    |
| 3    | John   |
| 1000 | Taylor |
| 1001 | Sam    |
+------+--------+
5 rows in set (0.00 sec)
How to find the rank of an array in C#

23 Jan, 2019
Array.Rank Property is used to get the rank of the Array. Rank is the number of dimensions of an array. For example, 1-D array returns 1, a 2-D array returns 2, and so on.
Syntax:
public int Rank { get; }
Property Value: It returns the rank (number of dimensions) of the Array of type System.Int32.
Below programs illustrate the use of above-discussed property:
Example 1:
// C# program to illustrate the// Array.Rank Propertyusing System;namespace geeksforgeeks {  class GFG {      // Main Method    public static void Main()    {          // declares a 1D Array of string.        string[] weekDays;          // allocating memory for days.        weekDays = new string[] {"Sun", "Mon", "Tue", "Wed",                                      "Thu", "Fri", "Sat" };          // using Rank Property        Console.WriteLine("Dimension of weekDays array: "                                        + weekDays.Rank);    }}}
Dimension of weekDays array: 1

Example 2:
// C# program to illustrate the// Array.Rank Propertyusing System;namespace geeksforgeeks {  class GFG {      // Main Method    public static void Main()    {          // declaring an 2-D array        int[, ] arr2d = new int[4, 2];          // declaring an 3-D array        int[,, ] arr3d = new int[4, 2, 3];          // declaring an jagged array        int[][] jdarr = new int[2][];          // using Rank Property        Console.WriteLine("Dimension of arr2d array: "                                         + arr2d.Rank);          Console.WriteLine("Dimension of arr3d array: "                                         + arr3d.Rank);          // for the jagged array it         // will always return 1        Console.WriteLine("Dimension of jdarr array: "                                         + jdarr.Rank);    }}}
Dimension of arr2d array: 2
Dimension of arr3d array: 3
Dimension of jdarr array: 1

Note:
A jagged array (an array of arrays) is a one-dimensional array so the value of its Rank property is 1.
Retrieving the value of this property is an O(1) operation.
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.array.rank?view=netframework-4.7.2
CSharp-Arrays
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Format a number with leading zeros in PHP

04 Jul, 2022
Often times, while writing a code we face situations where we need to pad a numbers/strings and make them of a default length. In this article, we will learn how to pad a number with leading zeros in PHP. Here are few examples for the better understanding of the task.Examples:  
Input :1234567
Output :01234567

Input :1234
Output :00001234
There are many ways to pad leading zeros in string format. But in case of string the best way to achieve the task is by using sprintf function and also you can use substr() function.  
sprintf() function
substr() function
Using sprintf() Function: The sprintf() function is used to return a formatted string. Syntax: 
sprintf(format, $variable)
// Returns the variable formatted according to the format provided. 
Example 1: This example uses sprintf() function to display the number with leading zeros.  
php
<?php$var = 1234567;echo sprintf('%08d', $var);?>
Output: 
01234567
Example 2: This example uses sprintf() function to display negative numbers with leading zeros. 
php
<?php$var1 = -10;$var2 = 10;echo sprintf('%04s', $var1) . "\n";echo sprintf('%04s', $var2);?>
Output: 
0-10
0010
In the above example, we tried to format the number as a string and messed up the negative. But that would not be the case if we format numbers using ‘%d’ rather than ‘%s’.
Example 3: 
php
<?php$var1 = -10;$var2 = 10;echo sprintf('%04d', $var1) . "\n";echo sprintf('%04d', $var2);?>
Output:  
-010
0010
Using substr() Function: This function is used to return part of a string. Syntax:  
substr( string $string , int $start, int $length )
// Returns the portion of string that define at start and length of the parameter. 
Example: 
php
<?php$num = 123;$str_length = 4; // Left padding if number < $str_length$str = substr("0000{$num}", -$str_length);echo sprintf($str);?>
Output: 
0123
Akanksha_Rai
gabaa406
sweetyty
Picked
PHP
PHP Programs
Web Technologies
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Integer sum() Method in Java

05 Dec, 2018
The java.lang.Integer.sum() is a built-in method in java which returns the sum of its arguments. The method adds two integers together as per the + operator.
Syntax :
public static int sum(int a, int b)
Parameter: The method accepts two parameters which are to be added with each other:a : the first integer value.b : the second integer value.
Return Value: The method returns the sum of its arguments.Exception: The method throws an ArithmeticException when the result overflows an int.
Examples
Input: a = 170, b = 455
Output: 625

Input: a = 45, b = 45
Output: 90
Below programs illustrate the Java.lang.Integer.sum() method:Program 1: For a positive number.
// Java program to illustrate the// Java.lang.Integer.sum() methodimport java.lang.*;  public class Geeks {      public static void main(String[] args)    {        int a = 62;        int b = 18;        // It will return the sum of two arguments.        System.out.println("The sum is =" + Integer.sum(a, b));    }}
The sum is =80

Program 2: Below program illustrates the exception.
// Java program to illustrate the// Java.lang.Integer.sum() methodimport java.lang.*;  public class Geeks {      public static void main(String[] args)    {        // When very large integer is taken        int a = 92374612162;         int b = 181;        // It will return the sum of two arguments.        System.out.println("The sum is =" + Integer.sum(a, b));    }}
prog.java:8: error: integer number too large: 92374612162
       int a = 92374612162;
               ^
1 error

Java-Functions
Java-Integer
Java-lang 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
Stream In Java
ArrayList in Java
Collections in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java
Python – Row-wise element Addition in Tuple Matrix

30 Dec, 2020
Sometimes, while working with Python tuples, we can have a problem in which we need to perform Row-wise custom elements addition in Tuple matrix. This kind of problem can have application in data domains. Let’s discuss certain ways in which this task can be performed.
Input :test_list = [[(‘Gfg’, 3)], [(‘best’, 1)]]cus_eles = [1, 2]Output : [[(‘Gfg’, 3, 1)], [(‘best’, 1, 2)]]
Input :test_list = [[(‘Gfg’, 6), (‘Gfg’, 3)]]cus_eles = [7]Output : [[(‘Gfg’, 6, 7), (‘Gfg’, 3, 7)]]
Method #1 : Using enumerate() + nested list comprehensionThe combination of above methods can be used to solve this problem. In this, we perform the task of adding elements using nested list comprehension and index iteration by enumerate().
# Python3 code to demonstrate working of # Row-wise element Addition in Tuple Matrix# Using enumerate() + list comprehension  # initializing listtest_list = [[('Gfg', 3), ('is', 3)], [('best', 1)], [('for', 5), ('geeks', 1)]]  # printing original listprint("The original list is : " + str(test_list))  # initializing Custom elescus_eles = [6, 7, 8]  # Row-wise element Addition in Tuple Matrix# Using enumerate() + list comprehensionres = [[sub + (cus_eles[idx], ) for sub in val] for idx, val in enumerate(test_list)]  # printing result print("The matrix after row elements addition : " + str(res)) 
The original list is : [[(‘Gfg’, 3), (‘is’, 3)], [(‘best’, 1)], [(‘for’, 5), (‘geeks’, 1)]]The matrix after row elements addition : [[(‘Gfg’, 3, 6), (‘is’, 3, 6)], [(‘best’, 1, 7)], [(‘for’, 5, 8), (‘geeks’, 1, 8)]]
 
Method #2 : Using zip() + list comprehensionThe combination of above functions can be used to solve this problem. In this, we perform the task of combining new row elements with respective rows using zip(), rather than enumerate().
# Python3 code to demonstrate working of # Row-wise element Addition in Tuple Matrix# Using zip() + list comprehension  # initializing listtest_list = [[('Gfg', 3), ('is', 3)], [('best', 1)], [('for', 5), ('geeks', 1)]]  # printing original listprint("The original list is : " + str(test_list))  # initializing Custom elescus_eles = [6, 7, 8]  # Row-wise element Addition in Tuple Matrix# Using zip() + list comprehensionres = [[(idx, val) for idx in key] for key,  val in zip(test_list, cus_eles)]  # printing result print("The matrix after row elements addition : " + str(res)) 
The original list is : [[(‘Gfg’, 3), (‘is’, 3)], [(‘best’, 1)], [(‘for’, 5), (‘geeks’, 1)]]The matrix after row elements addition : [[(‘Gfg’, 3, 6), (‘is’, 3, 6)], [(‘best’, 1, 7)], [(‘for’, 5, 8), (‘geeks’, 1, 8)]]
Python matrix-program
Python tuple-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 OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary
Word Dictionary using Tkinter

24 Jan, 2021
Prerequisite:
Tkinter
Pydictionary
Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python.
In this article, we will learn how to make Word Dictionary in Tkinter. 
PyDictionary is a dictionary (as in the English language dictionary) module for Python2 and Python3. PyDictionary provides the following services for a word:
meanings
translations
synonym
antonym
Import module
Create Normal Tkinter window
Add Some Button, Labels & Frames
Syntax:
# Button
Button(Object Name, text=”Enter Text”,**attr)
# Label
Label(Object Name, text=”Enter Text”, command=”Enter Command” , **attr)
# Frame
Frame(Object Name, **attr)
Make a function named as dict. This function will give the meaning, synonym & antonym of given word.
Execute code
Program:
Python3
# Import Required Libraryfrom tkinter import *from PyDictionary import PyDictionary  # Create Objectsdictionary = PyDictionary()root = Tk()  # Set geometryroot.geometry("400x400")    def dict():    meaning.config(text=dictionary.meaning(word.get())['Noun'][0])    synonym.config(text=dictionary.synonym(word.get()))    antonym.config(text=dictionary.antonym(word.get()))    # Add Labels, Button and FramesLabel(root, text="Dictionary", font=(    "Helvetica 20 bold"), fg="Green").pack(pady=10)  # Frame 1frame = Frame(root)Label(frame, text="Type Word", font=("Helvetica 15 bold")).pack(side=LEFT)word = Entry(frame, font=("Helvetica 15 bold"))word.pack()frame.pack(pady=10)  # Frame 2frame1 = Frame(root)Label(frame1, text="Meaning:- ", font=("Helvetica 10 bold")).pack(side=LEFT)meaning = Label(frame1, text="", font=("Helvetica 10"))meaning.pack()frame1.pack(pady=10)  # Frame 3frame2 = Frame(root)Label(frame2, text="Synonym:- ", font=("Helvetica 10 bold")).pack(side=LEFT)synonym = Label(frame2, text="", font=("Helvetica 10"))synonym.pack()frame2.pack(pady=10)  # Frame 4frame3 = Frame(root)Label(frame3, text="Antonym:- ", font=("Helvetica 10 bold")).pack(side=LEFT)antonym = Label(frame3, text="", font=("Helvetica 10"))antonym.pack(side=LEFT)frame3.pack(pady=10)  Button(root, text="Submit", font=("Helvetica 15 bold"), command=dict).pack()  # Execute Tkinterroot.mainloop()
Output:
Python Tkinter-exercises
Python Tkinter-projects
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sublime Text - Installation

Sublime Text editor is supported by the following major operating systems −
Windows
Linux and its distributions
OS X
You can download Sublime Text from its official website − www.sublimetext.com
In this chapter, you will learn about the installation of Sublime Text on various operating systems.
You will have to go follow the steps shown below to install Sublime Text on Windows −
Step 1 − Download the .exe package from the official website as shown below −
https://www.sublimetext.com/3
Step 2 − Now, run the executable file. This defines the environment variables. When you run the executable file, you can observe the following window on your screen. Click Next.
Step 3 − Now, choose a destination location to install Sublime Text3 and click Next.
Step 4 − Verify the destination folder and click Install.
Step 5 − Now, click Finish to complete the installation.
Step 6 − Upon a successful installation, your editor will appear as shown below −
You will have to follow the steps shown below to install Sublime Text on Linux distributions −
Step 1 − Using the command line terminal, install the packages for Sublime Text editor, using the command given below −
sudo add-apt-repository ppa:webupd8team/Sublime-Text-3

Step 2 − Update the packages using the following command −
sudo apt-get update

Step 3 − Install the Sublime Text repository using the following command −
sudo apt-get install Sublime-Text

After the successful execution of above mentioned commands, you will find that Sublime Text editor is installed on the system.
For OSX operating systems,
Download the .dmg file of Sublime Text Editor.
Download the .dmg file of Sublime Text Editor.
Open it and drag-and-drop in the Applications folder.
Open it and drag-and-drop in the Applications folder.
Follow the steps that you have seen in above two cases.
Follow the steps that you have seen in above two cases.
Launch the application.
Launch the application.
Dart Programming – Map

08 Mar, 2022
In Dart programming, Maps are dictionary-like data types that exist in key-value form (known as lock-key). There is no restriction on the type of data that goes in a map data type. Maps are very flexible and can mutate their size based on the requirements. However, it is important to note that all locks (keys) need to be unique inside a map data type.
We can declare Map in two ways: 
Using Map LiteralsUsing Map Constructors
Using Map Literals
Using Map Constructors
Map can be declared using map literals as shown below:  
Syntax: 
// Creating the Map using Map Literals
var map_name = { key1 : value1, key2 : value2, ..., key n : value n }
Example 1: 
Creating Map using Map Literals 
Dart
void main() {   // Creating Map using is literals  var gfg = {'position1' : 'Geek', 'position2' : 'for', 'position3' : 'Geeks'};     // Printing Its content  print(gfg);     // Printing Specific Content  // Key is defined  print(gfg['position1']);     // Key is not defined  print(gfg[0]);}
Output: 
{position1: Geek, position2: for, position3: Geeks}
Geek
null
Example 2: 
Dart
void main() {   // Creating Map using is literals  var gfg = {'position1' : 'Geek' 'for' 'Geeks'};     // Printing Its content  print(gfg);     // Printing Specific Content  // Key is defined  print(gfg['position1']);}
Output: 
{position1: GeekforGeeks}
GeekforGeeks
You have noticed that different strings get concatenated to one.
Example 3: 
Inserting a new value into Map 
Dart
void main() {   // Creating Map  var gfg = {'position1' : 'Geeks' 'for'  'Geeks'};     // Printing Its content before insertion  print(gfg);     // Inserting a new value in Map  gfg ['position0'] = 'Welcome to ';     // Printing Its content after insertion  print(gfg);     // Printing Specific Content  // Keys is defined  print(gfg['position0'] + gfg['position1']);}
Output: 
{position1: GeeksforGeeks}
{position1: GeeksforGeeks, position0: Welcome to }
Welcome to GeeksforGeeks
Syntax: 
// Creating the Map using Map Constructor
var map_name = new Map();
// Assigning value and key inside Map
map_name [ key ] = value;
Example 1:
Creating Map using Map Constructors  
Dart
void main() {   // Creating Map using Constructors  var gfg = new Map();     // Inserting values into Map  gfg [0] = 'Geeks';  gfg [1] = 'for';  gfg [2] = 'Geeks';     // Printing Its content  print(gfg);     // Printing Specific Content  // Key is defined  print(gfg[0]);}
Output:  
{0: Geeks, 1: for, 2: Geeks}
Geeks
Example 2: 
Assigning same key to different element 
Dart
void main() {   // Creating Map using Constructors  var gfg = new Map();     // Inserting values into Map  gfg [0] = 'Geeks';  gfg [0] = 'for';  gfg [0] = 'Geeks';     // Printing Its content  print(gfg);     // Printing Specific Content  // Key is defined  print(gfg[0]);}
Output:  
{0: Geeks}
Geeks
You have noticed that the other two values were simply ignored.
simmytarika5
rajeev0719singh
kothavvsaakash
Dart Data-types
Dart-Map
Dart
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.