code-rag-bench/online-tutorials huggingface dataset:
timetuple() Function Of Datetime.date Class In Python

23 Aug, 2021
timetuple() method returns a time.struct time object which is a named tuple. A named tuple object has attributes that may be accessed by an index or a name. The struct time object has properties for both the date and time fields, as well as a flag that specifies whether or not Daylight Saving Time is in effect. The year, month, and day fields of the named tuple provided by the timetuple() method will be set according to the date object, but the hour, minutes, and seconds values will be set to zero. The DST flag on the returned object will be set to -1. The characteristics of the time.struct time object may be accessed by index or attribute name. The struct time object contains attributes for expressing both date and time fields, which are kept in tuples :
Example 1: timetuple() with current date.
Here we are going demonstrate timetuple() of the current date. The current date is allocated to the DateTime object, and the timetuple() function is used to retrieve the properties of the object in tuples, which are then shown. A loop may also be used to display the characteristics of object.
Python3
import datetime  # creating current date objectcurrentDate = datetime.datetime.today()    # datetime instance's attributes# are returned as a tuple.currentDateTimeTuple = currentDate.timetuple()    # showing the object's tuplesprint(currentDateTimeTuple)print()print("Using a for loop, output the tuple values :")  for value in currentDateTimeTuple:    print(value)
Output:
time.struct_time(tm_year=2021, tm_mon=8, tm_mday=2, tm_hour=18, tm_min=32, tm_sec=56, tm_wday=0, tm_yday=214, tm_isdst=-1)
Using a for loop, output the tuple values :
2021
8
2
18
32
56
0
214
-1
Example 2: timetuple() with a specific date.
Consider another scenario in which we utilize a Christmas date. The DateTime object Christmas is created, and then the index of the tuple displays each property of that object.
Python3
import datetime  # creating xmas date objectxmas = datetime.datetime(2021, 12, 25)    # datetime instance's attributes# are returned as a tuple.xmasTimeTuple = xmas.timetuple()    # showing the object's tuplesprint(xmasTimeTuple)
Output:
time.struct_time(tm_year=2021, tm_mon=12, tm_mday=25, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=5, tm_yday=359, tm_isdst=-1)
Picked
Python-datetime
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Create a directory in Python
interview-series-juspay | Practice | GeeksforGeeks    

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested 
                                    against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code.
                                    On submission, your code is tested against multiple test cases consisting of all
                                        possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as
                                        the final solution code.
You can view the solutions submitted by other users from the submission tab.
Make sure you are not using ad-blockers.
Disable browser extensions.
We recommend using latest version of your browser for best experience.
Avoid using static/global variables in coding problems as your code is tested 
                                against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases in coding problems does not guarantee the 
                                correctness of code. On submission, your code is tested against multiple test cases
                                    consisting of all possible corner cases and stress constraints.
Some of the functionality of this site might not work properly if you have enabled AdBlocker or a similar extension.

                        Contest Home
                    

                        Quiz
                    

                        Coding Problems
                    

 Time Left :


 : 

 : 

 : 





Finish
                                Test


                        Contest Home
                    

                            Quiz
                        

                            Coding Problems
                        

Finish Test

Error
Error
Reminder
Click on the menu '' button to finish the test.
* All fields are mandatory.

                    Instructions
                

                    Leaderboard
                

                    Summary
                




0
 QUIZSCORE


Coding problem score has been deducted due to plagiarism.
CODING SCORE
0
RANK
 
 
You need to submit each quiz question after selecting the
                            option(s).

                All Problems
            
 Coding Score  :
0


 Solution Accepted

 Solution Accepted


 Wrong Answer

 Wrong Answer
Submissions

Problem


  Submissions 

Expected Outcome - runs the test cases against the code of Online Judge.
My Output - runs the test cases against your code.
PHP | max( ) Function

07 Mar, 2018
The max() function of PHP is used to find the numerically maximum value in an array or the numerically maximum value of several specified values. The max() function can take an array or several numbers as an argument and return the numerically maximum value among the passed parameters. The return type is not fixed, it can be an integer value or a float value based on input.
Syntax:
max(array_values)  

or

max(value1, value2, ...)

Parameters: This function accepts two different types of arguments which are explained below:
array_values : It specifies an array containing the values.value1, value2, ... : It specifies two or more than two values to be compared.
array_values : It specifies an array containing the values.
value1, value2, ... : It specifies two or more than two values to be compared.
Return Value: The max() function returns the numerically maximum value.
Examples:
Input : max(12, 4, 62, 97, 26)
Output : 97

Input : max(array(28, 36, 87, 12))
Output : 87

Below programs illustrate the working of max() in PHP:
Program 1:
<?php  echo (max(12, 4, 62, 97, 26));  ?>
Output:
97
Program 2:
<?php  echo (max(array(28, 36, 87, 12)). "<br>");  ?>
Output:
87
Important points to note :
max() function is used to find the numerically maximum number.
max() function can be used on two or more than two values or it can be used on an array.
The value returned is of mixed data type.
Reference:http://php.net/manual/en/function.max.php
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to Upload Image into Database and Display it using PHP ?
How to check whether an array is empty using PHP?
PHP | Converting string to Date and DateTime
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 ?
Python Bin | Count total bits in a number

01 Sep, 2020
Given a positive number n, count total bit in it. 
Examples:  
Input : 13
Output : 4
Binary representation of 13 is 1101

Input  : 183
Output : 8

Input  : 4096
Output : 13



 
We have existing solution for this problem please refer Count total bits in a number link. We can solve this problem quickly in Python using bin() function. Convert number into it’s binary using bin() function and remove starting two characters ‘0b’ of output binary string because bin function appends ‘0b’ as prefix in output string. Now print length of binary string that will be the count of bits in binary representation of input number. 
Python3
# Function to count total bits in a number def countTotalBits(num):          # convert number into it's binary and     # remove first two characters 0b.     binary = bin(num)[2:]     print(len(binary)) # Driver programif __name__ == "__main__":    num = 13    countTotalBits(num)
Output:  
4



 
jk06
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Convert integer to string in Python
Integer shortValue() Method in Java

05 Dec, 2018
The Integer.shortValue() is an inbuilt method of java.lang which returns the value of this Integer in the short type .
Syntax:
public short shortValue()

Parameters: The method does not take any parameters.
Return Value: The method returns the integer value represented by this object after converting it to type short.
Below programs illustrate the Integer.shortValue() method:Program 1: For positive integers.
// Java program that demonstrates// Integer.shortValue() method  import java.lang.*;  public class Geeks {      public static void main(String[] args)    {          Integer sh_object = new Integer(763);          // It will return the value of this Integer as a short type        short sh_value = sh_object.shortValue();        System.out.println(" The Value of sh_value = " + sh_value);    }}
The Value of sh_value = 763

Program 2: For negative number.
// Java program that demonstrates// Integer.shortValue() methodimport java.lang.*;  public class Geeks {      public static void main(String[] args)    {          Integer sh_object = new Integer(-43);          // It will return the value of this Integer as a short type        short sh_value = sh_object.shortValue();        System.out.println(" The Value of sh_value = " + sh_value);    }}
The Value of sh_value = -43

Program 3: For a decimal value and string.Note: It returns an error message when a decimal value and string is passed as an argument.
// java program that demonstrates// Integer.shortValue() methodimport java.lang.*;  public class Geeks {      public static void main(String[] args)    {          // passing a decimal value        Integer sh_object = new Integer(27.51);          short sh_value = sh_object.shortValue();        System.out.println(" The Value of sh_value = " + sh_value);          // passing a string        Integer sh_object2 = new Integer("51");          short sh_value2 = sh_object2.shortValue();        System.out.println(" The Value of sh_value2 = " + sh_value2);    }}
Output:
prog.java:10: error: no suitable constructor found for Integer(double)
    Integer sh_object = new Integer(27.51);
                        ^
    constructor Integer.Integer(int) is not applicable
      (argument mismatch; possible lossy conversion from double to int)
    constructor Integer.Integer(String) is not applicable
      (argument mismatch; double cannot be converted to String)
1 error

Java-Functions
Java-Integer
Java-lang package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java
pidof Command in Linux with Examples

26 May, 2022
pidof command is used to find out the process IDs of a specific running program. It is basically an identification number that is automatically assigned to each process when it is created. Syntax:
pidof [options] program1 program2 ... programN
1. To find pid of any process
pidof bash
 Use the name of the program as input to the command and command produced bash process ID in the output. 2. To get only one pid of a program
pidof -s bash
 By default, pidof displays all pids of named command or program. So to display only one process ID of the program we have to pass “-s” option with it. 3. To get pids of scripts
pidof -x bash
 The pidof command does not display pids of shell/perl/python scripts. We use the “-x” option to find the process ids of shells running the named script called bash. 4. To limit output based on the root directory
pidof -c bash 
 If we want that pidof returns only process ids that are running with the same root directory, we use “-c” command-line option. Note: This option is ignored for non-root users, as they are unable to check the current root directory of processes they do not own. 5. To omit processes
pidof -o 87223 bash
 If we want to ignore or omit processes with that process id, we can use pidof command to this. This is useful to ignore calling shell or shell script or specific pid. Here, it says we want to find all pids of bash and omit pid #87223. So, we use the given code for that. 6. To find pid of a program and kill it
p=$(pidof chrome)
kill $p
 In this, firstly we find all PIDs of chrome server and then kill it.
rkbhola5
linux-command
Linux-system-commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
scp command in Linux with Examples
chown command in Linux with Examples
SED command in Linux | Set 2
Introduction to Linux Operating System
nohup Command in Linux with Examples
Array Basics in Shell Scripting | Set 1
mv command in Linux with examples
chmod command in Linux with examples
screen command in Linux with Examples
Inheritance in Java - GeeksQuiz

13 Oct, 2021
Java

1) Private methods are final.
2) Protected members are accessible within a package and 
   inherited classes outside the package.
3) Protected methods are final.
4) We cannot override private methods. 
Base
Derived
Derived
Base
Base
Derived
Base
Derived
Base
Grandparent's Print()
Parent's Print()
Child's Print()
// Guess the output
// filename Main.java
class Grandparent {
    public void Print() {
        System.out.println("Grandparent's Print()");
    }
}
 
class Parent extends Grandparent {
    public void Print() {
    	super.Print();  
        System.out.println("Parent's Print()");
    }
}
 
class Child extends Parent {
    public void Print() {
        super.Print();  
        System.out.println("Child's Print()");
    }
}
 
class Main {
    public static void main(String[] args) {
        Child c = new Child();
        c.Print();
    }
}

Complex number is (10.0 + 15.0i)
Complex number is SOME_GARBAGE
Complex number is Complex@8e2fb5
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Django manage.py migrate command | Python

26 Sep, 2019
According to documentation, Migrations are Django’s way of propagating changes you make to your models (adding a field, deleting a model, etc.) into your database schema. They’re designed to be mostly automatic, but you’ll need to know when to make migrations when to run them, and the common problems you might run into.
migrate is run through the following command for a Django project.
 Python manage.py migrate 
migrate executes those SQL commands in the database file. So after executing migrate all the tables of your installed apps are created in your database file.
You can confirm this by installing SQLite browser and opening db.sqlite3 you can see all the tables appears in the database file after executing migrate command.
For example, if we make a model class-
from django.db import models  class Person(models.Model):    first_name = models.CharField(max_length = 30)    last_name = models.CharField(max_length = 30)
The corresponding sql command after using makemigrations will be
CREATE TABLE myapp_person (
"id" serial NOT NULL PRIMARY KEY,
"first_name" varchar(30) NOT NULL,
"last_name" varchar(30) NOT NULL
);

and using above command, table will be created in the database when we use migrate.Migrate command is covered in next article.and now form terminal running following command will create table for this model in your database
 Python manage.py migrate
Now if we check our database, a table with name geeks_geeksmodel is created,
Django-models
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Enumerate() in Python
Different ways to create Pandas Dataframe
Read a file line by line in Python
How to Install PIP on Windows ?
Python String | replace()
Python OOPs Concepts
Python Classes and Objects
*args and **kwargs in Python
Introduction To PYTHON
JP Morgan Chase Interview Experience

12 Dec, 2018
JP Morgan visited our campus for full time hiring for quant research and MGG(Model Governance Group). I applied for the MGG role.
Test 2 sectionsQuant – 35 minutes : Problems on probability, expected values, etc. Similar to ones in 50 challenging, heard on the street and BrainstellarCoding – 2 problems — https://leetcode.com/problems/letter-combinations-of-a-phone-number/https://www.geeksforgeeks.org/find-maximum-path-sum-in-a-binary-tree/
Interview
Round 1 : He asked me to code a simple problem. Given
    1

    2 3

    4 5 6

    7 8 9 10,  and so on.
Now Given n, that is the last number(10 in this case), we need to print the complete pattern
This was followed by questions from resume, how Google Maps work(i.e. How do they provide real time traffic data), some questions on Python, like difference between list and tuple? Also some discussions on interests, family background, etc. Chill discussion
2. Round 2 : Write a program to print Fibonacci numbers and then an extended version of the same.https://www.geeksforgeeks.org/count-ways-reach-nth-stair/
Again, some problems on Python, like https://stackoverflow.com/questions/209840/convert-two-lists-into-a-dictionary-in-python
A puzzle, https://www.geeksforgeeks.org/puzzle-26-know-average-salary-without-disclosing-individual-salaries/
3. Round 3 : HR – Interests, Do you want to go for higher studies or MBA?, Why JPMC?
4. Round 4 : A puzzle : https://brainstellar.com/puzzles/202
5. Round 5 : Few HR questions, got the offer!
JP Morgan
On-Campus
Interview Experiences
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Amazon Interview Experience SDE-2 (3 Years Experienced)
Amazon Interview Experience for SDE 1
Google Interview Questions
Nagarro Interview Experience | On-Campus 2021
Interview Experience League 2022
Amazon Interview Experience for SDE-1
Tiger Analytics Interview Experience for Data Analyst (On-Campus)
Nagarro Interview Experience
Tejas Networks Interview Experience for R&D Engineer
Zoho Interview | Set 3 (Off-Campus)
Django App Model – Python manage.py makemigrations command

26 Sep, 2019
According to documentation, Migrations are Django’s way of propagating changes you make to your models (adding a field, deleting a model, etc.) into your database schema. They’re designed to be mostly automatic, but you’ll need to know when to make migrations, when to run them, and the common problems you might run into.
makemigrations are run through the following command
Python manage.py makemigrations
If the above commands says no changes detected, You can also do it for individual apps.For example if you have 10 apps named a, b, c, d, e, f, g, h, i, j. You can run makemigrations individually for these apps.
Python manage.py makemigrations a 
Python manage.py makemigrations b 
Python manage.py makemigrations c 
and so on.
makemigrations basically generates the SQL commands for preinstalled apps (which can be viewed in installed apps in settings.py) and your newly created apps’ model which you add in installed apps. It does not execute those commands in your database file. So tables are not created after makemigrations.
After applying makemigrations you can see those SQL commands with sqlmigrate which shows all the SQL commands which have been generated by makemigrations.
For example, if we make a model class-
from django.db import models  class Person(models.Model):    first_name = models.CharField(max_length = 30)    last_name = models.CharField(max_length = 30)
The corresponding sql command after using makemigrations will be
CREATE TABLE myapp_person (
"id" serial NOT NULL PRIMARY KEY,
"first_name" varchar(30) NOT NULL,
"last_name" varchar(30) NOT NULL
);

and using above command, table will be created in the database when we use migrate.
Django-models
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Program for 0-1 Knapsack Problem

23 Oct, 2019
# A naive recursive implementation of 0-1 Knapsack Problem  # Returns the maximum value that can be put in a knapsack of# capacity Wdef knapSack(W, wt, val, n):      # Base Case    if n == 0 or W == 0 :        return 0      # If weight of the nth item is more than Knapsack of capacity    # W, then this item cannot be included in the optimal solution    if (wt[n-1] > W):        return knapSack(W, wt, val, n-1)      # return the maximum of two cases:    # (1) nth item included    # (2) not included    else:        return max(val[n-1] + knapSack(W-wt[n-1], wt, val, n-1),                   knapSack(W, wt, val, n-1))  # end of function knapSack  # To test above functionval = [60, 100, 120]wt = [10, 20, 30]W = 50n = len(val)print knapSack(W, wt, val, n)  # This code is contributed by Nikhil Kumar Singh
220

# A Dynamic Programming based Python # Program for 0-1 Knapsack problem# Returns the maximum value that can # be put in a knapsack of capacity Wdef knapSack(W, wt, val, n):    K = [[0 for x in range(W + 1)] for x in range(n + 1)]      # Build table K[][] in bottom up manner    for i in range(n + 1):        for w in range(W + 1):            if i == 0 or w == 0:                K[i][w] = 0            elif wt[i-1] <= w:                K[i][w] = max(val[i-1] + K[i-1][w-wt[i-1]],  K[i-1][w])            else:                K[i][w] = K[i-1][w]      return K[n][W]  # Driver program to test above functionval = [60, 100, 120]wt = [10, 20, 30]W = 50n = len(val)print(knapSack(W, wt, val, n))  # This code is contributed by Bhavya Jain
220

Please refer complete article on Dynamic Programming | Set 10 ( 0-1 Knapsack Problem) for more details!
knapsack
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Moment.js moment().valueOf() Function

29 Jul, 2020
The moment().valueOf() function is used to get the number of milliseconds since the Unix Epoch. Basically the Unix time is a system for describing a point in time.
Syntax:
moment().valueOf();
Parameters: This function has no parameter.
Return Value: This function returns the Unix Timestamp in milliseconds.
Installation of moment module:
You can visit the link to Install moment module. You can install this package by using this command.npm install momentAfter installing the moment module, you can check your moment version in command prompt using the command.npm version momentAfter that, you can just create a folder and add a file for example, index.js as shown below.
You can visit the link to Install moment module. You can install this package by using this command.npm install moment
npm install moment
After installing the moment module, you can check your moment version in command prompt using the command.npm version moment
npm version moment
After that, you can just create a folder and add a file for example, index.js as shown below.
Example 1: Filename: index.js
// Requiring the moduleconst moment = require('moment');  // Function callvar result = moment().valueOf();  console.log("Result:", result)
Steps to run the program:
The project structure will look like this:Run index.js file using below command:node index.jsOutput:Result: 1595006948726

The project structure will look like this:
Run index.js file using below command:node index.jsOutput:Result: 1595006948726

node index.js
Output:
Result: 1595006948726

Example 2: Filename: index.js
// Requiring the moduleconst moment = require('moment');   function getUnixTimeStamp() {   return moment().valueOf();}   // Function callvar result = getUnixTimeStamp();console.log("Unix Timestamp:", result)
Steps to run the program:
The project structure will look like this:Run index.js file using below command:node index.jsOutput:Unix Timestamp: 1595007021164

The project structure will look like this:
Run index.js file using below command:node index.jsOutput:Unix Timestamp: 1595007021164

node index.js
Output:
Unix Timestamp: 1595007021164

Reference: https://momentjs.com/docs/#/displaying/unix-timestamp-milliseconds/
Moment.js
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Count non zero values in each column of R dataframe

05 Apr, 2021
In this article, we are going to count the number of non-zero data entries in the data using R Programming Language.
To check the number of non-zero data entries in the data first we have to put that data in the data frame by using:
data <- data.frame(x1 = c(1,2,0,100,0,3,10), 
                  x2 = c(5,0,1,8,10,0,0),
                  x3 = 0)

print(data)
Output:
Now we have the data in the data frame. So, to count the number of non-zeroes entries in each column we use colSums() function. This function is used as:
colSums( data != 0)
Output:
As you can clearly see that there are 3 columns in the data frame and Col1 has 5 nonzeroes entries (1,2,100,3,10) and Col2 has 4 non-zeroes entries (5,1,8,10) and Col3 has 0 non-zeroes entries.
Example 1: Here we are going to create a dataframe and then count the non-zero values in each column.
R
# Create example data framedata <- data.frame(x1 = c(1,2,0,100,0,3,10),                      x2 = c(5,0,1,8,10,0,0),                   x3 = 0)  #  print the dataframeprint(data)   # check for every non zero entry using "data!=0" # and sum the number of entries using colSums()colSums(data != 0)
Output: 
Example 2: In this example, we are using iris3 dataset is used. 
R
# put the iris3 data in dataframedata <- data.frame(iris3)  # check the dimensions of dataframedim(data)  # check for every non zero entry using "data!=0" # and sum the number of entries using colSums()colSums(data != 0)
Output:
Example 3: In this example, the state.x77 dataset is used.
R
# put the state.x77 data in dataframedata <- data.frame(state.x77)  # check the dimensions of dataframedim(data)    # check for every non zero entry using "data!=0" # and sum the number of entries using colSums()colSums(data != 0)
Output:
Example 4: In this example, the USArrest dataset is used.
R
# put the USArrest data in dataframedata <- data.frame(USArrest)  # check the dimensions of dataframedim(data)    # check for every non zero entry using "data!=0" # and sum the number of entries using colSums()colSums(data != 0)
Output: 
Picked
R DataFrame-Programs
R-DataFrame
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Reshaping array as a vector in Julia – vec() Method

25 Mar, 2020
The vec() is an inbuilt function in julia which is used to reshape the specified array as a one-dimensional column vector i.e, 1D array.
Syntax:vec(a::AbstractArray)
Parameters:
a::AbstractArray: Specified array.
Returns: It returns the reshaped 1D array.
Example 1:
# Julia program to illustrate # the use of Array vec() method  # Reshaping the specified array as a # one-dimensional column vector # i.e, 1D array.A = ["a", "b", "c", "d"];println(vec(A))  # Reshaping the specified array as a # one-dimensional column vector # i.e, 1D array.B = ["ab" "bc"; "cd" "df"];println(vec(B))  # Reshaping the specified array as a # one-dimensional column vector # i.e, 1D array.C = cat(["a" "b"; "c" "d"], ["e" "f"; "g" "h"], ["i" "j"; "k" "l"], dims = 3);println(vec(C))
Output:
Example 2:
# Julia program to illustrate # the use of Array vec() method  # Reshaping the specified array as a # one-dimensional column vector # i.e, 1D array.A = [1, 2, 3, 4];println(vec(A))  # Reshaping the specified array as a # one-dimensional column vector # i.e, 1D array.B = [1 2; 3 4];println(vec(B))  # Reshaping the specified array as a # one-dimensional column vector # i.e, 1D array.C = cat([1 2; 3 4], [5 6; 7 8], [9 10; 11 12], dims = 3);println(vec(C))
Output:
Julia Array-functions
Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to select rows based on range of values of a column in an R data frame?

Extraction or selection of data can be done in many ways such as based on an individual value, range of values, etc. This is mostly required when we want to either compare the subsets of the data set or use the subset for analysis. The selection of rows based on range of value may be done for testing as well. We can do this by subset function.
Consider the below data frame −
 Live Demo
> x1<-rpois(20,2)
> x2<-rpois(20,5)
> x3<-rpois(20,10)
> df<-data.frame(x1,x2,x3)
> df
 x1 x2 x3
1 3 2 6
2 3 4 9
3 4 4 12
4 4 8 12
5 3 5 11
6 2 1 9
7 3 5 8
8 1 5 12
9 1 4 5
10 3 3 5
11 2 6 15
12 0 2 5
13 2 6 12
14 2 4 16
15 0 8 14
16 4 1 5
17 1 7 12
18 3 5 9
19 1 6 3
20 0 3 4
> subset(df,df$x1>0 & df$x1<4)
 x1 x2 x3
1 3 2 6
2 3 4 9
5 3 5 11
6 2 1 9
7 3 5 8
8 1 5 12
9 1 4 5
10 3 3 5
11 2 6 15
13 2 6 12
14 2 4 16
17 1 7 12
18 3 5 9
19 1 6 3
> subset(df,df$x1>=1 & df$x1<4)
 x1 x2 x3
1 3 2 6
2 3 4 9
5 3 5 11
6 2 1 9
7 3 5 8
8 1 5 12
9 1 4 5
10 3 3 5
11 2 6 15
13 2 6 12
14 2 4 16
17 1 7 12
18 3 5 9
19 1 6 3
> subset(df,df$x1>=1 & df$x1<3)
 x1 x2 x3
6 2 1 9
8 1 5 12
9 1 4 5
11 2 6 15
13 2 6 12
14 2 4 16
17 1 7 12
19 1 6 3
> subset(df,df$x1>2 & df$x1<=3)
 x1 x2 x3
1 3 2 6
2 3 4 9
5 3 5 11
7 3 5 8
10 3 3 5
18 3 5 9
> subset(df,df$x2>2 & df$x2<6)
 x1 x2 x3
2 3 4 9
3 4 4 12
5 3 5 11
7 3 5 8
8 1 5 12
9 1 4 5
10 3 3 5
14 2 4 16
18 3 5 9
20 0 3 4
> subset(df,df$x3>2 & df$x3<11)
 x1 x2 x3
1 3 2 6
2 3 4 9
6 2 1 9
7 3 5 8
9 1 4 5
10 3 3 5
12 0 2 5
16 4 1 5
18 3 5 9
19 1 6 3
20 0 3 4
Prove that the Hamiltonian Path is NP-Complete in TOC

A Hamilton cycle is a round trip path along n edges of graph G which visits every vertex once and returns to its starting vertex
Given below is an example of the Hamilton cycle path −
Hamilton cycle path: 1,2,8,7,6,5,4,3,1
The travelling salesman problem (TSP) is having a salesman and a set of cities. The salesman needs to visit each one of the cities starting from a certain one and returning to the same city i.e. back to starting position. The challenge of this problem is that the travelling salesman wants to minimise the total length of the trip.
To prove TSP is NP-Complete, first try to prove TSP belongs to Non-deterministic Polynomial (NP).
In TSP, we have to find a tour and check that the tour contains each vertex once.
Then, we calculate the total cost of the edges of the tour. Finally, we check if the cost is minimum or not. This can be done in polynomial time.
Therefore, TSP belongs to NP.
Next, we have to prove that TSP is NP-hard.
To prove this, one way is to show that the Hamiltonian cycle ≤p TSP (as we know that the Hamiltonian cycle problem is NP Complete).
Assume G = (V, E) to be an instance of the Hamiltonian cycle.
Hence, an instance of TSP is constructed. We can create the complete graph G' = (V, E'), where
E′={(i,j):i,j∈Vandi≠j
Thus, the cost function is defined as follows:
t(i,j)= 0 if (i,j) ∈ E
   =1 otherwise
Now, assume that a Hamiltonian cycle H exists in G. The cost of each edge in H is 0 in G' as each edge belongs to E. Therefore, H is having a cost of 0 in G'. Thus, if graph G has a Hamiltonian cycle, then graph G' has a tour of 0 cost.
Now let us assume that G' has a tour H’ of cost at most 0. The cost of edges in E' are 0 and 1 by definition. Hence, each edge must have a cost of 0 as the cost of H’ is 0. We finally conclude that H' contains only edges in E.
Finally proved that G has a Hamiltonian cycle, if and only if G' has a tour of cost at most 0. TSP is NP-complete.
Program to compare two fractions in C

Given two fractions with some numerator nume1 and nume2 and deno1 and deno2 as their respective denominator, the task is to compare both the fractions and find out the greater one. Like we have a fraction 1/2 and 2/3 and the higher one is 2/3 because the value of 1/2 is 0.5 and the value of 2/3 is 0.66667 which is higher.
Input 
first.nume = 2, first.deno = 3
second.nume = 4, second.deno = 3
Output 
4/3
Explanation 
2/3 = 0.66667 < 4/3 = 1.33333
Input 
first.nume = 1, first.deno = 2
second.nume = 4, second.deno = 3
Output 
4/3
//baadme likhunga
Start
Declare a struct Fraction with elements
   nume, deno
In function Fraction greater(Fraction first, Fraction sec)
   Step 1→ Declare and Initialize t Y = first.nume * sec.deno - first.deno *
sec.nume
   Step 2→ Return (Y > 0) ? first : sec
In function int main()
   Step 1→ Declare Fraction first = { 4, 5 }
   Step 2→Fraction sec = { 3, 4 }
   Step 3→ Fraction res = greater(first, sec)
   Step 4→ Print res.nume, res.deno
Stop
#include <stdio.h>
struct Fraction {
   int nume, deno;
};
// Get max of the two fractions
Fraction greater(Fraction first, Fraction sec){
   //check if the result is in negative then the
   //second fraction is greater else first is greater
   int Y = first.nume * sec.deno - first.deno * sec.nume;
   return (Y > 0) ? first : sec;
}
int main(){
   Fraction first = { 4, 5 };
   Fraction sec = { 3, 4 };
   Fraction res = greater(first, sec);
   printf("The greater fraction is: %d/%d\n", res.nume, res.deno);
   return 0;
}
If run the above code it will generate the following output −
The greater fraction is: 4/5
Catch block and type conversion in C++ - GeeksforGeeks

12 Nov, 2021
Predict the output of following C++ program.
C++
#include <iostream>using namespace std; int main(){    try    {        throw 'x';    }    catch(int x)    {        cout << " Caught int " << x;    }    catch(...)    {        cout << "Default catch block";    }}
Output:
 Default catch block
In the above program, a character ‘x’ is thrown and there is a catch block to catch an int. One might think that the int catch block could be matched by considering ASCII value of ‘x’. But such conversions are not performed for catch blocks. Consider the following program as another example where conversion constructor is not called for thrown object.
C++
#include <iostream>using namespace std; class MyExcept1 {}; class MyExcept2{public:     // Conversion constructor    MyExcept2 (const MyExcept1 &e )    {        cout << "Conversion constructor called";    }}; int main(){    try    {        MyExcept1 myexp1;        throw myexp1;    }    catch(MyExcept2 e2)    {        cout << "Caught MyExcept2 " << endl;    }    catch(...)    {        cout << " Default catch block " << endl;    }    return 0;}
Output:
Default catch block
As a side note, the derived type objects are converted to base type when a derived object is thrown and there is a catch block to catch base type. See this GFact for more details.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
yurychaikou
kashishsoda
C Language
C++
School Programming
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
std::sort() in C++ STL
Bitwise Operators in C/C++
rand() and srand() in C/C++
Left Shift and Right Shift Operators in C/C++
Vector in C++ STL
Initialize a vector in C++ (6 different ways)
std::sort() in C++ STL
Bitwise Operators in C/C++
Socket Programming in C/C++
How to catch EOFError Exception in Python?

An EOFError is raised when a built-in function like input() or raw_input() do not read any data before encountering the end of their input stream. The file methods like read() return an empty string at the end of the file.
The given code is rewritten as follows to catch the EOFError and find its type.
#eofError.py
try:
while True:
data = raw_input('prompt:')
print 'READ:', data
except EOFError as e:
print e
Then if we run the script at the terminal
$ echo hello | python eofError.py
prompt:READ: hello
prompt:EOF when reading a line
How to use jQuery.serializeArray() method to serialize data?

The serializeArray( ) method serializes all forms and form elements like the .serialize() method but returns a JSON data structure for you to work with.
Assuming we have following PHP content in serialize.php file −
<?php
if( $_REQUEST["name"] ) {

   $name = $_REQUEST['name'];
   echo "Welcome ". $name;
   $age = $_REQUEST['age'];
   echo "<br />Your age : ". $age;
   $sex = $_REQUEST['sex'];
   echo "<br />Your gender : ". $sex;
}
?>
The following is an example showing the usage of this method −
Live Demo
<html>

   <head>
      <title>The jQuery Example</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
       
      <script>
         $(document).ready(function() {
           
            $("#driver").click(function(event){
               
               $.post(
                  "/jquery/serialize.php",
                  $("#testform").serializeArray(),
                  function(data) {
                     $('#stage1').html(data);
                  }
               );
                   
               var fields = $("#testform").serializeArray();
               $("#stage2").empty();
                   
               jQuery.each(fields, function(i, field){
                  $("#stage2").append(field.value + " ");
               });
                   
            });
               
         });
      </script>
   </head>
   
   <body>
   
      <p>Click on the button to load result.html file:</p>
       
      <div id = "stage1" style = "background-color:blue;">
         STAGE - 1
      </div>
       
      <br />
       
      <div id = "stage2" style = "background-color:blue;">
         STAGE - 2
      </div>
       
      <form id = "testform">
       
         <table>
           
            <tr>
               <td><p>Name:</p></td>
               <td><input type = "text" name = "name" size = "40" /></td>
            </tr>
               
            <tr>
               <td><p>Age:</p></td>
               <td><input type = "text" name = "age" size = "40" /></td>
            </tr>
               
            <tr>
               <td><p>Sex:</p></td>
               <td> <select name = "sex">
                  <option value = "Male" selected>Male</option>
                  <option value = "Female" selected>Female</option>
               </select></td>
            </tr>
               
            <tr>
               <td colspan = "2">
                  <input type = "button" id = "driver" value = "Load Data" />
               </td>
            </tr>  
               
         </table>
           
      </form>
       
   </body>
</html>
How to use range-based for() loop with std::map?

Here we will see how to use the range based for loop for std::map type objects. In C++, we know that there are map type objects. That can store key value pairs. The map basically stores the pair objects. This pair object is used to store one key and corresponding value. These keys and values are implemented using templates, so we can use any type of data.
To use the range based for loop, we can define for loop that can iterate through each pair of the map. Let us see the code to get the better idea.
#include<iostream>
#include<map>
using namespace std;
main() {
   map<char, string> my_map;
   my_map.insert(pair<char, string>('A', "Apple"));
   my_map.insert(pair<char, string>('B', "Ball"));
   my_map.insert(pair<char, string>('C', "Cat"));
   my_map.insert(pair<char, string>('D', "Dog"));
   my_map.insert(pair<char, string>('E', "Eagle"));
   my_map.insert(pair<char, string>('F', "Flag"));
   my_map.insert(pair<char, string>('G', "Ghost"));
   my_map.insert(pair<char, string>('H', "Hill"));
   my_map.insert(pair<char, string>('I', "India"));
   my_map.insert(pair<char, string>('J', "Jug"));
   for(auto& key_val : my_map) {
      cout << "The " << key_val.first << " is pointing to: " << key_val.second << endl;
   }
}
The A is pointing to: Apple
The B is pointing to: Ball
The C is pointing to: Cat
The D is pointing to: Dog
The E is pointing to: Eagle
The F is pointing to: Flag
The G is pointing to: Ghost
The H is pointing to: Hill
The I is pointing to: India
The J is pointing to: Jug
Tryit Editor v3.7 - Show Java

public class CreateFileDir {  
  public static void main(String[] args) {  
    try {  
      File myObj = new File("C:\\Users\\MyName\\filename.txt");  
      if (myObj.createNewFile()) {  
        System.out.println("File created: " + myObj.getName());  
        System.out.println("Absolute path: " + myObj.getAbsolutePath());  
      } else {  
        System.out.println("File already exists.");  
      }  
    } catch (IOException e) {
      System.out.println("An error occurred.");
How to use OpenCV with GPU on Colab? | by C K | Towards Data Science

OpenCV’s ‘Deep Neural Network’ (dnn) module is a convenient tool for computer vision, it is very easy to apply some techniques such as Yolo and OpenPose. However, the major drawback of OpenCV was the lack of GPU support, resulting in slow inference. Luckily since OpenCV 4.2, NVIDIA GPU/CUDA is supported.
It still required some works to use GPU, you can check Pyimagesearch’s article here, they demonstrate how to set up a Ubuntu machine.
If you do not have a machine with GPU like me, you can consider using Google Colab, which is a free service with powerful NVIDIA GPU. It is also a lot easier to set up, most of the requirements are already satisfied. In this article, I will share how I set up the Colab environment for OpenCV’s dnn with GPU in just a few lines of code. You can also check here, I made slight changes based on the answer.
The code to assign the dnnto GPU is simple:
import cv2net = cv2.dnn.readNetFromCaffe(protoFile, weightsFile)net.setPreferableBackend(cv2.dnn.DNN_BACKEND_CUDA)net.setPreferableTarget(cv2.dnn.DNN_TARGET_CUDA)
However, if you run this cell directly on Colab, you will see this error:
So we need to do something.
If you check the version of the pre-installed OpenCV on Colab, you will see this:
We need to install cv2 ourselves.
First, run this cell:
%cd /content!git clone https://github.com/opencv/opencv!git clone https://github.com/opencv/opencv_contrib!mkdir /content/build%cd /content/build!cmake -DOPENCV_EXTRA_MODULES_PATH=/content/opencv_contrib/modules  -DBUILD_SHARED_LIBS=OFF  -DBUILD_TESTS=OFF  -DBUILD_PERF_TESTS=OFF -DBUILD_EXAMPLES=OFF -DWITH_OPENEXR=OFF -DWITH_CUDA=ON -DWITH_CUBLAS=ON -DWITH_CUDNN=ON -DOPENCV_DNN_CUDA=ON /content/opencv!make -j8 install
you will see something like this:
It is going to take a while, after completion you can check the version of OpenCV.
Let is it! Now you should be able to set the dnn to CUDA without error.
net.setPreferableBackend(cv2.dnn.DNN_BACKEND_CUDA)net.setPreferableTarget(cv2.dnn.DNN_TARGET_CUDA)
But the first step takes a lot of time, and you need to do it every time you start the notebook. This is time-consuming and not ideal.
One thing you can do here is to save the result of the first step to your Google Drive (you have to mount it ).
!mkdir  "/content/gdrive/My Drive/cv2_gpu"!cp  /content/build/lib/python3/cv2.cpython-36m-x86_64-linux-gnu.so   "/content/gdrive/My Drive/cv2_gpu"
Then copy it to your working directory next time you start the notebook.
!cp "/content/gdrive/My Drive/cv2_gpu/cv2.cpython-36m-x86_64-linux-gnu.so" .
and check the version to make sure it is done.
If you do not want to mount your Google Drive, you can upload it to the cloud somewhere and download it using !wget to your working dir.
That is it. Thanks for reading. Have fun with the GPU.
Boolean.CompareTo(Boolean) Method in C#

The Boolean.CompareTo(Boolean) method in C# is used to compare this instance to a specified Boolean object and returns an integer that indicates their relationship to one another.
Following is the syntax −
public int CompareTo (bool val);
Above, Val is a Boolean object to compare to the current instance.
Let us now see an example to implement the Boolean.CompareTo(Boolean) method −
using System;
public class Demo {
   public static void Main(){
      bool b1, b2;
      b1 = false;
      b2 = false;
      int res = b2.CompareTo(b1);
      if (res > 0)
         Console.Write("b1 > b2");
      else if (res < 0)
         Console.Write("b1 < b2");
      else
         Console.Write("b1 = b2");
   }
}
This will produce the following output −
b1 = b2
Add a shadow to an element with Bootstrap 4

To add a shadow to an element in Bootstrap, use the .shadow class in Bootstrap 4.
You can try to run the following code to add shadow to an element −
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Example</title>
      <link rel = "stylesheet" href = "https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <script src = "https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
   </head>
   <body>
      <div class = "container">
         <h1>Learning</h1>
         <div class = "shadow-lg p-4 mb-4 bg-light">Try programming examples</div>
         <div class = "shadow-sm p-4 mb-4 bg-light">Try programming examples</div>
         <div class =" shadow-none p-4 mb-4 bg-light">Play Quiz and check your knowledge</div>
      </div>
   </body>
</html>
MongoDB - Delete Document

In this chapter, we will learn how to delete a document using MongoDB.
MongoDB's remove() method is used to remove a document from the collection. remove() method accepts two parameters. One is deletion criteria and second is justOne flag.
deletion criteria − (Optional) deletion criteria according to documents will be removed.
deletion criteria − (Optional) deletion criteria according to documents will be removed.
justOne − (Optional) if set to true or 1, then remove only one document.
justOne − (Optional) if set to true or 1, then remove only one document.
Basic syntax of remove() method is as follows −
>db.COLLECTION_NAME.remove(DELLETION_CRITTERIA)

Consider the mycol collection has the following data.
{_id : ObjectId("507f191e810c19729de860e1"), title: "MongoDB Overview"},
{_id : ObjectId("507f191e810c19729de860e2"), title: "NoSQL Overview"},
{_id : ObjectId("507f191e810c19729de860e3"), title: "Tutorials Point Overview"}
Following example will remove all the documents whose title is 'MongoDB Overview'.
>db.mycol.remove({'title':'MongoDB Overview'})
WriteResult({"nRemoved" : 1})
> db.mycol.find()
{"_id" : ObjectId("507f191e810c19729de860e2"), "title" : "NoSQL Overview" }
{"_id" : ObjectId("507f191e810c19729de860e3"), "title" : "Tutorials Point Overview" }
If there are multiple records and you want to delete only the first record, then set justOne parameter in remove() method.
>db.COLLECTION_NAME.remove(DELETION_CRITERIA,1)
If you don't specify deletion criteria, then MongoDB will delete whole documents from the collection. This is equivalent of SQL's truncate command.
> db.mycol.remove({})
WriteResult({ "nRemoved" : 2 })
> db.mycol.find()
>

    44 Lectures 
     3 hours 

 Arnab Chakraborty

    54 Lectures 
     5.5 hours 

 Eduonix Learning Solutions

    44 Lectures 
     4.5 hours 

 Kaushik Roy Chowdhury

    40 Lectures 
     2.5 hours 

 University Code

    26 Lectures 
     8 hours 

 Bassir Jafarzadeh

    70 Lectures 
     2.5 hours 

 Skillbakerystudios
 Print
 Add Notes
 Bookmark this page
What is the difference between a++ and ++a in JavaScript?

++a returns the value of an after it has been incremented. It is a pre-increment operator since ++ comes before the operand.
a++ returns the value of a before incrementing. It is a post-increment operator since ++ comes after the operand.
You can try to run the following code to learn the difference between i++ and ++i −
<html>
   <body>  
      <script>
          var a =10;
          var b =20;
          //pre-increment operator
          a = ++a;
          document.write("++a = "+a);            
          //post-increment operator
          b = b++;
          document.write("<br> b++ = "+b);
      </script>
   </body>
</html>