code-rag-bench/online-tutorials huggingface dataset:
SQL GROUP BY Statement

The GROUP BY statement groups rows that have the same values into summary 
rows, like "find the number of customers in each country".
The GROUP BY statement is often used with aggregate functions (COUNT(), 
MAX(), 
MIN(), SUM(), 
AVG()) to group the result-set by one or more columns.
Below is a selection from the "Customers" table in the Northwind sample 
database:
The following SQL statement lists the number of customers in each country:
The following SQL statement lists the number of customers in each country, 
sorted high to low:
Below is a selection from the "Orders" table in the Northwind sample database:
And a selection from the "Shippers" table:
The following SQL statement lists the number of orders sent by each shipper:
List the number of customers in each country.
SELECT (CustomerID),
Country
FROM Customers
;

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.
How to valid DateofBirth using fluent Validation in C# if it exceeds current year?

To specify a validation rule for a particular property, call the RuleFor method, passing a lambda expression that indicates the property that you wish to validate
To run the validator, instantiate the validator object and call the Validate method, passing in the object to validate.
The Validate method returns a ValidationResult object. This contains two properties
IsValid - a boolean that says whether the validation suceeded.
Errors - a collection of ValidationFailure objects containing details about any validation failures
static void Main(string[] args) {
   List errors = new List();

   PersonModel person = new PersonModel();
   person.FirstName = "TestUser";
   person.LastName = "TestUser";
   person.AccountBalance = 100;
   person.DateOfBirth = DateTime.Now.Date.AddYears(1);

   PersonValidator validator = new PersonValidator();

   ValidationResult results = validator.Validate(person);

   if (results.IsValid == false) {
      foreach (ValidationFailure failure in results.Errors){
         errors.Add(failure.ErrorMessage);
      }
   }

   foreach (var item in errors){
      Console.WriteLine(item);
   }
   Console.ReadLine();

   }
}

public class PersonModel {
   public string FirstName { get; set; }
   public string LastName { get; set; }
   public decimal AccountBalance { get; set; }
   public DateTime DateOfBirth { get; set; }
}

public class PersonValidator : AbstractValidator{
   public PersonValidator(){
      RuleFor(p => p.DateOfBirth)
      .Must(BeAValidAge).WithMessage("Invalid {PropertyName}");
   }

   protected bool BeAValidAge(DateTime date){
      int currentYear = DateTime.Now.Year;
      int dobYear = date.Year;

      if (dobYear <= currentYear && dobYear > (currentYear - 120)){
         return true;
      }

      return false;
   }
}
Invalid Date Of Birth
Java - equals() Method

The method determines whether the Number object that invokes the method is equal to the object that is passed as an argument.
public boolean equals(Object o)

Here is the detail of parameters −
Any object.
The method returns True if the argument is not null and is an object of the same type and with the same numeric value. There are some extra requirements for Double and Float objects that are described in the Java API documentation.
The method returns True if the argument is not null and is an object of the same type and with the same numeric value. There are some extra requirements for Double and Float objects that are described in the Java API documentation.
public class Test { 

   public static void main(String args[]) {
      Integer x = 5;
      Integer y = 10;
      Integer z =5;
      Short a = 5;

      System.out.println(x.equals(y));  
      System.out.println(x.equals(z)); 
      System.out.println(x.equals(a));
   }
}
This will produce the following result −
false
true
false


    16 Lectures 
     2 hours 

 Malhar Lathkar

    19 Lectures 
     5 hours 

 Malhar Lathkar

    25 Lectures 
     2.5 hours 

 Anadi Sharma

    126 Lectures 
     7 hours 

  Tushar Kale

    119 Lectures 
     17.5 hours 

 Monica Mittal

    76 Lectures 
     7 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
What are the different ways of handling authentication popup window using Selenium?

We can handle authentication pop-up window using Selenium webdriver by incorporating the username and password within the application URL. The format of an URL along with credential should be − https://username:password@URL
Let us launch a web page having the authentication pop-up generated at page load −
The user Name and Password fields are having value as admin.
If we ignore this pop-up on clicking the Cancel button, we shall be navigated to the below page.
If proper credentials are entered and then the OK button is clicked, we shall be navigated to the below page.
In the above example, to handle the authentication pop-up, using the get method, the URL to be passed as a parameter should be - https://admin:admin@the−nternet.herokuapp.com/basic_auth.
from selenium import webdriver
#set chromodriver.exe path
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
#implicit wait
driver.implicitly_wait(0.5)
#maximize browser
driver.maximize_window()
#username, password value
p = "admin"
#url format
url = "https://" + p + ":" + p + "@" + "the-internet.herokuapp.com/basic_auth"
#launch URL
driver.get(url)
#identify element
l = driver.find_element_by_tag_name("p")
#obtain text
s = l.text
print("Text is: ")
print(s)
#close browser
driver.close()
Static vs Dynamic Binding in Java

In Java static binding refers to the execution of a program where type of object is determined/known at compile time i.e when compiler executes the code it know the type of object or class to which object belongs.While in case of dynamic binding the type of object is determined at runtime.
Also static binding uses type of class to bind while dynamic binding uses type of object as the resolution happens only at runtime because object only created during runtime due to which dynamic binding becomes slower than in case of static binding.
As private,final and static modifiers binds to the class level so methods and variables uses static binding and bonded by compiler while the other methods are bonded during runtime based upon runtime object.
In general we can say that overloaded methods are bonded using static binding while overridden methods are bonded using dynamic binding.
 Live Demo
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
public class StaticDynamicBinding {
   public static void main(String[] args) {
      Collection<String> col = new HashSet<>();
      col.add("hello");
      StaticDynamicBinding sdObj = new StaticDynamicBinding();
      sdObj.print(col);
      StaticDynamicBinding sdObj1 = new StaticDynamicBindingClass();
      sdObj1.print(col);
   }
   void print(Collection<String> col) {
      System.out.println("in collection method");
   }
   void print(HashSet<String> hs) {
      System.out.println("in hashset method");
   }
}
class StaticDynamicBindingClass extends StaticDynamicBinding {
   void print(Collection<String> col) {
      System.out.println("in collection method of child class");
   }
}
in collection method
in collection method of child class
PyQt5 – setChecked() method for Check Box

22 Apr, 2020
setChecked method is used to change the state of check box. By default it is un-checked after clicking on the check box widget its states get changed into checked, but with the help of setChecked method we can do it directly without clicking it.
Syntax : checkbox.setChecked(True)
Argument : It takes bool as argument.
Action performed : It will change the state of check box.
Below is the implementation.
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys    class Window(QMainWindow):      def __init__(self):        super().__init__()          # setting title        self.setWindowTitle("Python ")          # setting geometry        self.setGeometry(100, 100, 600, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()      # method for widgets    def UiComponents(self):          # creating the check-box        checkbox = QCheckBox('Check Box', self)          # setting geometry of check box        checkbox.setGeometry(200, 150, 100, 30)          # setting check box state to checked        checkbox.setChecked(True)    # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Iterate over a list in Python
p5.js | height variable

16 Apr, 2019
The height variable in p5.js is a system variable which stores the height of the drawing canvas. It sets the second parameter of createCanvas() function.
Syntax:
height
Below programs illustrate the height variable in p5.js:
Example 1: This example uses height variable to display the height of canvas.
function setup() {          // Create Canvas of size 380*80      createCanvas(380, 80);}   function draw() {          // Set the background color    background(220);          // Set the text size    textSize(16);          // Set the text alignment    textAlign(CENTER);          // Set the text color    fill(color('Green'));          // Display result    text("Height of Canvas is : "        + height, 180, 50);} 
Output:
Example 2: This example uses height variable to display the height of window.
function setup() {  // set height to window height height = windowHeight;  //create Canvas of size 380*80   createCanvas(380, height);}  function draw() {  background(220);  textSize(16);  textAlign(CENTER);  fill(color('Green'));  text("Height of Canvas is : "+height, 180, height/2); //use of height variable}
Output:
Reference: https://p5js.org/reference/#/p5/height
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Hide or show elements in HTML using display property
Difference Between PUT and PATCH Request
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Count number of elements in an array with MongoDB?

To count number of elements in an array, use the aggregate framework. Let us first create a collection with documents −
>db.countNumberOfElementsDemo.insertOne({"UserMessage":["Hi","Hello","Bye","Awesome"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cef8ec2ef71edecf6a1f6a1")
}
Display all documents from a collection with the help of find() method −
> db.countNumberOfElementsDemo.find().pretty();
This will produce the following output −
{
   "_id" : ObjectId("5cef8ec2ef71edecf6a1f6a1"),
   "UserMessage" : [
      "Hi",
      "Hello",
      "Bye",
      "Awesome"
   ]
}
Following is the query to count number of elements in an array −
> db.countNumberOfElementsDemo.aggregate({$project: { NumberOfElements: { $size:"$UserMessage" }}})
This will produce the following output −
{ "_id" : ObjectId("5cef8ec2ef71edecf6a1f6a1"), "NumberOfElements" : 4 }
Best Time to Buy and Sell Stock with Cooldown in C++

Suppose we have an array for which the ith element is the price of a given stock on the day i. We have to design an algorithm to find the maximum profit. We may complete as many transactions as we want (So, buy one and sell one share of the stock multiple times). But we have to follow these rules −
We may not engage in multiple transactions at the same time (So, we must sell the stock before you buy again).
After we sell our stock, we cannot buy stock on next day. (So cool down 1 day)
If the input is like [1,2,3,0,2], then the output will be 3, the sequence is like [buy, sell, cooldown, buy, sell]
To solve this, we will follow these steps −
endWithSell := 0, endWithBuy := -ve infinity, prevBuy := 0 and prevSell := 0
for i := 0 to size of the given arrayprevBuy := endWithBuyendWithBuy := max of endWithBuy and prevSell – Arr[i]prevSell := endWithSellendWithSell := max of endWithSell and prevBuy + Arr[i]
prevBuy := endWithBuy
endWithBuy := max of endWithBuy and prevSell – Arr[i]
prevSell := endWithSell
endWithSell := max of endWithSell and prevBuy + Arr[i]
return endWithSell
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int maxProfit(vector<int>& p) {
      int endWithSell = 0;
      int endWithBuy = INT_MIN;
      int prevBuy =0, prevSell = 0;
      for(int i =0;i<p.size();i++){
         prevBuy = endWithBuy;
         endWithBuy = max(endWithBuy,prevSell - p[i]);
         prevSell = endWithSell;
         endWithSell = max(endWithSell, prevBuy + p[i]);
      }
      return endWithSell;
   }
};
main(){
   Solution ob;
   vector<int> v = {1,2,3,0,2};
   cout << (ob.maxProfit(v));
}
[1,2,3,0,2]
3
Python | Vkeyboard (virtual keyboard) in kivy

05 Sep, 2019
Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, linux and Windows etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications.
VKeyboard is an onscreen keyboard for Kivy. Its operation is intended to be transparent to the user. Using the widget directly is NOT recommended. Read the section Request keyboard first.
Modes in Vkeyboard:
This virtual keyboard has a docked and free mode:
Docked mode: (VKeyboard.docked = True) Generally used when only one person is using the computer, like a tablet or personal computer etc.
Free mode: (VKeyboard.docked = False) Mostly for multitouch surfaces. This mode allows multiple virtual keyboards to be used on the screen.
If the docked mode changes, you need to manually call VKeyboard.setup_mode() otherwise, the change will have no impact.
During that call, the VKeyboard, implemented on top of a Scatter, will change the behavior of the scatter and position the keyboard near the target (if target and docked mode are set).
Basic Approach:
1) import kivy
2) import kivyApp
3) import vkeyboard
4) set kivy version (optional)
5) Create the Vkeyboard class
6) Create the App class
7) return the vkeyboard class
8) Run the App

# Implementation of the Approach:
# import kivy module  import kivy        # this restricts the kivy version i.e  # below this kivy version you cannot  # use the app or software  kivy.require("1.9.1")        # base Class of your App inherits from the App class.  # app:always refers to the instance of your application  from kivy.app import App  # VKeyboard is an onscreen keyboard# for Kivy. Its operation is intended# to be transparent to the user. from kivy.uix.vkeyboard import VKeyboard  # Create the vkeyboardclass Test(VKeyboard):    player = VKeyboard()  # Create the App classclass VkeyboardApp(App):    def build(self):        return Test()  # run the Appif __name__ == '__main__':    VkeyboardApp().run()
Output:
Python-gui
Python-kivy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Split the Even and Odd elements into two different lists

19 Apr, 2020
In this program, a list is accepted with the mixture of odd and even elements and based on whether the element is even or odd, it is split into two different lists.
Examples:
Input : [8, 12, 15, 9, 3, 11, 26, 23]
Output : Even lists: [8, 12, 26]
         Odd lists: [15, 9, 3, 11, 23]


Input : [2, 5, 13, 17, 51, 62, 73, 84, 95]
Output : Even lists: [2, 62, 84]
         Odd lists: [5, 13, 17, 51, 73, 95]

# Python code to split into even and odd lists# Function to splitdef Split(mix):    ev_li = []    od_li = []    for i in mix:        if (i % 2 == 0):            ev_li.append(i)        else:            od_li.append(i)    print("Even lists:", ev_li)    print("Odd lists:", od_li)  # Driver Codemix = [2, 5, 13, 17, 51, 62, 73, 84, 95]Split(mix)
Output:
Even lists: [2, 62, 84]
Odd lists: [5, 13, 17, 51, 73, 95]

Alternate Shorter Solution :
def Split(mix):    ev_li = [ele for ele in li_in if ele%2 ==0]    od_li = [ele for ele in li_in if ele%2 !=0]    print("Even lists:", ev_li)    print("Odd lists:", od_li)  # Driver Codemix = [2, 5, 13, 17, 51, 62, 73, 84, 95]Split(mix)
Output:
Even lists: [2, 62, 84]
Odd lists: [5, 13, 17, 51, 73, 95]

shubham_singh
zwwingfan
Python list-programs
python-list
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Drop rows from the dataframe based on certain condition applied on a column

05 Feb, 2019
Pandas provides a rich collection of functions to perform data analysis in Python. While performing data analysis, quite often we require to filter the data to remove unnecessary rows or columns.
We have already discussed earlier how to drop rows or columns based on their labels. However, in this post we are going to discuss several approaches on how to drop rows from the dataframe based on certain condition applied on a column. Retain all those rows for which the applied condition on the given column evaluates to True.
To download the CSV used in code, click here.
You are given the “nba.csv” dataset. Drop all the players from the dataset whose age is below 25 years.
Solution #1 : We will use vectorization to filter out such rows from the dataset which satisfy the applied condition.
# importing pandas as pdimport pandas as pd  # Read the csv file and construct the # dataframedf = pd.read_csv('nba.csv')  # Visualize the dataframeprint(df.head(15)  # Print the shape of the dataframeprint(df.shape)
Output :
In this dataframe, currently, we are having 458 rows and 9 columns. Let’s use vectorization operation to filter out all those rows which satisfy the given condition.
# Filter all rows for which the player's# age is greater than or equal to 25df_filtered = df[df['Age'] >= 25]  # Print the new dataframeprint(df_filtered.head(15)  # Print the shape of the dataframeprint(df_filtered.shape)
Output :As we can see in the output, the returned dataframe only contains those players whose age is greater than or equal to 25 years. Solution #2 : We can use the DataFrame.drop() function to drop such rows which does not satisfy the given condition.
# importing pandas as pdimport pandas as pd  # Read the csv file and construct the # dataframedf = pd.read_csv('nba.csv')  # First filter out those rows which# does not contain any datadf = df.dropna(how = 'all')  # Filter all rows for which the player's# age is greater than or equal to 25df.drop(df[df['Age'] < 25].index, inplace = True)  # Print the modified dataframeprint(df.head(15))  # Print the shape of the dataframeprint(df.shape)
Output :As we can see in the output, we have successfully dropped all those rows which do not satisfy the given condition applied to the ‘Age’ column.
pandas-dataframe-program
Python pandas-dataFrame
Python-pandas
Python
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()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Print Hello World Without using a Semicolon in Java

23 Nov, 2021
Every statement in Java must end with a semicolon as per the basics. However, unlike other languages, almost all statements in Java can be treated as expressions. However, there are a few scenarios when we can write a running program without semicolons. If we place the statement inside an if/for statement with a blank pair of parentheses, we don’t have to end it with a semicolon. Also, calling a function that returns void will not work here as void functions are not expressions.
Methods: 
Using if-else statementsUsing append() method of StringBuilder classUsing equals method of String class 
Using if-else statements
Using append() method of StringBuilder class
Using equals method of String class 
Method 1: Using if statement
Java
// Java program to Print Hello World Without Semicolon// Using if statement // Main classclass GFG {     // Main driver method    public static void main(String args[])    {         // Using if statement to        // print hello world        if (System.out.printf("Hello World") == null) {        }    }}
Hello World
Method 2: Using append() method of StringBuilder class
Java
// Java Program to Print Hello World Without Semicolon// Using append() method of String class // Importing required classesimport java.util.*; // Main classclass GFG {     // Main driver method    public static void main(String[] args)    {         // Using append() method to print statement        if (System.out.append("Hello World") == null) {        }    }}
Hello World
Method 3: Using equals method of String class
Java
// Java Program to Print Hello World Without Semicolon// Using equals() method of String class // Importing required classesimport java.util.*; // Main classclass GFG {     // Main driver method    public static void main(String args[])    {        // Using equals() method to print statement        if (System.out.append("Hello World").equals(null)) {        }    }}
Hello World
surindertarika1234
reetbatra25
java-basics
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Share Files On Local Network Using Apache File Server?

30 Mar, 2021
Normally we share files between our computers and mobiles using Gmail, Whatsapp, Bluetooth, etc. But here we are going to discuss sharing files using Apache Server from your computer. Your system has to be connected to a LAN for Accessing the files from one computer to another connected on a LAN.
The local server is the same as our web server. As our Web Server serves our needs anywhere and anytime. But Local server operates when multiple clients are connected to the same LAN(Local Area Network). And if we connect a router and connect our mobiles to the Wi-Fi of that router then we can access the files which were shared by the Computer on that server.
Apache HTTP Server is a very powerful HTTP server. It is the replacement for NCSA Server. It is Free of cost and open Source.
ComputerWi-Fi Router(For Mobile Users)Local Area Network Connection(Acts as Local Server)
Computer
Wi-Fi Router(For Mobile Users)
Local Area Network Connection(Acts as Local Server)
You need to download Apache24 from Google and install it on your device. Download the file which is available in 32 bit and 64bit.Unzip the downloaded files where you would like to install the same.Now, open the command prompt and navigate to the location where you have unzipped the folder.Now Use the below command to open the specific folder for starting the server.
You need to download Apache24 from Google and install it on your device. Download the file which is available in 32 bit and 64bit.
Unzip the downloaded files where you would like to install the same.
Now, open the command prompt and navigate to the location where you have unzipped the folder.
Now Use the below command to open the specific folder for starting the server.
cd Apache24/bin/httpd
Now After entering this command you will get a dialogue box for Allowing Access. You have to give access to all Public and Private Networks.
Now You can access the files on the network. Just by typing the host’s IP Address.
Here we have just placed an HTML File, so it is showing the text “It Works” in the browser. You can even place your HTML projects or Your Files in a Folder and Access them.
Example:
If you type in the below statement in the command prompt:
- 192.168.102.67/Geeks
You will get all the files stored in Geeks Folder which is Located in Apache24/htdocs folder.
To access the files on another machine connected to the same network just type the host computer IP Address forwarded by the folder name.
192.168.102.67/Geeks.
So you can access the files.
How To
TechTips
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Set Git Username and Password in GitBash?
How to Install Jupyter Notebook on MacOS?
How to Install and Use NVM on Windows?
How to Install Python Packages for AWS Lambda Layers?
How to Install Git in VS Code?
Docker - COPY Instruction
Setting up the environment in Java
How to Run a Python Script using Docker?
Running Python script on GPU.
How to setup cron jobs in Ubuntu
Java Program to Check If a Number is Neon Number or Not

15 Oct, 2021
A neon number is a number where the sum of digits of the square of the number is equal to the number. The task is to check and print neon numbers in a range.
Illustration:
Case 1:

Input  : 9
Output : Given number  9 is Neon number

Explanation : square of 9=9*9=81;
              sum of digit of square : 8+1=9(which is equal to given number)


Case 2:

Input : 8
Output : Given number is not a Neon number
 
Explanation : square of 8=8*8=64
              sum of digit of square : 6+4=10(which is not equal to given number)
Algorithm :
First, find the square of the given number.Find the sum of the digit of the square by using a loop. The condition checksum is equal to the given numberReturn trueElse return false.
First, find the square of the given number.
Find the sum of the digit of the square by using a loop. 
The condition checksum is equal to the given numberReturn trueElse return false.
Return trueElse return false.
Return true
Else return false.
Pseudo code : Square =n*n;
              while(square>0)
              {
              int r=square%10;
              sum+=r;
              square=square/10;
              }
Example:
Java
// Java Program to Check If a Number is Neon number or not // Importing java input/output libraryimport java.io.*; class GFG {     // Method to check whether number is neon or not    // Boolean type    public static boolean checkNeon(int n)    {        // squaring the number to be checked        int square = n * n;         // Initializing current sum to 0        int sum = 0;         // If product is positive        while (square > 0) {             // Step 1: Find remainder            int r = square % 10;             // Add remainder to the current sum            sum += r;             // Drop last digit of the product            // and store the number            square = square / 10;        }         // Condition check        // Sum of digits of number obtained is        // equal to original number        if (sum == n)             // number is neon            return true;        else             // number is not neon            return false;    }     // Main driver method    public static void main(String[] args)    {        // Custom input        int n = 9;         // Calling above function to check custom number or        // if user entered number via Scanner class        if (checkNeon(n))             // Print number considered is neon            System.out.println("Given number " + n                               + " is Neon number");        else             // Print number considered is not neon            System.out.println("Given number " + n                               + " is not a Neon number");    }}
Given number 9 is Neon number
Time Complexity: O(l) where l is the number of the digit in the square of the given number
 
clintra
surinderdawra388
simmytarika5
Picked
Technical Scripter 2020
Java
Java Programs
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Convert string to title case in JavaScript

23 Apr, 2019
We convert a string to title case in such a way that every new word begins with a capital(uppercase) letter.This can be achieved by following ways-1) By using replace() function
<script>function sentenceCase (str) {  if ((str===null) || (str===''))       return false;  else   str = str.toString();   return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() +       txt.substr(1).toLowerCase();});}  document.write(sentenceCase('geeks for geeks'));</script>
OUTPUT
Geeks For Geeks
2) By using For loop to titlecase a string
<script>function titleCase(str) {  str = str.toLowerCase().split(' ');  for (var i = 0; i < str.length; i++) {    str[i] = str[i].charAt(0).toUpperCase() + str[i].slice(1);   }  return str.join(' ');}document.write(titleCase("GEEKS FOR GEEKS"));</script>
OUTPUT
Geeks For Geeks
3) By using map() method
<script>function titleCase(str) {  return str.toLowerCase().split(' ').map(function(word) {    return (word.charAt(0).toUpperCase() + word.slice(1));  }).join(' ');}document.write(titleCase("converting string to titlecase"));</script>
OUTPUT
Converting String To Titlecase
javascript-string
Picked
JavaScript
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Remove elements from a JavaScript Array
Roadmap to Learn JavaScript For Beginners
Difference Between PUT and PATCH Request
JavaScript | Promises
How to filter object array based on attributes?
Lodash _.debounce() Method
JavaScript String includes() Method
JavaScript | fetch() Method
How to map, reduce and filter a Set element using JavaScript ?
Use of min() and max() in Python

06 Jun, 2021
Prerequisite: min() max() in Python Let’s see some interesting facts about min() and max() function. These functions are used to compute the maximum and minimum of the values as passed in its argument. or it gives the lexicographically largest value and lexicographically smallest value respectively, when we passed string or list of strings as arguments. 
python3
l= ["ab", "abc", "abd", "b"] l1="abc" # prints 'b'print(max(l)) # prints 'ab'print(min(l)) #prints 'c'print(max(l1)) #prints 'a'print(min(l1))
Here you notice that output comes according to lexicographical order. but we can also find output according to length of string or as our requirement by simply passing function name or lambda expression. Parameters: By default, min() and max() doesn’t require any extra parameters. however, it has an optional parameters: 
key – function that serves as a key for the min/max comparison 
 
Syntax: max(x1, x2, ..., xn, key=function_name)here x1, x2, x3.., xn passed arguments function_name : denotes which type of operation you want to perform on these arguments. Let function_name=len, so now output gives according to length of x1, x2.., xn.  
Return value:  
It returns a maximum or minimum of list according to the passed parameter.
 
Python3
# Python code explaining min() and max()l = ["ab", "abc", "bc", "c"] print(max(l, key = len))print(min(l, key = len))
abc
c
 
Explanation: In the above program, max() function takes two arguments: l(list) and key = len(function_name).this key = len(function_name) function transforms each element before comparing, it takes the value and returns 1 value which is then used within max() or min() instead of the original value.Here key convert each element of the list to its length and then compare each element according to its length. 
initially l = [“ab”, “abc”, “bc”, “c”] when we passed key=len as arguments then it works like l=[2,3,2,1] 
 
 
Python3
# Python code explaining min() and max()def fun(element):    return(len(element)) l =["ab", "abc", "bc", "c"]print(max(l, key = fun)) # you can also write in this formprint(max(l, key = lambda element:len(element)))
abc
abc
 
Another example:  
Python3
# Python code explaining min() and max()l = [{'name':'ramu', 'score':90, 'age':24},     {'name':'golu', 'score':70, 'age':19}] # here anonymous function takes item as an argument.print(max(l, key = lambda item:item.get('age')))
{'age': 24, 'score': 90, 'name': 'ramu'}
 
Similar we can use min() function instead of max() function as per requirement. 
rrlinus
Akanksha_Rai
simmytarika5
Python function-programs
Python
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
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON
How to install Ruby on Windows?

06 Oct, 2021
Prerequisite: Ruby Programming Language Before we start with the installation of Ruby on Windows, we must have first-hand knowledge of what Ruby is?. Ruby is a pure Object-Oriented language developed by Yukihiro Matsumoto (also known as Matz in the Ruby community) in the mid-1990s in Japan. Everything in Ruby is an object except the blocks but there are replacements too for it i.e procs and lambda. The objective of Ruby’s development was to make it act as a sensible buffer between human programmers and the underlying computing machinery. Ruby is based on many other languages like Perl, Lisp, Smalltalk, Eiffel and Ada. It is an interpreted scripting language which means most of its implementations execute instructions directly and freely, without previously compiling a program into machine-language instructions.
All the versions of Ruby for Windows can be downloaded from rubyinstaller.org. Download the latest version and follow the further instructions for its Installation.
Beginning with the installation:
Getting Started with License Agreement:
Selecting Installation Destination:
Selecting components to be installed:
Extracting Files and Installing:
Finishing Installation:
Installing MYSYS2 Components: 
Choose what to install:
Updating Database and signing keys:
Installing Files:
Downloading Packages:
Installing Packages:
To check if Ruby installed correctly, perform a version check for the same using the following command on the command-line:
ruby -v
Here’s a sample Program to begin with the use of Ruby Programming:Let’s consider a simple Hello World Program.
puts "Hello World"
 Using command-line, run the irb command. After this we can write the ruby code and it will run on command line.
how-to-install
Ruby-Basics
How To
Installation Guide
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PyQt5 | How to set value of Progress Bar ?

22 Apr, 2020
In this article we will see how to set the value of progress bar. Progress bar is basically a bar which is used to visualize the progression of an extended computer operation, such as a download, file transfer, or installation.
In order to set value to progress bar we will use setValue method.
Syntax : bar.setValue(value)
Argument : It takes integer as argument, which should vary from 0 to 100.
Action performed : It will set value to progress bar.
Code :
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import * import sys    class Window(QMainWindow):    def __init__(self):        super().__init__()          # setting title        self.setWindowTitle("Python ")          # setting geometry        self.setGeometry(100, 100, 600, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()      # method for widgets    def UiComponents(self):          # creating progress bar        bar = QProgressBar(self)          # setting geometry to progress bar        bar.setGeometry(200, 150, 200, 30)                  # setting value to progress bar        bar.setValue(50)    # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
p5.js | textSize() Function

16 Apr, 2019
The textSize() function in p5.js is used to set or return the font size of text. This function is used in all subsequent calls to the text() function.
Syntax:
textSize(size)
or
textSize()
Parameters: This function accepts single parameter sizewhich stores the size of the text in terms of pixels.
Below programs illustrate the textSize() function in p5.js:
Example 1: This example uses textSize() function to set the font size of text.
function setup() {          // Create Canvas of given size    createCanvas(380, 170);}  function draw() {          let string = "GeeksforGeeks";          // Set the background color    background(220);          // Set the text size    textSize(30);          // Set the text     text(string, 100, 30);}
Output:
Example 2: This example uses textSize() function to return the font size of text.
function setup() {          // Create Canvas of given size    createCanvas(380, 170);}  function draw() {          let string = "GeeksforGeeks";          // Set the background color    background(220);          // Set the text size    textSize(16);          // store the size of text    var u = textSize();          // Set the stroke color    stroke(255, 204, 0);      // Display result    text("Value of Text Size is : "            + u, 50, 30);}
Output:
Reference: https://p5js.org/reference/#/p5/textSize
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
React Native | Expo – BarCodeScanner

28 May, 2020
Our aim for this article is to understand the usage of BarCodeScanner component by Expo, by developing a simple Scanner app.Before moving onto the development part, we need to initialize the project and install the dependencies. So, open up the terminal and enter the following commands:
expo init // Choose the Blank template when prompted
Move into the project folder and then run the following command:
expo install expo-barcode-scanner
Now that we have installed the scanner component, it’s time to write the code. Let us start by importing the required components, code for which is shown below:
Now it’s time to get inside the App class and carry out the development process step by step
In this step we are going to prompt user, for the permission to access camera. Status of this request is stored in the state of the component, code for which is shown below:
Now, inside the render function we are going to return different views depending upon the status of our request as show below:
 After the user has given us the permission to access camera, we will return the BarCodeScanner component which is demonstrated in the next part.
Got the permission, it’s time to move on to the BarCodeScanner Component.
It’s time to define the barCodeScanned function to access the response data which is demonstrated in the next step.
We are going to alert the user with the response data as an example.
We have successfully completed the development process of this simple BarCodeScanner application. 
Github Repo Link: https://github.com/notnotparas/expo-BarCodeScanner
API Reference: https://docs.expo.io/versions/latest/sdk/bar-code-scanner/
react-js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
REST API (Introduction)
Difference Between PUT and PATCH Request
ReactJS | Router
How to float three div side by side using CSS?
Design a Tribute Page using HTML & CSS
Roadmap to Learn JavaScript For Beginners
JavaScript SyntaxError – Missing ) after argument list

24 Jul, 2020
This JavaScript exception missing ) after argument list occurs if there is an error in function calls. This could be a typing mistake, a missing operator, or an unescaped string.
Message:
SyntaxError: Expected ')' (Edge)
SyntaxError: missing ) after argument list (Firefox)

Error Type:
SyntaxError

Cause of Error: Somewhere in the code, there is an error with function calls. This could be either be a typing mistake, a missing operator, or an unescaped string.
Example 1: In this example, there is a missing operator in string concatenation, So the error has occurred.
HTML
<!DOCTYPE html><html><head>    <title>Syntax Error</title></head><body>    <script>        var str1 = 'This is ';        var str2 = 'GeeksforGeeks';        document.write(str1 str2);    </script></body></html>
Output(In console):
SyntaxError: missing ) after argument list

Example 2: In this example, there is a unescaped string, So the error has occurred.
HTML
<!DOCTYPE html><html><head>    <title>Syntax Error</title></head><body>    <script>        var str1 = 'This is ';        var str2 = 'GeeksforGeeks';        document.write(str1 \str2);    </script></body></html>
Output(in console):
SyntaxError: missing ) after argument list

JavaScript-Errors
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Pandas dataframe.mad()

19 Nov, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas dataframe.mad() function return the mean absolute deviation of the values for the requested axis. The mean absolute deviation of a dataset is the average distance between each data point and the mean. It gives us an idea about the variability in a dataset.
Syntax: DataFrame.mad(axis=None, skipna=None, level=None)
Parameters :axis : {index (0), columns (1)}skipna : Exclude NA/null values when computing the resultlevel : If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a Seriesnumeric_only : Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data. Not implemented for Series.
Returns : mad : Series or DataFrame (if level specified)
Example #1: Use mad() function to find the mean absolute deviation of the values over the index axis.
# importing pandas as pdimport pandas as pd  # Creating the dataframe df = pd.DataFrame({"A":[12, 4, 5, 44, 1],                   "B":[5, 2, 54, 3, 2],                    "C":[20, 16, 7, 3, 8],                   "D":[14, 3, 17, 2, 6]})  # Print the dataframedf
Let’s use the dataframe.mad() function to find the mean absolute deviation.
# find the mean absolute deviation # over the index axisdf.mad(axis = 0)
Output : 
Example #2: Use mad() function to find the mean absolute deviation of values over the column axis which is having some Na values in it.
# importing pandas as pdimport pandas as pd  # Creating the dataframe df = pd.DataFrame({"A":[12, 4, 5, None, 1],                   "B":[7, 2, 54, 3, None],                   "C":[20, 16, 11, 3, 8],                    "D":[14, 3, None, 2, 6]})  # To find the mean absolute deviation# skip the Na values when finding the mad valuedf.mad(axis = 1, skipna = True)
Output :
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
Python
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()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Tryit Editor v3.7

Tryit: HTML table - colgroup
Log functions in Java

The log functions in Java are part of java.lang.Math. The functions include log, log10, log1p. Let us see an example of each of these log functions −
static double log(double a)
The java.lang.Math.log(double a) returns the natural logarithm (base e) of a double value. Let us see an example −
import java.io.*;
public class Main {
   public static void main(String args[]) {
      // get two double numbers
      double x = 60984.1;
      double y = -497.99;
      // get the natural logarithm for x
      System.out.println("Math.log(" + x + ")=" + Math.log(x));
      // get the natural logarithm for y
      System.out.println("Math.log(" + y + ")=" + Math.log(y));
   }
}
Math.log(60984.1)=11.018368453441132
Math.log(-497.99)=NaN
static double log10(double a)
The java.lang.Math.log10(double a) returns the base 10 logarithm of a double value. Let us now see an example −
import java.io.*;
public class Main {
   public static void main(String args[]) {
      // get two double numbers
      double x = 60984.1;
      double y = 1000;
      // get the base 10 logarithm for x
      System.out.println("Math.log10(" + x + ")=" + Math.log10(x));
      // get the base 10 logarithm for y
      System.out.println("Math.log10(" + y + ")=" + Math.log10(y));
   }
}
Math.log10(60984.1)=4.78521661890635
Math.log10(1000.0)=3.0
static double log1p(double x)
The java.lang.Math.log1p(double x) returns the natural logarithm of the sum of the argument and 1.
import java.io.*;
public class Main {
   public static void main(String args[]) {
      // get two double numbers
      double x = 60984.1;
      double y = 1000;
      // call log1p and print the result
      System.out.println("Math.log1p(" + x + ")=" + Math.log1p(x));
      // call log1p and print the result
      System.out.println("Math.log1p(" + y + ")=" + Math.log1p(y));
   }
}
Math.log1p(60984.1)=11.018384851023473
Math.log1p(1000.0)=6.90875477931522
How to change text cursor color in Tkinter?

Tkinter Entry and text widgets are used to create single and multiline text input fields. In order to change the color of the cursor, we can specify the insertbackground property by assigning the color of the cursor.
In this example, we have created the text field and we have changed the color of the cursor by defining the insertbackground property.
#Import the tkinter library
from tkinter import *
#Create an instance of tkinter frame
win= Tk()
win.geometry("750x250")
#Create a text field
text= Text(win)
text.configure(bg= 'SteelBlue3',insertbackground='red')
text.pack()
win.mainloop()
Now, write something in the text field to see the reflected color of the cursor.
Add key-value pair in C# Dictionary

To add key-value pair in C# Dictionary, firstly declare a Dictionary.
IDictionary<int, string> d = new Dictionary<int, string>();
Now, add elements with KeyValuePair.
d.Add(new KeyValuePair<int, string>(1, "TVs"));
d.Add(new KeyValuePair<int, string>(2, "Appliances"));
d.Add(new KeyValuePair<int, string>(3, "Mobile"));
After adding elements, let us display the key-value pair.
 Live Demo
using System;
using System.Collections.Generic;
public class Demo {
   public static void Main() {
      IDictionary<int, string> d = new Dictionary<int, string>();
      d.Add(new KeyValuePair<int, string>(1, "TVs"));
      d.Add(new KeyValuePair<int, string>(2, "Appliances"));
      d.Add(new KeyValuePair<int, string>(3, "Mobile"));
      d.Add(new KeyValuePair<int, string>(4, "Tablet"));
      d.Add(new KeyValuePair<int, string>(5, "Laptop"));
      d.Add(new KeyValuePair<int, string>(6, "Desktop"));
      d.Add(new KeyValuePair<int, string>(7, "Hard Drive"));
      d.Add(new KeyValuePair<int, string>(8, "Flash Drive"));
      foreach (KeyValuePair<int, string> ele in d) {
         Console.WriteLine("Key = {0}, Value = {1}", ele.Key, ele.Value);
      }
   }
}
Key = 1, Value = TVs
Key = 2, Value = Appliances
Key = 3, Value = Mobile
Key = 4, Value = Tablet
Key = 5, Value = Laptop
Key = 6, Value = Desktop
Key = 7, Value = Hard Drive
Key = 8, Value = Flash Drive