code-rag-bench/online-tutorials huggingface dataset:
random.expovariate() function in Python

23 Dec, 2021
random module is used to generate random numbers in Python. Not actually random, rather this is used to generate pseudo-random numbers. That implies that these randomly generated numbers can be determined.
expovariate() is an inbuilt method of the random module. It is used to return a random floating point number with exponential distribution.
Syntax : random.expovariate(lambda)
Parameters :lambda : a non zero value
Returns : a random exponential distribution floating numberif the parameter is positive, the results range from 0 to positive infinityif the parameter is negative, the results range from 0 to negative infinity
Example 1:
# import the random moduleimport random  # determining the values of the parameterlambda = 1.5  # using the expovariate() methodprint(random.expovariate(lambda))
Output :
0.22759592233982198
Example 2: We can generate the number multiple times and plot a graph to observe the exponential distribution.
# import the required libraries import random import matplotlib.pyplot as plt     # store the random numbers in a  # list nums = [] alpha = 3    for i in range(100):     temp = random.paretovariate(alpha)    nums.append(temp)         # plotting a graph plt.plot(nums) plt.show()
Output :Example 3: We can create a histogram to observe the density of the exponential distribution.
# import the required libraries import random import matplotlib.pyplot as plt     # store the random numbers in a list nums = [] lambda = 1.5    for i in range(10000):     temp = random.expovariate(lambda)    nums.append(temp)         # plotting a graph plt.hist(nums, bins = 200) plt.show()
Output :
nnr223442
Python-random
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 for Bubble Sort - GeeksforGeeks

12 Feb, 2018
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order.
// Optimized implementation of Bubble sort#include <stdio.h>  void swap(int *xp, int *yp){    int temp = *xp;    *xp = *yp;    *yp = temp;}  // An optimized version of Bubble Sortvoid bubbleSort(int arr[], int n){   int i, j;   bool swapped;   for (i = 0; i < n-1; i++)   {     swapped = false;     for (j = 0; j < n-i-1; j++)     {        if (arr[j] > arr[j+1])        {           swap(&arr[j], &arr[j+1]);           swapped = true;        }     }       // IF no two elements were swapped by inner loop, then break     if (swapped == false)        break;   }}  /* Function to print an array */void printArray(int arr[], int size){    int i;    for (i=0; i < size; i++)        printf("%d ", arr[i]);    printf("n");}  // Driver program to test above functionsint main(){    int arr[] = {64, 34, 25, 12, 22, 11, 90};    int n = sizeof(arr)/sizeof(arr[0]);    bubbleSort(arr, n);    printf("Sorted array: \n");    printArray(arr, n);    return 0;}
Please refer complete article on Bubble Sort for more details!
BubbleSort
C++ Programs
Sorting
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Passing a function as a parameter in C++
Program to implement Singly Linked List in C++ using class
Const keyword in C++
cout in C++
Handling the Divide by Zero Exception in C++
Modulus of two double numbers | Practice | GeeksforGeeks

Given two floating point numbers a and b, find a%b.
 
Example 1:
Input:
a = 36.5, b = 5.0
Output:
1.5
Explanation:
36.5 % 5.0 = 1.5
Example 2:
Input:
a = 9.7, b = 2.3
Output:
0.5
Explanation:
9.7 % 2.3 = 0.5
 
Your Task:
You don't need to read input or print anything. Your task is to complete the function floatMod() which takes 2 doubles a, and b as input and returns a%b.
 
Expected Time Complexity: O(1)
Expected Auxiliary Space: O(1)
 
Constraints:
1 <= a,b<= 103
+1
badgujarsachin837 months ago
+1
badgujarsachin837 months ago
class Solution {
  public:
    double floatMod(double a, double b) {
        // code here
       return fmod(a,b);
    }
};
0
Fasil Shafi1 year ago
Fasil Shafi
class Solution {  public:    double floatMod(double a, double b) {
        return fmod(a,b);    }};
0
mawzir ।2 years ago
mawzir ।
N=int(input())for i in range(N):    n1=input()    l1=n1.split()    for i in range(len(l1)):        l1[i]=float(l1[i])    print(round((l1[0]%l1[1]),2))
0
Rony Hajong2 years ago
Rony Hajong
#include<bits stdc++.h="">using namespace std;int main(){    int t;    double a,b;
    cin>>t;    while (t--)    {        cin>>a>>b;        long long int p=a*10000000000;        long long int q=b*10000000000;
        long long int mod=p%q;        double mod_m=mod/10000000000.0;
        cout<<mod_m<<endl; }="" return="" 0;="" }="">
0
Hitesh Sandal4 years ago
Hitesh Sandal
https://ide.geeksforgeeks.o... here is the link to my code!for input 205.4 234.6its correct output is: 205.4, and my code's output is: 205.40 !and for some test case, correct output was 0.17 and my  code's output was 0.170005!
How to control number of digits after decimal point for every case!?
0
Tech Today4 years ago
Tech Today
def remainder(a,b):    return round(a%b,2)
test = int(input())for t in range(test):    a,b = map(float,input().split())    print(remainder(a,b))
0
Ratnesh Tiwari4 years ago
Ratnesh Tiwari
https://ide.geeksforgeeks.o...producing wrong output for
Input:93.83 108.86
Its Correct output is:93.83And My Code's output is:93.8
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

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.
How to pass check boxes data using JSP?

Checkboxes are used when more than one option is required to be selected.
Following is an example HTML code, CheckBox.htm, for a form with two checkboxes.
<html>
   <body>
      <form action = "main.jsp" method = "POST" target = "_blank">
         <input type = "checkbox" name = "maths" checked = "checked" /> Maths
         <input type = "checkbox" name = "physics" /> Physics
         <input type = "checkbox" name = "chemistry" checked = "checked" /> Chemistry
         <input type = "submit" value = "Select Subject" />
      </form>
   </body>
</html>
The above code will generate the following result −
Following is main.jsp JSP program to handle the input given by the web browser for the checkbox button.
<html>
   <head>
      <title>Reading Checkbox Data</title>
   </head>
   <body>
      <h1>Reading Checkbox Data</h1>
      <ul>
         <li><p><b>Maths Flag:</b>
            <%= request.getParameter("maths")%>
            </p></li>
         <li><p><b>Physics Flag:</b>
            <%= request.getParameter("physics")%>
            </p></li>
         <li><p><b>Chemistry Flag:</b>
            <%= request.getParameter("chemistry")%>
            </p></li>
      </ul>
   </body>
</html>
The above program will generate the following result −
Maths Flag :: on
Maths Flag :: on
Physics Flag:: null
Physics Flag:: null
Chemistry Flag:: on
Chemistry Flag:: on
How to select only one column from an R data frame and return it as a data frame instead of vector?

Generally, if we extract a single column from an R data frame then it is extracted as a vector but we might want it in data frame form so that we can apply operations of a data frame on it. Therefore, we can use single square brackets for the extraction with T (TRUE) or (FALSE) values and drop = FALSE so that the output becomes a data frame.
Consider the below data frame −
 Live Demo
set.seed(999)
x1<-rnorm(20,5,1)
x2<-rnorm(20,5,2)
x3<-rnorm(20,10,2)
x4<-rnorm(20,10,1.5)
x5<-rnorm(20,10,4)
df1<-data.frame(x1,x2,x3,x4,x5)
df1
       x1      x2        x3     x4      x5
1 4.718260 2.542873 9.028727 8.615033 7.428309
2 3.687440 6.286089 10.016996 11.747431 13.941194
3 5.795184 4.280474 7.435773 11.563103 5.085707
4 5.270070 5.588071 7.776842 11.655743 10.340899
5 4.722694 2.749463 10.601331 9.972138 5.183625
6 4.433976 6.284531 10.552958 8.279563 8.492609
7 3.121342 2.786525 5.898245 7.887731 15.454594
8 3.733209 3.230319 10.028380 9.576507 8.988469
9 4.032250 1.891810 11.164533 9.373345 14.025960
10 3.878991 4.746642 9.930547 11.494995 11.748597
11 6.325464 9.765328 9.766672 9.840571 16.634154
12 5.133977 6.202552 8.710036 9.895897 10.110741
13 5.938749 5.358723 13.488823 11.424552 6.085122
14 5.172538 7.161063 10.732189 9.375201 15.134917
15 5.957650 4.506376 9.866380 11.461001 5.481034
16 3.637314 0.772526 10.565225 10.093437 14.186631
17 5.068335 4.258945 11.135390 10.807633 7.688271
18 5.100658 6.045736 7.441568 6.902765 8.824823
19 5.901345 6.035611 10.870738 10.654647 9.032894
20 2.925643 2.194978 8.868998 9.759660 10.879791
Extracting column x1 −
df1[,c(T,F,F,F,F)]
[1] 4.718260 3.687440 5.795184 5.270070 4.722694 4.433976 3.121342 3.733209
[9] 4.032250 3.878991 6.325464 5.133977 5.938749 5.172538 5.957650 3.637314
[17] 5.068335 5.100658 5.901345 2.925643
is.vector(df1[,c(T,F,F,F,F)]) [1] TRUE
Extracting column x1 as a data frame −
df1[,c(T,F,F,F,F),drop=FALSE]
x1
1 4.718260
2 3.687440
3 5.795184
4 5.270070
5 4.722694
6 4.433976
7 3.121342
8 3.733209
9 4.032250
10 3.878991
11 6.325464
12 5.133977
13 5.938749
14 5.172538
15 5.957650
16 3.637314
17 5.068335
18 5.100658
19 5.901345
20 2.925643
Extracting different columns in the same way −
df1[,c(F,T,F,F,F),drop=FALSE]
  x2
1 2.542873
2 6.286089
3 4.280474
4 5.588071
5 2.749463
6 6.284531
7 2.786525
8 3.230319
9 1.891810
10 4.746642
11 9.765328
12 6.202552
13 5.358723
14 7.161063
15 4.506376
16 0.772526
17 4.258945
18 6.045736
19 6.035611
20 2.194978
df1[,c(F,F,T,F,F),drop=FALSE]
x3
1 9.028727
2 10.016996
3 7.435773
4 7.776842
5 10.601331
6 10.552958
7 5.898245
8 10.028380
9 11.164533
10 9.930547
11 9.766672
12 8.710036
13 13.488823
14 10.732189
15 9.866380
16 10.565225
17 11.135390
18 7.441568
19 10.870738
20 8.868998
df1[,c(F,F,F,F,T),drop=FALSE]
x5
1 7.428309
2 13.941194
3 5.085707
4 10.340899
5 5.183625
6 8.492609
7 15.454594
8 8.988469
9 14.025960
10 11.748597
11 16.634154
12 10.110741
13 6.085122
14 15.134917
15 5.481034
16 14.186631
17 7.688271
18 8.824823
19 9.032894
20 10.879791
Redis - List Lpop Command

Redis LPOP command removes and returns the first element of the list stored at the key.
String reply, the value of the first element, or nil when the key does not exist.
Following is the basic syntax of Redis LPOP command.
redis 127.0.0.1:6379> LPOP KEY_NAME

redis 127.0.0.1:6379> RPUSH list1 "foo" 
(integer) 1 
redis 127.0.0.1:6379> RPUSH list1 "bar" 
(integer) 2 
redis 127.0.0.1:6379> LPOP list1
"foo" 


    22 Lectures 
     40 mins

 Skillbakerystudios
 Print
 Add Notes
 Bookmark this page
How to trim spaces from field in MongoDB query?

To trim spaces from field, use $trim in MongoDB. Let us create a collection with documents −
> db.demo217.insertOne({"FullName":"   Chris Brown"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3e5d1e03d395bdc213470f")
}
> db.demo217.insertOne({"FullName":"   David Miller"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3e5d2503d395bdc2134710")
}
> db.demo217.insertOne({"FullName":"   John Doe"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3e5d2b03d395bdc2134711")
}
Display all documents from a collection with the help of find() method −
> db.demo217.find();
This will produce the following output −
{ "_id" : ObjectId("5e3e5d1e03d395bdc213470f"), "FullName" : "   Chris Brown" }
{ "_id" : ObjectId("5e3e5d2503d395bdc2134710"), "FullName" : "   David Miller" }
{ "_id" : ObjectId("5e3e5d2b03d395bdc2134711"), "FullName" : "   John Doe" }
Following is the query to trim spaces from field in MongoDB −
> db.demo217.aggregate([
...    { $project: { Name: { $trim: { input: "$FullName" } } } }
... ])
This will produce the following output −
{ "_id" : ObjectId("5e3e5d1e03d395bdc213470f"), "Name" : "Chris Brown" }
{ "_id" : ObjectId("5e3e5d2503d395bdc2134710"), "Name" : "David Miller" }
{ "_id" : ObjectId("5e3e5d2b03d395bdc2134711"), "Name" : "John Doe" }
What is MySQL GENERATED COLUMN and how to use it while creating a table?

Basically generated columns are a feature that can be used in CREATE TABLE or ALTER TABLE statements and is a way of storing the data without actually sending it through the INSERT or UPDATE clause in SQL. This feature has been added in MySQL 5.7. A generated column works within the table domain. Its syntax would be as follows −
column_name data_type [GENERATED ALWAYS] AS (expression)
[VIRTUAL | STORED] [UNIQUE [KEY]]
Here, first of all, specify the column name and its data type.
Then add the GENERATED ALWAYS clause to indicate that the column is a generated column.
Then, indicate whether the type of the generated column by using the corresponding option − VIRTUAL or STORED. By default, MySQL uses VIRTUAL if you don’t specify explicitly the type of the generated column.
After that, specify the expression within the braces after the AS keyword. The expression can contain literals, built-in functions with no parameters, operators, or references to any column within the same table. If you use a function, it must be scalar and deterministic.
Finally, if the generated column is stored, you can define a unique constraint for it.
In this example, we are creating a table named employee_data having the details of employees along with a generated column as follows −
mysql> Create table employee_data(ID INT AUTO_INCREMENT PRIMARY KEY, First_name VARCHAR(50) NOT NULL, Last_name VARCHAR(50) NOT NULL, FULL_NAME VARCHAR(90) GENERATED ALWAYS AS(CONCAT(First_name,' ',Last_name)));
Query OK, 0 rows affected (0.55 sec)

mysql> DESCRIBE employee_data;
+------------+-------------+------+-----+---------+-------------------+
| Field      | Type        | Null | Key | Default | Extra             |
+------------+-------------+------+-----+---------+-------------------+
| ID         | int(11)     | NO   | PRI | NULL    | auto_increment    |
| First_name | varchar(50) | NO   |     | NULL    |                   |
| Last_name  | varchar(50) | NO   |     | NULL    |                   |
| FULL_NAME  | varchar(90) | YES  |     | NULL    | VIRTUAL GENERATED |
+------------+-------------+------+-----+---------+-------------------+
4 rows in set (0.00 sec)

mysql> INSERT INTO employee_data(first_name, Last_name) values('Yashpal','Sharma');
Query OK, 1 row affected (0.09 sec)

mysql> INSERT INTO employee_data(first_name, Last_name) values('Krishan','Kumar');
Query OK, 1 row affected (0.09 sec)

mysql> INSERT INTO employee_data(first_name, Last_name) values('Rakesh','Arora');
Query OK, 1 row affected (0.08 sec)

mysql> Select * from employee_data;
+----+------------+-----------+----------------+
| ID | First_name | Last_name | FULL_NAME      |
+----+------------+-----------+----------------+
| 1  | Yashpal    | Sharma    | Yashpal Sharma |
| 2  | Krishan    | Kumar     | Krishan Kumar  |
| 3  | Rakesh     | Arora     | Rakesh Arora   |
+----+------------+-----------+----------------+
3 rows in set (0.00 sec)
Putting arrowheads on vectors in Matplotlib's 3D plot

To draw arrow heads vectors in 3D matplotlb's plot, we can take the following steps −
Create a 2D array, where x, y, z, u, v and w are the coordinates of the arrow locations and direction components of arrow vectors.
Create a 2D array, where x, y, z, u, v and w are the coordinates of the arrow locations and direction components of arrow vectors.
Using figure() method, create a new figure or activate an existing figure.
Using figure() method, create a new figure or activate an existing figure.
Add an '~.axes.Axes' to the figure as part of a subplot arrangement, using add_subplot() method.
Add an '~.axes.Axes' to the figure as part of a subplot arrangement, using add_subplot() method.
Plot a 3D field of arrows, using quiver() method.
Plot a 3D field of arrows, using quiver() method.
Using ylim, xlim, zlim, limit the range of the axes.
Using ylim, xlim, zlim, limit the range of the axes.
Set the title of the plot.
Set the title of the plot.
To display the figure, use show() method.
To display the figure, use show() method.
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
soa = np.array([[0, 0, 1, 1, -2, 0], [0, 0, 2, 1, 1, 0], [0, 0, 3, 2, 1, 0], [0, 0, 4, 0.5, 0.7, 0]])
X, Y, Z, U, V, W = zip(*soa)
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
ax.quiver(X, Y, Z, U, V, W, color='red')
ax.set_xlim([-1, 0.5])
ax.set_ylim([-1, 1.5])
ax.set_zlim([-1, 8])
ax.set_title("Vectors")
plt.show()
Print prime numbers with prime sum of digits in an array

Given with an array of elements and the task is to print those numbers whose digit sum is also prime and return -1 is not such digit exists in an array
Input: arr[]={2,4,3,19,25,6,11,12,18,7}
Output : 2, 3, 25, 11, 12, 7
Here, the given output is generated as it contains those additive numbers whose sum is also prime like − 2, 3, 7 are prime but 25(2+5=7), 11(1+1=2), 12(1+2=3) are also prime whereas numbers like 19(1+9=10) are not prime.
START
Step 1 -> Take array of int with values
Step 2 -> declare start variables as i, m, flag, flag1, sum, r, d, j, tem
Step 3 -> store size of array in m as sizeof(arr)/sizeof(arr[0])
Step 4 -> Loop For i=1 and i<m and i++
   Set flag=flag1=sum=0
   Set d=int(arr[i]/2
   Loop For j=2 and j<=d and j++
      IF arr[i]%j==0
         Set flag=1
         Break
      End IF
   End
   IF flag=0
      Set tem=arr[i]
         Loop While tem
            Set r=tem%10
            Set sum=sum+r
            Set tem=tem/10
         End
         Set d=int(sum/2)
         Loop For j=2 and j<=d and j++
            IF sum%j=0
               Set flag1=1
               break
            End
         End
      IF flag1=0
         Print arr[i]
      End
   End
End
STOP
#include<iostream>
using namespace std;
int main(){
   int arr[]={2,4,3,19,25,6,11,12,18,7};
   int i,m,flag,flag1,sum,r,d,j,tem;
   m=sizeof(arr)/sizeof(arr[0]);
   for(i=0;i<m;i++) {
      flag=flag1=sum=0;
      d=int(arr[i]/2);
      for(j=2;j<=d;j++){
         if(arr[i]%j==0) {
            flag=1;
            break;
         }
      }
      if(flag==0) {
         tem=arr[i];
         while(tem) {
            r=tem%10;
            sum=sum+r;
            tem=tem/10;
         }
         d=int(sum/2);
         for(j=2;j<=d;j++) {
            if(sum%j==0){
               flag1=1;
               break;
            }
         }
         if(flag1==0){
            cout<<arr[i]<<" ";
         }
      }
   }
}
if we run the above program then it will generate the following output
2 3 11 25 12 7
Lodash - get method

_.get(object, path, [defaultValue])

Gets the value at path of object. If the resolved value is undefined, the defaultValue is returned in its place.
object (Object) − The object to query.
object (Object) − The object to query.
path (Array|string) − The path of the property to get.
path (Array|string) − The path of the property to get.
[defaultValue] (*) − The value returned for undefined resolved values.
[defaultValue] (*) − The value returned for undefined resolved values.
(*) − Returns the resolved value.
(*) − Returns the resolved value.
var _ = require('lodash');
var object = { 'a': [{ 'b': { 'c': 3 } }] };
var result = _.get(object, 'a[0].b.c');

console.log(result);

result = _.get(object,   ['a', '0', 'b', 'c']);
console.log(result);
Save the above program in tester.js. Run the following command to execute this program.
\>node tester.js

3
3

 Print
 Add Notes
 Bookmark this page
Write a C program for electing a candidate in Elections by calling functions using Switch case

How to cast vote, count, and display the votes for each candidate that participates in elections using C language?
Let’s consider three persons who participated in elections. Here we need to write a code for the following −
Cast vote − Selecting a candidate by pressing the cast vote
Cast vote − Selecting a candidate by pressing the cast vote
Find vote count − Finding the total number of votes each candidate gains declaring the winner.
Find vote count − Finding the total number of votes each candidate gains declaring the winner.
All these operations are performed by calling each function using Switch case −
#include<stdio.h>
#define CANDIDATE_COUNT
#define CANDIDATE1 "ABC"
#define CANDIDATE2 "XYZ"
#define CANDIDATE3 "PQR"
int votescount1=0, votescount2=0, votescount3=0;
void castvote(){
   int choice;
   printf("\n\n ### Please choose your Candidate ####\n\n");
   printf("\n 1. %s", CANDIDATE1);
   printf("\n 2. %s", CANDIDATE2);
   printf("\n 3. %s", CANDIDATE3);
   printf("\n4. %s", “None of These");
   printf("\nInput your choice (1 - 4) : “);
   scanf("%d",&choice);
   switch(choice){
      case 1: votescount1++; break;
      case 2: votescount2++; break;
      case 3: votescount3++; break;
      default: printf("\n Error: Wrong Choice !! Please retry");
      //hold the screen
      getchar();
   }
   printf(“\n thanks for vote !!");
}
void votesCount(){
   printf("\n\n ##### Voting Statics ####");
   printf("\n %s - %d ", CANDIDATE1, votescount1);
   printf("\n %s - %d ", CANDIDATE2, votescount2);
   printf("\n %s - %d ", CANDIDATE3, votescount3);
}
int main(){
   int i;
   int choice;
   do{
      printf("\n\n ###### Welcome to Election/Voting 2019 #####");
      printf("\n\n 1. Cast the Vote");
      printf("\n 2. Find Vote Count");
      printf("\n 0. Exit");
      printf("\n Please enter your choice : ");
      scanf("%d", &choice);
      switch(choice){
         case 1: castvote();break;
         case 2: votesCount();break;
         default: printf("\n Error: Invalid Choice");
      }
   }while(choice!=0);
   //hold the screen
   getchar();
   return 0;
}
###### Welcome to Election/Voting 2019 #####
1. Cast the Vote
2. Find Vote Count
0. Exit
Please enter your choice : 1
### Please choose your Candidate ####
1. ABC
2. XYZ
3. PQR
4. None of These
Input your choice (1 - 4) : 1
thanks for vote !!
###### Welcome to Election/Voting 2019 #####
1. Cast the Vote
2. Find Vote Count
0. Exit
Please enter your choice : 1
### Please choose your Candidate ####
1. ABC
2. XYZ
3. PQR
4. None of These
Input your choice (1 - 4) : 1
thanks for vote !!
###### Welcome to Election/Voting 2019 #####
1. Cast the Vote
2. Find Vote Count
0. Exit
Please enter your choice : 2
##### Voting Statics ####
ABC - 2
XYZ - 0
PQR - 0
###### Welcome to Election/Voting 2019 #####
1. Cast the Vote
2. Find Vote Count
0. Exit
Please enter your choice :
What is Content Negotiation in Asp.Net webAPI C#?

Content negotiation is the process of selecting the best representation for a given
response when there are multiple representations available. Means, depending on the
Accept header value in the request, the server sends the response. The primary
mechanism for content negotiation in HTTP are these request headers −
Accept − Which media types are acceptable for the response, such as "application/json," "application/xml," or a custom media type such as "application/vnd.example+xml"
Accept-Charset − Which character sets are acceptable, such as UTF-8 or ISO 8859-1.
Accept-Encoding − Which content encodings are acceptable, such as gzip.
Accept-Language − The preferred natural language, such as "en-us".
The server can also look at other portions of the HTTP request. For example, if the
request contains an X-Requested-With header, indicating an AJAX request, the server
might default to JSON if there is no Accept header.
In content negotiation, the pipeline gets the IContentNegotiator service from the
HttpConfiguration object. It also gets the list of media formatters from the
HttpConfiguration.Formatters collection.
Next, the pipeline calls IContentNegotiator.Negotiate, passing in −
The type of object to serialize
The collection of media formatters
The HTTP request
The Negotiate method returns two pieces of information −
Which formatter to use
The media type for the response
If no formatter is found, the Negotiate method returns null, and the client receives
HTTP error 406 (Not Acceptable).
Let us consider StudentController like below.
using DemoWebApplication.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace DemoWebApplication.Controllers{
   public class StudentController : ApiController{
      List<Student> students = new List<Student>{
         new Student{
            Id = 1,
            Name = "Mark"
         },
         new Student{
            Id = 2,
            Name = "John"
         }
      };
   }
}
One of the standards of the RESTful service is that, the client should have the ability
to decide in which format they want the response - XML, JSON etc. A request that is
sent to the server includes an Accept header. Using the Accept header the client can
specify the format for the response. For example
Accept: application/xml returns XML
Accept: application/json returns JSON
The below output shows the response is of XML when we pass the Accept Header as
application/XML.
The below output shows the response is of JSON when we pass the Accept Header as
application/JSON.
When the response is being sent to the client in the requested format, notice that the
Content-Type header of the response is set to the appropriate value. For example, if
the client has requested application/xml, the server send the data in XML format and
also sets the Content-Type=application/xml.
We can also specify quality factor. In the example below, xml has higher quality
factor than json, so the server uses XML formatter and formats the data in XML.
application/xml;q=0.8,application/json;q=0.5
What are multicasting delegates in C#?

A delegate that holds a reference to more than one method is called multicasting delegate.
Let us see an example −
using System;
delegate void myDelegate(int val1, int val2);
public class Demo {
   public static void CalAdd(int val1, int val2) {
      Console.WriteLine("{0} + {1} = {2}", val1, val2, val1 + val2);
   }

   public static void CalSub(int val1, int val2) {
      Console.WriteLine("{0} - {1} = {2}", val1, val2, val1 - val2);
   }
}

public class Program {
   static void Main() {
      myDelegate d = new myDelegate(Demo.CalAdd);
      d += new myDelegate(Demo.CalSub);
      d(45, 70);
      d -= new myDelegate(Demo.CalAdd);
      d(95, 70);
      d += new myDelegate(Demo.CalSub);
      d(88, 6);
      d -= new myDelegate(Demo.CalAdd);
      d(40, 20);
      Console.Read();
   }
}
In the above example, our delegate is −
delegate void myDelegate(int val1, int val2);
Using the following, we have set a reference to more than one method in delegates i.e. CalAdd() and CalSub() −
myDelegate d = new myDelegate(Demo.CalAdd);
d += new myDelegate(Demo.CalSub);
d(45, 70);
d -= new myDelegate(Demo.CalAdd);
d(95, 70);
d += new myDelegate(Demo.CalSub);
d(88, 6);
d -= new myDelegate(Demo.CalAdd);
d(40, 20);
PyQt - QToolBar Widget

A QToolBar widget is a movable panel consisting of text buttons, buttons with icons or other widgets.
It is usually situated in a horizontal bar below menu bar, although it can be floating. Some useful methods of QToolBar class are as follows −
addAction()
Adds tool buttons having text or icon
addSeperator()
Shows tool buttons in groups
addWidget()
Adds controls other than button in the toolbar
addToolBar()
QMainWindow class method adds a new toolbar
setMovable()
Toolbar becomes movable
setOrientation()
Toolbar’s orientation sets to Qt.Horizontal or Qt.vertical
Whenever a button on the toolbar is clicked, ActionTriggered() signal is emitted. Additionally, it sends reference to QAction object associated with the event to the connected function.
A File toolbar is added in the toolbar area by calling addToolBar() method.
tb = self.addToolBar("File")

Although tool buttons with text captions can be added, a toolbar usually contains graphic buttons. A QAction object with an icon and name is added to the toolbar.
new = QAction(QIcon("new.bmp"),"new",self)
tb.addAction(new)

Similarly, open and save buttons are added.
Finally, actionTriggered() signal is connected to a slot function toolbtnpressed()
tb.actionTriggered[QAction].connect(self.toolbtnpressed)

The complete code to execute the example is as follows −
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *

class tooldemo(QMainWindow):
   def __init__(self, parent = None):
      super(tooldemo, self).__init__(parent)
      layout = QVBoxLayout()
      tb = self.addToolBar("File")
		
      new = QAction(QIcon("new.bmp"),"new",self)
      tb.addAction(new)
		
      open = QAction(QIcon("open.bmp"),"open",self)
      tb.addAction(open)
      save = QAction(QIcon("save.bmp"),"save",self)
      tb.addAction(save)
      tb.actionTriggered[QAction].connect(self.toolbtnpressed)
      self.setLayout(layout)
      self.setWindowTitle("toolbar demo")
		
   def toolbtnpressed(self,a):
      print "pressed tool button is",a.text()
		
def main():
   app = QApplication(sys.argv)
   ex = tooldemo()
   ex.show()
   sys.exit(app.exec_())
	
if __name__ == '__main__':
   main()
The above code produces the following output −

    146 Lectures 
     22.5 hours 

 ALAA EID
 Print
 Add Notes
 Bookmark this page
JavaScript function in href vs. onClick

Both onclick & href have different behaviors when calling JavaScript directly. Also the script in href won’t get executed if the time difference is short. This is for the time between two clicks.
Here’s an example showing the usage of href vs onClick in JavaScript.
 Live Demo
<html>
   <head>
      <title>JavaScript href vs onClick()</title>
      <script>
       function myFunc() {
         var v = 0;
         for (var j=0; j<1000; j++) {
            v+=j;
         }
         alert(v);
      }
      </script>
      <a href="javascript:myFunc()">href</a>
      <a href="#" onclick="javascript:myFunc()">onclick</a>
      </head>
   <body>
   </body>
</html>
Tryit Editor v3.7

Tryit: A list with discs
How can Keras be used to save model using hdf5 format in Python?

Tensorflow is a machine learning framework that is provided by Google. It is an open−source framework used in conjunction with Python to implement algorithms, deep learning applications and much more. It is used in research and for production purposes.
The ‘tensorflow’ package can be installed on Windows using the below line of code −
pip install tensorflow
Tensor is a data structure used in TensorFlow. It helps connect edges in a flow diagram. This flow diagram is known as the ‘Data flow graph’. Tensors are nothing but multidimensional array or a list.
Keras was developed as a part of research for the project ONEIROS (Open ended Neuro−Electronic Intelligent Robot Operating System). Keras is a deep learning API, which is written in Python. It is a high−level API that has a productive interface that helps solve machine learning problems.
It runs on top of Tensorflow framework. It was built to help experiment in a quick manner. It provides essential abstractions and building blocks that are essential in developing and encapsulating machine learning solutions. It is highly scalable, and comes with cross platform abilities. This means Keras can be run on TPU or clusters of GPUs. Keras models can also be exported to run in a web browser or a mobile phone as well.
Keras is already present within the Tensorflow package. It can be accessed using the below line of code.
import tensorflow
from tensorflow import keras
We are using the Google Colaboratory to run the below code. Google Colab or Colaboratory helps run Python code over the browser and requires zero configuration and free access to GPUs (Graphical Processing Units). Colaboratory has been built on top of Jupyter Notebook. Following is the code −
print("The model is saved to HDF5 format")
model.save('my_model.h5')
print("The same model is recreated with same weights and optimizer")
new_model = tf.keras.models.load_model('my_model.h5')
print("The architecture of the model is observed")
new_model.summary()
Code credit − https://www.tensorflow.org/tutorials/keras/save_and_load
The model newly created can be saved using the ‘save’ function.
The model newly created can be saved using the ‘save’ function.
It can be specifically saved to hdf5 format using the extension ‘h5’.
It can be specifically saved to hdf5 format using the extension ‘h5’.
This model is loaded using the previous weights and optimizer.
This model is loaded using the previous weights and optimizer.
The details about the new model is displayed on the console using the ‘summary’ method.
The details about the new model is displayed on the console using the ‘summary’ method.
JavaScript Assignment

Assignment operators assign values to JavaScript variables.
The **= operator is a part of ECMAScript 2016.
The = assignment operator assigns a value to a variable.
The += assignment operator adds a value to a variable.
The -= assignment operator subtracts a value from a variable.
The *= assignment operator multiplies a variable.
The /= assignment divides a variable.
The %= assignment operator assigns a remainder to a variable.
Use the correct assignment operator that will result in x being 15 (same as x = x + y).
x = 10;
y = 5;
x  y;

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.
The image() object in JavaScript.

The image object represents the HTML  element.
Following is the code for image object in JavaScript −
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result {
      font-size: 18px;
      font-weight: 500;
      color: rebeccapurple;
   }
</style>
</head>
<body>
<h1>The image() object in JavaScript</h1>
<div class="result"><br /></div>
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to display an image</h3>
<script>
   let resEle = document.querySelector(".result");
   let BtnEle = document.querySelector(".Btn");
   let newImage = new Image(500, 300);
   newImage.src = "https://i.picsum.photos/id/195/536/354.jpg";
   BtnEle.addEventListener("click", () => {
      resEle.appendChild(newImage);
   });
</script>
</body>
</html>
The above code will produce the following output −
On clicking the ‘CLICK HERE’ button −
How to search on a MySQL varchar column using a number?

Use INSERT() function from MySQL. It has the following parameters −
Let us first create a table −
mysql> create table DemoTable
   -> (
   -> Code varchar(100)
   -> );
Query OK, 0 rows affected (0.82 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('958575/98') ;
Query OK, 1 row affected (0.16 sec)

mysql> insert into DemoTable values('765432/99');
Query OK, 1 row affected (0.19 sec)

mysql> insert into DemoTable values('983456/91');
Query OK, 1 row affected (0.15 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-----------+
| Code      |
+-----------+
| 958575/98 |
| 765432/99 |
| 983456/91 |
+-----------+
3 rows in set (0.00 sec)
Here is the query to search on a varchar column using a number −
mysql> select *from DemoTable where Code =INSERT(76543299,7,0,'/');
This will produce the following output −
+-----------+
| Code      |
+-----------+
| 765432/99 |
+-----------+
1 row in set (0.00 sec)
Null Aware Operators in Dart Programming

Dart has different null aware operators that we can use to make sure that we are not accessing the null values and to deal with them in a subtle way.
Mainly, these are −
?? operator
?? operator
??= operator
??= operator
? operator
? operator
We will go through each of them in the following article.
The ?? operator returns the first expression if and only if it is not null.
Consider the example shown below −
void main() {
   var age;
   age = age ?? 23;
   print(age);

   var name = "mukul";
   name = name ?? "suruchi";
   print(name);
}
In the above example, we declared two variables and one of them is of null value and the other is not null and contains a string value. We are using the ?? operator when reassigning values to those variables. In the first variable, since the age is null, the ?? operator will return the second value, i.e., 23 and in the second case, the name variable is not null, hence the first value will be returned from the ?? operator.
23
mukul
The ??= operator in Dart is used when we want to assign a value if and only if it is not null.
Consider the example shown below −
void main() {
   var age;
   var myAge = 24;
   myAge ??= age;
   print(myAge);
}
In the above example we have two variables, one of them is null and the other contains an int value, when we try to assign the value of the age variable to myAge variable it did nothing, as age is null and hence the ??= doesn't change the original value of myAge variable.
24
The ? operator is used when we want to make sure that we don't invoke a function of a null value. It will call a function if and only if the object is not null.
Consider the example shown below −
void main() {
   var earthMoon;
   var length = earthMoon?.length;
   print(length);
}
In the above code, we know that the variable earthMoon has null as its value, so when we try to invoke the length function on it using the ? operator nothing changed, and the length variable is also a null value.
null
MySQL - RETURN Statement

The RETURN statement in MySQL is used to end the stored functions. Each stored function should have at least one RETURN statement. This is used only in functions in stored procedures triggers or, events you can use LEAVE instead of RETURN.
Following is the syntax of the RETURN statement is MySQL −
RETURN expression

Where, expression is the value to be returned.
Following query demonstrates how to use the RETURN statement with in a function.
DELIMITER //
CREATE FUNCTION Sample (bonus INT)
   RETURNS INT
   BEGIN
      DECLARE income INT;
      SET income = 0;
      myLabel: LOOP
         SET income = income + bonus;
         IF income < 10000 THEN
            ITERATE myLabel;
         END IF;
         LEAVE myLabel;
      END LOOP myLabel;
   RETURN income;
END; //
Query OK, 0 rows affected (0.41 sec)
mysql> DELIMITER ;
You can call the above created function as shown below −
mysql> SELECT Sample(1000);
+--------------+
| Sample(1000) | 
+--------------+
| 10000        |
+--------------+
1 row in set (0.15 sec)

Suppose we have created a table named Emp in the database using the CREATE statement as shown below −
mysql> CREATE TABLE Emp(Name VARCHAR(255), DOB DATE, Location VARCHAR(255));
Query OK, 0 rows affected (2.03 sec)
And we have inserted three records in the Emp table as −
mysql> INSERT INTO Emp VALUES ('Amit', DATE('1970-01-08'), 'Hyderabad');
mysql> INSERT INTO Emp VALUES ('Sumith', DATE('1990-11-02'), 'Vishakhapatnam');
mysql> INSERT INTO Emp VALUES ('Sudha', DATE('1980-11-06'), 'Vijayawada');
Following query creates a function named getDob()which accepts the name of the employee, retrieves and returns the value of DOB column.
mysql> DELIMITER //
mysql> CREATE FUNCTION test.getDob(emp_name VARCHAR(50))
   RETURNS DATE
   DETERMINISTIC
   BEGIN
      declare dateOfBirth DATE;
      select DOB into dateOfBirth from test.emp where Name = emp_name;
      return dateOfBirth;
   END//
Query OK, 0 rows affected (0.31 sec)
mysql> DELIMITER ;
If you call the function you can get date of birth of an employee as shown below −
mysql> SELECT getDob('Amit');
+----------------+
| getDob('Amit') |
+----------------+
| 1970-01-08     |
+----------------+
1 row in set (0.15 sec)


    31 Lectures 
     6 hours 

 Eduonix Learning Solutions

    84 Lectures 
     5.5 hours 

 Frahaan Hussain

    6 Lectures 
     3.5 hours 

 DATAhill Solutions Srinivas Reddy

    60 Lectures 
     10 hours 

 Vijay Kumar Parvatha Reddy

    10 Lectures 
     1 hours 

 Harshit Srivastava

    25 Lectures 
     4 hours 

 Trevoir Williams
 Print
 Add Notes
 Bookmark this page
Toutatis - OSINT Tool to Extract Information From Instagram Account - GeeksforGeeks

22 Nov, 2021
Information collected through public sources or social networking sites helps in building a social engineering attack environment. This is an OSINT technique to gather information. Toutatis tool is an automated tool developed in the Python Language and also comes as the package with the pip in python. This tool extracts sensitive information from an Instagram social networking site. Toutatis gathers more than enough information about the target like Phone number, Email address, Profile picture, and many more. Toutatis tool is available on GitHub and also you can install it through pip install toutatis in python.
Note: Make Sure You have Python Installed on your System, as this is a python-based tool. Click to check the Installation process: Python Installation Steps on Linux
Step 1: Use the following command to install the tool in your Kali Linux operating system.
git clone https://github.com/megadose/toutatis.git
Step 2: Now use the following command to move into the directory of the tool. You have to move in the directory in order to run the tool.
cd toutatis
Step 3: Run the setup.py file to complete the installation of the tool.
sudo python3 setup.py install
Step 4: All the dependencies have been installed in your Kali Linux operating system. Now use the following command to run the tool and check the help section.
toutatis -h
Example 1: Searching data for Username 1
toutatis -u geeksforgeeks -s <InsertYourInstagramSessionId>
We have got the details of geeksforgeeks username. This information can be used in Social Engineering attacks.
Example 2: Searching data for Username 2
toutatis -u thisisbillgates -s <InsertYourInstagramSessionId>
We have got the information for username 2.
We have displayed the profile picture of the user. Although if the account is private, then to you can view the image.
Kali-Linux
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Thread functions in C/C++
Array Basics in Shell Scripting | Set 1
scp command in Linux with Examples
chown command in Linux with Examples
nohup Command in Linux with Examples
Named Pipe or FIFO with example C program
mv command in Linux with examples
SED command in Linux | Set 2
Basic Operators in Shell Scripting
Start/Stop/Restart Services Using Systemctl in Linux
How to set the font size of text with JavaScript?

To set the font size, use the fontSize property in JavaScript. You can try to run the following code to set the font size of the text with JavaScript −
<!DOCTYPE html>
<html>
   <body>
      <h1>Heading 1</h1>
      <p id = "myID">
         This is Demo Text. This is Demo Text. This is Demo Text. This is Demo Text.
         This is Demo Text. This is Demo Text. This is Demo Text. This is Demo Text.
      </p>
      <button type = "button" onclick = "display()">Set Font Family and Size</button>
      
      <script>
         function display() {
            document.getElementById("myID").style.fontFamily = "verdana,sans-serif";
            document.getElementById("myID").style.fontSize = "smaller";
         }
      </script>
      
   </body>
</html>
PostgreSQL - ROLLUP - GeeksforGeeks

26 Feb, 2021
The PostgreSQL ROLLUP belongs to the GROUP BY clause that provides a short cut for defining multiple grouping sets. Multiple columns grouped together forms a group set.
Unlike the CUBE subclause, ROLLUP does not yield all possible grouping sets based on the specified columns. It just makes a subset of those. The ROLLUP presupposes a hierarchy between the input columns and yields all grouping sets that make sense only if the hierarchy is considered. That’s why ROLLUP is usually used to generate the subtotals and the grand total for reports.
Syntax:
SELECT
    column1,
    column2,
    column3,
    aggregate(column4)
FROM
    table_name
GROUP BY
    ROLLUP (column1, column2, column3);
To better understand the concept let’s create a new table and proceed to the examples.To create a sample table use the below command:
CREATE TABLE geeksforgeeks_courses(
    course_name VARCHAR NOT NULL,
    segment VARCHAR NOT NULL,
    quantity INT NOT NULL,
    PRIMARY KEY (course_name, segment)
);
Now insert some data into it using the below command:
INSERT INTO geeksforgeeks_courses(course_name, segment, quantity)
VALUES
    ('Data Structure in Python', 'Premium', 100),
    ('Algorithm Design in Python', 'Basic', 200),
    ('Data Structure in Java', 'Premium', 100),
    ('Algorithm Design in Java', 'Basic', 300);
Now that our table is set let’s look into examples.
Example 1:The following query uses the ROLLUP subclause to find the number of products sold by course_name(subtotal) and by all course_name and segments (total) as follows:
SELECT
    course_name,
    segment,
    SUM (quantity)
FROM
    geeksforgeeks_courses
GROUP BY
    ROLLUP (course_name, segment)
ORDER BY
    course_name,
    segment;
Output:
Example 2:The following statement performs a partial ROLL UP as follows:
SELECT
    segment,
    course_name,
    SUM (quantity)
FROM
    geeksforgeeks_courses
GROUP BY
    segment,
    ROLLUP (course_name)
ORDER BY
    segment,
    course_name;
Output:
postgreSQL-grouping-sets
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL - Create Auto-increment Column using SERIAL
PostgreSQL - CREATE PROCEDURE
PostgreSQL - GROUP BY clause
PostgreSQL - DROP INDEX
PostgreSQL - REPLACE Function
PostgreSQL - Copy Table
PostgreSQL - TIME Data Type
PostgreSQL - CREATE SCHEMA
PostgreSQL - Rename Table
PostgreSQL - Cursor