code-rag-bench/online-tutorials huggingface dataset:
Timing diagram of MVI instruction

18 Mar, 2020
Problem – Draw the timing diagram of the following code,
MVI B, 45 
Explanation of the command – It stores the immediate 8 bit data to a register or memory location.
Example: MVI B, 45Opcode: MVIOperand: B is the destination register and 45 is the source data which needs to be transferred to the register.’45’ data will be stored in the B register.
Algorithm –
Decide what is the opcode and what is the data. Here, opcode is ‘MVI B’ and data is 45.
Assume the memory address of the opcode and the data. For example:MVI B, 452000: Opcode2001: 45
MVI B, 452000: Opcode2001: 45
The opcode fetch will be same in all the instructions.
Only the read instruction of the opcode needs to be added in the successive T states.
For the opcode fetch the IO/M (low active) = 0, S1 = 1 and S0 = 1. Also, 4 T states will be required to fetch the opcode from memory.
For the opcode read the IO/M (low active) = 0, S1 = 1 and S0 = 0. Also, only 3 T states will be required to read data from memory.
In Opcode fetch ( t1-t4 T states ) –
00 – lower bit of address where opcode is stored.
20 – higher bit of address where opcode is stored.
ALE – Provides signal for multiplexed address and data bus. Only in t1 it used as address bus to fetch lower bit of address otherwise it will be used as data bus.RD (low active) – Signal is 1 in t1 & t4, no data is read by microprocessor. Signal is 0 in t2 & t3, data is read by microprocessor.WR (low active) – Signal is 1 throughout, no data is written by microprocessor.IO/M (low active) – Signal is 0 in throughout, operation is performing on memory.S0 and S1 – Signal is 1 in t1 to t4 states, as to fetch the opcode from the memory.
In Opcode read ( t5-t7 T states ) –
01 – lower bit of address where data is stored.
20 – higher bit of address where data is stored.
ALE – Provides signal for multiplexed address and data bus. Only in t5 it used as address bus to fetch lower bit of address otherwise it will be used as data bus.RD (low active) – Signal is 1 in t5 as no data is read by microprocessor. Signal is 0 in t6 & t7 as data is read by microprocessor.WR (low active) – Signal is 1 throughout, no data is written by microprocessor.IO/M (low active) – Signal is 0 in throughout, operation is performing on memory.S0 – Signal is 0 in throughout, operation is performing on memory to read data 45.S1 – Signal is 1 throughout, operation is performing on memory to read data 45.
aggarwal19
microprocessor
system-programming
Computer Organization & Architecture
microprocessor
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Lodash _.split() Method

30 Sep, 2020
The Lodash _.split() method splits the given string by the given separator and up to the given limit length.
Syntax:
_.split( string, separator, limit )

Parameters: This method accepts three parameters as mentioned above and described below:
string: The string to split.
separator: The separator by which string is to be split.
limit: The length to truncate results.
Return Value: This method returns an array.
Example 1:
Javascript
// Defining Lodash variable const _ = require('lodash');   var str = "Geeks-for-Geeks";  // Using _.replace() methodconsole.log(_.split(str, '-' ))
Output:
[ 'Geeks', 'for', 'Geeks' ]

Example 2: The array limited to size of 1.
Javascript
// Defining Lodash variable const _ = require('lodash');   var str = "Geeks-for-Geeks";  // Using _.replace() methodconsole.log(_.split(str, '-', 1 ))
Output:
[ 'Geeks' ]

Note: This will not work in normal JavaScript because it requires the lodash library to be installed and can be installed using npm install lodash.
JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
XQuery - max Function

The max function is used to get the maximum valued item present in a sequence.
max($seq as item()*)
$seq − provided sequence. A sequence can contain 0 or more items.
$seq − provided sequence. A sequence can contain 0 or more items.
let $items := (1,2,3,4,5,6)
let $max := max($items)
return
   <result>
      <max>{$max}</max>     
   </result>
<result>
   <max>6</max>  
</result>

In order to test the above-mentioned functionality, replace the contents of books.xqy (mentioned in Environment Setup chapter) with the above XQuery expression and execute the XQueryTester java program to verify the result.
Python | Pandas df.size, df.shape and df.ndim

03 Oct, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas .size, .shape and .ndim are used to return size, shape and dimensions of data frames and series.
Syntax: dataframe.sizeReturn : Returns size of dataframe/series which is equivalent to total number of elements. That is rows x columns.Syntax: dataframe.shapeReturn : Returns tuple of shape (Rows, columns) of dataframe/seriesSyntax: dataframe.ndimReturn : Returns dimension of dataframe/series. 1 for one dimension (series), 2 for two dimension (dataframe)
To download the data set used in following example, click here.
In the following examples, the data frame used contains data of some NBA players. The image of data frame before any operations is attached below.
Example:In this example, the output from size and shape is stored first. Since .size returns total number of elements, it is compared by multiplying rows and columns returned by the shape method. After that dimension of Dataframe and series is also checked using .ndim
# importing pandas moduleimport pandas as pd  # making data framedata = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv")  # dataframe.sizesize = data.size  # dataframe.shapeshape = data.shape  # dataframe.ndimdf_ndim = data.ndim  # series.ndimseries_ndim = data["Salary"].ndim  # printing size and shapeprint("Size = {}\nShape ={}\nShape[0] x Shape[1] = {}".format(size, shape, shape[0]*shape[1]))  # printing ndimprint("ndim of dataframe = {}\nndim of series ={}".format(df_ndim, series_ndim))
Output:
Size = 4122
Shape=(458, 9)
Shape[0] x Shape[1] = 4122
ndim of dataframe = 2
ndim of series=1
As it can be seen, rows x columns from .shape is equal to the value returned by .sizeAlso, ndim for dataframe was 2 and series is 1 which is true for all kind of dataframes and series.
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Convert integer to string in Python
Remove duplicate elements in Java with HashSet

Set implementations in Java has only unique elements. Therefore, it can be used to remove duplicate elements.
Let us declare a list and add elements −
List < Integer > list1 = new ArrayList < Integer > ();
list1.add(100);
list1.add(200);
list1.add(300);
list1.add(400);
list1.add(400);
list1.add(500);
list1.add(600);
list1.add(600);
list1.add(700);
list1.add(400);
list1.add(500);
Now, use the HashSet implementation and convert the list to HashSet to remove duplicates −
HashSet<Integer>set = new HashSet<Integer>(list1);
List<Integer>list2 = new ArrayList<Integer>(set);
Above, the list2 will now have only unique elements.
 Live Demo
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
public class Demo {
   public static void main(String[] argv) {
      List<Integer>list1 = new ArrayList<Integer>();
      list1.add(100);
      list1.add(200);
      list1.add(300);
      list1.add(400);
      list1.add(400);
      list1.add(500);
      list1.add(600);
      list1.add(600);
      list1.add(700);
      list1.add(400);
      list1.add(500);
      HashSet<Integer>set = new HashSet<Integer>(list1);
      List<Integer>list2 = new ArrayList<Integer>(set);
      System.out.println("List after removing duplicate elements:");
      for (Object ob: list2)
         System.out.println(ob);
   }
}
List after removing duplicate elements:
400
100
500
200
600
300
700
How to Save Pandas Dataframe as gzip/zip File? - GeeksforGeeks

26 Nov, 2020
Pandas is an open-source library that is built on top of NumPy library. It is a Python package that offers various data structures and operations for manipulating numerical data and time series. It is mainly popular for importing and analyzing data much easier. Pandas is fast and it has high-performance & productivity for users. 
The to_pickle() method in Pandas is used to pickle (serialize) the given object into the file. This method utilizes the syntax as given below :
Syntax:
DataFrame.to_pickle(self, path,
                   compression='infer',
                   protocol=4)

This method supports compressions like zip, gzip, bz2, and xz. In the given examples, you’ll see how to convert a DataFrame into zip, and gzip.
Example 1: Save Pandas Dataframe as zip File
Python3
# importing packagesimport pandas as pd  # dictionary of datadct = {'ID': {0: 23, 1: 43, 2: 12,                3: 13, 4: 67},         'Name': {0: 'Ajay', 1: 'Deep',                  2: 'Deepanshi', 3: 'Mira',                  4: 'Yash'},         'Marks': {0: 89, 1: 97, 2: 45, 3: 78,                   4: 56},         'Grade': {0: 'B', 1: 'A', 2: 'F', 3: 'C',                   4: 'E'}       }  # forming dataframe and printingdata = pd.DataFrame(dct)print(data)  # using to_pickle function to form file# by default, compression type infers from the file extension in specified path.# file will be created in the given pathdata.to_pickle('file.zip')
Output:
Example 2: Save Pandas Dataframe as gzip File.
Python3
# importing packagesimport pandas as pd  # dictionary of datadct = {"C1": range(5), "C2": range(5, 10)}  # forming dataframe and printingdata = pd.DataFrame(dct)print(data)  # using to_pickle function to form file# we can also select compression type# file will be created in the given pathdata.to_pickle('file.gzip')
Output:
In order to read the created files, you’ll need to use read_pickle() method. This method utilizes the syntax as given below:
pandas.read_pickle(filepath_or_buffer,  
               compression='infer')

Example 1: Reading zip file
Python3
# reading from the zip filepd.read_pickle('file.zip')
Output:
Example 2: Reading gzip File.
Python3
# reading from gzip filepd.read_pickle('file.gzip')
Output:
From the above two examples, we can see both of the compressed files can be read by the read_pickle() method without any changes except for the file extension.
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Defaultdict in Python
How to Install PIP on Windows ?
Deque in Python
Bar Plot in Matplotlib
Check if element exists in list in Python
Python math function | sqrt()
Python | Output Formatting
Python - Pandas dataframe.append()
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
TimeSpan.Subtract() Method in C# - GeeksforGeeks

30 Sep, 2019
This method is used to a get new TimeSpan object whose value is the difference of the specified TimeSpan object and this instance.
Syntax: public TimeSpan Subtract (TimeSpan t);
Parameter:t: This parameter specifies the time interval to be subtracted.
Return Value: It returns a new TimeSpan object whose value is the difference current instance and the value of t.
Exception: This method will give OverflowException when the resulting TimeSpan is smaller than smallest possible value or greater than the largest possible value.
Below programs illustrate the use of TimeSpan.Subtract(TimeSpan) Method:
Example 1:
// C# program to demonstrate the// TimeSpan.Subtract(TimeSpan) Methodusing System;  class GFG {      // Main Method    public static void Main()    {        try {              // creating the TimeSpan object            TimeSpan t1 = new TimeSpan(3, 22, 35, 33);            TimeSpan t2 = new TimeSpan(1, 11, 15, 16);            TimeSpan variable = t1.Subtract(t2);              Console.WriteLine("The Timespan is : {0}",                                            variable);        }          catch (OverflowException e)         {            Console.Write("Exception Thrown: ");            Console.Write("{0}", e.GetType(), e.Message);        }    }}
The Timespan is : 2.11:20:17

Example 2: For Overflow Exception
// C# program to demonstrate the// TimeSpan.Subtract(TimeSpan) Methodusing System;  class GFG {      // Main Method    public static void Main()    {        try {              // the TimeSpan object            TimeSpan t1 = TimeSpan.MinValue;            TimeSpan t2 = new TimeSpan(3, 22, 35, 33);            TimeSpan variable = t1.Subtract(t2);              Console.WriteLine("The Timespan is : {0}",                                            variable);        }          catch (OverflowException e)         {            Console.Write("Exception Thrown: ");            Console.Write("{0}", e.GetType(), e.Message);        }    }}
Exception Thrown: System.OverflowException

Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.timespan.subtract?view=netframework-4.7.2
shubham_singh
CSharp-method
CSharp-TimeSpan-Struct
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Extension Method in C#
HashSet in C# with Examples
C# | Inheritance
Partial Classes in C#
C# | Generics - Introduction
Top 50 C# Interview Questions & Answers
Switch Statement in C#
C# | How to insert an element in an Array?
Convert String to Character Array in C#
Linked List Implementation in C#
How to skip only first element of List in Scala - GeeksforGeeks

17 Apr, 2019
In Scala, list is defined under scala.collection.immutable package. A list is a collection of same type elements which contains immutable data. Let’s see how to print the element of given List, by skipping the first item in Scala.
List in Scala contains many suitable methods to perform simple operations like head(), tail(), isEmpty(). Coming to list, tail() method is used to skip the first element of the list.below are examples to skip only first element of List.Example :
// Scala program to skip only first element of Listimport scala.collection.immutable._  // Creating object object GFGobject{     // Main method     def main(args:Array[String])     {         // Creating and initializing immutable lists         val mylist: List[String] = List("Geeks", "For", "geeks", "is",                                          "a", "fabulous", "portal")           println(mylist.tail)       }}
List(For, geeks, is, a, fabulous, portal)

Example :
// Scala program to skip only first element of Listimport scala.collection.immutable._  // Creating object object GFG {     // Main method     def main(args:Array[String])     {         // range from 10 to 19        val myList = List.range(10, 19)        println(myList)           println("Using tail() method: " + myList.tail)    } }     
List(10, 11, 12, 13, 14, 15, 16, 17, 18)
Using tail() method: List(11, 12, 13, 14, 15, 16, 17, 18)

Scala
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Inheritance in Scala
Scala | Traits
Scala ListBuffer
Scala | Case Class and Case Object
Hello World in Scala
Scala | Functions - Basics
Scala | Decision Making (if, if-else, Nested if-else, if-else if)
Scala List map() method with example
Comments In Scala
Scala | Try-Catch Exceptions
PHP | settype() Function - GeeksforGeeks

14 Mar, 2018
The settype() function is a built-in function in PHP. The settype() function is used to the set the type of a variable. It is used to set type or modify type of an existing variable.
Syntax:
boolean settype($variable_name, $type)
Parameters: The settype() function accepts two parameters as shown in above syntax and are described below.
$variable_name: This parameter specifies the name of variablewhose type we want to modify. This parameter can be of any type that is, it can be of integer type or a string type etc.$type: This parameter specifies the type of variable that is needed. Possible values of this parameter are: boolean, integer, float, string, array, object, null.
$variable_name: This parameter specifies the name of variablewhose type we want to modify. This parameter can be of any type that is, it can be of integer type or a string type etc.
$type: This parameter specifies the type of variable that is needed. Possible values of this parameter are: boolean, integer, float, string, array, object, null.
Return value: This function returns a boolean type value. It returns TRUE in case of success and FALSE in case of failure.
Below programs illustrate the settype() function in PHP:
Program 1:
<?php  // PHP program to illustrate settype() function  $var1 = "123xyz";$var2 = 3;$r = true;settype($var1, "integer");settype($var2, "float");settype($r, "string");echo $var1."\n";echo $var2."\n";echo $r."\n";  ?>
Output:
123
3
1
Program 2:
<?php  // PHP program to illustrate settype() function  $var1 = "a12b";$var2 = 3.566;$r = true;settype($var1, "integer");settype($var2, "integer");settype($r, "string");echo $var1."\n";echo $var2."\n";echo $r."\n";  ?>
Output:
0
3
1

Reference:http://php.net/manual/en/function.settype.php
PHP-basics
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to fetch data from localserver database and display on HTML table using PHP ?
How to create admin login page using PHP?
PHP str_replace() Function
How to pass form variables from one page to other page in PHP ?
Different ways for passing data to view in Laravel
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Remove Newline from Character String in R - GeeksforGeeks

23 Aug, 2021
In this article, we are going to see how to remove the new line from a character string in R Programming Language.
Example:
Input: String with newline: "Hello\nGeeks\rFor\r\n Geeks"
Output: String after removing new line: "HelloGeeksFor Geeks"
gsub() function in R Language is used to replace all the matches of a pattern from a string. If the pattern is not found the string will be returned as it is.
Syntax:gsub(pattern, replacement, string, ignore.case=TRUE/FALSE)
Parameters:pattern: string to be matchedreplacement: string for replacementstring: String or String vectorignore.case: Boolean value for case-sensitive replacement
Example: R program to remove the newline from character string using gsub() function.
Syntax: gsub(“[\r\n]”, “”, string)
where
[\r\n] is a first parameter which is a pattern to remove new lines
“” is the second parameter that replaces when new line occurs as empty
string is the input string of characters.
Code:
R
# consider a stringstring = "Hello\nGeeks\nFor\nGeeks\n"  # display stringprint("Original string: ")cat(string)  # string after removing new linesprint("string after removing new lines: ")cat(gsub("[\r\n]", "", string))
Output:
[1] "Original string: "
Hello
Geeks
For
Geeks
[1] "string after removing new lines: "
HelloGeeksForGeeks
This function is available in stringr package which is  also used to remove the new line from a character string
Syntax: str_replace_all(string, “[\r\n]” , “”)
where
string is the first parameter that takes string as input.
[\r\n] is a second parameter which is a pattern to remove new lines
“” is the third parameter that replaces when new line occurs as empty
Example: R program to remove newline from string using stringr package
R
library(stringr)  # consider a stringstring="Hello\nGeeks\rFor\r\nGeeks\n"  # display stringprint("Original string: ")cat(string)  # string after removing new linesprint("string after removing new lines: ")print(str_replace_all(string, "[\r\n]" , ""))
Output:
[1] "Original string: "
Hello
Forks
Geeks
[1] "string after removing new lines: "
[1] "HelloGeeksForGeeks"
Picked
R String-Programs
R-strings
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
How to filter R dataframe by multiple conditions?
Convert Matrix to Dataframe in R
BigDecimal doubleValue() Method in Java - GeeksforGeeks

04 Dec, 2018
The java.math.BigDecimal.doubleValue() is an in-built function which converts the BigDecimal object to a double. This function converts the BigDecimal to Double.NEGATIVE_INFINITY or Double.POSITIVE_INFINITY as appropriate or according to the passed object, if its magnitude is too big to be represented as a double.
Note: The information about the decimal precision of the Double value of the given BigDecimal value can be lost even if the return value is finite.
Syntax:
public double doubleValue()
Parameters: The method does not accept any parameters.
Return Value: This method returns the double value of this BigDecimal Object.
Examples:
Input : 11234
Output : 11234.0

Input : 2679.30000
Output : 2679.3

Below programs illustrates the use of byteValueExact() Function:Program 1:
// Java program to demonstrate doubleValue() methodimport java.io.*;import java.math.*;  public class GFG {      public static void main(String[] args)    {          // Creating a BigDecimal object        BigDecimal big;          // Creating a Double object        Double dob;          big = new BigDecimal("4743");          // Assigning the converted value of bg to d        dob = big.doubleValue();          // Printing the corresponding double value        System.out.println("Double value of " + big + " is " + dob);    }}
Double value of 4743 is 4743.0

Program 2:
// Java program to demonstrate doubleValue() methodimport java.io.*;import java.math.*;  public class GFG {      public static void main(String[] args)    {          // Creating a BigDecimal object        BigDecimal big;          // Creating a Double object        Double dob;          big = new BigDecimal("6714592679.34008");          // Assigning the converted value of bg to d        dob = big.doubleValue();          // Printing the corresponding double value        System.out.println("Double value of " + big + " is " + dob);    }}
Double value of 6714592679.34008 is 6.71459267934008E9

Reference:https://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#doubleValue()
Java-BigDecimal
Java-Functions
java-math
Java-math-package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
HashMap in Java with Examples
Interfaces in Java
Initialize an ArrayList in Java
Object Oriented Programming (OOPs) Concept in Java
ArrayList in Java
How to iterate any Map in Java
Multidimensional Arrays in Java
Overriding in Java
Stack Class in Java
Collections in Java
How do you reverse a string in place in C or C++?

In this section we will see how to reverse a string in place. So we will not use some other memory spaces for reversing. In C++, we can use the std::string. But for C we have to use the character array. In this program we are using the character array to take the string. Then reversing it.
Input: A string “This is a string”
Output: The reversed string “gnirts a si sihT”
Input − The string
Output − The reversed string.
len := the length of the string
i := 0 and j := (len-1)
while i < j, do
   swap the characters from position i and j
   i := i + 1
   j := j - 1
done
 Live Demo
#include <iostream>
#include<cstring>
using namespace std;
void reverse(char s[]) {
   int len = strlen(s) ; //get the length of the string
   int i, j;
   for (i = 0, j = len - 1; i < j; i++, j--) {
      swap(s[i], s[j]);
   }
}
int main() {
   char s[20] = "This is a string";
   cout << "Main String: " << s <<endl;
   reverse(s);
   cout << "Reversed String: " << s <<endl;
}
Main String: This is a string
Reversed String: gnirts a si sihT
How to add two strings with a space in first string in JavaScript?

To add two strings we need a '+' operator to create some space between the strings, but when the first string itself has a space with in it, there is no need to assign space explicitly. 
In the following example since the string 'str1' has a space with in it, just only concatenation without space is adequate to add both the strings.
Live Demo
<html>
<body>
   <script>
      function str(str1, str2) {
         return (str1 + str2);
      }
      document.write(str("tutorix is the best ","e-learning platform"));
   </script>
</body>
</html>
tutorix is the best e-learning platform
In case if there is no space exist in first string then we have to create space(" ") and join the two strings as shown below. 
Live Demo
<html>
<body>
   <script>
      function str(str1, str2) {
         return (str1 + " " + str2);
      }
      document.write(str("tutorix is the best","e-learning platform"));
   </script>
</body>
</html>
tutorix is the best e-learning platform
Iterate over characters of a string in C++

24 Nov, 2020
Given a string str of length N, the task is to traverse the string and print all the characters of the given string.
Examples:
Input: str = “GeeksforGeeks”Output: G e e k s f o r G e e k s
Input: str = “Coder”Output: C o d e r
Naive Approach: The simplest approach to solve this problem is to iterate a loop over the range [0, N – 1], where N denotes the length of the string, using variable i and print the value of str[i].
Below is the implementation of the above approach:
C++
// C++ program to implement// the above approach  #include <bits/stdc++.h>using namespace std;  // Function to traverse the string and// print the characters of the stringvoid TraverseString(string &str, int N){     // Traverse the string    for (int i = 0; i < N; i++) {          // Print current character        cout<< str[i]<< " ";    }      }  // Driver Codeint main(){    string str = "GeeksforGeeks";          // Stores length of the string    int N = str.length();      TraverseString(str, N);}
G e e k s f o r G e e k s

Time Complexity: O(N)Auxiliary Space: O(1)
Auto keyword – based Approach: The string can be traversed using auto iterator.
Below is the implementation of the above approach:
C++
// C++ program to implement// the above approach  #include <bits/stdc++.h>using namespace std;  // Function to traverse the string and// print the elements of the stringvoid TraverseString(string &str, int N){    // Traverse the string    for (auto &ch : str) {          // Print current character        cout<< ch<< " ";    }}// Driver Codeint main(){    string str = "GeeksforGeeks";      // Stores length of the string    int N = str.length();      TraverseString(str, N);}
G e e k s f o r G e e k s

Time Complexity: O(N)Auxiliary Space: O(1)
Iterator – based Approach: The string can be traversed using iterator.
Below is the implementation of the above approach:
C++
// C++ program to implement// the above approach  #include <bits/stdc++.h>using namespace std;  // Function to traverse the string and// print the elements of the stringvoid TraverseString(string &str, int N){          // Stores address of     // a character of str    string:: iterator it;          // Traverse the string    for (it = str.begin(); it != str.end();                                   it++) {        // Print current character        cout<< *it<< " ";    }}  // Driver Codeint main(){    string str = "GeeksforGeeks";                // Stores length of the string    int N = str.length();    TraverseString(str, N);}
G e e k s f o r G e e k s

Time Complexity: O(N)Auxiliary Space: O(1)
cpp-iterator
cpp-string
C++
Strings
Strings
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Algorithms | Recursion | Question 5 - GeeksforGeeks

28 Jun, 2021
What does fun2() do in general?
int fun(int x, int y){    if (y == 0)   return 0;    return (x + fun(x, y-1));}  int fun2(int a, int b){    if (b == 0) return 1;    return fun(a, fun2(a, b-1));}
(A) x*y(B) x+x*y(C) xy(D) yxAnswer: (C)Explanation: The function multiplies x to itself y times which is xy.Quiz of this Question
Algorithms-Recursion
Algorithms Quiz
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Algorithms | Graph Traversals | Question 2
Algorithms | Graph Traversals | Question 12
Algorithms | Graph Traversals | Question 12
Algorithms | Graph Traversals | Question 1
Algorithms | Analysis of Algorithms | Question 17
Algorithms | Analysis of Algorithms | Question 8
Algorithms | Sorting | Question 5
Algorithms | Sorting | Question 7
Algorithms | Sorting | Question 1
Algorithms Quiz | Dynamic Programming | Question 8
VBScript Now Function

The Function Now returns the current system date and time.
Now()

<!DOCTYPE html>
<html>
   <body>
      <script language = "vbscript" type = "text/vbscript">
         a = Now()
         document.write("The Value of a : " & a)
       
      </script>
   </body>
</html>
When you save it as .html and execute it in Internet Explorer, then the above script will produce the following result −
The Value of a : 19/07/2013 3:04:09 PM
Profil3 – Find Potential Profiles of a Person in Kali Linux

30 Jun, 2021
Profil3 is a free and open-source tool available on GitHub. This tool is used to find potential profiles of a person on different sites. This tool is based upon OSINT Technology, which means Open Source Intelligence technology. This tool allows its users to find potential profiles of a person on social network sites, websites, and web applications. This tool also finds the email address associated with that user’s id. The tool provides you with many features. This tool will give you an alert to the presence of a data leak for the found emails. This tool is written in python. You must have python installed in your Kali Linux in order to use the tool. The Profil3 interface is very similar to Metasploit 1 and Metasploit. Profil3 provides a command-line interface that you can run on Kali Linux. The interactive console provides a number of helpful features, such as command completion and contextual help.
Step 1: Open your Kali Linux operating system and install the tool using the following command.
git clone https://github.com/Rog3rSm1th/Profil3r.git
cd Profil3r/
python3 setup.py install
Step 2: The tool has been downloaded and installed successfully. Use the following command to run the tool.
python3 profil3r.py -h
 The tool is running successfully. Now we will see an example of using the tool.
Example 1: Use the profil3r tool to find out all the internet information of the user.
python3 profil3r.py -p <user name>
Enter your username to scan.
You can see the tool has given all the publicly available information of the user. You can use the tool to scan your target username also. 
Kali-Linux
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
scp command in Linux with Examples
Docker - COPY Instruction
chown command in Linux with Examples
SED command in Linux | Set 2
nohup Command in Linux with Examples
chmod command in Linux with examples
Array Basics in Shell Scripting | Set 1
mv command in Linux with examples
Introduction to Linux Operating System
Basic Operators in Shell Scripting
Node.js MessageChannel.postMessage() Method

09 Jul, 2021
The MessagePort.postMessage() method is an inbuilt application programming interface of class Worker within worker_threads module which is used to send the message from one port to another.
Syntax:
const MessagePort.postMessage(value[, transferList])
Parameters: This method takes the value as a parameter which can contain any kind of object.
Return Value: This method sends the message from one port to another.
Example 1: Filename: index.js
Javascript
// Node.js program to demonstrate the// MessageChannel.postMessage() method // Importing worker_thread moduleconst { MessageChannel, receiveMessageOnPort }        = require('worker_threads'); // Creating and initializing the MessageChannelconst { port1, port2 } = new MessageChannel(); // Sending data to port 2// by using postMessage() methodport1.postMessage({ hello: 'world1' }); // Posting data in port 1// by using postMessage() methodport2.postMessage({ hello: 'world2' }); /// Display the resultconsole.log("received data in port1 : ");console.log(receiveMessageOnPort(port1)); console.log("received data in port2 : ");console.log(receiveMessageOnPort(port2)); // Closing the portsport1.close();port2.close();
Output:
received data in port1 :
{ message: { hello: 'world2' } }
received data in port2 :
{ message: { hello: 'world1' } }
Example 2: Filename: index.js
Javascript
// Node.js program to demonstrate the// MessageChannel.postMessage() method // Importing worker_thread module const { MessageChannel, receiveMessageOnPort }        = require('worker_threads'); // Creating and initializing the MessageChannelconst { port1, port2 } = new MessageChannel(); // Catching the event messageport2.on('message', (message) => console.log(message)); // Catching the event closeport2.on('close', () => console.log('closed!')); // Sending message to port2// by using postMessage() methodport1.postMessage('GFG'); // Closing port by using// close() methodport1.close();
Output:
GFG
closed!
Run the index.js file using the following command:
node index.js
Reference: https://nodejs.org/dist/latest-v12.x/docs/api/worker_threads.html#worker_threads_port_postmessage_value_transferlist
sweetyty
kapoorsagar226
Node.js-Methods
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program to check if a number is Positive, Negative, Odd, Even, Zero

09 May, 2022
Prerequisite : Loops in Python To check whether a number is positive, negative, odd, even or zero. This problem is solved using if...elif...else and nested if...else statement. 
Approach : 
A number is positive if it is greater than zero. We check this in the expression of if.
If it is False, the number will either be zero or negative.
This is also tested in subsequent expression.
In case of odd and even A number is even if it is perfectly divisible by 2.
 When the number is divided by 2, we use the remainder operator % to compute the remainder.If the remainder is not zero, the number is odd.
When the number is divided by 2, we use the remainder operator % to compute the remainder.
If the remainder is not zero, the number is odd.
Examples:
Input : 10
Output :
Positive number
10 is Even
Input : 0
Output : 0 is Even
Python
# Python Code to check if a number is# Positive, Negative, Odd, Even, Zero# Using if...elif...elsenum = 10if num > 0:   print("Positive number")elif num == 0:   print("Zero")else:   print("Negative number") # Checking for odd and evenif (num % 2) == 0:   print("{0} is Even".format(num))else:   print("{0} is Odd".format(num))
Output:
Positive number
10 is Even
Python
# Python Code to check if a number is# Positive, Negative, Odd, Even, Zero# Using Nested ifnum = 20if num >= 0:   if num == 0:       print("Zero")   else:       print("Positive number")else:   print("Negative number") # Checking for odd and evenif (num % 2) == 0:   print("{0} is Even".format(num))else:   print("{0} is Odd".format(num))
Output:
Positive number
20 is Even
simmytarika5
Python
School Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Python Dictionary
Reverse a string in Java
Arrays in C/C++
Introduction To PYTHON
Interfaces in Java
Python pass Statement

24 Aug, 2021
The pass statement is a null statement. But the difference between pass and comment is that comment is ignored by the interpreter whereas pass is not ignored. 
The pass statement is generally used as a placeholder i.e. when the user does not know what code to write. So user simply places pass at that line. Sometimes, pass is used when the user doesn’t want any code to execute. So user can simply place pass where empty code is not allowed, like in loops, function definitions, class definitions, or in if statements. So using pass statement user avoids this error.
Syntax:
pass
Example 1: Pass statement can be used in empty functions
Python3
def geekFunction:  pass
Example 2: pass statement can also be used in empty class
Python3
class geekClass:  pass
Example 3: pass statement can be used in for loop when user doesn’t know what to code inside the loop
Python3
n = 10for i in range(n):     # pass can be used as placeholder  # when code is to added later  pass
Example 4: pass statement can be used with conditional statements 
Python3
a = 10b = 20 if(a<b):  passelse:  print("b<a")
Example 5: lets take another example in which the pass statement get executed when the condition is true 
Python3
li =['a', 'b', 'c', 'd'] for i in li:    if(i =='a'):        pass    else:        print(i)
Output:
b
c
d
nusk3r
python-basics
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – Get Last N characters of a string

24 Feb, 2021
Given a string and an integer N, the task is to write a python program to print the last N characters of the string. 
Example:
Input: Geeks For Geeks!; N = 4
Output: eks!
Explanation: The given string is Geeks For Geeks! and the last 4 characters is eks!.
Input: PYTHON; N=1
Output: N
Explanation: The given string is PYTHON and the last character is N.
Method 1: Using a loop to get to the last N characters of the given string. 
Python3
# get inputStr = "Geeks For Geeks!"N = 4  # print the stringprint(Str)  # iterate loopwhile(N > 0):    # print character    print(Str[-N], end='')      # decrement the value of N    N = N-1
Output:
Geeks For Geeks!
eks!
Method 2: Using list slicing to print the last n characters of the given string. 
Python
# get inputStr = "Geeks For Geeks!"N = 4  # print the stringprint(Str)  # get length of stringlength = len(Str)  # create a new string of last N charactersStr2 = Str[length - N:]  # print Last N charactersprint(Str2)
Output:
Geeks For Geeks!
eks!
Python string-programs
Technical Scripter 2020
Python
Python Programs
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Similarity metrics of strings

12 Mar, 2019
This particular utility is quite in demand nowadays due to the similarity computation requirements in many fields of Computer Science such as Machine Learning, A.I and web development domains, hence techniques to compute similarity between any given containers can be quite useful. Let’s discuss certain ways in which this can be done.
Method #1 : Using Naive Approach(sum() + zip())We can perform this particular task using the naive approach, using sum and zip functions we can formulate a utility function that can compute the similarity of both the strings.
# Python3 code to demonstrate # similarity between strings# using naive method (sum() + zip())  # Utility function to compute similaritydef similar(str1, str2):    str1 = str1 + ' ' * (len(str2) - len(str1))    str2 = str2 + ' ' * (len(str1) - len(str2))    return sum(1 if i == j else 0                for i, j in zip(str1, str2)) / float(len(str1))  # Initializing stringstest_string1 = 'Geeksforgeeks'test_string2 = 'Geeks4geeks'  # using naive method (sum() + zip())# similarity between stringsres = similar(test_string1, test_string2)  # printing the resultprint ("The similarity between 2 strings is : " + str(res))
The similarity between 2 strings is : 0.38461538461538464

 
Method #2 : Using SequenceMatcher.ratio()There’s an inbuilt method, that helps to perform this particular task and is recommended to achieve this particular task as it doesn’t require custom approach but uses built in constructs to perform task more efficiently.
# Python3 code to demonstrate # similarity between strings# using SequenceMatcher.ratio()from difflib import SequenceMatcher  # Utility function to compute similaritydef similar(str1, str2):    return SequenceMatcher(None, str1, str2).ratio()  # Initializing stringstest_string1 = 'Geeksforgeeks'test_string2 = 'Geeks'  # using SequenceMatcher.ratio()# similarity between stringsres = similar(test_string1, test_string2)  # printing the resultprint ("The similarity between 2 strings is : " + str(res))
The similarity between 2 strings is :  0.5555555555555556

Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary
How to add custom fonts in Kivy – Python?

24 Feb, 2021
Prerequisites: Kivy Tutorial
Kivy is a platform-independent GUI tool in Python. It can run on Android, IOS, Linux and Windows, etc. This is the only GUI library from python which can independently run on the android device even we can use it on Raspberry pi also.  It is an open-source Python library for the rapid development of multi-touch applications. Its graphic engine is built over OpenGL, and it supports fast graphics pipeline. 
In this article, we will develop a GUI window using kivy framework of Python, and we will add a button on this window and we will add our own font style on this button’s text. For this task you should have a custom font style, don’t worry if you don’t have yours you can download from this link here you will get ample of font styles you can also download and unzip them. After unzipping you will get files in .ttf format keep those files because they are holding the actual font styles.
Step-by-step approach:
Basic Approach for using the custom font in kivy application:
Import button
Import kivyApp
Import labelbase
Import builder
Create App class
Return layout
Run an instance of the class
Implementation:
Python3
# importing button widget from kivy frameworkfrom kivy.uix.button import Buttonfrom kivy.app import App  # importing labelbase which which # register our custom font for applicationfrom kivy.core.text import LabelBasefrom kivy.lang import Builder    # this is the main class which will# render the whole applicationclass uiApp(App):      # method which will render our application    def build(self):        return Builder.load_string("""  # adding our buttonButton:      # text which will appear on first button    text:"first button"      # specifying the fontstyle name that we     # have registered in main.py file    font_name:"Lemonada"    font_size:65                                   """)    # registering our new custom fontstyleLabelBase.register(name='Lemonada',                    fn_regular='Lemonada-VariableFont_wght.ttf')  # running the applicationuiApp().run()
Output:
Python-kivy
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Convert integer to string in Python
Python | os.path.join() method
Create a Pandas DataFrame from Lists
Introduction To PYTHON
Python | Pandas DatetimeIndex.to_pydatetime()

29 Dec, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas DatetimeIndex.to_pydatetime() function return DatetimeIndex as object ndarray of datetime.datetime objects. The function does not take any input value.
Syntax: DatetimeIndex.to_pydatetime()
Parameters : None
Return : ndarray
Example #1: Use DatetimeIndex.to_pydatetime() function to convert the DatetimeIndex as object ndarray of datetime.datetime objects.
# importing pandas as pdimport pandas as pd  # Create the DatetimeIndex# Here 'S' represents secondly frequency didx = pd.DatetimeIndex(start ='2018-11-15 09:45:10', freq ='S', periods = 5)  # Print the DatetimeIndexprint(didx)
Output :
Now we want to convert the DatetimeIndex to datetime.datetime objects.
# convert to datetime.datetime objects.didx.to_pydatetime()
Output :As we can see in the output, the function has converted the DatetimeIndex object to python datetime.datetime object. Example #2: Use DatetimeIndex.to_pydatetime() function to convert the DatetimeIndex as object ndarray of datetime.datetime objects.
# importing pandas as pdimport pandas as pd  # Create the DatetimeIndex# Here 'M' represents monthly frequency didx = pd.DatetimeIndex(start ='2015-03-02', freq ='M', periods = 5)  # Print the DatetimeIndexprint(didx)
Output :
Now we want to convert the DatetimeIndex to datetime.datetime objects.
# convert to datetime.datetime objects.didx.to_pydatetime()
Output :As we can see in the output, the function has converted the DatetimeIndex object to python datetime.datetime object.
Python pandas-datetimeIndex
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Create a directory in Python