code-rag-bench/online-tutorials huggingface dataset:
Java Program to Guess a Random Number in a Range - GeeksforGeeks

04 Dec, 2020
Write a program that generates a random number and asks the user to guess what the number is. If the user’s guess is higher than the random number, the program should display Too high, try again. If the user’s guess is lower than the random number, the program should display Too low, try again. The program should use a loop that repeats until the user correctly guesses the random number.
Input: 15 (a random value that is not known before)
Output: Guess a number between 1 and 100: 
1
Too low, try again
Guess a number between 1 and 100: 
10
Too low, try again
Guess a number between 1 and 100: 
25
Too high, try again
Guess a number between 1 and 100: 
20
Too high, try again
Guess a number between 1 and 100: 
15
Yes, you guessed the number.
Example
Java
// Java Program to guess a Random Number Generation  import java.util.Random;import java.util.Scanner;  public class GFG {    public static void main(String[] args)    {          // stores actual and guess number        int answer, guess;            // maximum value is 100        final int MAX = 100;          // takes input using scanner        Scanner in = new Scanner(System.in);          // Random instance        Random rand = new Random();          boolean correct = false;          // correct answer        answer = rand.nextInt(MAX) + 1;          // loop until the guess is correct        while (!correct) {              System.out.println(                "Guess a number between 1 and 100: ");              // guess value            guess = in.nextInt();              // if guess is greater than actual            if (guess > answer) {                System.out.println("Too high, try again");            }              // if guess is less than actual            else if (guess < answer) {                System.out.println("Too low, try again");            }              // guess is equal to actual value            else {                  System.out.println(                    "Yes, you guessed the number.");                  correct = true;            }        }        System.exit(0);    }}
Output
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.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
Iterate through List in Java
PyQt5 QDockWidget – Setting Layout Direction - GeeksforGeeks

29 Jan, 2022
In this article we will see how we can set the layout direction to the QDockWidget. QDockWidget provides the concept of dock widgets, also know as tool palettes or utility windows. Dock windows are secondary windows placed in the dock widget area around the central widget in a QMainWindow(original window). Layout specifies how the children get arranged, by setting layout direction we can specify the order of the arrangement. 
In order to do this we will use setLayoutDirection method with the dock widget object.Syntax : dock.setLayoutDirection(direct)Argument : It takes direction object as argumentReturn : It returns None  
Below is the implementation  
Python3
# 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, 500, 400)         # calling method        self.UiComponents()         # showing all the widgets        self.show()     # method for components    def UiComponents(self):         # creating dock widget        dock = QDockWidget(self)         # setting title to the dock widget        dock.setWindowTitle("                   GfG ")          # push button        push = QPushButton("Press", self)         # setting widget to the dock        dock.setWidget(push)         # setting layout direction        dock.setLayoutDirection(Qt.RightToLeft)         # creating a label        label = QLabel("GfG", self)         # setting geometry to the label        label.setGeometry(100, 200, 300, 80)         # making label multi line        label.setWordWrap(True)         # setting geometry tot he dock widget        dock.setGeometry(100, 0, 200, 30)          # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :  
 
sagartomar9927
Python PyQt-QDockWidget
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
C# Program to Get Complete Path of Current Directory - GeeksforGeeks

21 Apr, 2022
Given a directory, now our task is to find the path of the given directory or current directory. So to this task, we use the GetCurrentDirectory() method of the Directory class. This method will return the complete path of the current directory. The result given by this method will not end with a backslash (\).
Syntax:
public static string GetCurrentDirectory();
Return: It will return a string that represents the path of the current directory. 
Exception: It will throw the following exceptions:
UnauthorizedAccessException: This exception occurs when the caller does not have the required permission.
NotSupportedException: This exception occurs when the operating system is Windows CE. It does not have the functionality of the current directory.
Example:
C#
// C# program to find the path of// the current directoryusing System;using System.IO; class GFG{ static void Main(){         // Finding the complete path of the current directory    // Using GetCurrentDirectory() method    Console.WriteLine("Current directory path: " +                      Directory.GetCurrentDirectory());}}
Output:
Current directory path: C:\Users\Sravan\ConsoleApplication12
simmytarika5
Picked
C#
C# Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Extension Method in C#
HashSet in C# with Examples
C# | Inheritance
Partial Classes in C#
C# | Generics - Introduction
Convert String to Character Array in C#
Program to Print a New Line in C#
Getting a Month Name Using Month Number in C#
Socket Programming in C#
C# Program for Dijkstra's shortest path algorithm | Greedy Algo-7
Ternary Plots in Plotly - GeeksforGeeks

01 Oct, 2020
A Plotly is a Python library that is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library.
A ternary plot is also known as a ternary graph, triangle plot, simplex plot which is a barycentric plot on three variables which sum to a constant. It graphically depicts the ratios of the three variables as positions in an equilateral triangle. It can be created using two-class i.e. express class and graph_objects class.
In plotly, express is an easy-to-use,high-level interface that helps to operates a variety of types of data and produce simple style figures. It provides scatter_ternary() method to create ternary plots.
Syntax: scatter_ternary( a=None, b=None, c=None, color=None,labels={},width=None, height=None)
Parameters:
a: Values from this column or array_like are used to position marks along the a axis in ternary coordinates.
b: Values from this column or array_like are used to position marks along the b axis in ternary coordinates.
c: Values from this column or array_like are used to position marks along the c axis in ternary coordinates.
color:  Either a name of a column in data_frame, or a pandas Series or array_like object. Values from this column or array_like are used to assign color to marks.
width: The figure width in pixels.
height: The figure height in pixels.
Example:
Python3
import plotly.express as px    df = px.data.iris()fig = px.scatter_ternary(df, a="sepal_length",                         b="sepal_width", c="petal_length",                         color="species", size_max=20)fig.show()
Output:
Let’s see one example of a ternary scatter plot with plotly graph objects to make it clear. It can be created using the Scatterternary() method.
Example:
Python3
import plotly.express as pximport plotly.graph_objects as go    df = px.data.iris()fig = go.Figure(go.Scatterternary({    'mode': 'markers',    'a': df['sepal_length'],    'b': df['sepal_width'],    'c': df['petal_length'],    'marker': {        'color': 'green',        'size': 14,        'line': {'width': 2}    }}))  fig.show()
Output:
Python-Plotly
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Taking input in Python
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
JavaScript string.valueOf() Method - GeeksforGeeks

07 Oct, 2021
Below is the example of the string.valueOf() Method.  
Example:  
javascript
<script>    var a = new String("GeeksforGeeks");    document.write(a.valueOf());</script>
Output:  
GeeksforGeeks
The string.valueOf() is an inbuilt method in JavaScript which is used to return the value of the given string.Syntax:  
string.valueOf()
Parameters: It does not accept any parameter.Return Values: It returns a string which represent the value of the given string object.JavaScript code to show the working of string.valueOf() method: Program 1:  
javascript
<script>    // Taking a string as input and printing it    // with the help of string.valueOf() function    var a = new String("GeeksforGeeks");    document.write(a.valueOf());</script>
Output:  
GeeksforGeeks
Program 2:  
javascript
<script>    // Taking a string as input and printing it    // with the help of string.valueOf() function    var a = new String("Geeks");    var b = new String("for");    var c = new String("Geeks");    document.write(a.valueOf(),b.valueOf(),c.valueOf());</script>
Output:  
GeeksforGeeks
 
Supported Browser:
Chrome 1 and above
Edge 12 and above
Firefox 1 and above
Internet Explorer 4 and above
Opera 3 and above
Safari 1 and above
ysachin2314
JavaScript-Methods
javascript-string
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Algorithms | Greedy Algorithms | Question 3 - GeeksforGeeks

28 Jun, 2021
A networking company uses a compression technique to encode the message before transmitting over the network. Suppose the message contains the following characters with their frequency:
character   Frequency    a            5    b           9    c           12    d           13    e           16    f           45
Note : Each character in input message takes 1 byte.
If the compression technique used is Huffman Coding, how many bits will be saved in the message?(A) 224(B) 800(C) 576(D) 324Answer: (C)Explanation:
Total number of characters in the message = 100. 
Each character takes 1 byte. So total number of bits needed = 800.

After Huffman Coding, the characters can be represented with:
f: 0
c: 100
d: 101
a: 1100
b: 1101
e: 111
Total number of bits needed = 224
Hence, number of bits saved = 800 - 224 = 576
See here for complete explanation and algorithm.

Quiz of this Question
Algorithms-Greedy Algorithms
Greedy Algorithms
Algorithms Quiz
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Algorithms | Graph Minimum Spanning Tree | Question 6
Algorithms | Sorting | Question 6
Algorithms | Recursion | Question 2
Algorithms | Sorting | Question 9
Algorithms | Sorting | Question 4
Algorithms | Analysis of Algorithms | Question 19
Algorithms | Sorting | Question 3
Algorithms | Sorting | Question 12
Algorithms | Sorting | Question 13
Algorithms | Backtracking | Question 1
How to LEFT ANTI join under some matching condition in Pandas - GeeksforGeeks

19 Dec, 2021
LEFT ANTI Join is the opposite of semi-join. excluding the intersection, it returns the left table. It only returns the columns from the left table and not the right.
On the created dataframes we perform left join and subset using isin() function to check if the part on which the datasets are merged is in the subset of the merged dataset.
Syntax:
DataFrame.isin(values)
Parameters: 
values: iterable, Series, DataFrame or dict
Returns: 
DataFrame
Example:
In the below code, we used the indicator to find the rows which are ‘Left_only’ and subset the merged dataset, and assign it to df. finally, we retrieve the part which is only in our first data frame df1. the output is antijoin of the two data frames.
Python3
# importing packagesimport pandas as pd  # anti-join# creating dataframes using pd.DataFrame() method.df1 = pd.DataFrame({    "city": ["new york", "chicago", "orlando", 'mumbai'],    "temperature": [21, 14, 35, 30],    "humidity": [65, 68, 75, 75],})df2 = pd.DataFrame({    "city": ["chicago", "new york", "orlando"],    "humidity": [67, 60, 70]})  # carrying out anti join using merge methoddf3 = df1.merge(df2, on='city', how='left', indicator=True)  df = df3.loc[df3['_merge'] == 'left_only', 'city']  d = df1[df1['city'].isin(df)]  print(d)
Output:
     city  temperature  humidity
3  mumbai           30        75
We can use the ‘~’ operator on the semi-join. It results in anti-join. 
Semi-join: Similar to inner join, semi-join returns the intersection but it only returns the columns from the left table and not the right. it has no duplicate values. 
Syntax:
[~df1[‘column_name’].isin(df2[‘column_name’])]
where, 
df1 is the first dataframe
df2 is the second dataframe
column_name is the matching column in both the dataframes
Example:
In this example, we merge df1 and df2 on ‘city’ by default it is  ‘inner join’, after merging, We exclude the part of df1 which is in df3 and print out the resultant dataframe. 
Python3
# codeimport pandas as pd  # inverse of semi-join:# creating dataframes using pd.DataFrame() method.df1 = pd.DataFrame({    "city": ["new york", "chicago", "orlando", 'mumbai'],    "temperature": [21, 14, 35, 30],    "humidity": [65, 68, 75, 75],})df2 = pd.DataFrame({    "city": ["chicago", "new york", "orlando"],    "humidity": [67, 60, 70]})  # carrying out anti join using merge methoddf3 = df1.merge(df2, on='city')  df = df1[~df1['city'].isin(df3['city'])]  print(df)
Output:
     city  temperature  humidity
3  mumbai           30        75
Picked
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
HTML abbr Tag - GeeksforGeeks

24 Mar, 2022
The <abbr> tag(Abbreviation) in HTML is used to define the abbreviation or short form of an element. The <abbr> and <acronym> tags are used as shortened versions and used to represent a series of letters. The abbreviation is used to provide useful information to the browsers, translation systems, and search-engines.Syntax: 
<abbr title=""> Short form </abbr>
Attribute: This tag accepts an optional attribute as mentioned above and described below:
title: It is used to specify extra information about the element. When the mouse moves over the element then it shows the information.
Example: 
html
<!DOCTYPE html><html>  <body>    <h1>GeeksforGeeks</h1>    <h2>This is <abbr> Tag</h2>    <abbr title="GeeksforGeeks">GFG</abbr></body>  </html>
Output:  
Supported Browser: 
Google Chrome
Internet Explorer
Firefox
Opera
Safari
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
shubhamyadav4
HTML-Tags
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to update Node.js and NPM to next version ?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
LocalDateTime toString() method in Java with Examples - GeeksforGeeks

30 Nov, 2018
The toString() method of LocalDateTime class is used to get the String representation of this LocalDateTime. This method is derived from the Object Class and behaves in the similar way.
Syntax:
public String toString()
Parameter: This method takes no parameters.
Returns: This method returns a String value which is the String representation of this LocalDateTime.
Below programs illustrate the LocalDateTime.toString() method:
Program 1:
// Program to illustrate the toString() method  import java.util.*;import java.time.*;  public class GfG {    public static void main(String[] args)    {          // Get the LocalDateTime instance        LocalDateTime dt = LocalDateTime.now();          // Get the String representation of this LocalDateTime        // using toString() method        System.out.println(dt.toString());    }}
2018-11-30T10:16:26.939

Program 2:
// Program to illustrate the toString() method  import java.util.*;import java.time.*;  public class GfG {    public static void main(String[] args)    {          // Get the LocalDateTime instance        LocalDateTime dt            = LocalDateTime                  .parse("2018-11-03T12:45:30");          // Get the String representation of this LocalDateTime        // using toString() method        System.out.println(dt.toString());    }}
2018-11-03T12:45:30

Reference: https://docs.oracle.com/javase/10/docs/api/java/time/LocalDateTime.html#toString()
Java-Functions
Java-LocalDateTime
Java-time package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
HashMap in Java with Examples
Stream In Java
Interfaces in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java
Multithreading in Java
Angular Material 7 - Badge

The <mat-badge>, an Angular Directive, is used to create a badges which is a small status descriptor for UI elements. A badge typically carries a number or other short set of characters, that appears in proximity to another UI element.
In this chapter, we will showcase the configuration required to draw a badge control using Angular Material.
Follow the following steps to update the Angular application we created in Angular 6 - Project Setup chapter −
Following is the content of the modified module descriptor app.module.ts.
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {MatBadgeModule, MatButtonModule, MatIconModule} from '@angular/material'
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
@NgModule({
   declarations: [
      AppComponent
   ],
   imports: [
      BrowserModule,
      BrowserAnimationsModule,
      MatBadgeModule, MatButtonModule, MatIconModule,
      FormsModule,
      ReactiveFormsModule
   ],
   providers: [],
   bootstrap: [AppComponent]
})
export class AppModule { }
Following is the content of the modified HTML host file app.component.html.
<p><span matBadge = "4" matBadgeOverlap = "false">Mail</span></p>
<p>
   <button mat-raised-button color = "primary"
      matBadge = "8" matBadgePosition = "before" matBadgeColor = "accent">
      Action
   </button>
</p>
<p><mat-icon matBadge = "15" matBadgeColor = "warn">home</mat-icon></p>
Verify the result.
As first, we've created a span, a button and a icon.
Then, we've added badges to each element using mat-badge attribute.

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    28 Lectures 
     2.5 hours 

 Anadi Sharma

    11 Lectures 
     7.5 hours 

 SHIVPRASAD KOIRALA

    16 Lectures 
     2.5 hours 

 Frahaan Hussain

    69 Lectures 
     5 hours 

 Senol Atac

    53 Lectures 
     3.5 hours 

 Senol Atac
 Print
 Add Notes
 Bookmark this page
Unix / Linux Shell - The if...else...fi statement

The if...else...fi statement is the next form of control statement that allows Shell to execute statements in a controlled way and make the right choice.
if [ expression ]
then
   Statement(s) to be executed if expression is true
else
   Statement(s) to be executed if expression is not true
fi

The Shell expression is evaluated in the above syntax. If the resulting value is true, given statement(s) are executed. If the expression is false, then no statement will be executed.
The above example can also be written using the if...else statement as follows −
#!/bin/sh

a=10
b=20

if [ $a == $b ]
then
   echo "a is equal to b"
else
   echo "a is not equal to b"
fi
Upon execution, you will receive the following result −
a is not equal to b


    129 Lectures 
     23 hours 

 Eduonix Learning Solutions

    5 Lectures 
     4.5 hours 

 Frahaan Hussain

    35 Lectures 
     2 hours 

 Pradeep D

    41 Lectures 
     2.5 hours 

 Musab Zayadneh

    46 Lectures 
     4 hours 

 GUHARAJANM

    6 Lectures 
     4 hours 

 Uplatz
 Print
 Add Notes
 Bookmark this page
Implement multiple conditions in MongoDB?

Let us first create a collection with documents −
> db.multipleConditionDemo.insertOne({"_id":1,"Name":"John"});
{ "acknowledged" : true, "insertedId" : 1 }
> db.multipleConditionDemo.insertOne({"_id":2,"Name":"Carol"});
{ "acknowledged" : true, "insertedId" : 2 }
> db.multipleConditionDemo.insertOne({"_id":3,"Name":"Sam"});
{ "acknowledged" : true, "insertedId" : 3 }
> db.multipleConditionDemo.insertOne({"_id":4,"Name":"David"});
{ "acknowledged" : true, "insertedId" : 4 }
Following is the query to display all documents from a collection with the help of find() method −
> db.multipleConditionDemo.find().pretty();
This will produce the following output −
{ "_id" : 1, "Name" : "John" }
{ "_id" : 2, "Name" : "Carol" }
{ "_id" : 3, "Name" : "Sam" }
{ "_id" : 4, "Name" : "David" }
Following is the query to implement multiple conditions in WHERE clause −
> db.multipleConditionDemo.remove({ $or: [ { _id: 2 }, { _id: 3 } ] });
WriteResult({ "nRemoved" : 2 })
Let us check the documents from the above collection once again −
> db.multipleConditionDemo.find().pretty();
This will produce the following output −
{ "_id" : 1, "Name" : "John" }
{ "_id" : 4, "Name" : "David" }
Properties elements() method in Java with Examples - GeeksforGeeks

11 Aug, 2021
The elements() method of Properties class is used to get the enumeration of this Properties object. It can be further used to retrieve the elements sequentially using this Enumeration received. 
Syntax:  
public Enumeration elements()
Parameters: This method do not accepts any parameters.Returns: This method returns an Enumeration of the values in this Properties object.Below programs illustrate the elements() method:Program 1:  
Java
// Java program to demonstrate// elements() method. import java.util.*; public class GFG {     // Main method    public static void main(String[] args)    {         // Create a properties and add some values        Properties properties = new Properties();        properties.put("Pen", 10);        properties.put("Book", 500);        properties.put("Clothes", 400);        properties.put("Mobile", 5000);         // Print Properties details        System.out.println("Current Properties: "                           + properties.toString());         // Creating an empty enumeration to store        Enumeration enu = properties.elements();         System.out.println("The enumeration of values are:");         // Displaying the Enumeration        while (enu.hasMoreElements()) {            System.out.println(enu.nextElement());        }    }}
Current Properties: {Book=500, Mobile=5000, Pen=10, Clothes=400}
The enumeration of values are:
500
5000
10
400
 
Program 2: 
Java
// Java program to demonstrate// elements() method. import java.util.*; public class GFG {     // Main method    public static void main(String[] args)    {         // Create a properties and add some values        Properties properties = new Properties();         properties.put(1, "100RS");        properties.put(2, "500RS");        properties.put(3, "1000RS");         // print Properties details        System.out.println("Current Properties: "                           + properties.toString());         // Creating an empty enumeration to store        Enumeration enu = properties.elements();         System.out.println("The enumeration of values are:");         // Displaying the Enumeration        while (enu.hasMoreElements()) {            System.out.println(enu.nextElement());        }    }}
Current Properties: {3=1000RS, 2=500RS, 1=100RS}
The enumeration of values are:
1000RS
500RS
100RS
 
References: https://docs.oracle.com/javase/9/docs/api/java/util/Properties.html#elements–
nidhi_biet
as5853535
Java - util package
Java-Functions
Java-Properties
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
Stream In Java
HashMap in Java with Examples
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Singleton Class in Java
Multithreading in Java
Python | Pandas Series.str.isalpha()

23 Aug, 2019
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 str.isalpha() method is used to check if all characters in each string in series are alphabetic(a-z/A-Z). Whitespace or any other character occurrence in the string would return false, but if there is a complete numeric value, then it would return NaN.
Syntax: Series.str.isalpha()
Return Type: Boolean series, Null values might be included too depending upon caller series.
To download the CSV used in code, click here.
In the following examples, the data frame used contains data of some NBA players. The image of data frame before any operations is attached below. Example #1:In this example, the isalpha() method is applied on the College column. Before that, the Null rows are removed using .dropna() method to avoid errors.
# importing pandas moduleimport pandas as pd  # making data framedata = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv")  # removing null values to avoid errorsdata.dropna(inplace = True)  # creating bool seriesdata["bool_series"]= data["College"].str.isalpha()  # displaydata
Output:As shown in the output image, the bool_series can be matched with the College column and it can be clearly seen that if the string contains only alphabets, True is returned. Example #2:In this example, the isalpha() method is applied on Name column twice. First a bool series is created for the original name column, after that the white spaces are removed using str.replace() method and then a new bool_series is created again.
# importing pandas moduleimport pandas as pd  # making data framedata = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv")  # removing null values to avoid errorsdata.dropna(inplace = True)  # creating bool series with original columndata["bool_series1"]= data["Name"].str.isalpha()  # removing white spacesdata["Name"]= data["Name"].str.replace(" ", "")  # creating bool series with new columndata["bool_series2"]= data["Name"].str.isalpha()  # displaydata.head(10)
Output:As shown in the output image, the Bool series was false for all values until the strings had whitespace. After removing white spaces, the bool series in only false where the string is having special characters.
Akanksha_Rai
Python pandas-series
Python pandas-series-methods
Python-pandas
Python-pandas-series-str
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function
transform() in C++

The transform function is present in the C++ STL. To use it, we have to include the algorithm header file. This is used to perform an operation on all elements. For an example if we want to perform square of each element of an array, and store it into other, then we can use the transform() function.
The transform function works in two modes. These modes are −
Unary operation mode
Binary operation mode
In this mode the function takes only one operator (or function) and convert into output.
#include <iostream>
#include <algorithm>
using namespace std;
int square(int x) {
   //define square function
   return x*x;
}
int main(int argc, char **argv) {
   int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
   int res[10];
   transform(arr, arr+10, res, square);
   for(int i = 0; i<10; i++) {
      cout >> res[i] >> "\n";
   }
}
1
4
9
16
25
36
49
64
81
100
In this mode the it can perform binary operation on the given data. If we want to add elements of two different array, then we have to use binary operator mode.
#include <iostream>
#include <algorithm>
using namespace std;
int multiply(int x, int y) {
   //define multiplication function
   return x*y;
}
int main(int argc, char **argv) {
   int arr1[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
   int arr2[10] = {54, 21, 32, 65, 58, 74, 21, 84, 20, 35};
   int res[10];
   transform(arr1, arr1+10, arr2, res, multiply);
   for(int i = 0; i<10; i++) {
      cout >> res[i] >> "\n";
   }
}
54
42
96
260
290
444
147
672
180
350
Python | Pandas Timestamp.isocalendar

14 Jan, 2019
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 Timestamp.isocalendar() function return a 3-tuple containing ISO year, week number, and weekday for the given Timestamp object.
Syntax :Timestamp.isocalendar()
Parameters : None
Return : Tuple
Example #1: Use Timestamp.isocalendar() function to return the date of the given Timestamp object based on ISO calendar.
# importing pandas as pdimport pandas as pd  # Create the Timestamp objectts = pd.Timestamp(year = 2011,  month = 11, day = 21,                  hour = 10, second = 49, tz = 'US/Central')  # Print the Timestamp objectprint(ts)
Output :
Now we will use the Timestamp.isocalendar() function to return the date in ts object based on ISO calendar.
# return the date as an ISO calendarts.isocalendar()
Output :
As we can see in the output, the Timestamp.isocalendar() function has returned a tuple containing the year, week number and the week day for the given Timestamp object.
Example #2: Use Timestamp.isocalendar() function to return the date of the given Timestamp object based on ISO calendar.
# importing pandas as pdimport pandas as pd  # Create the Timestamp objectts = pd.Timestamp(year = 2009, month = 5, day = 31,                  hour = 4, second = 49, tz = 'Europe/Berlin')  # Print the Timestamp objectprint(ts)
Output :
Now we will use the Timestamp.isocalendar() function to return the date in ts object based on ISO calendar
# return the date as an ISO calendarts.isocalendar()
Output :
As we can see in the output, the Timestamp.isocalendar() function has returned a tuple containing the year, week number and the week day for the given Timestamp object.
Python Pandas-Timestamp
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Convert timestamp to readable date/time in PHP

01 Aug, 2021
Problem: Convert timestamp to readable date/time in PHPSolution: This can be achieved with the help of date() function, which is an inbuilt function in PHP can be used to format the timestamp given by time() function. This function returns a string formatted according to the given format string using the given integer timestamp or the current time if no timestamp is given.
Example 1:
<?phpecho date('m/d/Y H:i:s', 1541843467);?>
Output:
11/10/2018 09:51:07

Example 2:
<?phpecho date('m/d/Y H:i:s', time());?>
Output:
Current Time in formatted form

Reference: http://php.net/manual/en/function.date.php
PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.
date-time-program
PHP-date-time
Picked
Technical Scripter 2018
PHP
Technical Scripter
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Plotly - 3D Scatter and Surface Plot

This chapter will give information about the three-dimensional (3D) Scatter Plot and 3D Surface Plot and how to make them with the help of Plotly.
A three-dimensional (3D) scatter plot is like a scatter plot, but with three variables - x, y, and z or f(x, y) are real numbers. The graph can be represented as dots in a three-dimensional Cartesian coordinate system. It is typically drawn on a two-dimensional page or screen using perspective methods (isometric or perspective), so that one of the dimensions appears to be coming out of the page.
3D scatter plots are used to plot data points on three axes in an attempt to show the relationship between three variables. Each row in the data table is represented by a marker whose position depends on its values in the columns set on the X, Y, and Z axes.
A fourth variable can be set to correspond to the color or size of the markers, thus, adding yet another dimension to the plot. The relationship between different variables is called correlation.
A Scatter3D trace is a graph object returned by go.Scatter3D() function. Mandatory arguments to this function are x, y and z each of them is a list or array object.
For example −
import plotly.graph_objs as go
import numpy as np
z = np.linspace(0, 10, 50)
x = np.cos(z)
y = np.sin(z)
trace = go.Scatter3d(
   x = x, y = y, z = z,mode = 'markers', marker = dict(
      size = 12,
      color = z, # set color to an array/list of desired values
      colorscale = 'Viridis'
      )
   )
layout = go.Layout(title = '3D Scatter plot')
fig = go.Figure(data = [trace], layout = layout)
iplot(fig)
The output of the code is given below −
Surface plots are diagrams of three-dimensional data. In a surface plot, each point is defined by 3 points: its latitude, longitude, and altitude (X, Y and Z). Rather than showing the individual data points, surface plots show a functional relationship between a designated dependent variable (Y), and two independent variables (X and Z). This plot is a companion plot to the contour plot.
Here, is a Python script to render simple surface plot where y array is transpose of x and z is calculated as cos(x2+y2)
import numpy as np
x = np.outer(np.linspace(-2, 2, 30), np.ones(30))
y = x.copy().T # transpose
z = np.cos(x ** 2 + y ** 2)
trace = go.Surface(x = x, y = y, z =z )
data = [trace]
layout = go.Layout(title = '3D Surface plot')
fig = go.Figure(data = data)
iplot(fig)
Below mentioned is the output of the code which is explained above −
Python – Filter Tuples with All Even Elements

02 Sep, 2020
Given List of tuples, filter only those with all even elements.
Input : test_list = [(6, 4, 2, 8), (5, 6, 7, 6), (8, 1, 2), (7, )]Output : [(6, 4, 2, 8)]Explanation : Only 1 tuple with all even elements.
Input : test_list = [(6, 4, 2, 9), (5, 6, 7, 6), (8, 1, 2), (7, )]Output : []Explanation : No tuple with all even elements.
Method #1 : Using loop
In this, we iterate each tuple, and check for all even elements using % operator and if even one element is odd, tuple is flagged and not added in result list.
Python3
# Python3 code to demonstrate working of # Filter Tuples with All Even Elements# Using loop  # initializing listtest_list = [(6, 4, 2, 8), (5, 6, 7, 6), (8, 0, 2), (7, )]  # printing original listprint("The original list is : " + str(test_list))  res_list = []for sub in test_list:    res = True           # check if all are even    for ele in sub:        if ele % 2 != 0:            res = False            break    if res:        res_list.append(sub)  # printing resultsprint("Filtered Tuples : " + str(res_list))
The original list is : [(6, 4, 2, 8), (5, 6, 7, 6), (8, 0, 2), (7, )]
Filtered Tuples : [(6, 4, 2, 8), (8, 0, 2)]

Method #2 : Using all() + list comprehension
In this, the task of checking for all elements to be even is done using all(), and list comprehension is used for task of filtering post checking.
Python3
# Python3 code to demonstrate working of # Filter Tuples with All Even Elements# Using all() + list comprehension  # initializing listtest_list = [(6, 4, 2, 8), (5, 6, 7, 6), (8, 0, 2), (7, )]  # printing original listprint("The original list is : " + str(test_list))  # testing for tuple to be even using all()res = [sub for sub in test_list if all(ele % 2 == 0 for ele in sub)]  # printing resultsprint("Filtered Tuples : " + str(res))
The original list is : [(6, 4, 2, 8), (5, 6, 7, 6), (8, 0, 2), (7, )]
Filtered Tuples : [(6, 4, 2, 8), (8, 0, 2)]

Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
How to update the value stored in a Dictionary in C#?

In C#, Dictionary is a generic collection which is generally used to store key/value pairs. In Dictionary, the key cannot be null, but value can be. A key must be unique. Duplicate keys are not allowed if we try to use duplicate key then compiler will throw an exception.
As mentioned above a value in a dictionary can be updated by using its key as the key is unique for every value.
myDictionary[myKey] = myNewValue;
Let’s take a dictionary of students having id and name. Now if we want to change the name of the student having id 2 from "Mrk" to "Mark".
 Live Demo
using System;
using System.Collections.Generic;
namespace DemoApplication{
   class Program{
      static void Main(string[] args){
         Dictionary<int, string> students = new Dictionary<int, string>{
            { 1, "John" },
            { 2, "Mrk" },
            { 3, "Bill" }
         };
         Console.WriteLine($"Name of student having id 2: {students[2]}");
         students[2] = "Mark";
         Console.WriteLine($"Updated Name of student having id 2: {students[2]}");
         Console.ReadLine();
      }
   }
}
The output of the above code is −
Name of student having id 2: Mrk
Updated Name of student having id 2: Mark
Python Program for Number of elements with odd factors in given range

03 Dec, 2018
Given a range [n,m], find the number of elements that have odd number of factors in the given range (n and m inclusive).
Examples:
Input  : n = 5, m = 100
Output : 8
The numbers with odd factors are 9, 16, 25, 
36, 49, 64, 81 and 100

Input  : n = 8, m = 65
Output : 6

Input  : n = 10, m = 23500
Output : 150

A Simple Solution is to loop through all numbers starting from n. For every number, check if it has an even number of factors. If it has an even number of factors then increment count of such numbers and finally print the number of such elements. To find all divisors of a natural number efficiently, refer All divisors of a natural number
An Efficient Solution is to observe the pattern. Only those numbers, which are perfect Squares have an odd number of factors. Let us analyze this pattern through an example.
For example, 9 has odd number of factors, 1, 3 and 9. 16 also has odd number of factors, 1, 2, 4, 8, 16. The reason for this is, for numbers other than perfect squares, all factors are in the form of pairs, but for perfect squares, one factor is single and makes the total as odd.
How to find number of perfect squares in a range?The answer is difference between square root of m and n-1 (not n)There is a little caveat. As both n and m are inclusive, if n is a perfect square, we will get an answer which is less than one the actual answer. To understand this, consider range [4, 36]. Answer is 5 i.e., numbers 4, 9, 16, 25 and 36.But if we do (36**0.5) – (4**0.5) we get 4. So to avoid this semantic error, we take n-1.
# Python program to count number of odd squares# in given range [n, m]  def countOddSquares(n, m):    return int(m**0.5) - int((n-1)**0.5)  # Driver coden = 5m = 100print("Count is", countOddSquares(n, m))  # This code is contributed by# Mohit Gupta_OMG <0_o>
Output:
Count is 8

Time Complexity: O(1)
Please refer complete article on Number of elements with odd factors in given range for more details!
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary
Python program to add two numbers
Python Program for Binary Search (Recursive and Iterative)
Python Program for factorial of a number
Python program to find second largest number in a list
Iterate over characters of a string in Python
Python program to interchange first and last elements in a list
Python | Convert set into a list
Appending to list in Python dictionary
Python | sympy.factor() method

12 Jun, 2019
With the help of sympy.factor() method, we can find the factors of mathematical expressions in the form of variables by using sympy.factor() method.
Syntax : sympy.factor(expression)Return : Return factor of mathematical expression.
Example #1 :In this example we can see that by using sympy.factor() method, we can find the factors of mathematical expression with variables. Here we use symbols() method also to declare a variable as symbol.
# import sympyfrom sympy import expand, symbols, factor  x, y = symbols('x y')gfg_exp = x + yexp = sympy.expand(gfg_exp**2)  # Use sympy.factor() methodfact = factor(exp)  print(fact)
Output :
(x + y)**2
Example #2 :
# import sympyfrom sympy import expand, symbols, factor  x, y, z = symbols('x y z')gfg_exp = x + y + zexp = sympy.expand(gfg_exp**2)  # Use sympy.factor() methodfact = factor(exp)  print(fact)
Output :
(x + y + z)**2
SymPy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL Tryit Editor v1.6

SELECT * FROM Customers
ORDER BY CustomerName ASC;
​
Edit the SQL Statement, and click "Run SQL" to see the result.
This SQL-Statement is not supported in the WebSQL Database.
The example still works, because it uses a modified version of SQL.
Your browser does not support WebSQL.
Your are now using a light-version of the Try-SQL Editor, with a read-only Database.
If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time.
Our Try-SQL Editor uses WebSQL to demonstrate SQL.
A Database-object is created in your browser, for testing purposes.
You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button.
WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object.
WebSQL is supported in Chrome, Safari, Opera, and Edge(79).
If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
Calculate distance and duration between two places using google distance matrix API in Python?

We almost all use google maps to check distance between source and destination and check the travel time. For developers and enthusiasts, google provide ‘google distance matrix API’ to calculate the distance and duration between two places.
To use google distance matrix api, we need google maps API keys, which you can get from below link:
https://developers.google.com/maps/documentation/distance-matrix/get-api-key
We can accomplish this by using different python library, like:
Pandas
googlemaps
Requests
Json
I am using very basic requests and json library. Using pandas you can fill multiple source and destination places at a time and get the result in csv file.
Below is the program to implement the same:
# Import required library
import requests
import json
#Enter your source and destination city
originPoint = input("Please enter your origin city: ")
destinationPoint= input("Please enter your destination city: ")
#Place your google map API_KEY to a variable
apiKey = 'YOUR_API_KEY'
#Store google maps api url in a variable
url = 'https://maps.googleapis.com/maps/api/distancematrix/json?'
# call get method of request module and store respose object
r = requests.get(url + 'origins = ' + originPoint + '&destinations = ' + destinationPoint + '&key = ' + apiKey)
#Get json format result from the above response object
res = r.json()
#print the value of res
print(res)
Please enter your origin city: Delhi
Please enter your destination city: Karnataka
{'destination_addresses': [‘Karnataka, India’],'origin_addresses': [‘Delhi, India’], 'rows': [{'elements': [{'distance': {'text': '1,942 km', 'value': 1941907}, 'duration': {'text': '1 day 9 hours', 'value': 120420},
'status': 'OK'}]}], 'status': 'OK'}