code-rag-bench/online-tutorials huggingface dataset:
Python - Graph Algorithms

Graphs are very useful data structures in solving many important mathematical challenges. For example computer network topology or analysing molecular structures of chemical compounds. They are also used in city traffic or route planning and even in human languages and their grammar. All these applications have a common challenge of traversing the graph using their edges and ensuring that all nodes of the graphs are visited. There are two common established methods to do this traversal which is described below.
Also called depth first search (DFS),this algorithm traverses a graph in a depth ward motion and uses a stack to remember to get the next vertex to start a search, when a dead end occurs in any iteration. We implement DFS for a graph in python using the set data types as they provide the required functionalities to keep track of visited and unvisited nodes.
class graph:
   def __init__(self,gdict=None):
      if gdict is None:
         gdict = {}
      self.gdict = gdict
# Check for the visisted and unvisited nodes
def dfs(graph, start, visited = None):
   if visited is None:
      visited = set()
   visited.add(start)
   print(start)
   for next in graph[start] - visited:
      dfs(graph, next, visited)
   return visited

gdict = { 
   "a" : set(["b","c"]),
   "b" : set(["a", "d"]),
   "c" : set(["a", "d"]),
   "d" : set(["e"]),
   "e" : set(["a"])
}
dfs(gdict, 'a')
When the above code is executed, it produces the following result −
a b d e c

Also called breadth first search (BFS),this algorithm traverses a graph breadth ward motion and uses a queue to remember to get the next vertex to start a search, when a dead end occurs in any iteration. Please visit this link in our website to understand the details of BFS steps for a graph.
We implement BFS for a graph in python using queue data structure discussed earlier. When we keep visiting the adjacent unvisited nodes and keep adding it to the queue. Then we start dequeue only the node which is left with no unvisited nodes. We stop the program when there is no next adjacent node to be visited.
import collections
class graph:
   def __init__(self,gdict=None):
      if gdict is None:
         gdict = {}
      self.gdict = gdict
def bfs(graph, startnode):
# Track the visited and unvisited nodes using queue
   seen, queue = set([startnode]), collections.deque([startnode])
   while queue:
      vertex = queue.popleft()
      marked(vertex)
      for node in graph[vertex]:
         if node not in seen:
            seen.add(node)
            queue.append(node)

def marked(n):
   print(n)

# The graph dictionary
gdict = { 
   "a" : set(["b","c"]),
   "b" : set(["a", "d"]),
   "c" : set(["a", "d"]),
   "d" : set(["e"]),
   "e" : set(["a"])
}
bfs(gdict, "a")
When the above code is executed, it produces the following result −
a c b d e
putpixel() function in C

23 Jan, 2018
The header file graphics.h contains putpixel() function which plots a pixel at location (x, y) of specified color.Syntax :
void putpixel(int x, int y, int color);

where, 
(x, y) is the location at which pixel
is to be put , and color specifies 
the color of the pixel.

Explanation : A RED color pixel at (50, 40) can be drawn by using putpixel(50, 40, RED). putpixel() function can be used to draw circles, lines and ellipses using various algorithms.
Below is the implementation of putpixel() function.
// C Implementation for putpixel()#include <graphics.h>#include <stdio.h>  // driver codeint main(){    // gm is Graphics mode which is    // a computer display mode that    // generates image using pixels.    // DETECT is a macro defined in    // "graphics.h" header file    int gd = DETECT, gm, color;      // initgraph initializes the    // graphics system by loading a    // graphics driver from disk    initgraph(&gd, &gm, "");      // putpixel function    putpixel(85, 35, GREEN);    putpixel(30, 40, RED);    putpixel(115, 50, YELLOW);    putpixel(135, 50, CYAN);    putpixel(45, 60, BLUE);    putpixel(20, 100, WHITE);    putpixel(200, 100, LIGHTBLUE);    putpixel(150, 100, LIGHTGREEN);    putpixel(200, 50, YELLOW);    putpixel(120, 70, RED);      getch();      // closegraph function closes the    // graphics mode and deallocates    // all memory allocated by    // graphics system .    closegraph();      return 0;}
Output :


c-graphics
computer-graphics
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Function Pointer in C
Multidimensional Arrays in C / C++
Left Shift and Right Shift Operators in C/C++
Different Methods to Reverse a String in C++
std::string class in C++
Unordered Sets in C++ Standard Template Library
rand() and srand() in C/C++
Enumeration (or enum) in C
What is the purpose of a function prototype?
ES6 | Array filter() Method

28 May, 2022
The Array filter() is an inbuilt method, this method creates a new array with elements that follow or pass the given criteria and condition. Few Examples have been implemented below for a better understanding of the concept Syntax:
var newArray = arr.filter(callback(element[, index[, array]])
[, thisArg])
Parameter: This method accepts 2 parameters which was mentioned above and described below:
Callback: The function is a predicate, to test each element of the array. Return true to keep the element, false otherwise. It accepts three arguments:element: The current element being processed in the array.index(Optional): The index of the current element being processed in the array.array(Optional): The array filter was called upon.
element: The current element being processed in the array.
index(Optional): The index of the current element being processed in the array.
array(Optional): The array filter was called upon.
thisArg(Optional): Value to use as this when executing the callback.
Example 1: The filter function filters all the numeric values in the array greater than 5 
javascript
var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];var result = numbers.filter(number => number > 5);console.log(result);
Output :
[ 6, 7, 8, 9, 10 ]
Time complexity: O(n) 
Auxiliary Space: O(1)
Example 2: The filter function filters all the words in the array which have length greater than 5 
javascript
var words = ["hi", "hello", "hey", "apple", "watermelon",            "lemon", "javascript"];var result = words.filter(word => word.length > 5);console.log(result);
Output :
[ 'watermelon', 'javascript' ]
Time complexity: O(n) 
Auxiliary Space: O(1)
Example 3: The filter function filters all invalid id of users from the array. 
javascript
var jsonarr = [    {        id: 1,        name: "joe"    },    {        id: -19,        name: "john"    },    {        id: 20,        name: "james"    },    {        id: 25,        name: "jack"    },    {        id: -10,        name: "joseph"    },    {        id: "not a number",        name: "jimmy"    },    {        id: null,        name: "jeff"    },] var result = jsonarr.filter(user => user.id > 0); console.log(result);
Output:
[{"id":1,"name":"joe"},{"id":20,"name":"james"},
{"id":25,"name":"jack"}] 
Time complexity: O(n) 
Auxiliary Space: O(1)
surbhikumaridav
JavaScript-ES
Picked
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
REST API (Introduction)
Node.js fs.readFileSync() Method
How to set the default value for an HTML <select> element ?
Python | Numpy numpy.matrix.any()

08 Apr, 2019
With the help of Numpy numpy.matrix.any() method, we are able to compare each and every element of one matrix with another or we can provide the axis on the we want to apply comparison if any of the element matches it return true.
Syntax : numpy.matrix.any()
Return : Return true if any match found else false
Example #1 :In this example we can see that with the help of matrix.any() method, we are able to compare any two matrix having different dimensions and if any match found then return true.
# import the important module in pythonimport numpy as np          # make a matrix with numpygfg1 = np.matrix('[1, 2, 3, 4]')gfg2 = np.matrix('[1, 2]')          # applying matrix.any() methodgeeks = (gfg1 == gfg2).any()    print(geeks)
True

Example #2 :
# import the important module in pythonimport numpy as np          # make a matrix with numpygfg1 = np.matrix('[1, 2, 3; 4, 5, 6; 7, 8, 9]')gfg2 = np.matrix('[1, 2, 3]')          # applying matrix.any() methodgeeks = (gfg1 == gfg2).any()    print(geeks)
True

Python numpy-Matrix Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function
Expression must have class type error in C++

20 Jun, 2022
The expression must have class type is an error that is thrown when the dot(.) operator is used to access an object’s properties, is used on pointers to objects.
Dot(‘.’) Operator is basically used for accessing the fields and methods of an object, but when a dot operator is used on the pointer to object in that condition, the error “Expression must have class” type is shown.
When the Dot(‘.’) operator is used on a pointer of class types object in that condition Dot(‘.’) Operator tries to find fields and methods of pointer type but in reality, they do not exist and because of that, we get this error.
Below is the code below to illustrate the above error: 
C++
// C++ program to illustrate the// Expression must have class// type error#include <iostream>using namespace std; // Classclass GeeksforGeeks {public:    // Function to display message    void showMyName()    {        cout << "Welcome to GeeksforGeeks!";    }}; // Driver Codeint main(){    // Object of the class    GeeksforGeeks* p = new GeeksforGeeks();     // Member function call    p.showMyName();     return 0;}
Output:  How to resolve this error? To solve the above error, the idea is to initialize the class without using the new operator i.e., instead of initializing the object as “className *obj = new className()”, initialize it as “className obj” to access the member function of the class using dot(‘.’) operator. Below is the program to illustrate the same: 
C++
// C++ program to illustrate how to// solve Expression must have class// type error#include <iostream>using namespace std; // Classclass GeeksforGeeks {public:    // Function to display message    void showMyName()    {        cout << "Welcome to GeeksforGeeks!";    }}; // Driver Codeint main(){    // Object of the class    GeeksforGeeks p;     // Member function call    p.showMyName();     return 0;}
Welcome to GeeksforGeeks!
Time Complexity: O(1)Auxiliary Space: O(1)
ayushkumarkk1
jayanth_mkv
CPP-Basics
cpp-operator
C++
C++ Programs
cpp-operator
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
Friend class and function in C++
Pair in C++ Standard Template Library (STL)
std::string class in C++
Header files in C/C++ and its uses
Sorting a Map by value in C++ STL
Program to print ASCII Value of a character
How to return multiple values from a function in C or C++?
Shallow Copy and Deep Copy in C++
Python | Creating a 3D List

04 Dec, 2017
A 3-D List means that we need to make a list that has three parameters to it, i.e., (a x b x c), just like a 3 D array in other languages. In this program we will try to form a 3-D List with its content as “#”. Lets look at these following examples:
Input : 
3 x 3 x 3
Output :
[[['#', '#', '#'], ['#', '#', '#'], ['#', '#', '#']],
 [['#', '#', '#'], ['#', '#', '#'], ['#', '#', '#']],
 [['#', '#', '#'], ['#', '#', '#'], ['#', '#', '#']]]

Input :
5 x 3 x 2
Output :
[[['#', '#', '#', '#', '#'],
  ['#', '#', '#', '#', '#'],
  ['#', '#', '#', '#', '#']],
 [['#', '#', '#', '#', '#'],
  ['#', '#', '#', '#', '#'],
  ['#', '#', '#', '#', '#']]]

# Python program to print 3D list# importing pretty printedimport pprint  def ThreeD(a, b, c):    lst = [[ ['#' for col in range(a)] for col in range(b)] for row in range(c)]    return lst      # Driver Codecol1 = 5col2 = 3row = 2# used the pretty printed functionpprint.pprint(ThreeD(col1, col2, row))
Output:
[[['#', '#', '#', '#', '#'],
  ['#', '#', '#', '#', '#'],
  ['#', '#', '#', '#', '#']],
 [['#', '#', '#', '#', '#'],
  ['#', '#', '#', '#', '#'],
  ['#', '#', '#', '#', '#']]]

Refer pprint() to get more insight into this topic.
Now let’s suppose we need to merge two 3D lists into one.
# Python program to merge two 3D list into one# importing pretty printedimport pprint  def ThreeD(a, b, c):    lst1 = [[ ['1' for col in range(a)] for col in range(b)] for row in range(c)]    lst2= [[ ['2' for col in range(a)] for col in range(b)] for row in range(c)]    # Merging using "+" operator    lst = lst1+lst2    return lst      # Driver Codecol1 = 3col2 = 3row = 3  # used the pretty printed functionpprint.pprint(ThreeD(col1, col2, row))
Output:
[[['1', '1', '1'], ['1', '1', '1'], ['1', '1', '1']],
 [['1', '1', '1'], ['1', '1', '1'], ['1', '1', '1']],
 [['1', '1', '1'], ['1', '1', '1'], ['1', '1', '1']],
 [['2', '2', '2'], ['2', '2', '2'], ['2', '2', '2']],
 [['2', '2', '2'], ['2', '2', '2'], ['2', '2', '2']],
 [['2', '2', '2'], ['2', '2', '2'], ['2', '2', '2']]]

python-list
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python OpenCV | cv2.blur() method

29 Nov, 2019
OpenCV-Python is a library of Python bindings designed to solve computer vision problems. cv2.blur() method is used to blur an image using the normalized box filter. The function smooths an image using the kernel which is represented as:
Syntax: cv2.blur(src, ksize[, dst[, anchor[, borderType]]])Parameters:src: It is the image whose is to be blurred.ksize: A tuple representing the blurring kernel size.dst: It is the output image of the same size and type as src.anchor: It is a variable of type integer representing anchor point and it’s default value Point is (-1, -1) which means that the anchor is at the kernel center.borderType: It depicts what kind of border to be added. It is defined by flags like cv2.BORDER_CONSTANT, cv2.BORDER_REFLECT, etcReturn Value: It returns an image.
Image used for all the below examples:Example #1:
# Python program to explain cv2.blur() method   # importing cv2 import cv2   # path path = r'C:\Users\Rajnish\Desktop\geeksforgeeks\geeks.png'  # Reading an image in default mode image = cv2.imread(path)   # Window name in which image is displayed window_name = 'Image'  # ksizeksize = (10, 10)  # Using cv2.blur() method image = cv2.blur(image, ksize)   # Displaying the image cv2.imshow(window_name, image) 
Output:
Example #2:
# Python program to explain cv2.blur() method   # importing cv2 import cv2   # path path = r'C:\Users\Rajnish\Desktop\geeksforgeeks\geeks.png'  # Reading an image in default mode image = cv2.imread(path)   # Window name in which image is displayed window_name = 'Image'  # ksizeksize = (30, 30)  # Using cv2.blur() method image = cv2.blur(image, ksize, cv2.BORDER_DEFAULT)   # Displaying the image cv2.imshow(window_name, image) 
Output:
Image-Processing
OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Convert integer to string in Python
Python | os.path.join() method
Create a Pandas DataFrame from Lists
Understanding PEAS in Artificial Intelligence

12 Jul, 2022
We know that there are different types of agents in AI. PEAS System is used to categorize similar agents together. The PEAS system delivers the performance measure with respect to the environment, actuators, and sensors of the respective agent. Most of the highest performing agents are Rational Agents.
Rational Agent: The rational agent considers all possibilities and chooses to perform a highly efficient action. For example, it chooses the shortest path with low cost for high efficiency. PEAS stands for a Performance measure, Environment, Actuator, Sensor. 
Performance Measure: Performance measure is the unit to define the success of an agent. Performance varies with agents based on their different precepts.Environment: Environment is the surrounding of an agent at every instant. It keeps changing with time if the agent is set in motion. There are 5 major types of environments: Fully Observable & Partially ObservableEpisodic & SequentialStatic & DynamicDiscrete & ContinuousDeterministic & StochasticActuator: An actuator is a part of the agent that delivers the output of action to the environment.Sensor: Sensors are the receptive parts of an agent that takes in the input for the agent.
Performance Measure: Performance measure is the unit to define the success of an agent. Performance varies with agents based on their different precepts.
Environment: Environment is the surrounding of an agent at every instant. It keeps changing with time if the agent is set in motion. There are 5 major types of environments: Fully Observable & Partially ObservableEpisodic & SequentialStatic & DynamicDiscrete & ContinuousDeterministic & Stochastic
Fully Observable & Partially Observable
Episodic & Sequential
Static & Dynamic
Discrete & Continuous
Deterministic & Stochastic
Actuator: An actuator is a part of the agent that delivers the output of action to the environment.
Sensor: Sensors are the receptive parts of an agent that takes in the input for the agent.
ilyaskarimovf
chhabradhanvi
anikmajumder303
Artificial Intelligence
Machine Learning
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C | Input and Output | Question 13

31 Aug, 2021
Which of the following is true(A) gets() can read a string with newline characters but a normal scanf() with %s can not.(B) gets() can read a string with spaces but a normal scanf() with %s can not.(C) gets() can always replace scanf() without any additional code.(D) None of the aboveAnswer: (B)Explanation: gets() can read a string with spaces but a normal scanf() with %s can not. Consider following program as an example.
If we enter “Geeks Quiz” as input in below program, the program prints “Geeks”
int main(){   char str[100];   scanf("%s", str);   printf("%s", str);}
But in the following program, if we enter “Geeks Quiz”, it prints “Geeks Quiz”
int main(){   char str[100];   gets(str);   printf("%s", str);}
Quiz of this Question
sweetyty
C-Input and Output Quiz
Input and Output
C Quiz
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – Concatenate two list of lists Row-wise

03 Aug, 2021
Given two matrices, the task is to write a Python program to add elements to each row from initial matrix.
Input : test_list1 = [[4, 3, 5,], [1, 2, 3], [3, 7, 4]], test_list2 = [[1, 3], [9, 3, 5, 7], [8]]
Output : [[4, 3, 5, 1, 3], [1, 2, 3, 9, 3, 5, 7], [3, 7, 4, 8]]
Explanation : Matrix is row wise merged.
Input : test_list1 = [[4, 3, 5,], [1, 2, 3], [3, 7, 4]], test_list2 = [[1], [9], [8]]
Output : [[4, 3, 5, 1], [1, 2, 3, 9], [3, 7, 4, 8]]
Explanation : Matrix is row wise merged.
Method #1 : Using enumerate() + loop
In this, we get each index of each initial matrix and append its all elements to the second matrix’s corresponding row.
Python3
# Python3 code to demonstrate working of# Concatenate 2 Matrix Row-wise# Using loop + enumerate()  # initializing liststest_list1 = [[4, 3, 5, ], [1, 2, 3], [3, 7, 4]]test_list2 = [[1, 3], [9, 3, 5, 7], [8]]  # printing original listsprint("The original list 1 is : " + str(test_list1))print("The original list 2 is : " + str(test_list2))  for idx, ele in enumerate(test_list1):    new_vals = []      # getting all values at same index row    for ele in test_list2[idx]:        new_vals.append(ele)      # extending the initial matrix    test_list1[idx].extend(new_vals)  # printing resultprint("The concatenated Matrix : " + str(test_list1))
Output:
The original list 1 is : [[4, 3, 5], [1, 2, 3], [3, 7, 4]]
The original list 2 is : [[1, 3], [9, 3, 5, 7], [8]]
The concatenated Matrix : [[4, 3, 5, 1, 3], [1, 2, 3, 9, 3, 5, 7], [3, 7, 4, 8]]
Method #2 : Using zip() + list comprehension
In this, we perform the task of concatenating rows using zip(), and iteration through each row happens using list comprehension.
Python3
# Python3 code to demonstrate working of# Concatenate 2 Matrix Row-wise# Using zip() + list comprehension  # initializing liststest_list1 = [[4, 3, 5, ], [1, 2, 3], [3, 7, 4]]test_list2 = [[1, 3], [9, 3, 5, 7], [8]]  # printing original listsprint("The original list 1 is : " + str(test_list1))print("The original list 2 is : " + str(test_list2))  # zip() combines the results# list comprehension provides shorthandres = list(sub1 + sub2 for sub1, sub2 in zip(test_list1, test_list2))  # printing resultprint("The concatenated Matrix : " + str(res))
Output:
The original list 1 is : [[4, 3, 5], [1, 2, 3], [3, 7, 4]]
The original list 2 is : [[1, 3], [9, 3, 5, 7], [8]]
The concatenated Matrix : [[4, 3, 5, 1, 3], [1, 2, 3, 9, 3, 5, 7], [3, 7, 4, 8]]
Python list-programs
Python
Python Programs
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 program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
No. of vowels and consonants in a given string in PL/SQL

05 Jul, 2018
Prerequisite – PL/SQL introduction
In PL/SQL code groups of commands are arranged within a block. A block group related declarations or statements. In declare part, we declare variables and between begin and end part, we perform the operations.
Given a string and the task is to find the number of vowels and consonants present in the string.Examples:
Input: str = 'Ramesh'
Output: Vowels = 2, Consonants = 4

Input: str = 'Ramesh is a Geek'
Output: Vowels = 6, Consonants = 7

Approach is to consider a character one by one and maintain a separate count for both vowels and consonants.
Below is the required implementation:
DECLARE     -- Here variable V is varchar datatype      -- and  flag variable is number datatype       -- variable c is char datatype .      v              VARCHAR2(400) := 'Ramesh is a Geek';     noofvowels     NUMBER := 0;     noofconsonants NUMBER := 0;     C              CHAR; BEGIN     FOR i IN 1..Length(v) LOOP         c := Substr(v, i, 1);           -- Check if the current character is vowel         IF c IN ( 'A', 'E', 'I', 'O', 'U' )             OR c IN ( 'a', 'e', 'i', 'o', 'u' ) THEN           noofvowels := noofvowels + 1;           -- Else current character is a consonant except space         ELSE           IF c NOT IN ( ' ' ) THEN             noofconsonants := noofconsonants + 1;           END IF;         END IF;     END LOOP;       dbms_output.Put_line('No. of Vowels: '                          || noofvowels);       dbms_output.Put_line('No. of Consonants: '                          || noofconsonants); END; -- Program End  
Output :
No. of Vowels: 6
No. of Consonants: 7

SQL-PL/SQL
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CTE in SQL
SQL Interview Questions
How to Update Multiple Columns in Single Update Statement in SQL?
Difference between DELETE, DROP and TRUNCATE
Difference between SQL and NoSQL
Window functions in SQL
Difference between DELETE and TRUNCATE
MySQL | Group_CONCAT() Function
MySQL | Regular expressions (Regexp)
SQL Correlated Subqueries
Python Program to Construct n*m Matrix from List

30 Jun, 2021
Given a list, the task is to write a python program that can construct n*m matrix.
Input : test_list = [6, 3, 7, 2, 6, 8, 4, 3, 9, 2, 1, 3], n, m = 3, 5 Output : “Matrix Not Possible” Explanation : List has 12 elements and 3*5 is 15, hence Matrix not possible.
Input : test_list = [6, 3, 7, 2, 6, 8], n, m = 2, 3 Output : [[6, 3, 7], [2, 6, 8]] Explanation : List converted to 2*3 matrix.  
Method : Using nested loop 
The constraint of n*m restricts size of list to be strictly n*m. Post achieving that, we can assign the appropriate rows and columns using nested loops.
Example 1:
Python3
# Python3 code to demonstrate working of# Construct n*m Matrix from List# Using loop  # initializing listtest_list = [6, 3, 7, 2, 6, 8, 4, 3, 9, 2, 1, 3]  # printing original listprint("The original list is : " + str(test_list))  # initializing n, mn, m = 3, 4  k = 0res = []if n*m != len(test_list):      # checking if Matrix Possible    res = "Matrix Not Possible"else:      # Constructing Matrix    for idx in range(0, n):        sub = []        for jdx in range(0, m):            sub.append(test_list[k])            k += 1        res.append(sub)  # printing resultprint("Constructed Matrix : " + str(res))
Output:
The original list is : [6, 3, 7, 2, 6, 8, 4, 3, 9, 2, 1, 3]
Constructed Matrix : [[6, 3, 7, 2], [6, 8, 4, 3], [9, 2, 1, 3]]
Example 2 : 
Python3
# Python3 code to demonstrate working of# Construct n*m Matrix from List# Using loop  # initializing listtest_list = [6, 3, 7, 2, 6, 8, 4, 3, 9, 2, 1, 3]  # printing original listprint("The original list is : " + str(test_list))  # initializing n, mn, m = 5, 4  k = 0res = []  # n*m == 20 > length, hence result not possible.if n*m != len(test_list):      # checking if Matrix Possible    res = "Matrix Not Possible"else:      # Constructing Matrix    for idx in range(0, n):        sub = []        for jdx in range(0, m):            sub.append(test_list[k])            k += 1        res.append(sub)  # printing resultprint("Constructed Matrix : " + str(res))
Output:
The original list is : [6, 3, 7, 2, 6, 8, 4, 3, 9, 2, 1, 3]
Constructed Matrix : Matrix Not Possible
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
How to Convert String to Datetime in R?

27 Dec, 2021
In this article, we will discuss how to convert String to Datetime in R Programming Language. We can convert string to DateTime by using the POSIXct function
Syntax: as.POSIXct(string, format=”%Y-%m-%d %H:%M:%S”, tz=”UTC”)
where
string is the input string
format represents the datetime format
tz specifies local time zone
Here we are going to take a string as input and convert it to DateTime.
R
# consider a stringstring = "2021-11-21 4:5:23" # convert string to datetimefinal = as.POSIXct(string, format="%Y-%m-%d %H:%M:%S", tz="UTC") # displayprint(final) # get the typeclass(final)
Output:
[1] "2021-11-21 04:05:23 UTC"
[1] "POSIXct" "POSIXt" 
Here we are taking a string from dataframe and then convert into DateTime 
Syntax: as.POSIXct(dataframe$column_name, format=”%Y-%m-%d %H:%M:%S”, tz=”UTC”)
where,
dataframe is the input dataframe
column_name is the string datetime column
R
# consider a dataframedataframe = data.frame(data = c( "2021-11-21 4:5:23",                                "2021-11-22 4:5:23",                                "2021-11-23 4:5:23",                                "2021-11-24 4:5:23",                                "2021-11-25 4:5:23")) # convert data column  to datetimeprint(as.POSIXct(dataframe$data,                 format="%Y-%m-%d %H:%M:%S",                 tz="UTC"))
Output:
[1] "2021-11-21 04:05:23 UTC" "2021-11-22 04:05:23 UTC"
[3] "2021-11-23 04:05:23 UTC" "2021-11-24 04:05:23 UTC"
[5] "2021-11-25 04:05:23 UTC"
surinderdawra388
Picked
R String-Programs
R-DateTime
R-strings
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to create Jumbotron using Bootstrap 5 ?

15 Sep, 2020
Bootstrap Jumbotron is a responsive component whose main goal is to draw the visitor’s attention or highlight a special piece of information. Inside a Jumbotron, you can make use of almost any other Bootstrap code to further increase its engagement value.
Uses of Jumbotron:
Image showcase
Highlighting content
Introduction for a Certain Topic
Approach:
To create a Jumbotron bootstrap provides a class named “jumbotron”. 
Bootstrap uses some default properties applied to Jumbotron, making it a very good ‘eye-catcher’.
Example 1: Creating a simple Jumbotron:
HTML
<!DOCTYPE html><html>  <head>    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"        integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"         crossorigin="anonymous"></head>  <body>    <div class="jumbotron">        <h1>Text to catch user attention/greeting.</h1>        <p class="lead">lorem ipsum.</p>          <hr class="my-4">                  <p>Some dummy text</p>    </div></body></html>
Output:
Example 2: To create a full-width Jumbotron we use the jumbotron-fluid class along with the Jumbotron class.
HTML
<!DOCTYPE html>   <html>  <head>    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"         integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"         crossorigin="anonymous"></head>  <body>    <div class="jumbotron jumbotron-fluid">        <div class="container">            <h1 class="display-4">Fluid jumbotron</h1>            <p class="lead">                This is a modified jumbotron that                 occupies the entire horizontal                 space of its parent.            </p>        </div>    </div></body>  </html>
Output
Example 3: We can also style the Jumbotron and add background images to make it more attractive as shown below.
HTML
<!DOCTYPE html><html>  <head>    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"         integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"         crossorigin="anonymous">      <style>        .jumbotron-image {            background-position: center center;            background-repeat: no-repeat;            background-size: cover;        }    </style></head>  <body>    <div class="jumbotron text-white jumbotron-image shadow"         style="background-image: url(https://media.geeksforgeeks.org/wp-content/uploads/20200914000601/gfg-300x200.jpg );">        <h2 class="mb-4">            Jumbotron with background image        </h2>          <p class="mb-4">            Hey, check this out.        </p>          <a class="btn btn-primary">            Click!        </a>    </div></body>  </html>
Output
Bootstrap-Misc
Bootstrap
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL SERVER | Bulk insert data from csv file using T-SQL command

09 Mar, 2021
In this article, we will cover bulk insert data from csv file using the T-SQL command in the SQL server. And will also cover the way is more useful and more convenient to perform such kind of operations. Let’s discuss it one by one. 
Introduction :Sometimes there is a scenario when we have to perform bulk insert data from .csv files into SQL Server database. We can use the GUI interface in SSMS(SQL Server Management Studio) to import data from Excel, CSV, etc files. What if we have millions of data to be imported, the above will be a time-consuming task so, now you will see how you can handle such kinds of operation.
Note – Requires INSERT and ADMINISTER BULK OPERATIONS permissions.
Alternative Approach :Here, in this article, we will provide a faster alternative to the above via few lines of T-SQL Command. 
BULK INSERT <DATABASE NAME>.<SCHEMA NAME>.<TABLE_NAME>
FROM '<FILE_PATH>'
WITH
(
-- input file format options
   [ [ , ] FORMAT = 'CSV' ]
   [ [ , ] FIELDQUOTE = 'quote_characters']
   [ [ , ] FORMATFILE = 'format_file_path' ]
   [ [ , ] FIELDTERMINATOR = 'field_terminator' ]
   [ [ , ] ROWTERMINATOR = 'row_terminator' ]
    )]
)
The most commonly used input parameters are the following as follows.
FIELDTERMINATOR –‘‘field_terminator’ is used as a separator between fields. The default field terminator is \t (tab character). ROWTERMINATOR –‘row_terminator’ is used to specify the end of the row. The default row terminator is \r\n (newline character). 
FIELDTERMINATOR –‘‘field_terminator’ is used as a separator between fields. The default field terminator is \t (tab character). 
ROWTERMINATOR –‘row_terminator’ is used to specify the end of the row. The default row terminator is \r\n (newline character). 
Importing CSV file into SQL table :Here, we will discuss importing CSV file into a table in SQL server. Consider the given below CSV file or you can use your own csv file to perform this operation. Let us try to import a csv file into our SQL table in SQL Server.
Now, let’s create the SQL table to store the above data.
Creating table –Here. We will create the table schema as per csv file records.
USE [Test]--Database name

CREATE TABLE [dbo].[Employee](                              
[Emp ID] bigint primary key,
[First Name] [varchar](50) NULL,
[Last Name] [varchar](50) NULL,
[Salary] bigint,
[City] [varchar](50)
)
Bulk Inserting –Let’s now bulk insert the file into the Employee SQL table :
BULK INSERT [Test].[dbo].[Employee]
FROM 'C:\data\employee_data.csv'
WITH (FIRSTROW = 2,
    FIELDTERMINATOR = ',',
    ROWTERMINATOR='\n' );
Output –After executing the above operation we can see the records have been inserted with few lines of code into the Employee table like below.
References :To get more info on the input format options, visit https://docs.microsoft.com/en-us/sql/t-sql/statements/bulk-insert-transact-sql?view=sql-server-2017#input-file-format-options.
CSV
SQL-Server
DBMS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What is a null-terminated string in C/C++?

In C the strings are basically array of characters. In C++ the std::string is an advancement of that array. There are some additional features with the traditional character array. The null terminated strings are basically a sequence of characters, and the last element is one null character (denoted by ‘\0’). When we write some string using double quotes (“...”), then it is converted into null terminated strings by the compiler.
The size of the string may smaller than the array size, but if there are some null character inside that array, that will be treated as the end of that string.
See the following example. Here we have defined one string using std::string, then we will provide the same string, but there will be one \0 inside it.
#include<iostream>
using namespace std;
main() {
   string my_string = "This is a sample text";
   cout << my_string << endl;
   my_string = "This is a sam\0ple text"; //check the \0
   cout << my_string;
}
This is a sample text
This is a sam
Python – math.perm() method

23 Jan, 2020
Math module in Python contains a number of mathematical operations, which can be performed with ease using the module. math.perm() method in Python is used to get the number of ways to choose k items from n items without repetition and with order. It Evaluates to n! / (n – k)! when k <= n and evaluates to 0 when k > n.This method is new in Python version 3.8.
Syntax: math.perm(n, k = None)
Parameters:n: A non-negative integerk: A non-negative integer. If k is not specified, it defaults to None
Returns: an integer value which represents the number of ways to choose k items from n items without repetition and with order. If k is none, method returns n!.
Code #1: Use of math.perm() method
# Python Program to explain math.perm() method  # Importing math moduleimport math  n = 10k = 2  # Get the number of ways to choose# k items from n items without# repetition and with ordernPk = math.perm(n, k)print(nPk)  n = 5k = 3  # Get the number of ways to choose# k items from n items without# repetition and with ordernPk = math.perm(n, k)print(nPk)
90
60

Code #2: When k > n
# Python Program to explain math.perm() method  # Importing math moduleimport math  # When k > n # math.perm(n, k) returns 0.n = 3k = 5  # Get the number of ways to choose# k items from n items without# repetition and with ordernPk = math.perm(n, k)print(nPk)
0

Code #3: If k is not specified
# Python Program to explain math.perm() method  # Importing math moduleimport math  # When k is not specified# It defaults to n and # math.perm(n, k) returns n ! n = 5  nPk = math.perm(n)print(nPk)
120

Reference: Python math library
Python math-library
Python math-library-functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
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
Python | datetime.timedelta() function
Extract week number from date in Pandas-Python

10 Jul, 2020
Many times, when working with some data containing dates we may need to extract the week number from a particular date. In Python, it can be easily done with the help of pandas.
Example 1:
# importing pandas as pdimport pandas as pd   # creating a dictionary containing a datedict = {'Date':["2015-06-17"]}  # converting the dictionary to a dataframedf = pd.DataFrame.from_dict(dict)  # converting the date to the required formatdf['Date'] = pd.to_datetime(df['Date'], errors ='coerce')df.astype('int64').dtypes  # extracting the week from the dateweekNumber = df['Date'].dt.week  print(weekNumber)
Output:
0    25
Name: Date, dtype: int64
Example 2: We can also do the same for multiple dates by adding more dates in the ‘Date’ object.
# importing pandas as pdimport pandas as pd   # creating a dictionary containing a datedict = {'Date':["2020-06-17", "2020-01-14",                 "2020-09-20", "2020-08-15"]}  # converting the dictionary to a # dataframedf = pd.DataFrame.from_dict(dict)  # converting the date to the required # formatdf['Date'] = pd.to_datetime(df['Date'],                            errors ='coerce')df.astype('int64').dtypes  # extracting the week from the dateweekNumber = df['Date'].dt.week  print(weekNumber)
Output:
Example 3: Extracting week number from dates for multiple dates using date_range() and to_series().
pandas.data_range(): It generates all the dates from the start to end dateSyntax:pandas.date_range(start, end, periods, freq, tz, normalize, name, closed)
Syntax:
pandas.date_range(start, end, periods, freq, tz, normalize, name, closed)
pandas.to_series(): It creates a Series with both index and values equal to the index keys.Syntax:Index.to_series(self, index, name)
Syntax:
Index.to_series(self, index, name)
# importing pandas as pdimport pandas as pd   # generating all dates in given range# with increment by daysallDates = pd.date_range('2020-06-27', '2020-08-03', freq ='W')  # converting dates to seriesseries = allDates.to_series()  series.dt.week
Output:
Example 4: In this example, we’ll be using pandas.Series() to generate dates and use a different way to convert the series to the dataframe.
pandas.Series(): Used to create a one-dimensional ndarray with axis labels.Syntax:
pandas.Series(data, index, dtype, name, copy, fastpath)
# importing pandas as pdimport pandas as pd   # generating the seriesdates = pd.Series(pd.date_range('2020-2-10',                                periods = 5,                                freq ='M'))  # converting to dataframedf = pd.DataFrame({'date_given': dates})  # extracting the week numberdf['week_number'] = df['date_given'].dt.week  df
Output:
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Matplotlib.axes.Axes.legend() in Python

19 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.
The Axes.legend() function in axes module of matplotlib library is used to place a legend on the axes.
Syntax: Axes.legend(self, *args, **kwargs)
Parameters: This method accepts the following parameters.
labels : This parameter is the list of labels to show next to the artists.
handles : This parameter is the list of Artists (lines, patches) to be added to the legend.
Returns:This method returns the matplotlib.legend.Legend instance.
Below examples illustrate the matplotlib.axes.Axes.legend() function in matplotlib.axes:
Example 1:
# Implementation of matplotlib functionimport matplotlib.pyplot as plt  fig, ax = plt.subplots()  line1, = ax.plot([1, 2, 3],                 label ="Line 1",                 color ="black",                  linewidth = 4,                 linestyle =':')  line2, = ax.plot([3, 2, 1],                  label ="Line 2",                 color ="green",                  linewidth = 4)    first_legend = ax.legend(handles =[line1],                          loc ='upper center')  ax.add_artist(first_legend)  ax.legend(handles =[line2], loc ='lower center')  fig.suptitle('matplotlib.axes.Axes.legend() \function Example\n', fontweight ="bold")  plt.show()
Output:
Example 2:
# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt  np.random.seed(19680801)  fig, ax = plt.subplots()for color in [ 'tab:green', 'tab:blue',               'tab:orange']:    n = 70    x, y = np.random.rand(2, n)    scale = 1000.0 * np.random.rand(n)    ax.scatter(x, y, c = color, s = scale,               label = color,               alpha = 0.35)  ax.legend()ax.grid(True)fig.suptitle('matplotlib.axes.Axes.legend() function\ Example\n', fontweight ="bold")  plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Lodash _.now() Method

14 Sep, 2020
The _.now() method is used to get the timestamp of the number of milliseconds that have elapsed since the Unix epoch (1 January 1970 00:00:00 UTC).
Syntax:
_.now()
Parameters: This method does not accept any parameter.
Return Value: This method returns the timestamp.
Example 1:
Javascript
// Defining Lodash variableconst _ = require('lodash');  // Getting the timestampconsole.log(_.now());
Output:
1599545119753

Example 2:
Javascript
// Defining Lodash variableconst _ = require('lodash');  // Creating print function to print// timestamp after delay of 10ms function print(){     setTimeout(() => {         console.log(`Current timestamp is: ${_.now()}`)     }, 10) }   // Running this function 5 times// using _.times() function. _.times(5, print) console.log("Type of timestamp is: ",     typeof(_.now())) 
Output:
Type of timestamp is:  number
Current timestamp is: 1599546710915
Current timestamp is: 1599546710916
Current timestamp is: 1599546710916
Current timestamp is: 1599546710916
Current timestamp is: 1599546710916

Note: This will not work in normal JavaScript because it requires the lodash library to be installed.
JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Custom list split

02 Jan, 2019
Development and sometimes machine learning applications require splitting lists into smaller list in a custom way, i.e on certain values on which split has to be performed. This is quite a useful utility to have knowledge about. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using list comprehension + zip()
By coupling the power of list comprehension and zip(), this task can be achieved. In this, we zip beginning and end of list and then keep slicing the list as they arrive and cutting off new lists from them.
# Python3 code to demonstrate # to perform custom list split# using list comprehension + zip()  # initializing string  test_list = [1, 4, 5, 6, 7, 3, 5, 9, 2, 4]  # initializing split index list split_list = [2, 5, 7]  # printing original listprint ("The original list is : " + str(test_list))  # printing original split index listprint ("The original split index list : " + str(split_list))  # using list comprehension + zip()# to perform custom list splitres = [test_list[i : j] for i, j in zip([0] +           split_list, split_list + [None])]  # printing resultprint ("The splitted lists are : " +  str(res))
The original list is : [1, 4, 5, 6, 7, 3, 5, 9, 2, 4]
The original split index list : [2, 5, 7]
The splitted lists are : [[1, 4], [5, 6, 7], [3, 5], [9, 2, 4]]

 Method #2 : Using itertools.chain() + zip()
The task performed by the list comprehension function of getting the split chunks can also be done using chain function. This is more useful when we wish to handle larger lists as this method is more efficient.
# Python3 code to demonstrate # to perform custom list split# using itertools.chain() + zip()from itertools import chain  # initializing string  test_list = [1, 4, 5, 6, 7, 3, 5, 9, 2, 4]  # initializing split index list split_list = [2, 5, 7]  # printing original listprint ("The original list is : " + str(test_list))  # printing original split index listprint ("The original split index list : " + str(split_list))  # using itertools.chain() + zip()# to perform custom list splittemp = zip(chain([0], split_list), chain(split_list, [None]))res = list(test_list[i : j] for i, j in temp)  # printing resultprint ("The splitted lists are : " +  str(res))
The original list is : [1, 4, 5, 6, 7, 3, 5, 9, 2, 4]
The original split index list : [2, 5, 7]
The splitted lists are : [[1, 4], [5, 6, 7], [3, 5], [9, 2, 4]]

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 12

28 Jun, 2021
The address sequence generated by tracing a particular program executing in a pure demand paging system with 100 bytes per page is0100, 0200, 0430, 0499, 0510, 0530, 0560, 0120, 0220, 0240, 0260, 0320, 0410.
Suppose that the memory can store only one page and if x is the address which causes a page fault then the bytes from addresses x to x + 99 are loaded on to the memory.How many page faults will occur ?(A) 0(B) 4(C) 7(D) 8Answer: (C)Explanation:

Address            Page faults    last byte in memory
0100         page fault,      199 
0200         page fault,      299
0430        page fault,      529 
0499         no page fault
0510         no page fault 
0530         page fault,     629
0560            no page fault 
0120         page fault,     219
0220         page fault,     319
0240            no page fault 
0260            no page fault 
0320        page fault,     419
0410            no page fault
So, 7 is the answer- (C)
Quiz of this Question
Gate IT 2007
GATE-Gate IT 2007
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33
GATE | GATE-CS-2014-(Set-3) | Question 20
GATE | GATE CS 2008 | Question 46
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE CS 2008 | Question 40
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 1996 | Question 63
GATE | GATE CS 2011 | Question 49
GATE | GATE-CS-2014-(Set-1) | Question 51