code-rag-bench/online-tutorials huggingface dataset:
JavaScript code for recursive Fibonacci series

We have to write a recursive function fibonacci() that takes in a number n and returns an array
with first n elements of fibonacci series. Therefore, let’s write the code for this function −
const fibonacci = (n, res = [], count = 1, last = 0) => {
   if(n){
      return fibonacci(n-1, res.concat(count), count+last, count);
   };
   return res;
};
console.log(fibonacci(8));
console.log(fibonacci(0));
console.log(fibonacci(1));
console.log(fibonacci(19));
The output in the console will be −
[
   1, 1, 2, 3,
   5, 8, 13, 21
]
[]
[ 1 ]
[
   1, 1, 2, 3, 5,
   8, 13, 21, 34, 55,
   89, 144, 233, 377, 610,
   987, 1597, 2584, 4181
]
Java Program to check for Integer overflow

To check for Integer overflow, we need to check the Integer.MAX_VALUE, which is the maximum value of an integer in Java.
Let us see an example wherein integers are added and if the sum is more than the Integer.MAX_VALUE, then an exception is thrown.
 Live Demo
public class Demo {
   public static void main(String[] args) {
      int val1 = 9898989;
      int val2 = 6789054;
      System.out.println("Value1: "+val1);
      System.out.println("Value2: "+val2);
      long sum = (long)val1 + (long)val2;
      if (sum > Integer.MAX_VALUE) {
         throw new ArithmeticException("Overflow!");
      }
      // displaying sum
      System.out.println("Sum: "+(int)sum);
   }
}
Value1: 9898989
Value2: 6789054
Sum: 16688043
In the above example, we have taken the following two integers −
int val1 = 9898989;
int val2 = 6789054;
Now we will cast and add them to a long.
long sum = (long)val1 + (long)val2;
If the result is more than the maximum value, then a exception is thrown.
if (sum > Integer.MAX_VALUE) {
   throw new ArithmeticException("Overflow!");
}
SciPy Sparse Data

Sparse data is data that has mostly unused elements (elements that don't carry any information ).
It can be an array like this one:
[1, 0, 2, 0, 0, 3, 0, 0, 0, 0, 0, 0]
Sparse Data: is a data set where most of the item values are zero.
Dense Array: is the opposite of a sparse array: most of the values are not zero.
In scientific computing, when we are dealing with partial derivatives in linear algebra we will come across sparse data.
SciPy has a module, scipy.sparse
that provides functions to deal with sparse data.
There are primarily two types of sparse matrices that we use:
CSC - Compressed Sparse Column. For efficient arithmetic, 
fast column slicing.
CSR - Compressed Sparse Row. For fast row slicing, faster 
matrix vector products
We will use the CSR matrix in this tutorial.
We can create CSR matrix by passing an arrray into function scipy.sparse.csr_matrix().
Create a CSR matrix from an array:
The example above returns:

  (0, 5)	1
  (0, 6)	1
  (0, 8)	2


From the result we can see that there are 3 items with value.
The 1. item is in row 0 position 
5 and has the value 
1.
The 2. item is in row 0 position 
6 and has the value 
1.
The 3. item is in row 0 position 
8 and has the value 
2.
Viewing stored data (not the zero items) with the data property:
Counting nonzeros with the count_nonzero() method:
Removing zero-entries from the matrix with the eliminate_zeros() method:
Eliminating duplicate entries with the sum_duplicates() method:
Eliminating duplicates by adding them:
Converting from csr to csc with the tocsc() method:
Note: Apart from the mentioned sparse specific operations, sparse matrices support all of the operations that normal matrices support e.g. reshaping, summing, arithemetic, broadcasting etc.
Insert the missing method to print the number of values in the array that are NOT zeros:
import numpy as np
from scipy.sparse import csr_matrix

arr = np.array([[0, 0, 0], [0, 0, 1], [1, 0, 2]])

print(csr_matrix(arr).())

Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
Assign Function to a Variable in Python - GeeksforGeeks

17 May, 2021
In this article, we are going to see how to assign a function to a variable in Python. In Python, we can assign a function to a variable. And using that variable we can call the function as many as times we want. Thereby, increasing code reusability. 
Implementation
Simply assign a function to the desired variable but without () i.e. just with the name of the function. If the variable is assigned with function along with the brackets (), None will be returned.
Syntax:
def func():
{
..
}

var=func

var()
var()
Example:
Python3
def a():  print("GFG")   # assigning function to a variablevar=a # calling the variablevar()
Output: 
GFG
The following programs will help you understand better:
Example 1: 
Python3
# defined functionx = 123 def sum():    x = 98    print(x)    print(globals()['x'])  # drivercodeprint(x) # assigning functionz = sum # invoke functionz()z()
Output:
123
98
123
98
123
Example 2: parameterized function
Python3
# function defineddef even_num(a):    if a % 2 == 0:        print("even number")    else:        print("odd number")  # drivercode# assigning functionz = even_num # invoke function with argumentz(67)z(10)z(7)
Output:
odd number
even number
odd number
Example 3:
Python3
# function defineddef multiply_num(a):    b = 40    r = a*b    return r  # drivercode# assigning functionz = multiply_num # invoke functionprint(z(6))print(z(10))print(z(100))
Output:
240
400
4000
anikaseth98
Python function-programs
Python-Functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Reading and Writing to text files in Python
sum() function in Python
Create a Pandas DataFrame from Lists
Adding base n numbers

In this problem, two numbers are given. The base of those numbers is n. We have to find the result of those number after addition in base n also.
At first, the numbers are converted into decimal numbers. From the decimal values, we can simply add them. Finally, the numbers are converted to base n number again.
The n base numbers are given as a string, because for those numbers, which have base greater than 9, it may contain some alphabets to represent numbers, like hexadecimal numbers, there are 6 letters (A-F).
Input: 
The base of a number system: 16
First number 2C
Second number 5F
Output:
The result of addition is: 8B
baseNtoDec(number, base)
Input − The number string of base N, the value of base N.
Output − The Decimal equivalent of the number in base N.
Begin
   len := length of number
   power := 1
   num := 0

   for i := len -1 down to 0, do
      if number[i] >= base, then
         return invalid number
      num := num + number[i] * power
      power := power * base
   done

   return num
End
decToBaseN(dec, base)
Input: The decimal number, the base N to convert a decimal number to that base.
Output: The number string of base N.
Begin
   while dec > 0, do
      res := concatenate (dec mod base) with res
      dec := dec / base
   done

   reverse the result
   return res
End
addBaseN(num1, num2, base)
Input: Two numbers in base N, the value of base N.
Output: The number after addition in base N.
Begin
   dec1 := baseNtoDec(num1, base)
   dec2 := baseNtoDec(num2, base)
   sum := decToBaseN(dec1 + dec2, base)
   return sum
End
#include<iostream>
#include<algorithm>
using namespace std;

int getVal(char c) {
   if(c >= '0' && c<='9')
      return int(c-'0');    //decimal value of given number
   else
      return int(c-'A'+10);    //for Alphanumeric numbers
}

char revVal(int n) {
   if(n >= 0 && n <=9)
      return char(n+'0');    //character value of given number
   else
      return char(n+'A'-10);    //for Alphanumeric numbers, get alphabet from decimal
}

int baseNtoDec(string number, int base) {
   int len = number.size();
   int power = 1;
   int num = 0;

   for(int i = len-1; i>= 0; i--) {    //from last digit to first digit
      if(getVal(number[i]) >= base)
         return INT_MIN;    //when a digit is >= base, return -ve infinity as error
      num += getVal(number[i])*power;
      power = power*base;
   }
   return num;
}

string decToBaseN(int dec, int base) {
   string res = "";    //empty string
   while(dec > 0) {
      res += revVal(dec%base);
      dec /= base;
   }

   reverse(res.begin(), res.end());    //reverse the string to get final answer
   return res;
}

int main() {
   int base;
   string num1, num2, sum;
   cout << "Enter Base: "; cin >> base;
   cout << "Enter first number in base "<<base<<": ";cin >> num1;
   cout << "Enter second number in base "<<base<<": ";cin >> num2;
   sum = decToBaseN((baseNtoDec(num1, base) + baseNtoDec(num2, base)), base);
   cout << "The result of addition is: " << sum;
}
Enter Base: 16
Enter first number in base 16: 2C
Enter second number in base 16: 5F
The result of addition is: 8B
GATE | GATE-CS-2007 | Question 56 - GeeksforGeeks

28 Jun, 2021
A virtual memory system uses First In First Out (FIFO) page replacement policy and allocates a fixed number of frames to a process. Consider the following statements:

P: Increasing the number of page frames allocated to a 
   process sometimes increases the page fault rate.
Q: Some programs do not exhibit locality of reference. 
Which one of the following is TRUE?(A) Both P and Q are true, and Q is the reason for P(B) Both P and Q are true, but Q is not the reason for P.(C) P is false, but Q is true(D) Both P and Q are falseAnswer: (B)Explanation:
First In First Out Page Replacement Algorithms: This is the simplest page replacement algorithm. In this algorithm, operating system keeps track of all pages in the memory in a queue, oldest page is in the front of the queue. When a page needs to be replaced page in the front of the queue is selected for removal.
FIFO Page replacement algorithms suffers from Belady’s anomaly :
Belady’s anomaly states that it is possible to have more page faults when increasing the number of page frames.
Solution:
Statement P: Increasing the number of page frames allocated to a process sometimes increases the page fault rate.
Correct, as FIFO page replacement algorithm suffers from belady’s anomaly which states above statement.
Statement Q: Some programs do not exhibit locality of reference. Correct, Locality often occurs because code contains loops that tend to reference arrays or other data structures by indices. So we can write a program does not contain loop and do not exhibit locality of reference.
So, both statement P and Q are correct but Q is not the reason for P as Belady’s Anomaly occurs for some specific patterns of page references.
See Question 1 of https://www.geeksforgeeks.org/operating-systems-set-13/
Reference :https://www.geeksforgeeks.org/page-replacement-algorithms-in-operating-systems/
This solution is contributed by Nitika BansalQuiz of this Question
GATE-CS-2007
GATE-GATE-CS-2007
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-CS-2014-(Set-3) | Question 38
GATE | GATE CS 2018 | Question 37
GATE | GATE-IT-2004 | Question 83
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2016 (Set 1) | Question 65
GATE | GATE-CS-2016 (Set 1) | Question 63
GATE | GATE-IT-2004 | Question 12
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2007 | Question 17
GATE | GATE CS 2010 | Question 33
Place a specific value for NULL values in a MySQL column

Use IFNULL() to find and place a specific value for NULL values. Let us first create a table −
mysql> create table DemoTable1878
   (
   FirstName varchar(20)
   );
Query OK, 0 rows affected (0.00 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1878 values('Chris');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1878 values(NULL);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1878 values('David');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1878 values(NULL);
Query OK, 1 row affected (0.00 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1878;
This will produce the following output −
+-----------+
| FirstName |
+-----------+
| Chris     |
| NULL      |
| David     |
| NULL      |
+-----------+
4 rows in set (0.00 sec)
Here is the query to work with IFNULL() −
mysql> select ifnull(FirstName,'Robert') from DemoTable1878;
This will produce the following output −
+----------------------------+
| ifnull(FirstName,'Robert') |
+----------------------------+
| Chris                      |
| Robert                     |
| David                      |
| Robert                     |
+----------------------------+
4 rows in set (0.00 sec)
Knight Probability in Chessboard in C++

Suppose we have one NxN chessboard, a knight starts at the r-th row and c-th column and attempts to make exactly K moves. Here the rows and columns are 0 indexed, so the top-left square is (0, 0), and the bottom-right square is (N-1, N-1).
A knight can move in 8 different cells from a cell, that can be shown in this diagram −
Each time the knight is to move, it chooses one of eight possible moves randomly. The knight continues moving until it has made exactly K moves or has moved off the chessboard. We have to find the probability that the knight remains on the board after it has stopped moving.
So if the input is like 3, 2, 0, 0, then the output will be 0.0625. This is because there are two moves (to (1,2), (2,1)) that will keep the knight on the board. Now from each of those positions, there are also two moves that will keep the knight on the board. So here the total probability the knight stays on the board is 0.0625.
To solve this, we will follow these steps −
Define one direction array dir, this is like [[-2,-1], [-2, 1],[2,-1], [2, 1], [1,2], [1,-2], [-1,2], [-1,-2]]
Define recursive method solve(), this will take x, y, n, k, and 3d array dp
if x >= n or y >= n or x < 0 or y < 0, then return 0
if k is 0, then return 1
if dp[k,x,y] is not -1, then return dp[k,x,y]
dp[k, x, y] := 0
for i in range 0 to 7dp[k,x,y] := solve(x+dir[i,0], y + dir[i, 1], n, k – 1, dp)
dp[k,x,y] := solve(x+dir[i,0], y + dir[i, 1], n, k – 1, dp)
return dp[k,x,y]
From the main method, do the following
make a 3d array of size (k + 1) x N x N. Fill this with – 1
return solve(r, c, N, k, dp) / (8^K)
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
int dir[8][2] = {{-2, -1}, {-2, 1}, {2, -1}, {2, 1}, {1, 2}, {1, -2}, {-1, 2}, {-1, -2}};
class Solution {
   public:
   double solve(int x, int y, int n, int k, vector < vector < vector < double > > >& dp){
      if(x >= n || y >= n || x < 0 || y < 0 ) return 0.0;
      if(k == 0) return 1.0;
      if(dp[k][x][y] != -1) return dp[k][x][y];
      dp[k][x][y] = 0;
      for(int i = 0; i < 8; i++){
         dp[k][x][y] += solve(x + dir[i][0], y + dir[i][1], n, k - 1, dp);
      }
      return dp[k][x][y];
   }
   double knightProbability(int N, int K, int r, int c) {
      vector < vector < vector < double > > > dp (K + 1, vector < vector < double > >(N, vector < double >(N, -1))) ;
      return solve(r, c, N, K, dp) / pow(8, K);
   }
};
main(){
   Solution ob;
   cout << (ob.knightProbability(3, 2, 0, 0));
}
3
2
0
0
0.0625
How do I create a Python namespace?

Each package, module, class, function and method function owns a "namespace" in which variable names are resolved. When a function, module or package is evaluated (that is, starts execution), a namespace is created. So if you want to create a namespace, you just need to call a function, instantiate an object, import a module or import a package. For example, we can create a class called Namespace and when you create an object of that class, you're basically creating a namespace.
In this class, you can also pass variable names to attach to the namespace, for example,
class Namespace:
    def __init__(self, **kwargs):
        self.__dict__.update(kwargs)
args = Namespace(a=1, b='c')
print args.a, args.b
This will give the output:
1 c
ISRO | ISRO CS 2015 | Question 78 - GeeksforGeeks

05 Apr, 2018
Consider the following C declaration
struct (
short s[5];
union {
float y;
long z;
}u;
}t;

Assume that the objects of the type short, float and long occupy 2 bytes, 4 bytes and 8 bytes, respectively. The memory requirement for variable t, ignoring alignment consideration, is(A) 22 bytes(B) 18 bytes(C) 14 bytes(D) 10 bytesAnswer: (B)Explanation: Refer: GATE-CS-2000 | Question 17Quiz of this Question
ISRO
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
ISRO | ISRO CS 2013 | Question 54
ISRO | ISRO CS 2015 | Question 51
ISRO | ISRO CS 2008 | Question 50
ISRO | ISRO CS 2009 | Question 30
ISRO | ISRO CS 2011 | Question 22
ISRO | ISRO CS 2014 | Question 48
ISRO | ISRO CS 2007 | Question 78
ISRO | ISRO CS 2014 | Question 34
ISRO | ISRO CS 2013 | Question 2
ISRO | ISRO CS 2013 | Question 7
GATE | GATE-CS-2000 | Question 49 - GeeksforGeeks

28 Jun, 2021
Given relations r(w, x) and s(y, z), the result of
SELECT DISTINCT w, x
       FROM r, s 
is guaranteed to be same as r, provided
(A) r has no duplicates and s is non-empty(B) r and s have no duplicates(C) s has no duplicates and r is non-empty(D) r and s have the same number of tuplesAnswer: (A)Explanation: See question 3 of https://www.geeksforgeeks.org/database-management-system-set-1/Quiz of this Question
GATE-CS-2000
GATE-GATE-CS-2000
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-CS-2014-(Set-3) | Question 38
GATE | GATE-IT-2004 | Question 83
GATE | GATE CS 2018 | Question 37
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2016 (Set 1) | Question 65
GATE | GATE-CS-2016 (Set 1) | Question 63
GATE | GATE-CS-2007 | Question 17
GATE | GATE-IT-2004 | Question 12
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2007 | Question 64
Insert sequential number in MySQL?

You can insert sequential number in MySQL using session variable. The syntax is as follows −
SELECT @anyVariableName − = anyIntegerValue;
UPDATE yourTableName SET yourColumnName = @anyVariableName − = @anyVariableName+IncrementStep;
To understand the above syntax, let us create a table. The query to create a table is as follows −
mysql> create table SequentialNumberDemo
   -> (
   -> SequentialNumber int not null
   -> );
Query OK, 0 rows affected (0.84 sec)
Insert records in the table using insert command. The query is as follows −
mysql> insert into SequentialNumberDemo values(100);
Query OK, 1 row affected (0.11 sec)

mysql> insert into SequentialNumberDemo values(10);
Query OK, 1 row affected (0.22 sec)

mysql> insert into SequentialNumberDemo values(9);
Query OK, 1 row affected (0.15 sec)

mysql> insert into SequentialNumberDemo values(60);
Query OK, 1 row affected (0.11 sec)

mysql> insert into SequentialNumberDemo values(50);
Query OK, 1 row affected (0.14 sec)

mysql> insert into SequentialNumberDemo values(40);
Query OK, 1 row affected (0.13 sec)
Display all records from the table using select statement. The query is as follows −
mysql> select *from SequentialNumberDemo;
The following is the output −
+------------------+
| SequentialNumber |
+------------------+
|              100 |
|               10 |
|                9 |
|               60 |
|               50 |
|               40 |
+------------------+
6 rows in set (0.00 sec)
Look at the above output, the number is not in a sequential order. Here is the query to get the sequential number beginning from 1. At first, set the sequence −
mysql> select @sequence: = 0;
The output −
+---------------+
| @sequence:= 0 |
+---------------+
|             0 |
+---------------+
1 row in set (0.03 sec)
Now, the query to update and begin the sequence from 1 −
mysql> update SequentialNumberDemo set SequentialNumber = @sequence − = @sequence+1;
Query OK, 6 rows affected (0.15 sec)
Rows matched − 6 Changed − 6 Warnings − 0
Check the table records once again. The query is as follows −
mysql> select *from SequentialNumberDemo;
The following is the output −
+------------------+
| SequentialNumber |
+------------------+
| 1                |
| 2                |
| 3                |
| 4                |
| 5                |
| 6                |
+------------------+
6 rows in set (0.00 sec)
Python | Numpy.expand_dims() method

17 Sep, 2019
With the help of Numpy.expand_dims() method, we can get the expanded dimensions of an array by using Numpy.expand_dims() method.
Syntax : Numpy.expand_dims()
Return : Return the expanded array.
Example #1 :In this example we can see that using Numpy.expand_dims() method, we are able to get the expanded array using this method.
# import numpyimport numpy as np  # using Numpy.expand_dims() methodgfg = np.array([1, 2])print(gfg.shape)  gfg = np.expand_dims(gfg, axis = 0)print(gfg.shape)
Output :
(2, )(1, 2)
Example #2 :
# import numpyimport numpy as np  # using Numpy.expand_dims() methodgfg = np.array([[1, 2], [7, 8]])print(gfg.shape)  gfg = np.expand_dims(gfg, axis = 0)print(gfg.shape)
Output :
(2, 2)(1, 2, 2)
Python numpy-Basics
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
Difference between Register Mode and Register Indirect Mode

04 Jul, 2022
Prerequisite – Addressing Modes 
1. Register Mode: In register addressing mode, the operand is placed in one of the 8-bit or 16-bit general-purpose registers. The data is in the register that is specified by the instruction.
Example:
MOV R1, R2 
Instruction has register R2 and R2 has operand. 
2. Register Indirect ode: In register indirect addressing mode, the address of the operand is placed in any one of the registers. The instruction specifies a register that contains the address of the operand. 
Example:
ADD R1, (R2) 
Instruction has register R2 and R2 has the memory address of operand. 
Difference between Register Mode and Register Indirect Mode are as follows:time-consumingregisteredregistered
annieahujaweb2020
Computer Organization & Architecture
Difference Between
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Direct Access Media (DMA) Controller in Computer Architecture
Control Characters
Architecture of 8085 microprocessor
Pin diagram of 8086 microprocessor
I2C Communication Protocol
Class method vs Static method in Python
Difference between BFS and DFS
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Differences between JDK, JRE and JVM
Write a program to calculate the least common multiple of two numbers JavaScript

We are required to write a function that accepts two numbers and returns their least common
multiple.
The least common multiple of two numbers a and b is the smallest positive integer that is
divisible by both a and b.
For example − The LCM of 6 and 8 is 24 because 24 is the smallest positive integer that is
divided by both 6 and 8.
One of the many ways of calculating LCM of two numbers a and b is by dividing the product of a
and b by the greatest integer (also known as greatest common divisor or GCD) that divides both
a and b.
In case of 6 and 8, their product is 48 and the greatest integer that divides them both is 2 so
their LCM is −
(6*8)/2 = 24
Having these things clear, now let’s move to the coding part −
const lcm = (a, b) => {
   let min = Math.min(a, b);
   while(min >= 2){
      if(a % min === 0 && b % min === 0){
         return (a*b)/min;
      };
      min--;
   };
   return (a*b);
};
console.log(lcm(6, 8));
console.log(lcm(16, 18));
console.log(lcm(0, 8));
console.log(lcm(11, 28));
console.log(lcm(18, 34));
Since the greatest integer that exactly divides both the numbers will still be smaller or equal to
the smaller of the two numbers, we are calculating LCM for, we run a decrementing loop from
the smaller number all the way down to 2.
If in our iterations we find any number that divides both the numbers we can guarantee that it’s
the largest number that divides them both because we are in a decrementing loop, so we return
right there with the LCM.
If we iterate through the complete it means that we didn’t found any such number and 1 is the
only number that divides them both (in other terms the numbers are co-prime), so we simply
return their product.
The output in the console will be −
24
144
0
308
306
Lodash - GeeksforGeeks

10 Dec, 2021
Lodash is a JavaScript library that works on the top of underscore.js. It helps in working with arrays, strings, objects, numbers, etc. It provides us with various inbuilt functions and uses a functional programming approach which that coding in JavaScript easier to understand because instead of writing repetitive functions, tasks can be accomplished with a single line of code. It also makes it easier to work with objects in JavaScript if they require a lot of manipulation to be done upon them.
It provides various inbuilt functions for collections, arrays, to manipulate objects, and other utility methods that we can use directly instead of writing them from scratch. It makes it easier to iterate over the arrays, strings as well as objects. Its modular methods enable the creation of composite functions easier.
Installation: It can be used directly using the CDN link or can be installed using npm or yarn.
Method 1: We can directly use the file in the browser. Go to the official documentation and copy the lodash.min.js file CDN link and paste this link inside the head section.
<script type=”text/JavaScript” src = “https://cdn.jsdelivr.net/npm/lodash@4.17.20/lodash.min.js”></script>
Method 2: We can install it with npm. Make sure that you have Node.js and npm installed.
npm install lodash
If you are using yarn then you can use the following command:
yarn install lodash
Now in order to use the Lodash library, you need to require it in the code file.
const _ = require("lodash"); 
Now let’s understand how to use Lodash with the help of the code example.
Example: In this example, we will simply create an empty string using the lodash _.stubString() method.
index.js
Output:
"" Empty String
Learn more about Lodash.js:
Introduction
Array Complete Reference
Collection Complete Reference
Function Complete Reference
Lang Complete Reference
Math Complete Reference
Object Complete Reference
Seq Complete Reference–
String Complete Reference
Util Complete Reference
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ...
Learn C++ Programming Step by Step - A 20 Day Curriculum!
Must Do Coding Questions for Product Based Companies
Types of Distributed System
What is Handle Pruning?
How to Install MySQL on Linux?
Floyd’s Cycle Finding Algorithm
How to count rows with SELECT COUNT(*) with SQLAlchemy?
How to Add External JAR File to an IntelliJ IDEA Project?
Difference Between NPDA and DPDA
How do I automatically download files from a pop up dialog using selenium-python?

We can automatically download files from a pop up dialog using Selenium webdriver with Python. After clicking the download link, a dialog box appears for the user to select various options to Save the file.
We have to programmatically configure the path where the download has to be performed such that every time the Firefox browser is launched, the Firefox profile is proper to perform the download at the desired location.
Open the address bar of Firefox, and enter about:config and press Enter . All the browser preferences shall be available with Edit and Toggle buttons. We shall use the Firefox Options class to set the download preferences for the browser.
from selenium import webdriver
from selenium.webdriver.firefox.options import Options
#object of Options class
op = Options()
#save file to path defined for recent download with value 2
op.set_preference("browser.download.folderList",2)
#disable display Download Manager window with false value
op.set_preference("browser.download.manager.showWhenStarting", False)
#download location
op.set_preference
("browser.download.dir","C:\\Users\\ghs6kor\\Documents\\Download")
#MIME set to save file to disk without asking file type to used to open file
op.set_preference
("browser.helperApps.neverAsk.saveToDisk",
"application/octet-stream,application/vnd.ms-excel")
#set geckodriver.exe path
driver = webdriver.Firefox(executable_path="C:\\geckodriver.exe",
firefox_options=op)
driver.maximize_window()
#launch URL
driver.get("https://the-internet.herokuapp.com/download");
#click download link
l = driver.find_element_by_link_text("xls-sample1.xls")
l.click()
The file downloaded at the declared location.
Python Bokeh – Making Interactive Legends

28 Jul, 2020
Bokeh is a Python interactive data visualization. It renders its plots using HTML and JavaScript. It targets modern web browsers for presentation providing elegant, concise construction of novel graphics with high-performance interactivity.
The legend of a graph reflects the data displayed in the graph’s Y-axis. In Bokeh, the legends correspond to glyphs. There are two ways to make legends interactive: 
Hiding
Muting
A Glyph can be hidden from the legend by setting the legend click_policy property to “hide”.
Example :
Python3
# importing the modules from bokeh.plotting import figure, output_file, show   # file to save the model output_file("gfg.html")          # instantiating the figure object graph = figure(title = "Bokeh Hiding Glyphs")   # plotting the graphgraph.vbar(x = 1,  top = 5,           width = 1, color = "violet",           legend_label = "Violet Bar")graph.vbar(x = 2,  top = 5,           width = 1, color = "green",           legend_label = "Green Bar")graph.vbar(x = 3,  top = 5,           width = 1, color = "yellow",           legend_label = "Yellow Bar")graph.vbar(x = 4,  top = 5,           width = 1, color = "red",           legend_label = "Red Bar")  # enable hiding of the glyphsgraph.legend.click_policy = "hide"  # displaying the model show(graph) 
Output : 
Hiding the glyph makes it vanish completely, on the other hand, muting the glyph just de-emphasizes the glyph based on the parameters. A Glyph can be muted from the legend by setting the legend click_policy property to “mute”. 
Python3
# importing the modules from bokeh.plotting import figure, output_file, show   # file to save the model output_file("gfg.html")          # instantiating the figure object graph = figure(title = "Bokeh Hiding Glyphs")   # plotting the graphgraph.vbar(x = 1,  top = 5,           width = 1, color = "violet",           legend_label = "Violet Bar",           muted_alpha=0.2)graph.vbar(x = 2,  top = 5,           width = 1, color = "green",           legend_label = "Green Bar",           muted_alpha=0.2)graph.vbar(x = 3,  top = 5,           width = 1, color = "yellow",           legend_label = "Yellow Bar",           muted_alpha=0.2)graph.vbar(x = 4,  top = 5,           width = 1, color = "red",           legend_label = "Red Bar",           muted_alpha=0.2)  # enable hiding of the glyphsgraph.legend.click_policy = "mute"  # displaying the model show(graph) 
Output :  
Python-Bokeh
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Different ways to create Pandas Dataframe
Taking input in Python
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
C program to create Indian National Flag using Graphics - GeeksforGeeks

01 Apr, 2021
In this article, we will discuss how to draw the Indian National Flag using Graphics.
Approach:
Draw a rectangle using the function rectangle().
Equally, divide the above rectangle into three parts by creating the line using the function line().
Draw double lines on each other i.e., draw 4 lines and among them, 2 lines will act as a divider between Red (Light red as there is no direct saffron color present in the graphics library) & White, and the other 2 lines will divide White and Green color.
The Ashoka Chakra will be made using the function circle().
To finish, all the spaces will be filled using the functions setfillstyle() and floodfill().
Below is the implementation of the above approach:
C
// C program for the above approach  #include <conio.h>#include <graphics.h>#include <stdio.h>  // Driver Codevoid main(){    // Initialize of gdriver with    // DETECT macros    initgraph(&gd, &gm, "C:\\turboc3\\bgi");      // Creating the base rectangle    line(250, 100, 250, 600);    line(250, 100, 250, 600);      // Fil the White Color    setfillstyle(SOLID_FILL, WHITE);      // Create and fill the top strip    rectangle(225, 600, 275, 610);    rectangle(200, 610, 300, 620);      floodfill(227, 608, 15);    floodfill(202, 618, 15);      // Fill the Light Red Color    setfillstyle(SOLID_FILL, LIGHTRED);      // Create and fill the ashoka    // chakra with Blue    rectangle(250, 100, 650, 280);    line(250, 160, 650, 160);    floodfill(252, 158, 15);      // Fill the Blue Color    setfillstyle(SOLID_FILL, BLUE);      // Create and fill the left    // part of the middle strip      // Create a Circle    circle(450, 190, 30);    floodfill(452, 188, 15);      // Fill the White Color    setfillstyle(SOLID_FILL, WHITE);      // Create and fill the right    // part of the middle strip    line(250, 160, 480, 160);    line(250, 220, 480, 220);    floodfill(252, 162, 15);      // Fill the White Color    setfillstyle(SOLID_FILL, WHITE);      // Create and fill the bottom    // strip    line(480, 160, 650, 160);    line(480, 220, 650, 220);    floodfill(482, 162, 15);      // Fill the Green Color    setfillstyle(SOLID_FILL, GREEN);      line(250, 220, 650, 220);    floodfill(252, 278, 15);      // Close the initialized gdriver    closegraph();}
Output:
c-graphics
computer-graphics
C Language
C Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
TCP Server-Client implementation in C
'this' pointer in C++
Exception Handling in C++
Multithreading in C
UDP Server-Client implementation in C
Strings in C
UDP Server-Client implementation in C
Arrow operator -> in C/C++ with Examples
C Program to read contents of Whole File
Header files in C/C++ and its uses
Cassandra - CQL User Defined Datatypes

CQL provides the facility of creating and using user-defined data types. You can create a data type to handle multiple fields. This chapter explains how to create, alter, and delete a user-defined data type.
The command CREATE TYPE is used to create a user-defined data type. Its syntax is as follows −
CREATE TYPE <keyspace name>. <data typename>
( variable1, variable2).

Given below is an example for creating a user-defined data type. In this example, we are creating a card_details data type containing the following details.
cqlsh:tutorialspoint> CREATE TYPE card_details (
   ... num int,
   ... pin int,
   ... name text,
   ... cvv int,
   ... phone set<int>
... );

Note − The name used for user-defined data type should not coincide with reserved type names.
Use the DESCRIBE command to verify whether the type created has been created or not.
CREATE TYPE tutorialspoint.card_details (
   num int,
   pin int,
   name text,
   cvv int,
   phone set<int>
   );

ALTER TYPE − command is used to alter an existing data type. Using ALTER, you can add a new field or rename an existing field.
Use the following syntax to add a new field to an existing user-defined data type.
ALTER TYPE typename
ADD field_name field_type; 

The following code adds a new field to the Card_details data type. Here we are adding a new field called email.
cqlsh:tutorialspoint> ALTER TYPE card_details ADD email text;

Use the DESCRIBE command to verify whether the new field is added or not.
cqlsh:tutorialspoint> describe type card_details;
CREATE TYPE tutorialspoint.card_details (
   num int,
   pin int,
   name text,
   cvv int,
   phone set<int>,
   );

Use the following syntax to rename an existing user-defined data type.
ALTER TYPE typename
RENAME existing_name TO new_name;

The following code changes the name of the field in a type. Here we are renaming the field email to mail.
cqlsh:tutorialspoint> ALTER TYPE card_details RENAME email TO mail;

Use the DESCRIBE command to verify whether the type name changed or not.
cqlsh:tutorialspoint> describe type card_details;
CREATE TYPE tutorialspoint.card_details (
   num int,
   pin int,
   name text,
   cvv int,
   phone set<int>,
   mail text
   );

DROP TYPE is the command used to delete a user-defined data type. Given below is an example to delete a user-defined data type.
Before deleting, verify the list of all user-defined data types using DESCRIBE_TYPES command as shown below.
cqlsh:tutorialspoint> DESCRIBE TYPES;
card_details card

From the two types, delete the type named card as shown below.
cqlsh:tutorialspoint> drop type card;

Use the DESCRIBE command to verify whether the data type dropped or not.
cqlsh:tutorialspoint> describe types;

card_details


    27 Lectures 
     2 hours 

 Navdeep Kaur

    34 Lectures 
     1.5 hours 

 Bigdata Engineer
 Print
 Add Notes
 Bookmark this page
How to catch NotImplementedError Exception in Python?

User-defined base classes can raise NotImplementedError to indicate that a method or behavior needs to be defined by a subclass, simulating an interface. This exception is derived from RuntimeError. In user defined base classes, abstract methods should raise this exception when they require derived classes to override the method.
import sys
try:
   class Super(object):
        @property
        def example(self):
            raise NotImplementedError("Subclasses should implement this!")
   s = Super()
   print s.example
except Exception as e:
    print e
    print sys.exc_type
Subclasses should implement this!
<type 'exceptions.NotImplementedError'>
Creating a Node.js server

The mostly used core modules of Node.js are −
http − used to launch a simple server, send requests
http − used to launch a simple server, send requests
https − used to launch a ssl secured http server
https − used to launch a ssl secured http server
path − used to handle path based on operating system
path − used to handle path based on operating system
fs − It’s a file system handling module
fs − It’s a file system handling module
os − its used for os related operations
os − its used for os related operations
Lets build a simple http server using Node.js −
Create a javascript file App.js (name it as you like) in an editor like visual studio code .
App.js
const http = require(‘http’);
function reqListener(req, res){
   console.log(‘Hello’);
}
const server = http.createServer(reqListener);
server.listen(3000);
Explaination
We used const keyword instead of var or let to import a module because this variable reference will not changed in file.
Require is a reserved keyword in Node, it helps to import pre-defined core modules and used defined modules.
Importing pre-defined modules like http does not require to add ./ in front of them. But if requires to import a custom used defined module then it is done as shown below −
const user = require(‘./User’);
Adding .js extenstion to file in require function is not mandatory for javascript file. But any other file formats will require to add an extension in require function.
The imported module http has a createServer method which takes request listener as an parameter. This argument function will be executed on every new http request to Node server.
We can use anonymous function or a next-gen javascript arrow function as well in createServer method −
Anonymous function in createServer
const http = require(‘http’);
const server = http.createServer(function(){
   console.log(‘Hello’);
});
server.listen(3000);
Using next-gen Javascript
const http = require(‘http’);
const server = http.createServer((req, res)=>{
   console.log(‘Hello’);
});
server.listen(3000);
createServer method of http module returns us a server. We can use a listen method on server to run it on a given port. listen method takes port number as an argument.
Executing App.js file
Open terminal inside folder where App.js is located and run command − node App.js
Running this command will keep a event loop running listening for any http request on port 3000.
Checking console log messages on terminal
Now, open a browser and navigate to localhost:3000, check in terminal console for a log statement. On console of terminal we will see Hello message printed.
As of now, we have not returned any response back to browser, so we wont see any output on it. We will see how to return and display response messages on browser in next articles.
How to use JavaScript to redirect a webpage after 5 seconds?

To redirect a webpage after 5 seconds, use the setInterval() method to set the time interval. Add the webpage in window.location.href object.
You can try to run the following code to learn how to redirect a webpage after 5 seconds −
Live Demo
<!DOCTYPE html>
<html>
   <body>
      <script>
         setTimeout(function(){
            window.location.href = 'https://www.tutorialspoint.com/javascript/';
         }, 5000);
      </script>
      <p>Web page redirects after 5 seconds.</p>
   </body>
</html>
Tryit Editor v3.7 - Show Java

public class WriteToFile {  
  public static void main(String[] args) {  
    try {  
      FileWriter myWriter = new FileWriter("filename.txt");
      myWriter.write("Files in Java might be tricky, but it is fun enough!");
      myWriter.close();
      System.out.println("Successfully wrote to the file.");
    } catch (IOException e) {
      System.out.println("An error occurred.");
C program to draw the Olympics Logo using graphics - GeeksforGeeks

14 Apr, 2021
In this article, we will discuss how to design the Olympics Logo using Graphics.
Draw five circles according to positions in the logo using the function circle().
To achieve the outline effect, draw 5 smaller circles over it.
There is a black circle as well in the logo and to prevent it from blending in, change the background color.
Color all the circles and the background to their respective colors using functions setfillstyle() and floodfill().
Below is the implementation of the above approach:
C
// C program for the above approach  #include <conio.h>#include <graphics.h>#include <stdio.h>  // Driver Codevoid main(){    int gd = DETECT, gm;      // Initialize of gdriver    initgraph(&gd, &gm, "C:\\turboc3\\bgi");      // Create Background color as Grey    setfillstyle(SOLID_FILL, DARKGRAY);    floodfill(50, 50, 15);      // Create two circles in each    // another & color Blue    setfillstyle(SOLID_FILL, BLUE);    circle(300, 300, 100);    circle(300, 300, 90);    floodfill(202, 300, 15);      // Create two circles in each    // another & color Yellow    setfillstyle(SOLID_FILL, YELLOW);    circle(400, 400, 100);    circle(400, 400, 90);    floodfill(322, 350, 15);    floodfill(302, 400, 15);      // Create two circles in each    // another & color Black    setfillstyle(SOLID_FILL, BLACK);    circle(520, 300, 100);    circle(520, 300, 90);    floodfill(442, 350, 15);    floodfill(422, 300, 15);      // Create two circles in each    // another & color Green    setfillstyle(SOLID_FILL, GREEN);    circle(620, 400, 100);    circle(620, 400, 90);    floodfill(522, 400, 15);    floodfill(542, 350, 15);      // Create two circles in each    // another & color Red    setfillstyle(SOLID_FILL, RED);    circle(740, 300, 100);    circle(740, 300, 90);    floodfill(642, 300, 15);    floodfill(662, 350, 15);      // Hold the screen for a while    getch();      // Close the initialized gdriver    closegraph();}
Output:
c-graphics
computer-graphics
C Language
C Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Multidimensional Arrays in C / C++
Left Shift and Right Shift Operators in C/C++
Converting Strings to Numbers in C/C++
Function Pointer in C
Strings in C
Arrow operator -> in C/C++ with Examples
C Program to read contents of Whole File
Header files in C/C++ and its uses
Basics of File Handling in C
Python object() method - GeeksforGeeks

22 Sep, 2021
Python object() function returns the empty object, and the Python object takes no parameters.
In python, each variable to which we assign a value/container is treated as an object. Object in itself is a class. Let’s discuss the properties and demonstration of how this class can be utilized for day-day programming.
Syntax : object()
Parameters :  None
Returns : Object of featureless class. Acts as base for all object
Python3
# Python 3 code to demonstrate# working of object() # declaring the object of class objectobj = object() # printing its typeprint("The type of object class object is : ")print(type(obj)) # printing its attributesprint("The attributes of its class are : ")print(dir(obj))
Output: 
The type of object class object is : The attributes of its class are : [‘__class__’, ‘__delattr__’, ‘__dir__’, ‘__doc__’, ‘__eq__’, ‘__format__’, ‘__ge__’, ‘__getattribute__’, ‘__gt__’, ‘__hash__’, ‘__init__’, ‘__le__’, ‘__lt__’, ‘__ne__’, ‘__new__’, ‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’, ‘__setattr__’, ‘__sizeof__’, ‘__str__’, ‘__subclasshook__’] 
Objects of object class cannot add new attributes to it.
These objects are uniquely made and do not equate to one other, i.e don’t return true once compared.
the object acts as a base class for all the custom objects that we make.
Python3
# Python 3 code to demonstrate# properties of object() # declaring the objects of class objectobj1 = object()obj2 = object() # checking for object equalityprint("Is obj1 equal to obj2 : " + str(obj1 == obj2)) # trying to add attribute to objectobj1.name = "GeeksforGeeks"
Output: 
Is obj1 equal to obj2 : False
Exception:
Traceback (most recent call last):
  File "/home/46b67ee266145958c7cc22d9ee0ae759.py", line 12, in 
    obj1.name = "GeeksforGeeks"
AttributeError: 'object' object has no attribute 'name'
kumar_satyam
Python-Built-in-functions
python-object
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists