code-rag-bench/online-tutorials huggingface dataset:
getters and setters in JavaScript classes?

Classes allow using getters and setters. It is smart to use getters and setters for the properties, especially if you want to do something special with the value before returning them, or before you set them. To add getters and setters in the class, use the get and set keywords.
 In the following example, getters and setters were added to the class 'Company' and the property value is obtained by using a 'get' keyword. 
Live Demo
<html>
<body>
<p id="method"></p>
<script>
   class Company {
      constructor(brand) {
         this.Compname = brand;
      }
      get name() {
         return this.Compname;
      }
      set name(x) {
         this.Compname = x;
      }
   }
   myName = new Company("Tutorialspoint");
   document.getElementById("method").innerHTML = myName.Compname;
</script>
</body>
</html>
Tutorialspoint
Python - Filter Pandas DataFrame by Time

To filter DataFrame by time, use the loc and set the condition in it to fetch records. At first, import the required library −
import pandas as pd
Create a Dictionary of list with date records −
d = {'Car': ['BMW', 'Lexus', 'Audi', 'Mercedes', 'Jaguar', 'Bentley'],'Date_of_Purchase': ['2021-07-10', '2021-08-12', '2021-06-17', '2021-03-16', '2021-05-19', '2021-08-22']
   }
Creating a dataframe from the above dictionary of lists −
dataFrame = pd.DataFrame(d)

Now, let’s say we need to fetch cars purchased after a specific date. For this, we use loc −
resDF = dataFrame.loc[dataFrame["Date_of_Purchase"] > "2021-07-15"]
Following is the complete code −
import pandas as pd

# dictionary of lists
d = {'Car': ['BMW', 'Lexus', 'Audi', 'Mercedes', 'Jaguar', 'Bentley'],'Date_of_Purchase': ['2021-07-10', '2021-08-12', '2021-06-17', '2021-03-16', '2021-05-19', '2021-08-22']
   }

# creating dataframe from the above dictionary of lists
dataFrame = pd.DataFrame(d)
print"DataFrame...\n",dataFrame

# fetch cars purchased after 15th July 2021
resDF = dataFrame.loc[dataFrame["Date_of_Purchase"] > "2021-07-15"]

# print filtered data frame
print"\nCars purchased after 15th July 2021: \n",resDF
This will produce the following output −
DataFrame...
        Car   Date_of_Purchase
0       BMW         2021-07-10
1     Lexus         2021-08-12
2      Audi         2021-06-17
3  Mercedes         2021-03-16
4    Jaguar         2021-05-19
5   Bentley         2021-08-22

Cars purchased after 15th July 2021:
       Car   Date_of_Purchase
1    Lexus         2021-08-12
5  Bentley         2021-08-22
How to find the size of an int[] in C/C++?

In this section, we will see how we can get the size of an integer array in C or C++? The size of int[] is basically counting the number of elements inside that array. To get this we can use the sizeof() operator. If the array name is passed inside the sizeof(), then it will return total size of memory blocks that are occupied by the array. Now if we divide it by the size of each element, then we can get number of elements.
Let us see the following example to get the better idea about it.
#include <iostream>
using namespace std;
int main() {
   int data[] = {11, 22, 33, 44, 55, 66, 77, 88, 99, 91, 82, 73, 64};
   cout << "Memory occupied by data[]: " << sizeof(data) << endl;
   cout << "Size of data[] array: " << sizeof(data)/sizeof(data[0]) << endl;
}
Memory occupied by data[]: 52
Size of data[] array: 13
Cryptography with Python - Reverse Cipher

The previous chapter gave you an overview of installation of Python on your local computer. In this chapter you will learn in detail about reverse cipher and its coding.
The algorithm of reverse cipher holds the following features −
Reverse Cipher uses a pattern of reversing the string of plain text to convert as cipher text.
Reverse Cipher uses a pattern of reversing the string of plain text to convert as cipher text.
The process of encryption and decryption is same.
The process of encryption and decryption is same.
To decrypt cipher text, the user simply needs to reverse the cipher text to get the plain text.
To decrypt cipher text, the user simply needs to reverse the cipher text to get the plain text.
The major drawback of reverse cipher is that it is very weak. A hacker can easily break the cipher text to get the original message. Hence, reverse cipher is not considered as good option to maintain secure communication channel,.
Consider an example where the statement This is program to explain reverse cipher is to be implemented with reverse cipher algorithm. The following python code uses the algorithm to obtain the output.
message = 'This is program to explain reverse cipher.'
translated = '' #cipher text is stored in this variable
i = len(message) - 1

while i >= 0:
   translated = translated + message[i]
   i = i - 1
print(“The cipher text is : “, translated)
You can see the reversed text, that is the output as shown in the following image −
Plain text is stored in the variable message and the translated variable is used to store the cipher text created.
Plain text is stored in the variable message and the translated variable is used to store the cipher text created.
The length of plain text is calculated using for loop and with help of index number. The characters are stored in cipher text variable translated which is printed in the last line.
The length of plain text is calculated using for loop and with help of index number. The characters are stored in cipher text variable translated which is printed in the last line.

    10 Lectures 
     2 hours 

 Total Seminars

    10 Lectures 
     2 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
Batch Script - CLS

This batch command clears the screen.
cls

@echo off 
Cls
The command prompt screen will be cleared.
What is the implicit implementation of the interface and when to use implicit implementation of the interface in C#?

C# interface members can be implemented explicitly or implicitly.
Implicit implementations don't include the name of the interface being implemented before the member name, so the compiler infers this. The members will be exposed as public and will be accessible when the object is cast as the concrete type.
The call of the method is also not different. Just create an object of the class and invoke it.
Implicit interface cannot be used if there is same method name declared in multiple interfaces
interface ICar {
   void displayCar();
}
interface IBike {
   void displayBike();
}
class ShowRoom : ICar, IBike {
   public void displayCar() {
      throw new NotImplementedException();
   }
   public void displayBike() {
      throw new NotImplementedException();
   }
}
class Program {
   static void Main() {
      ICar car = new ShowRoom();
      IBike bike = new ShowRoom();
      Console.ReadKey();
   }
}
C library function - strcspn()

The C library function size_t strcspn(const char *str1, const char *str2)  calculates the length of the initial segment of str1, which consists entirely of characters not in str2.
Following is the declaration for strcspn() function.
size_t strcspn(const char *str1, const char *str2)
str1 − This is the main C string to be scanned.
str1 − This is the main C string to be scanned.
str2 − This is the string containing a list of characters to match in str1.
str2 − This is the string containing a list of characters to match in str1.
This function returns the number of characters in the initial segment of string str1 which are not in the string str2.
The following example shows the usage of strcspn() function.
#include <stdio.h>
#include <string.h>

int main () {
   int len;
   const char str1[] = "ABCDEF4960910";
   const char str2[] = "013";

   len = strcspn(str1, str2);

   printf("First matched character is at %d\n", len + 1);
   
   return(0);
}
Let us compile and run the above program that will produce the following result −
First matched character is at 10


    12 Lectures 
     2 hours 

 Nishant Malik

    12 Lectures 
     2.5 hours 

 Nishant Malik

    48 Lectures 
     6.5 hours 

 Asif Hussain

    12 Lectures 
     2 hours 

 Richa Maheshwari

    20 Lectures 
     3.5 hours 

 Vandana Annavaram

    44 Lectures 
     1 hours 

 Amit Diwan
 Print
 Add Notes
 Bookmark this page
How to add 5 hours to current time in MySQL?

To add 5 hours in current time, we will use now() function from MySQL. The syntax is as
follows −
SELECT date_add(now(),interval some integer value hour);
Now, I am applying the above query to add 5 hours to current time. The query is as follows −
mysql> SELECT date_add(now(),interval 5 hour);

The following is the output
+---------------------------------+
| date_add(now(),interval 5 hour) |
+---------------------------------+
| 2018-10-11 15:59:23             |
+---------------------------------+
1 row in set (0.00 sec)
Look at the output above, it has increased the current time by 5 hours
C# program to find the most frequent element

Let’s say our string is −
String s = "HeathLedger!";
Now create a new array.
int []cal = new int[maxCHARS];
Create a new method and pass both the string and the new array in it. Find the maximum occurrence of a character.
static void calculate(String s, int[] cal) {
   for (int i = 0; i < s.Length; i++)
   cal[s[i]]++;
}
Let us see the complete code −
 Live Demo
using System;
class Demo {
   static int maxCHARS = 256;
   static void calculate(String s, int[] cal) {
      for (int i = 0; i < s.Length; i++)
      cal[s[i]]++;
   }

   public static void Main() {
      String s = "thisisit!";
      int []cal = new int[maxCHARS];
      calculate(s, cal);
      for (int i = 0; i < maxCHARS; i++)
      if(cal[i] > 1) {
         Console.WriteLine("Character "+(char)i);
         Console.WriteLine("Occurrence = " + cal[i] + " times");
      }
   }
}
Character i
Occurrence = 3 times
Character s
Occurrence = 2 times
Character t
Occurrence = 2 times
Program to find the Largest Number using Ternary Operator in C++

In this problem, we are given some numbers. Our task is to create a Program
to Find the Largest Number using Ternary Operator in C++.
The elements can be −
Two Numbers
Three Numbers
Four Numbers
Code Description − Here, we are given some numbers (two or three or four). We need to find the maximum element out of these numbers using a ternary
operator.
Let’s take a few examples to understand the problem,
Input − 4, 54
Output − 54
Input − 14, 40, 26
Output − 40
Input − 10, 54, 26, 62
Output − 62
We will use ternary Operator, for two, three and four element for finding the
maximum element of the four.
Implementing Ternary operator for
Two numbers (a, b),
a > b ? a : b
Three numbers (a, b, c),
(a>b) ? ((a>c) ? a : c) : ((b>c) ? b : c)
Four numbers (a, b, c, d),
(a>b && a>c && a>d) ?
   a :
   (b>c && b>d) ?
      b :
      (c>d)? c : d
Program to illustrate the working of our solution for two numbers −
 Live Demo
#include <iostream>
using namespace std;
int main() {
   int a = 4, b = 9;
   cout<<"The greater element of the two elements is "<<( (a > b) ? a :b );
   return 0;
}
The greater element of the two elements is 9
Program to illustrate the working of our solution for three numbers −
 Live Demo
#include <iostream>
using namespace std;
int findMax(int a, int b, int c){
   int maxVal = (a>b) ?
   ((a>c) ?
   a : c) :
   ((b>c) ?
   b : c);
   return maxVal;
}
int main() {
   int a = 4, b = 13, c = 7;
   cout<<"The greater element of the two elements is "<<findMax(a, b,c);
   return 0;
}
The greater element of the two elements is 13
Program to illustrate the working of our solution for four numbers −
 Live Demo
#include <iostream>
using namespace std;
int findMax(int a, int b, int c, int d){
   int maxVal= ( (a>b && a>c && a>d) ? a : (b>c && b>d) ? b : (c>d)? c : d );
   return maxVal;
}
int main() {
   int a = 4, b = 13, c = 7, d = 53;
   cout<<"The greater element of the two elements is "<<findMax(a, b, c, d);
   return 0;
}
The greater element of the two elements is 53
How to find the sum of every n values if missing values exists in the R data frame?

To find the sum of every n values in R data frame columns if there exist missing values, we can use rowsum function along with rep function that will repeat the sum for rows and na.rm=TRUE to exclude the rows with missing values. For example, if we have a data frame called df that contains 4 columns each containing twenty values with some missing values then we can find the row sums for every 5 rows by using the command rowsum(df,rep(1:5,each=4),na.rm=TRUE).
 Live Demo
x1<-sample(c(NA,rpois(2,5)),20,replace=TRUE)
x2<-sample(c(NA,rpois(2,10)),20,replace=TRUE)
df1<-data.frame(x1,x2)
df1
    x1   x2
1   4    10
2   5    10
3  NA     7
4   4     7
5   4    NA
6   5     7
7   4    NA
8  NA    NA
9   5    10
10  4    NA
11  NA   NA
12  5    NA
13  4    NA
14  4    NA
15  5    NA
16 NA    10
17 NA    NA
18  4    7
19  5    7
20 NA    NA
Finding the column sums for every 5 rows in df1 if missing values exists in the data frame −
rowsum(df1,rep(1:5,each=4),na.rm=TRUE)
   x1   x2
1  13   34
2  13    7
3  14   10
4  13   10
5   9   14
 Live Demo
y1<-sample(c(NA,rnorm(2)),20,replace=TRUE)
y2<-sample(c(NA,rnorm(2)),20,replace=TRUE)
y3<-sample(c(NA,rnorm(2)),20,replace=TRUE)
df2<-data.frame(y1,y2,y3)
df2
       y1           y2         y3
1   0.9563337   -1.1412663    0.1873961
2   2.4693175    0.5661012    0.1873961
3    NA           0.5661012   NA
4   2.4693175    NA           0.4860115
5  NA            NA           NA
6   0.9563337    NA           NA
7   0.9563337   -1.1412663   0.1873961
8   2.4693175   -1.1412663    NA
9   0.9563337    NA           0.1873961
10  2.4693175    0.5661012    0.4860115
11 NA            NA           0.4860115
12 NA           -1.1412663    0.1873961
13 NA           -1.1412663    NA
14 NA            NA           0.1873961
15  0.9563337   -1.1412663   0.4860115
16  0.9563337   -1.1412663   0.1873961
17 NA            NA          0.4860115
18  0.9563337   -1.1412663   NA
19  0.9563337   -1.1412663   NA
20  2.4693175    0.5661012   0.4860115
Finding the column sums for every 5 rows in df2 if missing values exists in the data frame −
rowsum(df2,rep(1:5,each=4),na.rm=TRUE)
     y1           y2          y3
1  5.894969  -0.009063996  0.8608037
2  4.381985  -2.282532593  0.1873961
3  3.425651  -0.575165146  1.3468152
4  1.912667  -3.423798889  0.8608037
5  4.381985  -1.716431443  0.9720230
How to use if...else statement at the command line in Python?

There are multiple ways in which you can use if else construct in the command line in python. For example, bash supports multiline statements, which you can use like:
$ python -c '
> a = True
> if a:
> print("a is true")
> '
This will give the output:
a is true
If you prefer to have the python statement in a single line, you can use the \n newline between the commands. For example,
$ python -c $'a = True\nif a: print("a is true");'
This will give the output:
a is true
Stack Program in C

We shall see the stack implementation in C programming language here. You can try the program by clicking on the Try-it button. To learn the theory aspect of stacks, click on visit previous page.
#include <stdio.h>

int MAXSIZE = 8;       
int stack[8];     
int top = -1;            

int isempty() {

   if(top == -1)
      return 1;
   else
      return 0;
}
   
int isfull() {

   if(top == MAXSIZE)
      return 1;
   else
      return 0;
}

int peek() {
   return stack[top];
}

int pop() {
   int data;
	
   if(!isempty()) {
      data = stack[top];
      top = top - 1;   
      return data;
   } else {
      printf("Could not retrieve data, Stack is empty.\n");
   }
}

int push(int data) {

   if(!isfull()) {
      top = top + 1;   
      stack[top] = data;
   } else {
      printf("Could not insert data, Stack is full.\n");
   }
}

int main() {
   // push items on to the stack 
   push(3);
   push(5);
   push(9);
   push(1);
   push(12);
   push(15);

   printf("Element at top of the stack: %d\n" ,peek());
   printf("Elements: \n");

   // print stack data 
   while(!isempty()) {
      int data = pop();
      printf("%d\n",data);
   }

   printf("Stack full: %s\n" , isfull()?"true":"false");
   printf("Stack empty: %s\n" , isempty()?"true":"false");
   
   return 0;
}
If we compile and run the above program, it will produce the following result −
Element at top of the stack: 15
Elements:
15
12
1 
9 
5 
3 
Stack full: false
Stack empty: true


    42 Lectures 
     1.5 hours 

 Ravi Kiran

    141 Lectures 
     13 hours 

 Arnab Chakraborty

    26 Lectures 
     8.5 hours 

 Parth Panjabi

    65 Lectures 
     6 hours 

 Arnab Chakraborty

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    64 Lectures 
     10.5 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page
SQL Tryit Editor v1.6

SELECT * FROM Customers
WHERE City LIKE '_ondon';
​
Edit the SQL Statement, and click "Run SQL" to see the result.
This SQL-Statement is not supported in the WebSQL Database.
The example still works, because it uses a modified version of SQL.
Your browser does not support WebSQL.
Your are now using a light-version of the Try-SQL Editor, with a read-only Database.
If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time.
Our Try-SQL Editor uses WebSQL to demonstrate SQL.
A Database-object is created in your browser, for testing purposes.
You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button.
WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object.
WebSQL is supported in Chrome, Safari, Opera, and Edge(79).
If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
How to convert an integer into a date object in Python?

You can use the fromtimestamp function from the datetime module to get a date from a UNIX timestamp. This function takes the timestamp as input and returns the datetime object corresponding to the timestamp.
import datetime
timestamp = datetime.datetime.fromtimestamp(1500000000)
print(timestamp.strftime('%Y-%m-%d %H:%M:%S'))
This will give the output −
2017-07-14 08:10:00
How to “return an object” in C++?

An object is an instance of a class. Memory is only allocated when an object is created and not when a class is defined.
An object can be returned by a function using the return keyword. A program that demonstrates this is given as follows −
 Live Demo
#include <iostream>
using namespace std;
class Point {
   private:
   int x;
   int y;
   public:
   Point(int x1 = 0, int y1 = 0) {
      x = x1;
      y = y1;
   }
   Point addPoint(Point p) {
      Point temp;
      temp.x = x + p.x;
      temp.y = y + p.y;
      return temp;
   }
   void display() {
      cout<<"x = "<< x <<"\n";
      cout<<"y = "<< y <<"\n";
   }
};
int main() {
   Point p1(5,3);
   Point p2(12,6);
   Point p3;
   cout<<"Point 1\n";
   p1.display();
   cout<<"Point 2\n";
   p2.display();
   p3 = p1.addPoint(p2);
   cout<<"The sum of the two points is:\n";
   p3.display();
   return 0;
}
The output of the above program is as follows.
Point 1
x = 5
y = 3
Point 2
x = 12
y = 6
The sum of the two points is:
x = 17
y = 9
Now, let us understand the above program.
The class Point has two data members i.e. x and y. It has a parameterized constructor and also 2 member functions. The function addPoint() adds two Point values and returns an object temp that stores the sum. The function display() prints the values of x and y. The code snippet for this is given as follows.
class Point {
   private:
   int x;
   int y;
   public:
   Point(int x1 = 0, int y1 = 0) {
      x = x1;
      y = y1;
   }
   Point addPoint(Point p) {
      Point temp;
      temp.x = x + p.x;
      temp.y = y + p.y;
      return temp;
   }
   void display() {
      cout<<"x = "<< x <<"\n";
      cout<<"y = "<< y <<"\n";
   }
};
In the function main(), 3 objects of class Point are created. First values of p1 and p2 are displayed. Then the sum of values in p1 and p2 is found and stored in p3 by calling function addPoint(). Value of p3 is displayed. The code snippet for this is given as follows.
Point p1(5,3);
Point p2(12,6);
Point p3;
cout<<"Point 1\n";
p1.display();
cout<<"Point 2\n";
p2.display();
p3 = p1.addPoint(p2);
cout<<"The sum of the two points is:\n";
p3.display();
PyQt5 – How to add multiple items to the ComboBox ?

24 Jun, 2021
In this article we will see how we can add multiple items to the combo box at single time. We know we can add item to the combo box with the help of addItem method but this method add only single item at a time. In order to add multiple items at a single time we have to use addItems method which will add all the items at once instead of one by one. 
Syntax : combo_box.addItems(item_list)Argument : It takes list as argumentAction performed : It will add all the list item to the combo box  
Below is the implementation –  
Python3
# importing librariesfrom PyQt5.QtWidgets import *from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import *from PyQt5.QtCore import *import sys  class Window(QMainWindow):     def __init__(self):        super().__init__()         # setting title        self.setWindowTitle("Python ")         # setting geometry        self.setGeometry(100, 100, 600, 400)         # calling method        self.UiComponents()         # showing all the widgets        self.show()     # method for widgets    def UiComponents(self):         # creating a combo box widget        combo_box = QComboBox(self)         # setting geometry of combo box        combo_box.setGeometry(200, 150, 120, 30)         # geek list        geek_list = ["Geek", "Geeky Geek", "Legend Geek", "Ultra Legend Geek"]         # adding list of items to combo box        combo_box.addItems(geek_list) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :  
 
sagar0719kumar
Python PyQt5-ComboBox
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Java Program to Get the Union & Intersection of Two TreeSet

28 Dec, 2020
The union of two TreeSets is a Set of all the elements present in the two TreeSets. As the set does not contain duplicate values, so the union of two TreeSets also does not have duplicate values. Union of two TreeSets can be done using the addAll() method from java.util.TreeSet. TreeSet stores distinct values in sorted order, so the union can be done using the addition of set2 to set1, the addAll() method adds all the values of set2 that not present in set1 in sorted order.
The intersection of two TreeSet is a Set of all the same elements of set1 and set2. The intersection of two TreeSets also does not contain duplicate values. The intersection of two TreeSets can be done using the retainAll() method from java.util.TreeSet. The retainAll() method removes all the elements that are not same in both the TreeSets.
Example:
Input : set1 = {10, 20, 30}
    set2 = {20, 30, 40, 50}

Output: Union = {10, 20, 30, 40, 50}
    Intersection = {20, 30}
    
Input : set1 = {a, b, c}
    set2 = {b, d, e}
Output: Union = {a, b, c, d, e}
    Intersection = {b}
Below is the implementation:
Java
// Java Program to Get the Union//& Intersection of Two TreeSet  import java.util.*;  public class GFG {    public static void main(String[] args)    {          // New TreeSet1        TreeSet<Integer> treeSet1 = new TreeSet<>();          // Add elements to treeSet1        treeSet1.add(10);        treeSet1.add(20);        treeSet1.add(30);          // New TreeSet1        TreeSet<Integer> treeSet2 = new TreeSet<>();          // Add elements to treeSet2        treeSet2.add(20);        treeSet2.add(30);        treeSet2.add(40);        treeSet2.add(50);          // Print the TreeSet1        System.out.println("TreeSet1: " + treeSet1);          // Print the TreeSet1        System.out.println("TreeSet2: " + treeSet2);          // New TreeSet        TreeSet<Integer> union = new TreeSet<>();          // Get a Union using addAll() method        union.addAll(treeSet2);        union.addAll(treeSet1);        // Print the Union        System.out.println("Union: " + union);          // New TreeSet        TreeSet<Integer> intersection = new TreeSet<>();        intersection.addAll(treeSet1);        intersection.retainAll(treeSet2);        // Print the intersection        System.out.println("Intersection: " + intersection);    }}
TreeSet1: [10, 20, 30]
TreeSet2: [20, 30, 40, 50]
Union: [10, 20, 30, 40, 50]
Intersection: [20, 30]
java-treeset
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Introduction to Java
Exceptions in Java
Java Programming Examples
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
Traverse Through a HashMap in Java
Extends vs Implements in Java
GATE | GATE CS 2013 | Question 65

13 Sep, 2021
Determine the maximum length of the cable (in km) for transmitting data at a rate of 500 Mbps in an Ethernet LAN with frames of size 10,000 bits. Assume the signal speed in the cable to be 2,00,000 km/s.(A) 1(B) 2(C) 2.5(D) 5Answer: (B)Explanation:
Data should be transmitted at the rate of 500 Mbps.
Transmission Time >= 2*Propagation Time
=> 10000/(500*1000000) <= 2*length/200000
=> length = 2km (max)
so, answer will be: (B) 2km 
Quiz of this Question
anikakapoor
GATE-CS-2013
GATE-GATE CS 2013
Computer Networks Quiz
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Create custom Turtle shapes in Python?

19 Apr, 2021
In Turtle, by default, we have an arrowhead-shaped cursor for drawing on the canvas. This can be changed to some other predefined shape or we can also create a custom shape and register it under a name. Not just that, we can even use gif format images to replace our cursor.
The shape() function is used to set the shape of the cursor. The pre-defined shapes include turtle, arrow, circle, square and triangle.  
Python3
import turtle # turtle objectc_turtle = turtle.Turtle()   # changing the cursor# shape to circlec_turtle.shape('circle')
 
The turtle module has register_shape() function for registering custom shapes.  
Syntax : turtle.register_shape(name, shape) Parameters :  
name : a string- the name of the shape to be registered.
 
shape : a tuple of tuples containing the coordinates for the custom shape.
 
 
The n-tuple argument for the shape parameter, denotes the relative position of each corner of an n-sided polygon. Let us try to create a simple diamond shape to understand this.Consider this diamond, having length of diagonal = 20, in a Cartesian plane :
 
 
 
To create this shape, we need to pass these coordinates in clockwise order.
 
Python3
import turtle # turtle objectdimond_turtle = turtle.Turtle() # the coordinates# of each cornershape =((0, 0), (10, 10), (20, 0), (10, -10)) # registering the new shapeturtle.register_shape('diamond', shape) # changing the shape to 'diamond'dimond_turtle.shape('diamond')
Using images for Turtle cursorTo use an image as the cursor, we need to pass the image file path as parameter to register_shape(). Note that this image has to be in gif format. 
Python3
import turtle # turtle objectimg_turtle = turtle.Turtle()  # registering the image# as a new shapeturtle.register_shape('example.gif') # setting the image as cursorimg_turtle.shape('example.gif')
 
arorakashish0911
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL – Array Data Type

30 Jun, 2022
PostgreSQL Supports the concept of Arrays. All data type has a companion array associated with it irrespective of the properties of  the data type.It is available even for user-defined data types.
Syntax: variable_name DATA TYPE [];
Now that we know the use and need of Arrays in PostgreSQL, let’s look into some examples. Example 1: First we create a table(say, contacts) where the phones column is defined as an array of text as follows:
CREATE TABLE contacts (
    id serial PRIMARY KEY,
    name VARCHAR (100),
    phones TEXT []
);
Now we insert some contacts to our table as follows:
INSERT INTO contacts (name, phones)
VALUES
    (
        'Raju Kumar',
        '{"(408)-589-5841"}'
    ),
    (
        'Nikhil Aggarwal',
        '{"(408)-589-5841"}'
    ),
    (
        'Anshul Aggarwal',
        '{"(408)-589-5841"}'
    ),
    (
        'Puja Singh',
        '{"(408)-589-5842", "(408)-589-58423"}'
    );
Now we query for the contact data as follows:
SELECT
    name,
    phones
FROM
    contacts;
Output:  Example 2: In the same table we created in the above example we will query to know who has the phone number (408)-589-5842 irrespective of the position of the phone number in the phone’s array, using ANY() function as follows:
SELECT
    name,
    phones
FROM
    contacts
WHERE
    '(408)-589-5842' = ANY (phones);
Output: 
surinderdawra388
postgreSQL
postgreSQL-dataTypes
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
UGC-NET | UGC NET CS 2017 Jan – III | Question 50

27 Nov, 2018
Consider a disk queue with I/O requests on the following cylinders in their arriving order:
6, 10, 12, 54, 97, 73, 128, 15, 44, 110, 34, 45 
The disk head is assumed to be at cylinder 23 and moving in the direction of decreasing number of cylinders. Total number of cylinders in the disk is 150. The disk head movement using SCAN-scheduling algorithm is:(A) 172(B) 173(C) 227(D) 228Answer:Explanation: According to SCAN disk scheduling algorithm:
When it completed its last given sequence from input, it stops.So, total disk head movement = 23+128 = 151.
So, none option matches.Quiz of this Question
UGC-NET
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to create an alert in JavaFX?

An alert is a dialog which shows pre-built dialog types. You can create an alert by instantiating the javafx.scene.control.Alert class. This class is a subclass of the Dialog class. You can create required type of dialog bypassing the respective parameter at the time of instantiation as −
Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
The following Example demonstrates the creation of an Alert.
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonBar.ButtonData;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Dialog;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
public class AlertExample extends Application {
   public void start(Stage stage) {
      //Creating a dialog
      Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
      //Setting the title
      alert.setTitle("Alert");
      ButtonType type = new ButtonType("Ok", ButtonData.OK_DONE);
      //Setting the content of the dialog
      alert.setContentText("This is a confirmmation alert");
      //Adding buttons to the dialog pane
      alert.getDialogPane().getButtonTypes().add(type);
      //Setting the label
      Text txt = new Text("Click the button to show the dialog");
      Font font = Font.font("verdana", FontWeight.BOLD, FontPosture.REGULAR, 12);
      txt.setFont(font);
      //Creating a button
      Button button = new Button("Show Dialog");
      //Showing the dialog on clicking the button
      button.setOnAction(e -> {
         alert.showAndWait();
      });
      //Creating a vbox to hold the button and the label
      HBox pane = new HBox(15);
      //Setting the space between the nodes of a HBox pane
      pane.setPadding(new Insets(50, 150, 50, 60));
      pane.getChildren().addAll(txt, button);
      //Creating a scene object
      Scene scene = new Scene(new Group(pane), 595, 300, Color.BEIGE);
      stage.setTitle("Alert");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}
MySQL INSERT INTO SELECT into a table with AUTO_INCREMENT

Let us create a table −
mysql> create table DemoTable1923
   (
   UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   UserName varchar(20)
   );
Query OK, 0 rows affected (0.00 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1923(UserId,UserName)
     select 101 as UserId,'Chris' as UserName;
Query OK, 1 row affected (0.00 sec)
Records: 1  Duplicates: 0  Warnings: 0

mysql> insert into DemoTable1923(UserId,UserName)
    select 102 as UserId,'Robert' as UserName;
Query OK, 1 row affected (0.00 sec)
Records: 1  Duplicates: 0  Warnings: 0

mysql> insert into DemoTable1923(UserId,UserName)
    select 103 as UserId,'Sam' as UserName;
Query OK, 1 row affected (0.00 sec)
Records: 1  Duplicates: 0  Warnings: 0
Display all records from the table using select statement −
mysql> select * from DemoTable1923;
This will produce the following output −
+--------+----------+
| UserId | UserName |
+--------+----------+
|    101 | Chris    |
|    102 | Robert   |
|    103 | Sam      |
+--------+----------+
3 rows in set (0.00 sec)
How to represent the mean with vertical line in a histogram created by hist function in R?

The value of mean is an important characteristic of the data to be represented by a histogram, therefore, one might want to plot it with the histogram. If the histogram is created by using hist function then we can create a vertical line on the histogram with the help of abline function by defining mean of the data for vertical argument v.
set.seed(101)
x<-rnorm(10000,2,0.75)
hist(x)
Adding a blue color line at the mean value of x in the histogram −
abline(v=mean(x),col="blue",lwd=2)
abline(v=mean(x),col="blue",lwd=8)
exit - Unix, Linux Command

exit-The exit command terminates a script, just as in a C program. It can also return a value, which is available to the script's parent process.
exit
exit-Issuing the exit command at the shell prompt will cause the shell to exit.

In some cases, if you have jobs running in the background, the shell will remind you that they are running and simply return you to the command prompt. In this case, issuing exit again will terminate those jobs and exit the shell.
Common aliases for exit include "bye", "logout", and "lo".Every command returns an exit status (sometimes referred to as a return status or exit code). A successful command returns a 0, while an unsuccessful one returns a non-zero value that usually can be interpreted as an error code. Well-behaved UNIX commands, programs, and utilities return a 0 exit code upon successful completion, though there are some exceptions.

Likewise, functions within a script and the script itself return an exit status. The last command executed in the function or script determines the exit status. Within a script, an exit nnn command may be used to deliver an nnn exit status to the shell (nnn must be an integer in the 0 - 255 range).

EXAMPLE-1:
To exit from shell:
$ exitoutput:# su ubuntuubuntu@ubuntu:~$ exitexitroot@ubuntu:/home/ubuntu#

EXAMPLE-2:
exit command is used to return the succsess/failure of functionality in script.
# cat test.sh
#!/bin/bashecho "This is a test."# Terminate our shell script with success messageexit 0
root@ubuntu:/home/ubuntu# ./test.shThis is a test.root@ubuntu:/home/ubuntu# echo $?0
root@ubuntu:/home/ubuntu# cat test.sh#!/bin/bashecho "This is a test."# Terminate our shell script with failure messageexit 1
root@ubuntu:/home/ubuntu# ./test.shThis is a test.root@ubuntu:/home/ubuntu# echo $?1

    129 Lectures 
     23 hours 

 Eduonix Learning Solutions

    5 Lectures 
     4.5 hours 

 Frahaan Hussain

    35 Lectures 
     2 hours 

 Pradeep D

    41 Lectures 
     2.5 hours 

 Musab Zayadneh

    46 Lectures 
     4 hours 

 GUHARAJANM

    6 Lectures 
     4 hours 

 Uplatz
 Print
 Add Notes
 Bookmark this page
Python - Box Plots

Boxplots are a measure of how well distributed the data in a data set is. It divides the data set into three quartiles. This graph represents the minimum, maximum, median, first quartile and third quartile in the data set. It is also useful in comparing the distribution of data across data sets by drawing boxplots for each of them.
Boxplot can be drawn calling Series.box.plot() and DataFrame.box.plot(), or DataFrame.boxplot() to visualize the distribution of values within each column.
For instance, here is a boxplot representing five trials of 10 observations of a uniform random variable on [0,1).
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.rand(10, 5), columns=['A', 'B', 'C', 'D', 'E'])
df.plot.box(grid='True')
 
Its output is as follows −

    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
How to resolve CORS issue in C# ASP.NET WebAPI?

Cross-Origin Resource Sharing (CORS) is a mechanism that uses additional HTTP headers to tell browsers to give a web application running at one origin, access to selected resources from a different origin. A web application executes a cross-origin HTTP request when it requests a resource that has a different origin (domain, protocol, or port) from its own.
For example, let us consider an application which is having its front end (UI) and back end (Service). Say the front-end is served from https://demodomain-ui.com and the backend is served from from https://demodomain-service.com/api. If an end user tries to access the application, for security reasons the browsers restrict cross-origin HTTP requests initiated from the UI.
So to overcome this, the CORS standard is needed because it allows servers to
specify not just who can access its assets, but also how the assets can be accessed.
Cross-origin requests are made using the standard HTTP request methods. Most
servers will allow GET requests, meaning they will allow resources from external
origins (say, a web page) to read their assets. HTTP requests methods like PATCH,
PUT, or DELETE. The following are the HTTP headers added by the CORS
standard −
Access-Control-Allow-Origin
Access-Control-Allow-Origin
Access-Control-Allow-Credentials
Access-Control-Allow-Credentials
Access-Control-Allow-Headers
Access-Control-Allow-Headers
Access-Control-Allow-Methods
Access-Control-Allow-Methods
Access-Control-Expose-Headers
Access-Control-Expose-Headers
Access-Control-Max-Age
Access-Control-Max-Age
Access-Control-Request-Headers
Access-Control-Request-Headers
Access-Control-Request-Method
Access-Control-Request-Method
Origin
Origin
Enabling CORS at global level −
The first is to install the Microsoft.AspNet.WebApi.Cors from the Nuget package manager.
Then Open the file App_Start/WebApiConfig.cs. Add the following code to the
WebApiConfig.Register method −
Enabling CORS at Controller and Action level −
We can also enable CORS at the controller or action method level like below.
using System.Web.Http;
using System.Web.Http.Cors;
namespace DemoWebApplication.Controllers{
   [EnableCors("*", "*", "*")] //Controller level
   public class DemoController : ApiController{
      [EnableCors("*", "*", "*")] //Action level
      public IHttpActionResult Get(int id){
         return Ok();
      }
   }
}
Similarly, we can disable the cors by using [DisableCors] attribute.
Java class Keyword

❮ Java Keywords

Create a class named "Main":
public class Main {
  public static void main(String[] args) {
    System.out.println("Hello World");
  }
}


Try it Yourself »

The class keyword is used to create a class.
Every line of code that runs in Java must be inside a class. A class should always start with an uppercase first letter, and the name of the java file must match the class name.
A class is like an object constructor. See the example below to see how we can use it to create an object.
Create an object of Main called "myObj" and print the value of x:
public class Main {
  int x = 5;

  public static void main(String[] args) {
    Main myObj = new Main();
    System.out.println(myObj.x);
  }
}


Try it Yourself »

Read more about classes and objects in our Java Classes/Objects Tutorial.

❮ Java Keywords

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.
How to insert a Python object in MySQL?

Assuming that a MySQL database named 'test' is present on the server and a table named employee is also created. Let the table have five fields fname, lname, age, gender, and salary.
Suppose we want to insert a tuple object containing data of a record defined as follows into the Msql database.
t1=('Steven', 'Assange', 21, 'M', 2001)
To establish an interface between MySQL and Python 3, you need to install the PyMySQL module. Then you can set up the connection using the following statements
import PyMySQL
# Open database connection
db = PyMySQL.connect("localhost","root","","test" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
Next step is to set up the insert query using data in the tuple
sql="insert into employee values(%s,%s,%d,%s,%d)" %t1
Now this query is executed using execute() method of the cursor object
cursor.execute(sql)
If you check the contents of the employee table, it will show a new record added to it.
SAS - Scatter Plots

A scatterplot is a type of graph which uses values from two variables plotted in a Cartesian plane. It is usually used to find out the relationship between two variables. In SAS we use PROC SGSCATTER to create scatterplots.
Please note that we create the data set named CARS1 in the first example and use the same data set for all the subsequent data sets. This data set remains in the work library till the end of the SAS session.
The basic syntax to create a scatter-plot in SAS is −
PROC sgscatter  DATA = DATASET;
   PLOT VARIABLE_1 * VARIABLE_2
   / datalabel = VARIABLE group = VARIABLE;
RUN;

Following is the description of parameters used −
DATASET is the name of data set.
DATASET is the name of data set.
VARIABLE is the variable used from the dataset.
VARIABLE is the variable used from the dataset.
In a simple scatterplot we choose two variables form the dataset and group them with respect a third variable. We can also label the data. The result shows how the two variables are scattered in the Cartesian plane.
PROC SQL;
create table CARS1 as
SELECT make, model, type, invoice, horsepower, length, weight
FROM 
SASHELP.CARS
WHERE make in ('Audi','BMW')
;
RUN;

TITLE 'Scatterplot - Two Variables';
PROC sgscatter  DATA = CARS1;
   PLOT horsepower*Invoice 
   / datalabel = make group = type grid;
   title 'Horsepower vs. Invoice for car makers by types';
RUN; 
When we execute the above code, we get the following output −
we can use an estimation parameter to predict the strength of correlation between by drawing an ellipse around the values. We use the additional options in the procedure to draw the ellipse as shown below.
proc sgscatter data = cars1; 
compare y = Invoice  x = (horsepower length)  
         / group = type  ellipse =(alpha = 0.05 type = predicted); 
title
'Average Invoice vs. horsepower for cars by length'; 
title2
'-- with 95% prediction ellipse --'
; 
format
Invoice dollar6.0;
run;

When we execute the above code, we get the following output −
We can also have a scatterplot involving more than two variables by grouping them into pairs. In the example below we consider three variables and draw a scatter plot matrix. We get 3 pairs of resulting matrix.
PROC sgscatter  DATA = CARS1;
   matrix horsepower invoice length
   / group = type;

   title 'Horsepower vs. Invoice vs. Length for car makers by types';
RUN; 

When we execute the above code, we get the following output −

    50 Lectures 
     5.5 hours 

 Code And Create

    124 Lectures 
     30 hours 

 Juan Galvan

    162 Lectures 
     31.5 hours 

 Yossef Ayman Zedan

    35 Lectures 
     2.5 hours 

 Ermin Dedic

    167 Lectures 
     45.5 hours 

 Muslim Helalee
 Print
 Add Notes
 Bookmark this page
Python - Check if two lists have any element in common

During manipulating data using python lists, we come across a situation where we need to know if two lists are entirely different from each other or they have any element in common. This can be found out by comparing the elements in the two lists with the below approaches decribed.
In a for loop we use the in clause to check in an element is present in the list or not. We will stretch this logic to compare the elements of the lists by choosing an element from first list and checking its presence in the second list. So we will have nested for loop to do this check.
 Live Demo
#Declaring lists
list1=['a',4,'%','d','e']
list2=[3,'f',6,'d','e',3]
list3=[12,3,12,15,14,15,17]
list4=[12,42,41,12,41,12]

# In[23]:

#Defining function to check for common elements in two lists
def commonelems(x,y):
   common=0
   for value in x:
      if value in y:
         common=1
   if(not common):
      return ("The lists have no common elements")
   else:
   return ("The lists have common elements")

# In[24]:

#Checking two lists for common elements
print("Comparing list1 and list2:")
print(commonelems(list1,list2))
print("\n")
print("Comparing list1 and list3:")
print(commonelems(list1,list3))
print("\n")
print("Comparing list3 and list4:")
print(commonelems(list3,list4))
Running the above code gives us the following result
Comparing list1 and list2:
The lists have common elements
Comparing list1 and list3:
The lists have no common elements
Comparing list3 and list4:
The lists have common elements
Another approach to find, if two lists have common elements is to use sets. The sets have unordered collection of unique elements. So we convert the lists into sets and then create a new set by combining the given sets. If they have some common elements then the new set will not be empty.
 Live Demo
list1=['a',4,'%','d','e']
list2=[3,'f',6,'d','e',3]

# Defining function two check common elements in two lists by converting to sets
def commonelem_set(z, x):
   one = set(z)
   two = set(x)
   if (one & two):
      return ("There are common elements in both lists:", one & two)
   else:
   return ("There are no common elements")

# Checking common elements in two lists for
z = commonelem_set(list1, list2)
print(z)

def commonelem_any(a, b):
out = any(check in a for check in b)

# Checking condition
   if out:
      return ("The lists have common elements.")
   else:
   return ("The lists do not have common elements.")

print(commonelem_any(list1, list2))
Running the above code gives us the following result
('There are common elements in both lists:', {'d', 'e'})
The lists have common elements.
What are Lvalues and Rvalues in C++?

An lvalue (locator value) represents an object that occupies some identifiable location in memory (i.e. has an address).
rvalues are defined by exclusion. Every expression is either an lvalue or an rvalue, so, an rvalue is an expression that does not represent an object occupying some identifiable location in memory.
For example, An assignment expects an lvalue as its left operand, so the following is valid −
int i = 10;
But this is not:
int i;
10 = i;
This is because i has an address in memory and is a lvalue. While 10 doesn't have an identifiable memory location and hence is an rvalue. So assigning the value of i to 10 doesn't make any sense.