code-rag-bench/online-tutorials huggingface dataset:
How to Plot a Logistic Regression Curve in R?

27 Jan, 2022
In this article, we will learn how to plot a Logistic Regression Curve in the R programming Language.
Logistic regression is basically a supervised classification algorithm. That helps us in creating a differentiating curve that separates two classes of variables. To Plot the Logistic Regression curve in the R Language, we use the following methods.
Dataset used: Sample4
To plot the logistic regression curve in base R, we first fit the variables in a logistic regression model by using the glm() function. The glm() function is used to fit generalized linear models, specified by giving a symbolic description of the linear predictor. Then we use that model to create a data frame where the y-axis variable is changed to its predicted value derived by using the predict() function with the above-created model. Then we plot a scatter plot of original points by using the plot() function and predicted values by using the lines() function.
Syntax:
logistic_model <- glm( formula, family, dataframe )
plot( original_dataframe )
lines( predicted_dataframe )
Parameter:
formula: determines the symbolic description of the model to be fitted.
family: determines the description of the error distribution and link function to be used in the model.
dataframe: determines the data frame to be used for fitting purpose
Example: Plot logistic regression
R
# load dataframedf <- read.csv("Sample4.csv") # create logistic regression modellogistic_model <- glm(var1 ~ var2, data=df, family=binomial) #Data frame with hp in ascending orderPredicted_data <- data.frame(var2=seq(  min(df$var2), max(df$var2),len=500)) # Fill predicted values using regression modelPredicted_data$var1 = predict(  logistic_model, Predicted_data, type="response") # Plot Predicted data and original data pointsplot(var1 ~ var2, data=df)lines(var1 ~ var2, Predicted_data, lwd=2, col="green")
Output:
To plot the logistic curve using the ggplot2 package library, we use the stat_smooth() function. The argument method of function with the value “glm” plots the logistic regression curve on top of a ggplot2 plot. So, we first plot the desired scatter plot of original data points and then overlap it with a regression curve using the stat_smooth() function.
Syntax:
plot + stat_smooth( method=”glm”, se, method.args )
Parameter:
se: determines a boolean that tells whether to display confidence interval around smooth.
method.args: determines the method function for logistic curve.
Example: Plot logistic regression
R
# load library ggplot2library(ggplot2) # load data from CSVdf <- read.csv("Sample4.csv") # Plot Predicted data and original data pointsggplot(df, aes(x=var2, y=var1)) + geom_point() +      stat_smooth(method="glm", color="green", se=FALSE,                method.args = list(family=binomial))
Output:
sweetyty
sumitgumber28
Picked
R-Charts
R-Graphs
R-plots
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python program to print current hour, minute, second and microsecond

09 Dec, 2021
In this article, we are going to discuss how to print current hour, minute, second, and microsecond using Python. In order to print hour, minute and microseconds we need to use DateTime module in Python.
datetime.now().hour(): This method returns the current hour value of the datetime object.
datetime.now().minute(): This method returns the current minute value of the datetime object.
datetime.now().second(): This method returns the current second value of the datetime object.
datetime.now().microsecond(): This method returns the current microsecond value of the datetime object.
Below are the various implementations using examples that depict how to print current hour, minute, second, and microsecond in python.
Example 1: To print time, hour, minute, second, and microsecond
Python3
# importing datetime modulefrom datetime import datetime  # now is a method in datetime module is# used to retrieve current data,timemyobj = datetime.now() # printing current hour using hour# classprint("Current hour ", myobj.hour)  # printing current minute using minute# classprint("Current minute ", myobj.minute) # printing current second using second# classprint("Current second ", myobj.second) # printing current microsecond using# microsecond classprint("Current microsecond ", myobj.microsecond)
Output:
Example 2: To print object, time, hour, minute, second, and microsecond.
Python3
# importing datetime modulefrom datetime import datetime  # now is a method in datetime module is# used to retrieve current data,timemyobj = datetime.now()  # printing the object itselfprint("Object:", myobj) # printing current hour using hour# classprint("Current hour ", myobj.hour)  # printing current minute using minute# classprint("Current minute ", myobj.minute) # printing current second using second# classprint("Current second ", myobj.second) # printing current microsecond using microsecond# classprint("Current microsecond ", myobj.microsecond)
Output:
simmytarika5
Picked
Python datetime-program
Python-datetime
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Set the focus to HTML form element using JavaScript

20 May, 2019
To set focus to an HTML form element, the focus() method of JavaScript can be used. To do so, call this method on an object of the element that is to be focused, as shown in the example.
Example 1: The focus() method is set to the input tag when user clicks on Focus button.
<!DOCTYPE html><html>  <head>    <title>        Set focus to HTML form element    </title></head>  <body>    <p>        Click on button to set focus        on input field    </p>          <form>        <input type="text" id="input1">                  <br><br>                  <button type="button" onclick="focusInput()">            Set Focus        </button>    </form>          <script>        function focusInput() {            document.getElementById("input1").focus();        }    </script></body>  </html>                    
Output:
Before Clicking the button:
After Clicking the button:
Example 2: This example focuses on the input field automatically on page load.
<!DOCTYPE html><html>  <head>    <title>        Set focus to HTML form element    </title></head>  <body>      <p>        Click on button to focus        on the input field.    </p>          <form>        Name: <input type="text" id="input1">                  <br><br>                  Age: <input type="text" id="input2">    </form>          <script>        window.onload = function() {            document.getElementById("input1").focus();        }    </script></body>  </html>                    
Output:
Example 3: The following program focuses on the input field when clicked on Focus button. To blur the focused input field, the blur() property can be used.
<!DOCTYPE html><html>  <head>    <title>        Set focus to HTML form element    </title></head>  <body>    <p>        Click on button to focus        on the input field.    </p>          <form>        <input type="text" id="input1">                  <br><br>                  <button type="button" onclick="focusInput()">            Focus        </button>                  <button type="button" onclick="blurInput()">            Blur        </button>    </form>          <script>        function focusInput() {            document.getElementById("input1").focus();        }        function blurInput() {            document.getElementById("input1").blur();        }    </script></body>  </html>                    
Output:
Before Clicking the button:
After Clicking on Focus button:
After Clicking on Blur button:
HTML-DOM
Picked
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Roadmap to Learn JavaScript For Beginners
Difference between var, let and const keywords in JavaScript
Remove elements from a JavaScript Array
Differences between Functional Components and Class Components in React
Hide or show elements in HTML using display property
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Roadmap to Learn JavaScript For Beginners
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Python | Pandas Series.str.extract()

27 Mar, 2019
Series.str can be used to access the values of the series as strings and apply several methods to it. Pandas Series.str.extract() function is used to extract capture groups in the regex pat as columns in a DataFrame. For each subject string in the Series, extract groups from the first match of regular expression pat.
Syntax: Series.str.extract(pat, flags=0, expand=True)
Parameter :pat : Regular expression pattern with capturing groups.flags : int, default 0 (no flags)expand : If True, return DataFrame with one column per capture group.
Returns : DataFrame or Series or Index
Example #1: Use Series.str.extract() function to extract groups from the string in the underlying data of the given series object.
# importing pandas as pdimport pandas as pd  # importing re for regular expressionsimport re  # Creating the Seriessr = pd.Series(['New_York', 'Lisbon', 'Tokyo', 'Paris', 'Munich'])  # Creating the indexidx = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5']  # set the indexsr.index = idx  # Print the seriesprint(sr)
Output :
Now we will use Series.str.extract() function to extract groups from the strings in the given series object.
# extract groups having a vowel followed by# any characterresult = sr.str.extract(pat = '([aeiou].)')  # print the resultprint(result)
Output :
As we can see in the output, the Series.str.extract() function has returned a dataframe containing a column of the extracted group.
Example #2 : Use Series.str.extract() function to extract groups from the string in the underlying data of the given series object.
# importing pandas as pdimport pandas as pd  # importing re for regular expressionsimport re  # Creating the Seriessr = pd.Series(['Mike', 'Alessa', 'Nick', 'Kim', 'Britney'])  # Creating the indexidx = ['Name 1', 'Name 2', 'Name 3', 'Name 4', 'Name 5']  # set the indexsr.index = idx  # Print the seriesprint(sr)
Output :
Now we will use Series.str.extract() function to extract groups from the strings in the given series object.
# extract groups having any capital letter# followed by 'i' and any other characterresult = sr.str.extract(pat = '([A-Z]i.)')  # print the resultprint(result)
Output :
As we can see in the output, the Series.str.extract() function has returned a dataframe containing a column of the extracted group.
Python-pandas
Python-pandas-series-str
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python string | digits

16 Oct, 2018
In Python3, string.digits is a pre-initialized string used as string constant. In Python, string.digits will give the lowercase letters ‘0123456789’.
Syntax : string.digits
Parameters : Doesn’t take any parameter, since it’s not a function.
Returns : Return all digit letters.
Note : Make sure to import string library function inorder to use string.digits
Code #1 :
# import string library function import string     # Storing the value in variable result result = string.digits     # Printing the value print(result) 
Output :
0123456789
 Code #2 : Given code checks if the string input has only digit letters
# importing string library function import string      # Function checks if input string # har only digits or not def check(value):     for letter in value:                      # If anything other than digit         # letter is present, then return         # False, else return True         if letter not in string.digits:             return False    return True     # Driver Code input1 = "0123 456 789"print(input1, "--> ",  check(input1))      input2 = "12.0124"print(input2, "--> ", check(input2))      input3 = "12345"print(input3, "--> ", check(input3)) 
Output:
0123 456 789 -->  False
12.0124 -->  False
12345 -->  True
Applications :The string constant digits can be used in many practical applications. Let’s see a code explaining how to use digits to generate strong random passwords of given size.
# Importing random to generate # random string sequence import random     # Importing string library function import string     def rand_pass(size):             # Takes random choices from     # ascii_letters and digits     generate_pass = ''.join([random.choice( string.ascii_uppercase +                                             string.ascii_lowercase +                                             string.digits)                                             for n in range(size)])                                 return generate_pass     # Driver Code  password = rand_pass(10) print(password)       
Output:
2R8gaoDKqn
python-string
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Can we return this keyword from a method in java?

The "this" keyword in Java is used as a reference to the current object, within an instance method or a constructor. Using this you can refer the members of a class such as constructors, variables, and methods.
Yes, you can return this in Java i.e. The following statement is valid.
return this;
When you return "this" from a method the current object will be returned.
In the following Java example, the class Student has two private variables name and age. From a method setValues() we are reading values from user and assigning them to these (instance) variables and returning the current object.
public class Student {
   private String name;
   private int age;
   public Student SetValues(){
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the name of the student: ");
      String name = sc.nextLine();
      System.out.println("Enter the age of the student: ");
      int age = sc.nextInt();
      this.name = name;
      this.age = age;
      return this;
   }
   public void display() {
      System.out.println("name: "+name);
      System.out.println("age: "+age);
   }
   public static void main(String args[]) {
      Student obj = new Student();
      obj = obj.SettingValues();
      obj.display();
   }
}
Enter the name of the student:
Krishna Kasyap
Enter the age of the student:
21
name: Krishna Kasyap
age: 21
How does underscore "_" work in Python files?

The underscore (_) is special in Python. There are 5 cases for using the underscore in Python.
1. For storing the value of last expression in interpreter.
The python interpreter stores the last expression value to the special variable called ‘_’.
>>> 12 + 10
22
>>> _
22
2. For ignoring the specific values.
The underscore is also used for ignoring the specific values in several languages like elixir, erlang, python, etc. If you don’t need the specific values or the values are not used, just assign the values to underscore.
>>> _, _, a = (1, 2, 3)
>>> a
3
3. To give special meaning to name of variables and functions.
Variable names with single preceding underscores are used for private variables, functions, classes. Anything with this convention are ignored in from module import *. There are many other conventions you can check out at: https://hackernoon.com/understanding-the-underscore-of-python-309d1a029edc
4. To separate the digits of number literal value.
In python, to avoid having to deal with extremely large numbers, you can put underscores to make numbers easily readable.
>>> a = 7_200_000_000   # 7.2 billion easily readable
>>> a
7200000000
Note that the last feature was added to python in v3.6
How to adjust the alignments of the text in JavaFX?

You can set a fixed width for the text in user space by setting the value to the wrappingWidth property. Once you do so, given width is considered as the boundary of the text in user coordinates and, the text is arranged width in the given width.
If you haven’t given any value for this property, by default, the length longest line in the text is considered as the width of the bounding box.
Text alignment is the arrangement of the text horizontally within the bounding box. You can adjust the alignment of the text using the setTextAlignment() method. This method accepts one of the constants of the enum named TextAlignment and adjusts the text accordingly. This enum provides 3 constants −
CENTER − Aligns the text in the center of the bounding box.
CENTER − Aligns the text in the center of the bounding box.
JUSTIFY − Justifies the text alignment within the bounding box.
JUSTIFY − Justifies the text alignment within the bounding box.
LEFT − Aligns the text to the left.
LEFT − Aligns the text to the left.
RIGHT − Aligns the text to the right.
RIGHT − Aligns the text to the right.
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Scanner;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.scene.text.Text;
import javafx.scene.text.TextAlignment;
public class TextAllignment extends Application {
   public void start(Stage stage) throws FileNotFoundException {
      //Reading the contents of a text file.
      InputStream inputStream = new FileInputStream("D:\\sample.txt");
      Scanner sc = new Scanner(inputStream);
      StringBuffer sb = new StringBuffer();
      while(sc.hasNext()) {
         sb.append(" "+sc.nextLine()+"\n");
      }
      //Creating a text object
      Text text = new Text(10.0, 25.0, sb.toString());
      //Wrapping the text
      text.setWrappingWidth(565);
      //Setting the alignment
      text.setTextAlignment(TextAlignment.Right);
      //Setting the stage
      Group root = new Group(text);
      Scene scene = new Scene(root, 595, 150, Color.BEIGE);
      stage.setTitle("Text Alignment");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}
Assume following are the contents of the sample.txt file −
Tutorials Point originated from the idea that there exists a class of readers who respond better 
to online content and prefer to learn new skills at their own pace from the comforts of their drawing rooms.
The journey commenced with a single tutorial on HTML in 2006 and elated by the response it generated, 
we worked our way to adding fresh tutorials to our repository which now proudly flaunts a wealth of 
tutorials and allied articles on topics ranging from programming languages to web designing to academics 
and much more.
In the same way, if you change the alignment value you will get the outputs
accordingly as −
LEFT −
CENTER −
JUSTIFY −
JavaScript subtraction of two float values?

To correctly subtract two float values, use parseFloat() along with toFixed().
Following is the code −
var firstValue=4.3;
var secondValue=3.8;
console.log("The first Value="+parseFloat(firstValue).toFixed(1)+" The
second Value="+parseFloat(secondValue).toFixed(1))
var result = parseFloat(firstValue).toFixed(1) -
parseFloat(secondValue).toFixed(1);
console.log("Result is="+result);
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo309.js.
This will produce the following output −
PS C:\Users\Amit\javascript-code> node demo309.js
The first Value=4.3 The second Value=3.8
Result is=0.5
How to add Analog Clock in ReactJS ? - GeeksforGeeks

14 Dec, 2021
In this article, we are going to learn how we can add Analog Clock in ReactJs. React is a free and open-source front-end JavaScript library for building user interfaces or UI components. It is maintained by Facebook and a community of individual developers and companies.
Approach: To add our Analog clock we are going to use the analog-clock-react package because it is powerful, lightweight, and fully customizable. After that, we will add our clock on our homepage using the installed package.
Create ReactJs Application: You can create a new ReactJs project using the below command:
npx create-react-app gfg
Install the required package: Now we will install the analog-clock-react package using the below command:
npm i analog-clock-react
Project Structure: It will look like this.
Adding Clock: In this example, we are going to add the clock on the homepage of our app using the package that we installed. For this, add the below content in the App.js file.
App.js
import AnalogClock from 'analog-clock-react';   export default function ReactClock() {  let options = {    width: "300px",    border: true,    borderColor: "#2e2e2e",    baseColor: "#17a2b8",    centerColor: "#459cff",    centerBorderColor: "#ffffff",    handColors: {      second: "#d81c7a",      minute: "#ffffff",      hour: "#ffffff"    }  };     return (    <div>      <h2>React Clock - GeeksforGeeks</h2>      <AnalogClock {...options} />    </div>  )}
Explanation: In the above example first, we are importing the AnalogClock component from the analog-clock-react package. After that, we are creating an options variable and storing the settings in this variable. Then we are using our AnalogClock component to display the clock.
Steps to run the application: Run the below command in the terminal to run the app.
npm start
Output:
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to set background images in ReactJS ?
How to navigate on path by button click in react router ?
How to create a table in ReactJS ?
ReactJS useNavigate() Hook
Axios in React: A Guide for Beginners
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
Convert a string to an integer in JavaScript
HTML - <isindex> tag

The HTML <isindex> tag is used for querying a document through a text field. The tag can be used anywhere but head tag is preferable. It is a deprecated tag and should not be used.
<!Doctype html>
<html>

   <head>
      <title>HTML isindex Tag</title>
      <isindex prompt = "Search" />
   </head>

</html>
This tag supports all the global attributes described in − HTML Attribute Reference
The HTML <isindex> tag also supports the following additional attributes −
This tag supports all the event attributes described in − HTML Events Reference

    19 Lectures 
     2 hours 

 Anadi Sharma

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    18 Lectures 
     1.5 hours 

 Frahaan Hussain

    57 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)

    54 Lectures 
     6 hours 

 DigiFisk (Programming Is Fun)

    45 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)
 Print
 Add Notes
 Bookmark this page
How to generate ObjectID in MongoDB?

To generate ObjectID, use the below syntax in the MonogDB shell −
new ObjectId()
Let us implement the above syntax to generate ObjectID in MongoDB −
> new ObjectId()
ObjectId("5cd7bf2f6d78f205348bc646")

> new ObjectId()
ObjectId("5cd7bf316d78f205348bc647")

> new ObjectId()
ObjectId("5cd7bf336d78f205348bc648")

> new ObjectId()
ObjectId("5cd7bf346d78f205348bc649")

> new ObjectId()
ObjectId("5cd7bf356d78f205348bc64a")

> new ObjectId()
ObjectId("5cd7bf396d78f205348bc64b")

> new ObjectId()
ObjectId("5cd7bf3a6d78f205348bc64c")
As shown above, every time you will get a new ObjectId.
How to display Absolute value of a number in C#?

To find the absolute value of a number in C#, use the Math.Abs method.
Set numbers first −
int val1 = 77;
int val2 = -88;
Now take two new variables and get the Absolute value of the above two numbers −
int abs1 = Math.Abs(val1);
int abs2 = Math.Abs(val2);
Let us see the complete code to display Absolute value of a number −
 Live Demo
using System;

class Program {
   static void Main() {
      int val1 = 77;
      int val2 = -88;

      Console.WriteLine("Before...");
      Console.WriteLine(val1);
      Console.WriteLine(val2);
      int abs1 = Math.Abs(val1);
      int abs2 = Math.Abs(val2);
      Console.WriteLine("After...");
      Console.WriteLine(abs1);
      Console.WriteLine(abs2);
   }
}
Before...
77
-88
After...
77
88
In JavaScript Why do we use "use strict"?

Strict Mode is a feature introduced in ES5 that allows you to place a program, or a function, in a “strict” mode.
This strict context prevents certain actions from being taken and throws more exceptions (generally providing the user with more information). Some specific features of strict mode −
Variables not declared but being assigned directly will fail. An attempt to assign foo = "bar"; where ‘foo’ hasn’t been defined will fail.
Variables not declared but being assigned directly will fail. An attempt to assign foo = "bar"; where ‘foo’ hasn’t been defined will fail.
You cannot use eval in strict mode
You cannot use eval in strict mode
You cannot reassign arguments array inside a function
You cannot reassign arguments array inside a function
Use of with statements is not allowed
Use of with statements is not allowed
You can use your scripts in strict mode as follows −
Add the following at the top of a script to enable it for the whole script −
"use strict";
If you want to use it only within a function then add it only in that context.
function strictFunc() {
   "use strict";
   // rest of function
}
Converting numbers to Indian currency using JavaScript

Suppose we have any number and are required to write a JavaScript function that takes in a number and returns its Indian currency equivalent.
toCurrency(1000) --> ₹4,000.00
toCurrency(129943) --> ₹1,49,419.00
toCurrency(76768798) --> ₹9,23,41,894.00
The code for this will be −
const num1 = 1000;
const num2 = 129943;
const num3 = 76768798;
const toIndianCurrency = (num) => {
   const curr = num.toLocaleString('en-IN', {
      style: 'currency',
      currency: 'INR'
   });
return curr;
};
console.log(toIndianCurrency(num1));
console.log(toIndianCurrency(num2));
console.log(toIndianCurrency(num3));
And the output in the console will be −
₹1,000.00
₹1,29,943.00
₹7,67,68,798.00
Variable Scope in C++

A scope is a region of the program and broadly speaking there are three places, where variables can be declared −
Inside a function or a block which is called local variables,
Inside a function or a block which is called local variables,
In the definition of function parameters which is called formal parameters.
In the definition of function parameters which is called formal parameters.
Outside of all functions which is called global variables.
Outside of all functions which is called global variables.
We will learn what is a function and it's parameter in subsequent chapters. Here let us explain what are local and global variables.
Variables that are declared inside a function or block are local variables. They can be used only by statements that are inside that function or block of code. Local variables are not known to functions outside their own. Following is the example using local variables −
#include <iostream>
using namespace std;
 
int main () {
   // Local variable declaration:
   int a, b;
   int c;
 
   // actual initialization
   a = 10;
   b = 20;
   c = a + b;
 
   cout << c;
 
   return 0;
}
Global variables are defined outside of all the functions, usually on top of the program. The global variables will hold their value throughout the life-time of your program.
A global variable can be accessed by any function. That is, a global variable is available for use throughout your entire program after its declaration. Following is the example using global and local variables −
#include <iostream>
using namespace std;
 
// Global variable declaration:
int g;
 
int main () {
   // Local variable declaration:
   int a, b;
 
   // actual initialization
   a = 10;
   b = 20;
   g = a + b;
  
   cout << g;
 
   return 0;
}
A program can have same name for local and global variables but value of local variable inside a function will take preference. For example −
#include <iostream>
using namespace std;
 
// Global variable declaration:
int g = 20;
 
int main () {
   // Local variable declaration:
   int g = 10;
 
   cout << g;
 
   return 0;
}
When the above code is compiled and executed, it produces the following result −
10

When a local variable is defined, it is not initialized by the system, you must initialize it yourself. Global variables are initialized automatically by the system when you define them as follows −
It is a good programming practice to initialize variables properly, otherwise sometimes program would produce unexpected result.

    154 Lectures 
     11.5 hours 

 Arnab Chakraborty

    14 Lectures 
     57 mins

 Kaushik Roy Chowdhury

    30 Lectures 
     12.5 hours 

 Frahaan Hussain

    54 Lectures 
     3.5 hours 

 Frahaan Hussain

    77 Lectures 
     5.5 hours 

 Frahaan Hussain

    12 Lectures 
     3.5 hours 

 Frahaan Hussain
 Print
 Add Notes
 Bookmark this page
Convert a String to a List of Characters in Java

Let’s say the following is our string −
String str = "Website!";
Now, convert the above string to a list of characters −
List<Character>list = str.chars().mapToObj(n -> (char)n).collect(Collectors.toList());
Following is the program to convert a string to a list of characters in Java −
 Live Demo
import java.util.*;
import java.util.stream.Collectors;
public class Demo {
   public static void main(String[] args){
      String str = "Website!";
      System.out.println("String = "+str);
      List<Character>list = str.chars().mapToObj(n -> (char)n).collect(Collectors.toList());
      System.out.println("List of Characters = "+list);
   }
}
String = Website!
List of Characters = [W, e, b, s, i, t, e, !]
How to remove the HTML tags from a given string in Java?

A String is a final class in Java and it is immutable, it means that we cannot change the object itself, but we can change the reference to the object. The HTML tags can be removed from a given string by using replaceAll() method of String class. We can remove the HTML tags from a given string by using a regular expression. After removing the HTML tags from a string, it will return a string as normal text.
public String replaceAll(String regex, String replacement)
public class RemoveHTMLTagsTest {
   public static void main(String[] args) {
      String str = "<p><b>Welcome to Tutorials Point</b></p>";
      System.out.println("Before removing HTML Tags: " + str);
      str = str.replaceAll("\\<.*?\\>", "");
      System.out.println("After removing HTML Tags: " + str);
   }
}
Before removing HTML Tags: <p><b>Welcome to Tutorials Point</b></p>
After removing HTML Tags: Welcome to Tutorials Point
How to disable “Establishing SSL connection without server's identity verification is not recommended” warning when connecting to MySQL database in Java?

To disable the warning while connecting to a database in Java, use the below concept −
autoReconnect=true&useSSL=false
The complete syntax is as follows −
yourJdbcURL="jdbc:mysql://localhost:yourPortNumber/yourDatabaseName?autoReconnect=true&useSSL=false";
Here is the warning message if you do not include “useSSL=false” −
Wed Feb 06 18:53:39 IST 2019 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
The snapshot is as follows −
If you want to avoid the above MySQL warning, use the syntax mention in the beginning.
The Java code is as follows −
import java.sql.Connection;
import java.sql.DriverManager;
public class AvoidSQLWarnDemo {
   public static void main(String[] args) {
      String JdbcURL = "jdbc:mysql://localhost:3306/mybusiness?" + "autoReconnect=true&useSSL=false";
      String Username = "root";
      String password = "123456";
      Connection con = null;
      try {
         con = DriverManager.getConnection(JdbcURL, Username, password);
         System.out.println("Your JDBC URL is as follows:" + JdbcURL);
      } catch (Exception exec) {
         exec.printStackTrace();
      }
   }
}
After running the above java program, you won’t get the warning. However, you will get the following output −
Python String ljust() Method

Python string  method ljust() returns the string left justified in a string of length width. Padding is done using the specified fillchar (default is a space). The original string is returned if width is less than len(s).
Following is the syntax for ljust() method −
str.ljust(width[, fillchar])

width − This is string length in total after padding.
width − This is string length in total after padding.
fillchar − This is filler character, default is a space.
fillchar − This is filler character, default is a space.
This method returns the string left justified in a string of length width. Padding is done using the specified fillchar (default is a space). The original string is returned if width is less than len(s).
The following example shows the usage of ljust() method.
#!/usr/bin/python

str = "this is string example....wow!!!";
print str.ljust(50, '0')
When we run above program, it produces following result −
this is string example....wow!!!000000000000000000


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
JavaScript String - charAt() Method

charAt() is a method that returns the character from the specified index.
Characters in a string are indexed from left to right. The index of the first character is 0, and the index of the last character in a string, called stringName, is stringName.length – 1.
Use the following syntax to find the character at a particular index.
string.charAt(index);

index − An integer between 0 and 1 less than the length of the string.
Returns the character from the specified index.
Try the following example.
<html>
   <head>
      <title>JavaScript String charAt() Method</title>
   </head>
   
   <body>  
      <script type = "text/javascript">
         var str = new String( "This is string" );
         document.writeln("str.charAt(0) is:" + str.charAt(0)); 
         document.writeln("<br />str.charAt(1) is:" + str.charAt(1)); 
         document.writeln("<br />str.charAt(2) is:" + str.charAt(2)); 
         document.writeln("<br />str.charAt(3) is:" + str.charAt(3)); 
         document.writeln("<br />str.charAt(4) is:" + str.charAt(4)); 
         document.writeln("<br />str.charAt(5) is:" + str.charAt(5)); 
      </script>      
   </body>
</html>
str.charAt(0) is:T 
str.charAt(1) is:h 
str.charAt(2) is:i 
str.charAt(3) is:s 
str.charAt(4) is: 
str.charAt(5) is:i 


    25 Lectures 
     2.5 hours 

 Anadi Sharma

    74 Lectures 
     10 hours 

 Lets Kode It

    72 Lectures 
     4.5 hours 

 Frahaan Hussain

    70 Lectures 
     4.5 hours 

 Frahaan Hussain

    46 Lectures 
     6 hours 

 Eduonix Learning Solutions

    88 Lectures 
     14 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page
C++ goto statement

A goto statement provides an unconditional jump from the goto to a labeled statement in the same function.
NOTE − Use of goto statement is highly discouraged because it makes difficult to trace the control flow of a program, making the program hard to understand and hard to modify. Any program that uses a goto can be rewritten so that it doesn't need the goto.
The syntax of a goto statement in C++ is −
goto label;
..
.
label: statement;

Where label is an identifier that identifies a labeled statement. A labeled statement is any statement that is preceded by an identifier followed by a colon (:).
#include <iostream>
using namespace std;
 
int main () {
   // Local variable declaration:
   int a = 10;

   // do loop execution
   LOOP:do {
      if( a == 15) {
         // skip the iteration.
         a = a + 1;
         goto LOOP;
      }
      cout << "value of a: " << a << endl;
      a = a + 1;
   } 
   while( a < 20 );
 
   return 0;
}
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19

One good use of goto is to exit from a deeply nested routine. For example, consider the following code fragment −
for(...) {
   for(...) {
      while(...) {
         if(...) goto stop;
         .
         .
         .
      }
   }
}
stop:
cout << "Error in program.\n";

Eliminating the goto would force a number of additional tests to be performed.  A simple break  statement would not work here, because it would only cause the program to exit from the innermost loop.

    154 Lectures 
     11.5 hours 

 Arnab Chakraborty

    14 Lectures 
     57 mins

 Kaushik Roy Chowdhury

    30 Lectures 
     12.5 hours 

 Frahaan Hussain

    54 Lectures 
     3.5 hours 

 Frahaan Hussain

    77 Lectures 
     5.5 hours 

 Frahaan Hussain

    12 Lectures 
     3.5 hours 

 Frahaan Hussain
 Print
 Add Notes
 Bookmark this page
Insert into a Binary Search Tree in C++

Suppose we have a binary search tree. we have to write only one method, that performs the insertion operation with a node given as a parameter. We have to keep in mind that after the operation, the tree will remain BST also. So if the tree is like −
if we insert 5, then the tree will be −
To solve this, we will follow these steps −
This method is recursive. this is called insert(), this takes a value v.
if root is null, then create a node with given value v and make that as root
if value of root > v, thenleft of root := insert(left of the root, v)
left of root := insert(left of the root, v)
else right of the root := insert(right of the root, v)
return root
Let us see the following implementation to get a better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class TreeNode{
   public:
      int val;
      TreeNode *left, *right;
      TreeNode(int data){
         val = data;
         left = right = NULL;
      }
};
void insert(TreeNode **root, int val){
   queue<TreeNode*> q;
   q.push(*root);
   while(q.size()){
      TreeNode *temp = q.front();
      q.pop();
      if(!temp->left){
         if(val != NULL)
            temp->left = new TreeNode(val);
         else
            temp->left = new TreeNode(0);
         return;
      }
      else{
         q.push(temp->left);
      }
      if(!temp->right){
         if(val != NULL)
            temp->right = new TreeNode(val);
         else
            temp->right = new TreeNode(0);
         return;
      }
      else{
         q.push(temp->right);
      }
   }
}
TreeNode *make_tree(vector<int> v){
   TreeNode *root = new TreeNode(v[0]);
   for(int i = 1; i<v.size(); i++){
      insert(&root, v[i]);
   }
   return root;
}
void tree_level_trav(TreeNode*root){
   if (root == NULL) return;
      cout << "[";
   queue<TreeNode *> q;
   TreeNode *curr;
   q.push(root);
   q.push(NULL);
   while (q.size() > 1) {
      curr = q.front();
      q.pop();
      if (curr == NULL){
         q.push(NULL);
      }
      else {
         if(curr->left)
            q.push(curr->left);
         if(curr->right)
            q.push(curr->right);
         if(curr->val == 0 || curr == NULL){
            cout << "null" << ", ";
         }
         else{
            cout << curr->val << ", ";
         }
      }
   }
   cout << "]"<<endl;
}
class Solution {
public:
   TreeNode* insertIntoBST(TreeNode* root, int val) {
      if(!root)return new TreeNode(val);
      if(root->val > val){
         root->left = insertIntoBST(root->left, val);
      }
      else root->right = insertIntoBST(root->right, val);
         return root;
   }
};
main(){
   Solution ob;
   vector<int> v = {4,2,7,1,3};
   TreeNode *root = make_tree(v);
   tree_level_trav(ob.insertIntoBST(root, 5));
}
[4,2,7,1,3]
5
[4,2,7,1,3,5]
How to perform arithmetic operations on a date in Python?

It is very easy to do date and time maths in Python using timedelta objects. Whenever you want to add or subtract to a date/time, use a datetime.datetime(), then add or subtract datetime.timedelta() instances. A timedelta object represents a duration, the difference between two dates or times. The timedelta constructor has the following function signature −
datetime.timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])
Note − All arguments are optional and default to 0. Arguments may be ints, longs, or floats, and may be positive or negative. You can read more about it here − https://docs.python.org/2/library/datetime.html#timedelta-objects
An example of using the timedelta objects and dates −
import datetime
old_time = datetime.datetime.now()
print(old_time)
new_time = old_time - datetime.timedelta(hours=2, minutes=10)
print(new_time)
This will give the output −
2018-01-04 11:09:00.694602
2018-01-04 08:59:00.694602
timedelta() arithmetic is not supported for datetime.time() objects; if you need to use offsets from an existing datetime.time() object, just use datetime.datetime.combine() to form a datetime.datetime() instance, do your calculations, and 'extract' the time again with the .time() method.
Subtracting 2 datetime objects gives a timedelta object. This timedelta object can be used to find the exact difference between the 2 datetimes.
t1 = datetime.datetime.now()
t2 = datetime.datetime.now()
print(t1 - t2)
print(type(t1 - t2))
This will give the output −
-1 day, 23:59:56.653627
<class 'datetime.timedelta'>
CSS Layout - The display Property

The display property is the most important CSS property for controlling layout.
The display property specifies if/how an element is displayed.
Every HTML element has a default display value depending on what type 
of element it is. The default display value for most elements is block or 
inline.
Click to show panel
This panel contains a <div> element, which is hidden by default (display: none).
It is styled with CSS, and we use JavaScript to show it (change it to (display: block).
A block-level element always starts on a new line and takes up the full width available 
(stretches out to the left and right as far as it can).
Examples of block-level elements:
<div>
<h1> - <h6>
<p>
<form>
<header>
<footer>
<section>
An inline element does not start on a new line and only takes up as much width as necessary.
This is an inline <span> element 
inside a paragraph.
Examples of inline elements:
<span>
<a>
<img>
display: none; is commonly used with JavaScript to hide 
and show elements without deleting and recreating them. Take a look at our last 
example on this page if you want to know how this can be achieved.
The <script> element uses display: none; 
as default. 
As mentioned, every element has a default display value. However, you can 
override this.
Changing an inline element to a block element, or vice versa, can be useful for 
making the page look a specific way, and still follow the web standards.
A common example is making inline <li> elements for horizontal menus:
Note: Setting the display property of an element only changes how the element is displayed, 
NOT what kind of element it is. So, an inline element with display: block; is not allowed
to have other block elements inside it.
The following example displays <span> elements as block elements:
The following example displays <a> elements as block elements:
display:none
Remove
visibility:hidden
Hide
Reset
Reset All
Hiding an element can be done by setting the display property to 
none. 
The element will be hidden, and the page will be displayed as if the element is not 
there:
visibility:hidden; also hides an element.
However, the element will still take up the same space 
as before. The element will be hidden, but still affect the layout:
Differences between display: none; and visibility: hidden;
This example demonstrates display: none; versus visibility: hidden;
Using CSS together with JavaScript to show content
This example demonstrates how to use CSS and JavaScript to show an element on 
click.
Hide the <h1> element. It should still take up the same space as before.
<style>
h1 {
  : ;
}
</style>

<body>
  <h1>This is a heading</h1>
  <p>This is a paragraph</p>
  <p>This is a paragraph</p>
</body>

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.
AnalyzeTheChat — Python-based WhatsApp chat analyzer | by Aqeel Anwar | Towards Data Science

Analyze your WhatsApp chat in the form of interesting graphs
A couple of weeks ago my wife and I started looking at our Whatsapp chat over the last year. There were too many messages and we simply couldn’t go over all of them. I have been using Python for over 3 years now and thought of creating a very simple analyzer to provide me with some useful insights into our WhatsApp chat. The resulting graphs were pretty interesting.
In this article, I will go through the GitHub repository I created for analyzing WhatsApp chat.
To check out the online easy-to-use demo without going through the hassle of installing the repository and Python packages, please click below and follow the instructions.
AnalyzeTheChat is a Python-based repository to generate useful statistics for your WhatsApp chat. It crawls the provided .txt file of the WhatsApp chat and generates a pandas dataframe. This dataframe is then processed to plot the following contact-wise and time-wise statistics
Number of messages per contact
Number of words per contact
Number of average words per message per contact
Number of emojis per contact
The average number of emojis per message per contact
Number of Media per contact
Number of keywords per contact
Number of messages per hour
Number of messages per weekday
Number of messages per month
Number of messages per year
An example of generates statistics can be seen below
It is advisable to make a new virtual environment (with python 3.6) for this project. Step-by-Step details on creating a virtual environment can be found here
Once you have created the virtual environment, activate it, and use the following command to clone the repository.
git clone https://github.com/aqeelanwar/AnalyzeTheChat.git
cd AnalyzeTheChatpip install -r requirements.txt
Export the WhatsApp chat you like to analyze using the following steps
Open the WhatsApp chatClick the three vertical dots on top-rightClick MoreClick Export ChatClick Without MediaSave the generated .txt file where it is accessible
Open the WhatsApp chat
Click the three vertical dots on top-right
Click More
Click Export Chat
Click Without Media
Save the generated .txt file where it is accessible
# Genericpython main.py --path <path-to-chat> --save_as <save-type># Examplepython main.py --path theoffice.txt --keyword 'jello' --save_as pdf
The results are saved in the results folder in the format selected by the user through the argument save_as.
AnalyzeTheChat is a python-baed WhatsApp chat analyzer that generates interesting bar graphs. It can be used to analyze the activity of a person or a group chat to deduce useful results. The online demo can be found here