code-rag-bench/online-tutorials huggingface dataset:
Node.js path.normalize() Method

13 Oct, 2021
The path.normalize() method is used to normalize the given path. Normalization resolves the (.) and (..) segments of the path to their correct form. If the method encounters multiple path separators, it replaces all of them by a single platform-specific path separator. This method preserves all trailing separators.
Syntax:
path.normalize( path )
Parameters: This method accepts single parameter path which holds the file path that would be normalized. A TypeError is thrown if this parameter is not a string.
Return Value: It returns a string with the normalized form of the path.
Below example illustrates the path.normalize() method in node.js:
Example:
// Node.js program to demonstrate the   // path.normalize() method  // Import the path moduleconst path = require('path');   path1 = path.normalize("/users/admin/.");console.log(path1)   path2 = path.normalize("/users/admin/..");console.log(path2)   path3 = path.normalize("/users/admin/../comments")console.log(path3);   path4 = path.normalize("/users///admin///comments")console.log(path4);
Output:
\users\admin
\users
\users\comments
\users\admin\comments
Reference: https://nodejs.org/api/path.html#path_path_normalize_path
Node.js-Methods
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
Node.js fs.readFileSync() Method
Node.js fs.writeFile() Method
How to update NPM ?
Difference between promise and async await in Node.js
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
chkconfig command in Linux with Examples

15 May, 2019
chkconfig command is used to list all available services and view or update their run level settings. In simple words it is used to list current startup information of services or any particular service, updating runlevel settings of service and adding or removing service from management.
Synopsis:
chkconfig --list [name]
chkconfig --add name
chkconfig --del name
chkconfig --override name
chkconfig [--level levels] name 
chkconfig [--level levels] name

Options:
To List current status of all system services.chkconfig --list
chkconfig --list
To View current status of a particular services.chkconfig --list rhnsd
chkconfig --list rhnsd
For Disabling a Service: By default 2 3 4 5 run levels are affected by this command to disable certain run levels only, add –level attribute followed by run level.chkconfig rhnsd off
chkconfig rhnsd off
Enabling a Service: By default 2 3 4 5 run levels are affected by this command to enable certain run levels only, add –level attribute followed by run level.chkconfig rhnsd on
chkconfig rhnsd on
To Delete a Servicechkconfig del rhnsd
chkconfig del rhnsd
To add a Servicechkconfig add rhnsd
chkconfig add rhnsd
linux-command
Linux-networking-commands
Linux-system-commands
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Draw Rainbow using Turtle Graphics in Python

15 Oct, 2020
Turtle is an inbuilt module in Python. It provides: 
Drawing using a screen (cardboard).Turtle (pen).
Drawing using a screen (cardboard).
Turtle (pen).
To draw something on the screen, we need to move the turtle (pen), and to move the turtle, there are some functions like the forward(), backward(), etc.
Prerequisite: Turtle Programming Basics
In this section, we will discuss how to draw a Rainbow using two different ways using Turtle Graphics.
Approach: 
Import Turtle.Set screenMake Turtle ObjectDefine colors used for drawingLoop to draw semi-circles oriented by 180-degree position.
Import Turtle.
Set screen
Make Turtle Object
Define colors used for drawing
Loop to draw semi-circles oriented by 180-degree position.
Example 1:
python3
# Import turtle packageimport turtle # Creating a turtle screen objectsc = turtle.Screen() # Creating a turtle object(pen)pen = turtle.Turtle() # Defining a method to form a semicircle# with a dynamic radius and colordef semi_circle(col, rad, val):     # Set the fill color of the semicircle    pen.color(col)     # Draw a circle    pen.circle(rad, -180)     # Move the turtle to air    pen.up()     # Move the turtle to a given position    pen.setpos(val, 0)     # Move the turtle to the ground    pen.down()     pen.right(180)  # Set the colors for drawingcol = ['violet', 'indigo', 'blue',       'green', 'yellow', 'orange', 'red'] # Setup the screen featuressc.setup(600, 600) # Set the screen color to blacksc.bgcolor('black') # Setup the turtle featurespen.right(90)pen.width(10)pen.speed(7) # Loop to draw 7 semicirclesfor i in range(7):    semi_circle(col[i], 10*(      i + 8), -10*(i + 1)) # Hide the turtlepen.hideturtle()
Output:
Example 2:
Python3
import turtle mypen= turtle.Turtle()mypen.shape('turtle')mypen.speed(10) window= turtle.Screen()window.bgcolor('white')rainbow= ['red','orange','yellow','green','blue','indigo','violet']size= 180mypen.penup()mypen.goto(0,-180)for color in rainbow:    mypen.color(color)    mypen.fillcolor(color)    mypen.begin_fill()    mypen.circle(size)    mypen.end_fill()    size-=20 turtle.done()
Output:
pulkitagarwal03pulkit
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
strings.Compare() Function in Golang with Examples

21 Apr, 2020
The Compare() function is an inbuilt function in the Golang programming language which is used to compare two strings. It is used to compare two strings in lexicographical order (order in which the words are arranged alphabetically, similar to the way we search words in dictionary) or to find out if the strings are equal or not. It returns an integer value as follows:
Syntax:
func Compare(s1, s2 string) int
Returns 0 if the strings are equal (s1==s2)
Returns 1 if string 1 is greater than string 2 (s1 > s2)
Returns -1 is string 1 is lesser than string 2 (s1 < s2)
Example 1:
// Golang program to illustrate the use of// the strings.Compare() Functionpackage main  import (    "fmt"    "strings")  func main() {      var s1 = "Geeks"    var s2 = "GeeksforGeeks"    var s3 = "Geeks"      // using the function    fmt.Println(strings.Compare(s1, s2))    fmt.Println(strings.Compare(s2, s3))    fmt.Println(strings.Compare(s3, s1))  }
Output:
-1
1
0

Explanation: The first output comes -1 as the first string is “Geeks” which is lexicographically lesser than the second string “GeeksforGeeks”. The second output comes 1 as the first string is “GeeksforGeeks” which is lexicographically greater than the second string “Geeks”. The third output comes as 0 as the first string is “Geeks” which is equal to the second string “Geeks”.
Example 2:
// Golang program to illustrate the use of// the strings.Compare() Functionpackage main  import (    "fmt"    "strings")  func main() {      var s1 = "apple"    var s2 = "Apple"    var s3 = "Apricot"          // using the function    fmt.Println(strings.Compare(s1, s2))    fmt.Println(strings.Compare(s2, s3))    fmt.Println(strings.Compare(s3, s1))  }
Output:
1
-1
-1

Explanation: The first output comes 1 as the first string is “apple” which is lexicographically greater than the second string “Apple” as the characters are compared sequentially from left to right using the Unicode Character Set and the ASCII value of ‘a’ is 97 and that of ‘A’ is 65. Therefore apple is greater than Apple.The second output comes -1 as the first string is “Apple” which is lexicographically lesser than the second string “Apricot”. The third output comes as -1 as the first string is “Apricot” which is lexicographically lesser than the second string “apple” as ‘A’ is lesser than ‘a’.
Golang-String
Picked
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Parse JSON in Golang?
Constants- Go Language
Time Durations in Golang
Loops in Go Language
How to iterate over an Array using for loop in Golang?
Structures in Golang
Strings in Golang
Go Variables
time.Parse() Function in Golang With Examples
Class and Object in Golang
Node.js fs.createReadStream() Method

11 Oct, 2021
The createReadStream() method is an inbuilt application programming interface of fs module which allow you to open up a file/stream and read the data present in it.Syntax:  
fs.createReadStream( path, options )
Parameters: This method accept two parameters as mentioned above and described below:  
path: This parameter holds the path of the file where to read the file. It can be string, buffer or URL.
options: It is an optional parameter that holds string or object.
Return Value: This method returns the fs.ReadStream object.Below examples illustrate the createReadStream() method in Node.js:Example 1:  
javascript
// Node.js program to demonstrate the // fs.createReadStream() method   // Include fs modulelet fs = require('fs'),  // Use fs.createReadStream() method// to read the filereader = fs.createReadStream('input.txt');  // Read and display the file data on consolereader.on('data', function (chunk) {    console.log(chunk.toString());});
Output:  
input.txt file data:
GeeksforGeeks: A computer science portal for geeks
Example 2:  
javascript
// Node.js program to demonstrate the // fs.createReadStream() method   // Include fs modulelet fs = require('fs'),  // Use fs.createReadStream() method// to read the filereader = fs.createReadStream('input.txt', {    flag: 'a+',    encoding: 'UTF-8',    start: 5,    end: 64,    highWaterMark: 16});  // Read and display the file data on consolereader.on('data', function (chunk) {    console.log(chunk);});
Output:  
forGeeks: A comp
uter science por
tal for geeks
Reference: https://nodejs.org/api/fs.html#fs_fs_createreadstream_path_options 
simranarora5sos
Node.js-fs-module
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Variables in LISP

16 Oct, 2021
Similar to other languages, in LISP variables are named places that store a particular value, but they are not declared the way you declare variables in C++ or Java i.e you don’t need to mention data-type of variables when declaring them as LISP is dynamically typed.
LISP supports two types of variables:
Local variablesGlobal variables
Local variables
Global variables
They are also called Lexical variables, these variables are defined inside a particular function and only the code within the binding form can refer to them as they can not be accessed outside of that function. Parameters of the functions are also local variables.
Defining a local variable:
New local variables can be created using the special operator LET. These variables then can be used within the body of the LET. The syntax for creating a variable with LET is:
(let (variable)
  body-of-expressions)
A let expression has two parts 
The first part consists of instructions for creating a variable and assigning values to them
The second part consists of a list of s-expressions
Now let’s create local variables using the above-mentioned syntax
Lisp
(let ((x 10) (y 20) z)  (format t "Local Variables :~%")  (format t "x = ~a, y = ~a & z=~a~%" x y z))
Here we have assigned x and y with initial values and for z no value is provided, hence NIL will be set as z’s default value.
Output : 
Local Variables :
x = 10, y = 20 & z=NIL
These are the variables that have a global scope i.e. you can call access them from anywhere in the program. In LISP global variables are also called Dynamic variables.
Defining a global variable:
New global variables can be defined using DEFVAR and DEFPARAMETER construct. The difference between both of them is that DEFPARAMETER always assigns initial value and DEFVAR form can be used to create a global variable without giving it a value.
The syntax for creating global variables is:
(defvar *name* initial-value
  "Documentation string")
  
(defparameter *name* initial-value
  "Documentation string")  
Example:
Let’s create a global variable that holds the rate of the pencil as *pencil-rate*, and with help of one function calculate the total bill by multiplying the total number of pencils with our global variable  *pencil-rate*.
Lisp
(defparameter *pencil-rate* 10  "Pencil rate is set to 10")  (defun calc-bill (n)  "Calculates the total bill by multiplying the number of pencils with its global rate"  (* *pencil-rate* n))  (write (calc-bill 20))
Output:
200
It is a proper naming convention to define global variables to start and end with asterisks because as global variables can be accessed anywhere in the program, there can be local variables with the same name, hence for avoiding this possibility by accident this naming convention is used. Example. *global*
LISP-Basics
Picked
LISP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Scala List filterNot() method with example

26 Jul, 2019
The filterNot() method is utilized to select all elements of the list which does not satisfies a stated predicate.
Method Definition: def filterNot(p: (A) => Boolean): List[A]
Return Type: It returns a new list consisting all the elements of the list which does not satisfies the given predicate.
Example #1:
// Scala program of filterNot()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Creating a list        val m1 = List(5, 12, 3, 13)                  // Applying filterNot method        val result = m1.filterNot(_ < 10)                  // Displays output        println(result)          }}
List(12, 13)

Example #2:
// Scala program of filterNot()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Creating a list        val m1 = List(5, 12, 3, 13)                  // Applying filterNot method        val result = m1.filterNot(_ < 3)                  // Displays output        println(result)          }}
List(5, 12, 3, 13)

Scala
Scala-list
Scala-Method
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE CS 2019 | Question 42

18 Feb, 2019
Assume that in a certain computer, the virtual addresses are 64 bits long and the physical addresses are 48 bits long. The memory is word addressable. The page size is 8k Band the word size is 4 bytes. The Translation Look-aside Buffer (TLB) in the address translation path has 128 valid entries. At most how many distinct virtual addresses can be translated without any TLB miss?(A) 16 x 210(B) 8 x 220(C) 4 x 220(D) 256 x 210Answer: (D)Explanation:
Number of words in a page 
= Page size / word size
= 8 KB / 4 B 
= 2 K
= 2 * 210 
Since TLB can hold 128 valid entries, therefore, TLB can translate
= 128 * number of words in page 
= 128 * 2 * 210
= 256 * 210 addresses with TLB hit 
So, option (D) is correct.Quiz of this Question
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove duplicate elements in an Array using STL in C++

31 May, 2022
Given an array, the task is to remove the duplicate elements from the array using STL in C++ Examples:
Input: arr[] = {2, 2, 2, 2, 2}
Output: arr[] = {2}

Input: arr[] = {1, 2, 2, 3, 4, 4, 4, 5, 5}
Output: arr[] = {1, 2, 3, 4, 5}
Approach: This can be done using set in standard template library. Set type variable in STL automatically removes duplicating element when we store the element in it. Below is the implementation of the above approach: 
CPP
// C++ program to remove the// duplicate elements from the array// using STL in C++ #include <bits/stdc++.h>using namespace std; // Function to remove duplicate elementsvoid removeDuplicates(int arr[], int n){     int i;     // Initialise a set    // to store the array values    set<int> s;     // Insert the array elements    // into the set    for (i = 0; i < n; i++) {         // insert into set        s.insert(arr[i]);    }     set<int>::iterator it;     // Print the array with duplicates removed    cout << "\nAfter removing duplicates:\n";    for (it = s.begin(); it != s.end(); ++it)        cout << *it << ", ";    cout << '\n';} // Driver codeint main(){    int arr[] = { 4, 2, 3, 3, 2, 4 };     int n = sizeof(arr) / sizeof(arr[0]);     // Print array    cout << "\nBefore removing duplicates:\n";    for (int i = 0; i < n; i++)        cout << arr[i] << " ";     // call removeDuplicates()    removeDuplicates(arr, n);     return 0;}
Before removing duplicates:
4 2 3 3 2 4 
After removing duplicates:
2, 3, 4,
Time Complexity : O(NlogN)
Space Complexity : O(N) 
tausifsiddiqui
cpp-array
STL
Arrays
C++
Arrays
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE CS 2013 | Question 65 - GeeksforGeeks

13 Aug, 2019
Consider an instruction pipeline with five stages without any branch prediction: Fetch Instruction (FI), Decode Instruction (DI), Fetch Operand (FO), Execute Instruction (EI) and Write Operand (WO). The stage delays for FI, DI, FO, EI and WO are 5 ns, 7 ns, 10 ns, 8 ns and 6 ns, respectively. There are intermediate storage buffers after each stage and the delay of each buffer is 1 ns. A program consisting of 12 instructions I1, I2, I3, ..., I12 is executed in this pipelined processor. Instruction I4 is the only branch instruction and its branch target is I9. If the branch is taken during the execution of this program, the time (in ns) needed to complete the program is
(A) 132(B) 165(C) 176(D) 328Answer: (B)Explanation:
Pipeline will have to be stalled till Ei stage of l4 completes, 
as Ei stage will tell whether to take branch or not. 

After that l4(WO) and l9(Fi) can go in parallel and later the
following instructions.
So, till l4(Ei) completes : 7 cycles * (10 + 1 ) ns = 77ns
From l4(WO) or l9(Fi) to l12(WO) : 8 cycles * (10 + 1)ns = 88ns
Total = 77 + 88 = 165 ns
Quiz of this Question
GATE-CS-2013
GATE-GATE CS 2013
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-CS-2014-(Set-3) | Question 38
GATE | GATE-IT-2004 | Question 83
GATE | GATE CS 2018 | Question 37
GATE | GATE-CS-2016 (Set 1) | Question 65
GATE | GATE-CS-2016 (Set 1) | Question 63
GATE | GATE-CS-2007 | Question 17
GATE | GATE-IT-2004 | Question 12
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2007 | Question 64
GATE | GATE-CS-2014-(Set-3) | Question 65
How can we export data to a CSV file whose filename name contains timestamp at which the file is created?

Sometimes we need to export data into a CSV file whose name has a timestamp at which that file is created. It can be done with the help of MySQL prepared statement. To illustrate it we are using the following example −
Example
The queries in the following example will export the data from table ‘student_info’ to the CSV file having a timestamp in its name.
mysql> SET @time_stamp = DATE_FORMAT(NOW(),'_%Y_%m_%d_%H_%i_%s');
Query OK, 0 rows affected (0.00 sec)

mysql> SET @FOLDER = 'C:/mysql/bin/mysql-files';
Query OK, 0 rows affected (0.00 sec)

mysql> SET @FOLDER = 'C:/mysql/bin/mysql-files/';
Query OK, 0 rows affected (0.00 sec)

mysql> SET @PREFIX = 'Student15';
Query OK, 0 rows affected (0.00 sec)

mysql> SET @EXT = '.CSV';
Query OK, 0 rows affected (0.00 sec)

mysql> SET @Command = CONCAT("SELECT * FROM Student_info INTO OUTFILE '",@FOLDER, @PREFIX, @time_stamp, @EXT,"' FIELDS ENCLOSED BY '\"' TERMINATED BY ';'
ESCAPED BY '\"'"," LINES TERMINATED BY '\r\n';");
Query OK, 0 rows affected (0.00 sec)

mysql> PREPARE stmt FROM @command;
Query OK, 0 rows affected (0.00 sec)
Statement prepared

mysql> execute stmt;
Query OK, 6 rows affected (0.07 sec)
The above query will create CSV file name ‘student_2017_12_10_18_52_46.CSV’ i.e. a CSV file with timestamp value, having the following data −
101;"YashPal";"Amritsar";"History"
105;"Gaurav";"Chandigarh";"Literature"
125;"Raman";"Shimla";"Computers"
130;"Ram";"Jhansi";"Computers"
132;"Shyam";"Chandigarh";"Economics"
133;"Mohan";"Delhi";"Computers"
How can I display MySQL query result vertically?

With the use of ego, \G option at end of a statement, we can get the result set in vertical format. Consider the following example −
mysql> Select * from Student where name = 'Aarav'\G
*************************** 1. row ***************************
  Name: Aarav
RollNo: 150
 Grade: M.SC
1 row in set (0.00 sec)
C++ String Library - front

It returns a reference to the first character of the string.
Following is the declaration for std::string::front.
char& front();
const char& front() const;
none
It returns a reference to the first character of the string.
if an exception is thrown, there are no changes in the string.
In below example for std::string::front.
#include <iostream>
#include <string>

int main () {
   std::string str ("Sairamkrishna Mammahe");
   str.front() = 'A';
   std::cout << str << '\n';
   return 0;
}
Aairamkrishna Mammahe

 Print
 Add Notes
 Bookmark this page
How can we map multiple date formats using Jackson in Java?

A Jackson is a Java-based library and it can be useful to convert Java objects to JSON and JSON to Java Object. We can map the multiple date formats in the Jackson library using @JsonFormat annotation, it is a general-purpose annotation used for configuring details of how values of properties are to be serialized. The @JsonFormat has three important fields: shape, pattern, and timezone. The shape field can define structure to use for serialization (JsonFormat.Shape.NUMBER and JsonFormat.Shape.STRING), the pattern field can be used in serialization and deserialization. For date, the pattern contains SimpleDateFormat compatible definition and finally, the timezone field can be used in serialization, default is system default timezone.
@Target(value={ANNOTATION_TYPE,FIELD,METHOD,PARAMETER,TYPE})
@Retention(value=RUNTIME)
public @interface JsonFormat

import java.io.*;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonDateformatTest {
   final static ObjectMapper mapper = new ObjectMapper();
   public static void main(String[] args) throws Exception {
      JacksonDateformatTest jacksonDateformat = new JacksonDateformatTest();
      jacksonDateformat.dateformat();
   }
   public void dateformat() throws Exception {
      String json = "{\"createDate\":\"1980-12-08\"," + "\"createDateGmt\":\"1980-12-08 3:00 PM GMT+1:00\"}";
      Reader reader = new StringReader(json);
      Employee employee = mapper.readValue(reader, Employee.class);
      System.out.println(employee);
   }
}
// Employee class
class Employee implements Serializable {
   @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd", timezone = "IST")
   private Date createDate;
   @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm a z", timezone = "IST")
   private Date createDateGmt;
   public Date getCreateDate() {
      return createDate;
   }
   public void setCreateDate(Date createDate) {
      this.createDate = createDate;
   }
   public Date getCreateDateGmt() {
      return createDateGmt;
   }
   public void setCreateDateGmt(Date createDateGmt) {
      this.createDateGmt = createDateGmt;
   }
   @Override
   public String toString() {
      return "Employee [\ncreateDate=" + createDate + ", \ncreateDateGmt=" + createDateGmt + "\n]";
   }
}
Employee [
 createDate=Mon Dec 08 00:00:00 IST 1980,
 createDateGmt=Mon Dec 08 07:30:00 IST 1980
]
Java Guava | Booleans.countTrue() method with Examples - GeeksforGeeks

30 Jan, 2019
The countTrue() method of Booleans Class in Guava Library is used to count the number of values that are true in the specified boolean values passed as the parameter.
Syntax:
public static int countTrue(boolean... values)

Parameters: This method accepts the boolean values among which the true values are to be count.
Return values: This method returns an integer value which is the count of values that are true.
Example-1 :
// Java code to show implementation of// Guava's Booleans.countTrue() method  import com.google.common.primitives.Booleans;import java.util.Arrays;  class GFG {      // Driver's code    public static void main(String[] args)    {          // Creating a Boolean array        boolean[] arr = { false, true, false,                          true, true };          // Using Booleans.countTrue() method to        // get the number of values that are true        System.out.println(Booleans.countTrue(arr));    }}
3

Example 2 :
// Java code to show implementation of// Guava's Booleans.countTrue() method  import com.google.common.primitives.Booleans;import java.util.Arrays;  class GFG {      // Driver's code    public static void main(String[] args)    {        // Creating a Boolean array        boolean[] arr = { false, false,                          false, false };          // Using Booleans.countTrue() method to        // get the number of values that are true        System.out.println(Booleans.countTrue(arr));    }}
0

Reference: https://google.github.io/guava/releases/20.0/api/docs/com/google/common/primitives/Booleans.html#countTrue-boolean...-
Guava-Booleans
Java-Functions
java-guava
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Initialize an ArrayList in Java
Overriding in Java
Multidimensional Arrays in Java
LinkedList in Java
ArrayList in Java
PriorityQueue in Java
How to iterate any Map in Java
Queue Interface In Java
Stack Class in Java
Object Oriented Programming (OOPs) Concept in Java
Corona Virus Live Updates for India – Using Python

06 Oct, 2020
As we know the whole world is being affected by the COVID-19 pandemic and almost everyone is working from home. We all should utilize this duration at best, to improve our technical skills or writing some good Pythonic scripts. Let’s see a simple Python script to demonstrate the state-wise coronavirus cases in India. This Python script fetches the live data from the Ministry of Health Affairs Official Website. Then data is represented in the horizontal bar graph.To run this script follow the below installation –  
$ pip install bs4
$ pip install tabulate
$ pip install matplotlib
$ pip install numpy 
$ pip install requests

  Let’s try to execute the script step-by-step. Step #1:  
Python3
# importing libraries import requestsfrom bs4 import BeautifulSoupfrom tabulate import tabulateimport osimport numpy as npimport matplotlib.pyplot as plt
 Step #2:  
Python3
extract_contents = lambda row: [x.text.replace('\n', '') for x in row]URL = 'https://www.mohfw.gov.in/'   SHORT_HEADERS = ['SNo', 'State','Indian-Confirmed(Including Foreign Confirmed)','Cured','Death']   response = requests.get(URL).contentsoup = BeautifulSoup(response, 'html.parser')header = extract_contents(soup.tr.find_all('th')) stats = []all_rows = soup.find_all('tr') for row in all_rows:    stat = extract_contents(row.find_all('td'))        if stat:        if len(stat) == 4:            # last row            stat = ['', *stat]            stats.append(stat)        elif len(stat) == 5:            stats.append(stat) stats[-1][0] = len(stats)stats[-1][1] = "Total Cases" 
 Step #3:  
Python3
objects = []for row in stats :    objects.append(row[1])    y_pos = np.arange(len(objects)) performance = []for row in stats[:len(stats)-1] :    performance.append(int(row[2])) performance.append(int(stats[-1][2][:len(stats[-1][2])-1])) table = tabulate(stats, headers=SHORT_HEADERS)print(table)
Output:  
Step #4:  
Python3
plt.barh(y_pos, performance, align='center', alpha=0.5,                 color=(234/256.0, 128/256.0, 252/256.0),                 edgecolor=(106/256.0, 27/256.0, 154/256.0))   plt.yticks(y_pos, objects)plt.xlim(1,performance[-1]+1000)plt.xlabel('Number of Cases')plt.title('Corona Virus Cases')plt.show()
Output:  
 
chiragarora3
kjangid897
Python-projects
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Program for compound interest


16 Jun, 2022

Let us prior discuss the formula for compound interest. The formula to calculate compound interest annually is given by: 
A = P(1 + R/100) t 
Compound Interest = A - P 
Where, A is amount P is the principal amount R is the rate and T is the time span
Example: 
Input : Principle (amount): 1200
        Time: 2
        Rate: 5.4
Output : Compound Interest = 133.099243
Example
Python3
 

 
 










# Python3 program to find compound
# interest for given values.
 
 
def compound_interest(principle, rate, time):
 
    # Calculates compound interest
    Amount = principle * (pow((1 + rate / 100), time))
    CI = Amount - principle
    print("Compound interest is", CI)
 
 
# Driver Code
compound_interest(10000, 10.25, 5)






Compound interest is 6288.946267774416
Method 2:  Finding compound interest of given values without using pow() function.
Python3
 

 
 










# Python code
# To find compound interest 
 
# inputs 
p= 1200   # principle amount 
t= 2      # time 
r= 5.4    # rate 
# calculates the compound interest
a=p*(1+(r/100))**t  # formula for calculating amount 
ci=a-p  # compound interest = amount - principal amount
# printing compound interest value
print(ci)






133.0992000000001
Time complexity: O(1)
Auxiliary Space: O(1)
Please refer complete article on Program to find compound interest for more details!
shivikapriya
wrestlemania(wwe)
laxmigangarajula03
hasani

Python Programs

Writing code in comment? 
                                    Please use ide.geeksforgeeks.org, 
                                    generate link and share the link here.
Python | Finding frequency in list of tuples

28 Feb, 2019
In python we need to handle various forms of data and one among them is list of tuples in which we may have to perform any kind of operation. This particular article discusses the ways of finding the frequency of the 1st element in list of tuple which can be extended to any index. Let’s discuss certain ways in which this can be performed.
Method #1 : Using map() + count()The map function can be used to accumulate the indices of all the tuples in a list and the task of counting the frequency can be done using the generic count function of python library.
# Python3 code to demonstrate# finding frequency in list of tuples# using map() + count()  # initializing list of tuplestest_list = [('Geeks', 1), ('for', 2), ('Geeks', 3)]  # printing the original listprint ("The original list is : " + str(test_list))  # using map() + count()# finding frequency in list of tuples res = list(map(lambda i : i[0], test_list)).count('Geeks')  # printing resultprint ("The frequency of element is : " + str(res))
The original list is : [('Geeks', 1), ('for', 2), ('Geeks', 3)]
The frequency of element is : 2

 Method #2 : Using Counter() + list comprehensionList comprehension performs the task of getting the first element of the tuples and the counting part is handled by Counter function of collection library.
# Python3 code to demonstrate# finding frequency in list of tuples# using Counter() + list comprehensionfrom collections import Counter  # initializing list of tuplestest_list = [('Geeks', 1), ('for', 2), ('Geeks', 3)]  # printing the original listprint ("The original list is : " + str(test_list))  # using Counter() + list comprehension# finding frequency in list of tuples res = Counter(i[0] for i in test_list)  # printing resultprint ("The frequency of element is : " + str(res['Geeks']))
The original list is : [('Geeks', 1), ('for', 2), ('Geeks', 3)]
The frequency of element is : 2

Python list-programs
Python tuple-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
MongoDB – Increment Operator ( $inc )

19 Apr, 2020
MongoDB provides different types of field update operators to update the values of the fields of the documents and $inc operator is one of them. This operator is used to increase the values of the fields to the specified amount or to increase the field by the given value.
You can also use this operator in embedded/nested documents. You can use this operator in methods like update(), updateOne() etc. according to your requirements.
This operator accepts positive and negative values.
If the given field does not exist, then this operator will create field and set the value of that field.
This operator will generate an error, if you use this operator with null value field.
It is an atomic operation in a single document.
Syntax:
{ $inc: { field1: amount1, field2: amount2, ... } }
In the following examples, we are working with:
Database: GeeksforGeeksCollection: contributorDocument: three documents that contain the details of the contributors in the form of field-value pairs.
In this example, we are updating the fields of an employee’s document whose name is Mohit by incrementing the value of publish articles field to 10 and decreasing the value of the salary field to -100.
db.contributor.update({name: "Mohit"}, {$inc: {publisharticles: 10, salary: -100}})
In this example, we are updating the field of an employee’s document whose name is Mohit by incrementing the value of a field to 10.
db.contributor.update({name: "Priya", "points._id": "g_1"}, {$inc: {"points.$.a":10}})
In this example, we are updating the field of an employee’s document whose name is Mohit by incrementing the value of a rank to 2.
db.contributor.update({name: "Amu"}, {$inc: {"personal.rank": 2}})
MongoDB
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between Static and Dynamic Hazard

04 May, 2020
1. Static Hazard :Static hazard occur in combinational circuits and can be eliminated by using redundant gates. Static hazard is further classified as:
1. Static-1 hazard
2. Static-0 hazard 
2. Dynamic hazard :When the output changes several times then it should change from 1 to 0 or 0 to 1 only once, it is called dynamic hazard. Dynamic hazard occur when the output changes for two adjacent input combinations while changing, the output should change only once. But it may change three or more times in short intervals because of different delays in several paths. Dynamic hazards occur only in multilevel circuit.
Difference between Static and Dynamic Hazard :
Difference Between
Digital Electronics & Logic Design
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Mathematics | Conditional Probability

28 Jun, 2021
Conditional probability P(A | B) indicates the probability of event ‘A’ happening given that event B happened.
    

We can easily understand the above formula using the below diagram. Since B has already happened, the sample space reduces to B. So the probability of A happening becomes  divided by P(B)
Example:In a batch, there are 80% C programmers, and 40% are Java and C programmers. What is the probability that a C programmer is also Java programmer?
Let A --> Event that a student is Java programmer
    B --> Event that a student is C programmer
    P(A|B) = P(A ∩ B) / P(B)
           = (0.4) / (0.8)
           = 0.5
So there are 50% chances that student that knows C also 
knows Java 
Product Rule:Derived from above definition of conditional probability by multiplying both sides with P(B)

   P(A ∩ B) = P(B) * P(A|B) 
Understanding Conditional probability through tree:Computation for Conditional Probability can be done using tree, This method is very handy as well as fast when for many problems.
Example: In a certain library, twenty percent of the fiction books are worn and need replacement. Ten percent of the non-fiction books are worn and need replacement. Forty percent of the library’s books are fiction and sixty percent are non-fiction. What is the probability that a book chosen at random are worn? Draw a tree diagram representing the data.
Solution: Let F represents fiction books and N represents non-fiction books. Let W represents worn books and G represents non-worn books.
P(worn)= P(N)*P(W | N) + P(F)*P(W | F)
              
           = 0.6*0.1  +  0.4* 0.2      
           = 0.14


Exercise:1) What is the value of P(A|A)?
2) Let P(E) denote the probability of the event E. Given P(A) = 1, P(B) = 1/2, the values of P(A | B) and P(B | A) respectively are (GATE CS 2003)(A) 1/4, 1/2(B) 1/2, 1/14(C) 1/2, 1(D) 1, 1/2See this for solution.
References:http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-042j-mathematics-for-computer-science-fall-2010/video-lectures/lecture-19-conditional-probability/
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
VaibhavRai3
Tushar512
Engineering Mathematics
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Permutation of a given string using inbuilt function

03 Aug, 2020
A permutation, also called an “arrangement number” or “order”, is a rearrangement of the elements of an ordered list S into a one-to-one correspondence with S itself. A string of length n has n! permutation.
Examples:
Input :  str = 'ABC'
Output : ABC 
         ACB 
         BAC 
         BCA 
         CAB 
         CBA
We have existing solution for this problem please refer Permutations of a given string using STL link. We can also solve this problem in python using inbuilt function permutations(iterable).
# Function to find permutations of a given stringfrom itertools import permutations  def allPermutations(str):            # Get all permutations of string 'ABC'     permList = permutations(str)       # print all permutations     for perm in list(permList):         print (''.join(perm))        # Driver programif __name__ == "__main__":    str = 'ABC'    allPermutations(str)
ABC
ACB
BAC
BCA
CAB
CBA

Permutation and Combination in Python
Permutations of a given string with repeating charactersThe idea is to use dictionary to avoid printing duplicates.
from itertools import permutationsimport string  s = "GEEK"a = string.ascii_lettersp = permutations(s)  # Create a dictionaryd = []for i in list(p):      # Print only if not in dictionary    if (i not in d):        d.append(i)        print(''.join(i))
GEEK
GEKE
GKEE
EGEK
EGKE
EEGK
EEKG
EKGE
EKEG
KGEE
KEGE
KEEG

Divyu_Pandey
Python string-programs
Python-Built-in-functions
python-string
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Enumerate() in Python
Different ways to create Pandas Dataframe
How to Install PIP on Windows ?
Python String | replace()
Python OOPs Concepts
Python Classes and Objects
*args and **kwargs in Python
Introduction To PYTHON
Create a Pandas DataFrame from Lists
DateTime.CompareTo() Method in C#

The DateTime.CompareTo() method in C# is used to compare the value of this instance to a specified DateTime value.
Following is the syntax −
public int CompareTo (DateTime val);
Above, Val is the date to be compared.
It returns an integer value,
<0 − If this instance is earlier than Val
0 − If this instance is the same as Val
>0 − If this instance is later than Val
Let us now see an example to implement the DateTime.CompareTo() method −
using System;
public class Demo {
   public static void Main(){
      DateTime date1 = new DateTime(2019, 05, 20, 6, 20, 40);
      DateTime date2 = new DateTime(2019, 05, 20, 6, 20, 40);
      Console.WriteLine("DateTime 1 = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} ", date1);
      Console.WriteLine("DateTime 2 = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} ", date2);
      int res = date1.CompareTo(date2);
      // returns equal to 0 since date1 is equal to date2
      Console.WriteLine(res);
   }
}
This will produce the following output −
DateTime 1 = 20 November 2019, 06:20:40
DateTime 2 = 20 November 2019, 06:20:40
0
Let us now see another example to implement the DateTime.CompareTo() method −
using System;
public class Demo {
   public static void Main(){
      DateTime date1 = new DateTime(2019, 08, 20, 6, 20, 40);
      DateTime date2 = new DateTime(2019, 05, 20, 6, 20, 40);
      Console.WriteLine("DateTime 1 = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} ", date1);
      Console.WriteLine("DateTime 2 = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} ", date2);
      int res = date1.CompareTo(date2);
      // returns >0 since date1 is later than date2
      Console.WriteLine(res);
   }
}
This will produce the following output −
DateTime 1 = 20 August 2019, 06:20:40
DateTime 2 = 20 May 2019, 06:20:40
1
How to position horizontal scroll bar at center of DIV?

To position horizontal scroll bar at center of div, use the scrollleft. You can try to run the following code to position horizontal scroll bar in div.
The scroll bar is positioned at center of div:
Live Demo
<html>
   <head>
   
      <title>jQuery Scroll</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
       
      <script>
         $(document).ready(function(){
             
          $(document).ready(function(){
            var outerContent = $('.demo');
            var innerContent = $('.demo > div');
           
            outerContent.scrollLeft( (innerContent.width() - outerContent.width()) / 2);
   
            });
               
         });
      </script>
       
      <style>
        html, body, div {
            margin:0;
            padding:0;
        }
        .demo {
            width:400px;
            overflow-x:scroll;
        }
       
        #viewContainer {
            height:120px;
            width:1000px;
            display:table;
        }
        .myclass {
            width:250px;
            height:100%;
            display:table-cell;
            border:2px solid blue;
        }
         </style>
    </head>    
<body>
     
<div class="demo">
  <div id="viewContainer">
    <div class="myclass" id="farLeft">Far left</div>
    <div class="myclass" id="left">left</div>
    <div class="myclass" id="center">center</div>
    <div class="myclass" id="right">right</div>
    <div class="myclass" id="farRight">Far right</div>
  </div>
</div>    

</body>
</html>
How to check if a variable is an integer in JavaScript?

To check if a variable is an integer, check the value using parseInt() and check with === operator.
You can try to run the following code to check the existence of an integer −
Live Demo
<html>
   <head>
      <script>
         var a = 10;
         if (a === parseInt(a, 10))
            alert("Integer!")
         else
           alert("Not an integer!")
      </script>
   </head>
   <body>
   </body>
</html>
cmp - Unix, Linux Command

cmp - Compare two files, and if they differ, tells the first byte and line number where they differ.
cmp options... FromFile [ToFile]
'cmp' reports the differences between two files character by character, instead of line by line. As a result, it is more useful than 'diff' for comparing binary files. For text files, 'cmp' is useful mainly when you want to know only whether two files are identical. For files that are identical, 'cmp' produces no output. When the files differ, by default, 'cmp' outputs the byte offset and line number where the first difference occurs. You can use the '-s' option to suppress that information, so that 'cmp' produces no output and reports whether the files differ using only its exit status. Unlike 'diff', 'cmp' cannot compare directories; it can only compare two files.
Compare two files
$ cat sample.txt
This is a sample text file
$ cat sample1.txt
This is another sample file
$ cmp sample.txt sample1.txt
sample.txt sample1.txt differ: byte 10, line 1


    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
Apache Commons Collections - Union

CollectionUtils class of Apache Commons Collections library provides various utility methods for common operations covering wide range of use cases. It helps avoid writing boilerplate code. This library is very useful prior to jdk 8 as similar functionalities are now provided in Java 8's Stream API.
union() method of CollectionUtils can be used to get the union of two collections.
Following is the declaration for org.apache.commons.collections4.CollectionUtils.union() method −
public static <O> Collection<O> union(Iterable<? extends O> a, Iterable<? extends O> b)

a − The first collection, must not be null.
a − The first collection, must not be null.
b − The second collection, must not be null.
b − The second collection, must not be null.
The union of the two collections.
The following example shows the usage of org.apache.commons.collections4.CollectionUtils.union() method. We'll get the union of two lists.
import java.util.Arrays;
import java.util.List;
import org.apache.commons.collections4.CollectionUtils;

public class CollectionUtilsTester {
   public static void main(String[] args) {
      //checking inclusion
      List<String> list1 = Arrays.asList("A","A","A","C","B","B");
      List<String> list2 = Arrays.asList("A","A","B","B");
      
      System.out.println("List 1: " + list1);
      System.out.println("List 2: " + list2);
      System.out.println("Union of List 1 and List 2: "+ CollectionUtils.union(list1, list2));
   }
}
This produces the following output −
List 1: [A, A, A, C, B, B]
List 2: [A, A, B, B]
Union of List 1 and List 2: [A, A, A, B, B, C]

 Print
 Add Notes
 Bookmark this page
SAP HANA - SQL Explain Plans

SQL explain plans are used to generate detail explanation of SQL statements. They are used to evaluate execution plan that SAP HANA database follows to execute the SQL statements.
The results of explain plan are stored into EXPLAIN_PLAN_TABLE for evaluation. To use Explain Plan, passed SQL query must be a data manipulation language (DML).
SELECT − retrieve data from the a database
SELECT − retrieve data from the a database
INSERT − insert data into a table
INSERT − insert data into a table
UPDATE − updates existing data within a table
UPDATE − updates existing data within a table
SQL Explain Plans cannot be used with DDL and DCL SQL statements.
EXPLAIN PLAN_TABLE in database consists of multiple columns. Few common column names − OPERATOR_NAME, OPERATOR_ID, PARENT_OPERATOR_ID, LEVEL and POSITION, etc.
COLUMN SEARCH value tells the starting position of column engine operators.
ROW SEARCH value tells the starting position of row engine operators.
EXPLAIN PLAN SET STATEMENT_NAME = ‘statement_name’ FOR <SQL DML statement>

SELECT Operator_Name, Operator_ID
FROM explain_plan_table
WHERE statement_name = 'statement_name';
DELETE FROM explain_plan_table WHERE statement_name = 'TPC-H Q10';


    25 Lectures 
     6 hours 

 Sanjo Thomas

    26 Lectures 
     2 hours 

 Neha Gupta

    30 Lectures 
     2.5 hours 

 Sumit Agarwal

    30 Lectures 
     4 hours 

 Sumit Agarwal

    14 Lectures 
     1.5 hours 

 Neha Malik

    13 Lectures 
     1.5 hours 

 Neha Malik
 Print
 Add Notes
 Bookmark this page
How to clone an array using spread operator in JavaScript?

Cloning is nothing but copying an array into another array. In olden days, the slice() method is used to clone an array, but ES6 has provided spread operator(...) to make our task easy. Lets' discuss both the methods.
In the following example slice() method is used to copy the array. slice() is used to slice the array from one index to another index. Since there is are no indexes provided the slice() method would slice the whole array. After slicing, the sliced part is copied into another array using assignment operator(=). 
 Live Demo
<html>
<body>
   <script>
      const games = ['cricket', 'hockey', 'football','kabaddi'];
      const clonegames = games.slice();
      document.write(clonegames);
   </script>
</body>
</html>
cricket,hockey,football,kabaddi
Es6 has brought many new features in which spread operator is a predominant one. This operator has many uses and cloning is one of those uses. 
Live Demo
<html>
<body>
   <script>
      const games = ['cricket', 'hockey', 'football','kabaddi'];
      const clonegames = [...games];
      document.write(clonegames);
   </script>
</body>
</html>
cricket,hockey,football,kabaddi