code-rag-bench/online-tutorials huggingface dataset:
p5.js | translate() function

16 Apr, 2019
The translate() function in p5.js is used to specify the amount to displace objects within the display window. The x parameter is used to specify the left/right translation and y parameter is used to specify up/down translation.
Syntax:
translate(x, y, [z])
or
translate(vector)
Parameters: This function accepts three parameters as mentioned above and described below:
x: This parameter stores the value of left/right translation.
y: This parameter stores the value of up/down translation.
z: This parameter stores the value of forward/backward translation.
In another syntax, we can only provide the p5 vector object.
Below programs illustrate the translate() function in p5.js:
Example 1: This example uses translate() function to specify the amount to displace objects.
function setup() {          // Create Canvas of given size    createCanvas(580, 450);}  function draw() {          // Set the background color    background(220);          // Fill the color    fill('lightgreen');          // Set the border weight    strokeWeight(5);          // Create rectangle    rect(10, 10, 400, 300);          // Translate the rectangle    translate(30, 30);          // Create rectangle    rect(10, 10, 400, 300);          // Translate the rectangle    translate(30, 30);          // Create rectangle    rect(10, 10, 400, 300);}
Output:
Example 2: This example uses translate() function to specify the amount to displace objects within the display window.
function setup() {          // Create Canvas of given size    createCanvas(580, 450);}  function draw() {          // Set the background color    background(220);          for(var i=0, j=255; i<255, j>0; i++, j--) {        fill(i, j, i);    }          // Set the stroke weight    strokeWeight(5);          // Use translate function    translate(width / 2, height / 2);          translate(p5.Vector.fromAngle(millis() / 1000, 200));          // Create rectangle    rect(10, 10, 40, 30);}
Output:
Reference: https://p5js.org/reference/#/p5/translate
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to set default button for JFrame in Java?

To set default button for JFrame, use the setDefaultButton() method −
JFrame frame = new JFrame();
frame.getRootPane().setDefaultButton(button);
The following is an example to set default button for JFrame −
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
public class SwingDemo {
   public static void main(String args[]) {
      JButton button = new JButton("Demo Button!");
      JFrame frame = new JFrame();
      frame.setSize(500, 300);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getRootPane().setDefaultButton(button);
      button.setMnemonic(KeyEvent.VK_A);
      button.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            System.out.println("Button pressed!");
            button.setEnabled(!button.isEnabled());
         }
      });
      frame.add(button);
      frame.setVisible(true);
   }
}
On pressing the above button, the following is displayed on Console −
C++ Program to Find the Connected Components of an UnDirected Graph

Weakly or Strongly Connected for a given a undirected graph can be found out using DFS. This is a C++ program of this problem.
Begin
Function fillorder() = fill stack with all the vertices.
   a) Mark the current node as visited and print it
   b) Recur for all the vertices adjacent to this vertex
   c) All vertices reachable from v are processed by now, push v to Stack
End
Begin
Function DFS() :
   a) Mark the current node as visited and print it
   b) Recur for all the vertices adjacent to this vertex
End
#include <iostream>
#include <list>
#include <stack>
using namespace std;
class G {
   int m;
   list<int> *adj;
   //declaration of functions
   void fillOrder(int n, bool visited[], stack<int> &Stack);
   void DFS(int n, bool visited[]);
   public:
      G(int N); //constructor
      void addEd(int v, int w);
      int print();
      G getTranspose();
};
G::G(int m) {
   this->m = m;
   adj = new list<int> [m];
}
void G::DFS(int n, bool visited[]) {
   visited[n] = true; // Mark the current node as visited and print it
   cout << n << " ";
   list<int>::iterator i;
   //Recur for all the vertices adjacent to this vertex
   for (i = adj[n].begin(); i != adj[n].end(); ++i)
      if (!visited[*i])
         DFS(*i, visited);
}
G G::getTranspose() {
   G g(m);
   for (int n = 0; n< m; n++) {
      list<int>::iterator i;
      for (i = adj[n].begin(); i != adj[n].end(); ++i) {
         g.adj[*i].push_back(n);
      }
   }
   return g;
}
void G::addEd(int v, int w) {
   adj[v].push_back(w); //add w to v's list
}
void G::fillOrder(int v, bool visited[], stack<int> &Stack) {
   visited[v] = true; //Mark the current node as visited and print it
   list<int>::iterator i;
   //Recur for all the vertices adjacent to this vertex
   for (i = adj[v].begin(); i != adj[v].end(); ++i)
      if (!visited[*i])
         fillOrder(*i, visited, Stack);
         Stack.push(v);
}
int G::print() { //print the solution
   stack<int> Stack;
   bool *visited = new bool[m];
   for (int i = 0; i < m; i++)
      visited[i] = false;
      for (int i = 0; i < m; i++)
         if (visited[i] == false)
            fillOrder(i, visited, Stack);
   G graph= getTranspose(); //Create a reversed graph
   for (int i = 0; i < m; i++) //Mark all the vertices as not visited
      visited[i] = false;
   int count = 0;
   //now process all vertices in order defined by Stack
   while (Stack.empty() == false) {
      int v = Stack.top();
      Stack.pop(); //pop vertex from stack
      if (visited[v] == false) {
         graph.DFS(v, visited);
         cout << endl;
      }
      count++;
   }
   return count;
}
int main() {
   G g(5);
   g.addEd(2, 1);
   g.addEd(3, 2);
   g.addEd(1, 0);
   g.addEd(0, 3);
   g.addEd(3, 1);
   cout << "Following are strongly connected components
   in given graph \n";
   if (g.print() > 1) {
      cout << "Graph is weakly connected.";
   } else {
      cout << "Graph is strongly connected.";
   }
   return 0;
}
Following are strongly connected components in given
graph
4
0 1 2 3
Graph is weakly connected.
Byte-compile Python libraries

Python is an interpreter based language. However it internally compiles the source code to byte code when a script (.py extension) is run and afterwards the bytecode version is automatically removed. When a module (apart from the precompiled built-in modules) is first imported, its compiled version is also automatically built but saved with .pyc extension in __pycache__ folder. Subsequent calls to import same module again won't recompile the module instead uses the one already built.
However, a Python script file with .py extension can be compiled expilicitly without running it. The 'py_compile' module contains 'compile()' function for that purpose. Name of resultant .pyc file is appended by version number of Python. In case of Python 3.7, the name has 'cpython-37' suffix.
You won't need this module normally. However it can be useful when installing modules for shared use, especially if some users don't have permission to write the byte-code cache files in the directory containing the source code.
The module has a command line interface. It can be imported using –m switch as follows
E:\python37>python -m py_compile hello.py
This will create and store 'hello.cpython-37.pyc' file in __pycache__ subfolder.
The byte-compilation can also be done programmatically using compile() function in py_compile module.
import py_compile
py_compile.compile("hello.py")
The bytecode file with .pyc extension can be directly executed from command line just as normal script with .py extension.
E:\python37>python __pycache__/hello.cpython-37.pyc
However, it can be executed by interpreter of same version with which the bytecode file was compiled. If we try to run it with any other version of Python following error will be displayed.
C:\python36>python e:hello.cpython-37.pyc
RuntimeError: Bad magic number in .pyc file
The py_compile module has another function main() which compiles several source files. The files named as arguments are compiled and the resulting byte-code is cached in the normal manner. This function does not search a directory structure to locate source files; it only compiles files named explicitly.
The module also defines PyCompileError exception which is raised when an error occurs while attempting to compile the file. (This will be raised only if doraise option is set to True for compile() function.
The optimize option of compile() function controls the optimization level and is passed to the built-in compile() function. The default of -1 selects the optimization level of the current interpreter.
Query By Example (QBE) - GeeksforGeeks

09 Aug, 2021
If we talk about normal queries we fire on the database they should be correct and in a well-defined structure which means they should follow a proper syntax if the syntax or query is wrong definitely we will get an error and due to that our application or calculation definitely going to stop. So to overcome this problem QBE was introduced. QBE stands for Query By Example and it was developed in 1970 by Moshe Zloof at IBM. 
It is a graphical query language where we get a user interface and then we fill some required fields to get our proper result. 
In SQL we will get an error if the query is not correct but in the case of QBE if the query is wrong either we get a wrong answer or the query will not be going to execute but we will never get any error. 
Note-: In QBE we don’t write complete queries like SQL or other database languages it comes with some blank so we need to just fill that blanks and we will get our required result. 
Example Consider the example where a table ‘SAC’ is present in the database with Name, Phone_Number, and Branch fields. And we want to get the name of the SAC-Representative name who belongs to the MCA Branch. If we write this query in SQL we have to write it like
SELECT NAME 
FROM SAC 
WHERE BRANCH = 'MCA'"
And definitely, we will get our correct result. But in the case of QBE, it may be done as like there is a field present and we just need to fill it with “MCA” and then click on the SEARCH button we will get our required result. 
Points about QBE:  
Supported by most of the database programs.
It is a Graphical Query Language.
Created in parallel to SQL development.
 
fathah
DBMS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Deadlock in DBMS
Types of Functional dependencies in DBMS
KDD Process in Data Mining
Conflict Serializability in DBMS
Two Phase Locking Protocol
What is Temporary Table in SQL?
Introduction of Relational Algebra in DBMS
MySQL | Regular expressions (Regexp)
Difference between Where and Having Clause in SQL
Difference between File System and DBMS
Breacher - Tool To Find Admin Login Pages And EAR Vulnerabilites - GeeksforGeeks

18 Jul, 2021
Breacher is a free and open-source tool available on GitHub.  Breacher is used as an information-gathering tool. This tool can be used to get information about our target(domain). We can target any domain using  Breacher. The interactive console provides a number of helpful features, such as command completion and contextual help. This tool is written in python, so you must have python installed in your Kali Linux to use this tool. 
Breacher is a python script to find admin login pages and EAR vulnerabilities. This tool uses different libraries, such as the Big path list (789 paths). Breacher tool supports PHP, asp JSP, and HTML extensions. Before scanning the web apps for the admin panel, it checks for robots.txt. This tool also supports custom paths and follows the technique of multi-threading on demand.
Before scanning web apps. Breacher Checks for potential EAR vulnerabilities
Breacher Checks for robots.txt before scanning.
Breacher Support for custom paths to find admin panels
Breacher follows the technique of Multi-threading on demand
Breacher uses Big path list (798 paths)
Breacher Supports php, asp and html extensions.
Breacher is a python script to find admin login pages and EAR vulnerabilities
Breacher is an open source tool you can download the tool for free.
Breacher has interactive console provides a number of helpful features.
Step 1: Open your kali linux operating system and install the tool using the following command.
git clone https://github.com/s0md3v/Breacher.git
cd Breacher
Step 2: Use the following command to list out the content of the tool and use the second command to run the tool.
ls
python breacher.py
The tool is running successfully now we will see some examples of using the tool.
Example 1: Use Breacher tool to check all paths without threads
python breacher.py -u <domain>
You can see that we are getting many admin panels in the website domain. Similarly, you can use the tool to scan your own website.
Example 2: Use the Breacher tool to check all paths with PHP extensions.
python breacher.py -u <website domain> --type php 
You can see that we are getting many admin panels in the website domain. Similarly, you can use the tool to scan your domain. It can even find the robots.txt file of the web application.
Example 3: Use the Breacher tool to check all paths with PHP extensions with threads.
python breacher -u <domain> --type php --fast
Example 4: Use the Breacher tool to add a custom path.
python breacher.py -u <domain>
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
scp command in Linux with Examples
mv command in Linux with examples
Docker - COPY Instruction
SED command in Linux | Set 2
chown command in Linux with Examples
nohup Command in Linux with Examples
Named Pipe or FIFO with example C program
Thread functions in C/C++
uniq Command in LINUX with examples
Start/Stop/Restart Services Using Systemctl in Linux
GATE | GATE CS 2020 | Question 30 - GeeksforGeeks

27 Sep, 2021
If there are m input lines n output lines for a decoder that is used to uniquely address a byte addressable 1 KB RAM, then the minimum value of m+n is ________ .
Note – This question was Numerical Type.(A) 18(B) 1034(C) 10(D) 1024Answer: (B)Explanation: According to Decoder:
We need 210 outputs to map 1 KB RAM. For this we need 10 × 210 decoder.Therefore,
Here m = 10 and n = 210 
Hence,
m + n = 10 + 210 = 10 + 1024 = 1034  
Option (B) is correct.
YouTubeGeeksforGeeks GATE Computer Science16.4K subscribersCombinational Circuits Part-2 with Rishabh Setiya | GeeksforGeeks GATEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0023:37 / 37:14•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=fhyTnWhFIpA" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE MOCK 2017 | Question 24
GATE | GATE-CS-2006 | Question 47
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
Python delattr() Function - GeeksforGeeks

03 Dec, 2021
Python delattr() Function is used to delete attributes from a class. It takes two arguments, the first one is the class object from which we want to delete, second is the name of the attribute which we want to delete.
Syntax
delattr (object, name)  
Parameters
Parameter
Description
object
An object from which we want to delete the attribute
name
The name of the attribute we want to delete
The delattr() method returns a complex number.
Example 1:
A class course is created with attributes name, duration, price, rating. An instance of the class is created and now we delete the rating attribute using delattr() method. Finally, we check if the rating attribute is present or not. A try block is used to handle the keyError
class course:    name = "data structures using c++"    duration_months = 6    price = 20000    rating = 5 # creating an object of courseprint(course.rating) # deleting the rating attribute from objectdelattr(course, 'rating') # checking if the rating attribute is there or nottry:    print(course.rating)except Exception as e:    print(e)
5
type object 'course' has no attribute 'rating'
Example 2:
A class course is created with attributes name, duration, price, rating. An instance of class is created and now we delete the price attribute using delattr() method. Finally, we check if the price attribute is present or not. A try block is used to handle the keyError
class course:    name = "data structures using c++"    duration_months = 6    price = 20000    rating = 5  # creating an object of courseprint(course.price) # deleting the price attribute from objectdelattr(course, 'price') # checking if the price attribute is there or nottry:    print(course.price)except Exception as e:    print(e)
20000
type object 'course' has no attribute 'price'
surinderdawra388
Picked
Python-Functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
Python - Avoid Spaces in string length - GeeksforGeeks

05 Sep, 2020
Given a String, compute all the characters, except spaces.
Input : test_str = ‘geeksforgeeks 33 best’Output : 19Explanation : Total characters are 19.
Input : test_str = ‘geeksforgeeks best’Output : 17Explanation : Total characters are 17 except spaces.
Method #1 : Using isspace() + sum()
In this, we check for each character to be equal not to space() using isspace() and not operator, sum() is used to check frequency.
Python3
# Python3 code to demonstrate working of # Avoid Spaces in Characters Frequency# Using isspace() + sum()  # initializing stringtest_str = 'geeksforgeeks 33 is   best'  # printing original stringprint("The original string is : " + str(test_str))  # isspace() checks for space # sum checks count res = sum(not chr.isspace() for chr in test_str)      # printing result print("The Characters Frequency avoiding spaces : " + str(res)) 
The original string is : geeksforgeeks 33 is   best
The Characters Frequency avoiding spaces : 21


Method #2 : Using sum() + len() + map() + split()
In this, we perform split on spaces and extract words without spaces, then the length() of is computed using len() extended to each word using map(), the summation of all lengths computed using sum() is final result.
Python3
# Python3 code to demonstrate working of # Avoid Spaces in Characters Frequency# Using sum() + len() + map() + split()  # initializing stringtest_str = 'geeksforgeeks 33 is   best'  # printing original stringprint("The original string is : " + str(test_str))  # len() finds individual word Frequency # sum() extracts final Frequencyres = sum(map(len, test_str.split()))      # printing result print("The Characters Frequency avoiding spaces : " + str(res)) 
The original string is : geeksforgeeks 33 is   best
The Characters Frequency avoiding spaces : 21


Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
Offset Columns in Bootstrap

An offset is used to push columns over for more spacing. To use offsets on large displays, use the .col-md-offset-* classes. 
You can try to run the following code to learn how to work with offset columns in Bootstrap −
 Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Example</title>
      <link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet">
      <script src = "/scripts/jquery.min.js"></script>
      <script src = "/bootstrap/js/bootstrap.min.js"></script>
   </head>
   <body>
      <div class = "box">
         <h1>Heading One</h1>
         <div class = "row" >
            <div class = "col-xs-6 col-md-offset-3" style = "background-color: #dedef8;
               box-shadow: inset 1px -1px 1px #444, inset -1px 1px 1px #444;">
               <p>This is demo text. This is demo text.</p>
            </div>
         </div>
      </div>
   </body>
</html>
C# - Logical Operators

Following table shows all the logical operators supported by C#. Assume variable A holds Boolean value true and variable B holds Boolean value false, then −
The following example demonstrates all the logical operators available in C# −
using System;

namespace OperatorsAppl {
   class Program {
      static void Main(string[] args) {
         bool a = true; 
         bool b = true;
         
         if (a && b) {
            Console.WriteLine("Line 1 - Condition is true");
         }
         
         if (a || b) {
            Console.WriteLine("Line 2 - Condition is true");
         }
         
         /* lets change the value of  a and b */
         a = false;
         b = true;
         
         if (a && b) {
            Console.WriteLine("Line 3 - Condition is true");
         } else {
            Console.WriteLine("Line 3 - Condition is not true");
         }
         
         if (!(a && b)) {
            Console.WriteLine("Line 4 - Condition is true");
         }
         Console.ReadLine();
      }
   }
}
When the above code is compiled and executed, it produces the following result −
Line 1 - Condition is true
Line 2 - Condition is true
Line 3 - Condition is not true
Line 4 - Condition is true


    119 Lectures 
     23.5 hours 

 Raja Biswas

    37 Lectures 
     13 hours 

 Trevoir Williams

    16 Lectures 
     1 hours 

 Peter Jepson

    159 Lectures 
     21.5 hours 

 Ebenezer Ogbu

    193 Lectures 
     17 hours 

 Arnold Higuit

    24 Lectures 
     2.5 hours 

 Eric Frick
 Print
 Add Notes
 Bookmark this page
How can I create a stacked line graph with matplotlib?

To create a stacked lines graph with Python, we can take the following Steps −
Create x, y, y1 and y2 points using numpy.
Create x, y, y1 and y2 points using numpy.
Plot the lines using numpy with the above data (Step 1) and labels mentioned.
Plot the lines using numpy with the above data (Step 1) and labels mentioned.
Fill the color between curve y=e^x and y=0, using the fill_between() method.
Fill the color between curve y=e^x and y=0, using the fill_between() method.
Fill the color between curve y=2x and y=0, using the fill_between() method.
Fill the color between curve y=2x and y=0, using the fill_between() method.
Fill the color between curve y=log(x) and y=0, using fill_between() method.
Fill the color between curve y=log(x) and y=0, using fill_between() method.
Place the curve text using the legend() method.
Place the curve text using the legend() method.
To display the figure, use the show() method.
To display the figure, use the show() method.
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
x = np.linspace(1, 5, 100)
y = x * 2
y1 = np.log(x)
y2 = np.exp(x)

plt.plot(x, y, label=r'$y=2^x$')
plt.plot(x, y1, label=r'$y=\log{x}$')
plt.plot(x, y2, label=r'$y=e^x$')
plt.fill_between(x, y2, 0, color='orange')
plt.fill_between(x, y, 0, color='blue')
plt.fill_between(x, y1, 0, color='red')
plt.legend()
plt.show()
How to inject JavaScript in WebBrowser control?

To inject JavaScript in WebBrowser control, use the following steps −
 Firstly, create a Windows Forms application in Visual Studio.
 Now, drag a WebBrowser control to the form
 Set the Url property.
 Right-click the project, choose to Add reference... → COM → Type Libraries
 Select "Microsoft HTML Object Library"
  Add the following code to inject JavaScript.
private void myWebBrowser(object sender, WebBrowserDocumentCompletedEventArgs e){
 
   // head element
   HtmlElement hElement = weBrowser.Document.GetElementsByTagName("head")[0];

   // script element
   HtmlElement sElement = weBrowser.Document.CreateElement("script");
   IHTMLScriptElement val = (IHTMLScriptElement)sElement.DomElement;

   element.text = "function sayHello() {
      alert('Weclome')
   }";
   hElement.AppendChild(sElement);
   weBrowser.Document.InvokeScript("How you doing?");
}
Program to check we can make arithmetic progression from sequence in Python

Suppose we have a list of numbers called nums. We have to check whether the elements present in nums are forming AP series or not. As we know in AP (Arithmetic Progression) series the common difference between any two consecutive elements is the same.
So, if the input is like nums = [9,1,17,5,13], then the output will be True because if we sort them, it will be [1,5,9,13,17] and here common difference is 4 for each pair of elements.
To solve this, we will follow these steps −
nums := sort the list nums
nums := sort the list nums
if number of elements in nums > 1, thenconst := nums[1] - nums[0]
if number of elements in nums > 1, then
const := nums[1] - nums[0]
const := nums[1] - nums[0]
otherwise,return True
otherwise,
return True
return True
for i in range 0 to size of nums -1, doif nums[i+1] - nums[i] is not same as const, thenreturn False
for i in range 0 to size of nums -1, do
if nums[i+1] - nums[i] is not same as const, thenreturn False
if nums[i+1] - nums[i] is not same as const, then
return False
return False
return True
return True
Let us see the following implementation to get better understanding −
 Live Demo
def solve(nums):
   nums = sorted(nums)

   if len(nums) > 1:
      const = nums[1] - nums[0]
   else:
      return True
   for i in range(len(nums)-1):
      if nums[i+1] - nums[i] != const:
         return False
   return True

nums = [9,1,17,5,13]
print(solve(nums))
[9,1,17,5,13]
True
Setting the focus to a specific Tkinter entry widget

Tkinter has many universal methods that add functionalities to widgets and elements. In order to set the focus to a particular widget, we have the focus_set() method which is used to focus a specific widget in a group of widgets present in an application.
In this example, we have created numeric keys in the range 0-9. We have set the focus for Numeric key ‘2’.
#Import the required libraries
from tkinter import *
import webbrowser
#Create an instance of tkinter frame
win = Tk()
win.geometry("750x400")
#Define function for different operations
def close():
   win.destroy()
#Create a Label widget
text=Label(win, text="", font=('Helvetica bold ',25))
text.place(x= 110, y= 50,)
#Create Button widgets
b1=Button(win, text= "1")
b1.place(x=220, y=20)
b2=Button(win, text= "2")
b2.place(x=250, y=20)
b3=Button(win, text= "3")
b3.place(x=280, y=20)
b4=Button(win, text= "4")
b4.place(x=220, y=50)
b5=Button(win, text= "5")
b5.place(x=250, y=50)
b6=Button(win, text= "6")
b6.place(x=280, y=50)
b7=Button(win, text= "7")
b7.place(x=280, y=80)
b8=Button(win, text= "8")
b8.place(x=250, y=80)
b9=Button(win, text= "9")
b9.place(x=280, y=80)
b0=Button(win, text= "0")
b0.place(x=220, y=80)
#Set the focus on button b1
b2.focus_set()
b2=Button(win, text= "Close", command= close)
b2.place(x=240,y= 140)
win.mainloop()
Running the above code will display the focus for numeric key ‘2’.
To change the focus of the widget, just add the focus_set.() method to the widget you want to set focus on.
Java program to generate a calculator using the switch case

The following program accepts two integer variables, takes an operator regarding the operation. According to the selected operator, the program performs the respective operation and print the result.
import java.util.Scanner;
public class ab39_CalculatorUsingSwitch {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter value of 1st number ::");
      int a = sc.nextInt();

      System.out.println("Enter value of 2nd number ::");
      int b = sc.nextInt();

      System.out.println("Select operation");
      System.out.println("Addition-a: Subtraction-s: Multiplication-m: Division-d: ");
      char ch = sc.next().charAt(0);
      switch(ch) {
         case 'a' :
         System.out.println("Sum of the given two numbers: "+(a+b));
         break;
         case 's' :
         System.out.println("Difference between the two numbers: "+(a-b));
         break;
         case 'm' :
         System.out.println("Product of the two numbers: "+(a*b));
         case 'd' :
         System.out.println("Result of the division: "+(a/b));
         break;
         default :
         System.out.println("Invalid grade");
      }
   }
}
Enter value of 1st number ::
52
Enter value of 2nd number ::
85
Select operation
Addition-a: Subtraction-s: Multiplication-m: Division-d:
a
Sum of the given two numbers: 137
Erlang - register

This is used to register a process in the system.
register(atom,pid)

atom − This is the registered name to give to the process.
atom − This is the registered name to give to the process.
Pid − this is the process id which needs to be bound to the atom.
Pid − this is the process id which needs to be bound to the atom.
None
-module(helloworld). 
-export([start/0, call/2]). 

call(Arg1, Arg2) -> 
   io:fwrite("~p~n",[Arg1]). 

start() -> 
   Pid = spawn(?MODULE, call, ["hello", "process"]), 
   register(myprocess, Pid), 
   io:fwrite("~p~n",[registered()]).
When we run the above program, we will get the following result.
[kernel_safe_sup,rex,erl_prim_loader,kernel_sup,inet_db,global_name_server,
code_server,file_server_2,application_controller,init,user,standard_error,
global_group,error_logger,standard_error_sup,myprocess]
"hello"

 Print
 Add Notes
 Bookmark this page
Program to Implement Queue in Python

When it is required to implement a queue using Python, a queue class is created, and methods to add and delete elements are defined. An instance of the class is created, and these methods are called using the instance and relevant output is displayed.
Below is a demonstration of the same −
 Live Demo
class Queue_struct:
   def __init__(self):
      self.items = []

   def check_empty(self):
      return self.items == []

   def enqueue_elem(self, data):
      self.items.append(data)

   def dequeue_elem(self):
      return self.items.pop(0)

my_instance = Queue_struct()
while True:
   print('Enqueue <value>')
   print('Dequeue')
   print('Quit')
   my_input = input('What operation would you perform ? ').split()

   operation = my_input[0].strip().lower()
   if operation == 'Enqueue':
      my_instance.enqueue_elem(int(my_input[1]))
   elif operation == 'Dequeue':
      if my_instance.check_empty():
         print('The queue is empty...')
      else:
         print('The deleted value is : ', my_instance.dequeue_elem())
   elif operation == 'Quit':
      break
Enqueue <value>
Dequeue
Quit
What operation would you perform ? Enqueue 45
Enqueue <value>
Dequeue
Quit
What operation would you perform ? Enqueue 56
Enqueue <value>
Dequeue
Quit
What operation would you perform ? Enqueue 89
Enqueue <value>
Dequeue
Quit
What operation would you perform ? Dequeue
Enqueue <value>
Dequeue
Quit
What operation would you perform ? Dequeue
Enqueue <value>
Dequeue
Quit
What operation would you perform ? Quit
The ‘Queue_struct’ class with required attributes is created.
The ‘Queue_struct’ class with required attributes is created.
It has an ‘init’ function that is used to create an empty list.
It has an ‘init’ function that is used to create an empty list.
Another method named ‘check_empty’ that checks to see if a list is empty.
Another method named ‘check_empty’ that checks to see if a list is empty.
Another method named ‘enqueue_elem’ is defined that adds elements to the empty list.
Another method named ‘enqueue_elem’ is defined that adds elements to the empty list.
A method named ‘dequeue_elem’ is defined, that deletes elements from the list.
A method named ‘dequeue_elem’ is defined, that deletes elements from the list.
An object of the ‘Queue_struct’ class is created.
An object of the ‘Queue_struct’ class is created.
The user input is taken for the operation that needs to be performed.
The user input is taken for the operation that needs to be performed.
Depending on the user’ choice, the operation is performed.
Depending on the user’ choice, the operation is performed.
Relevant output is displayed on the console.
Relevant output is displayed on the console.
Can we create an object for the abstract class in java?

A method which does not have body is known as abstract method. It contains only method signature with a semi colon and, an abstract keyword before it.
public abstract myMethod();
To use an abstract method, you need to inherit it by extending its class and provide implementation to it.
A class which contains 0 or more abstract methods is known as abstract class. If it contains at least one abstract method, it must be declared abstract.
Once a class is abstract it indicates that it may contain incomplete methods hence you cannot create an object of the abstract class.
If you try to instantiate an abstract class a compile time error is generated saying “class_name is abstract; cannot be instantiated”.
In the following Java example, we have an abstract class MyClass which contains an concrete method with name display. We are trying to instantiate this class using the new keyword.
abstract class MyClass {
   public abstract void display() {
      System.out.println("This is a method of abstract class");
   }
   public static void main(String args[]) {
      new MyClass();
   }
}
On compiling this class generates a compile time error as −
MyClass.java:6: error: MyClass is abstract; cannot be instantiated
   new MyClass();
^
1 error
mformat - Unix, Linux Command

The mformat command is used to add an MS-DOS filesystem to a
low-level formatted diskette. Its syntax is:



mformat [-t cylinders] [-h heads] [-n sectors]
  [-f size] [-1] [-4] [-8]
  [-v volume_label]
  [-F] [-S sizecode] [-X]
  [-2 sectors_on_track_0] [-3]
  [-0 rate_on_track_0] [-A rate_on_other_tracks]
  [-M software_sector_size]
  [-N serial_number] [-a]
  [-C] [-H hidden_sectors] [-I fsVersion]
  [-r root_sectors] [-L fat_len]
  [-B boot_sector] [-k]
  [-m media_descriptor]
  drive:




Mformat adds a minimal MS-DOS filesystem (boot sector, FAT, and
root directory) to a diskette that has already been formatted by a Unix
low-level format.


The following options are supported: (The S, 2, 1 and M options may not
exist if this copy of mtools has been compiled without the USE_2M
option)


The following options are the same as for Dos’s format command:




Mformat returns 0 on success or 1 on failure.


It doesn’t record bad block information to the Fat, use
mbadblocks for that.






    ./configure; make dvi; dvips mtools.dvi






    ./configure; make html


A premade html can be found at:
oohttp://mtools.linux.luI
and also at:
oohttp://www.tux.org/pub/knaff/mtoolsI




    ./configure; make info















Advertisements


    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
How to pull value from array of ObjectIDs in MongoDB?

To pull value from array of ObjectIDs, use $pull in MongoDB. Let us create a collection with documents −
> db.demo258.insertOne({"arrayOfObjectsId":[ ObjectId("5e47a5e81627c0c63e7dba92"),ObjectId("5e47a5e51627c0c63e7dba91")]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e47a8211627c0c63e7dba97")
}
Display all documents from a collection with the help of find() method −
> db.demo258.find();
This will produce the following output −
{ "_id" : ObjectId("5e47a8211627c0c63e7dba97"), "arrayOfObjectsId" : [ ObjectId("5e47a5e81627c0c63e7dba92"), ObjectId("5e47a5e51627c0c63e7dba91") ] }
Following is the query to pull value from array of ObjectIDs −
> db.demo258.update( { }, { $pull: { arrayOfObjectsId: { $in: [ ObjectId("5e47a5e81627c0c63e7dba92") ] } } } );
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo258.find();
This will produce the following output −
{ "_id" : ObjectId("5e47a8211627c0c63e7dba97"), "arrayOfObjectsId" : [ ObjectId("5e47a5e51627c0c63e7dba91") ] }
HTML5 video full preload in JavaScript

Use the oncanplaythrough event to completely preload video. You can try to run the following code.
<!DOCTYPE html>
<html>
   <body>
      <video id="myVideo" width="400" height="200" controls oncanplaythrough="display()">
         <source src="/html5/foo.ogg" type="video/ogg" />
         <source src="/html5/foo.mp4" type="video/mp4" />
         Your browser does not support the video element.
      </video>
      <script>
         function display() {
            alert("Can be played without pausing for buffering.");
        }
</script>
</body>
</html>
How to draw sine waves with HTML5 SVG?

To draw sine waves with SVG, use the following that closely approximates half of a sine wave. I have used a cubic-bezier approximation. Use the <path> element.
<!DOCTYPE html>
<html>
   <head>
      <title>SVG</title>
      <meta charset = "utf-8" />
   </head>
   <body>
      <h2 align = "center">HTML5 SVG Sine Waves</h2>
      <svg width = "150px" height = "200px" viewBox = "0 0 100 100">
         <path stroke = "#00FF00" fill = "none" d = "M0,0 C36.42,0,70.58,100,100,100" />
      </svg>
   </body>
</html>
Python PIL | composite() method

15 Nov, 2021
Syntax: PIL.Image.composite(image1, image2, mask)
Parameters:image1 – The first image.image2 – The second image. Must have the same mode and size as the first image.mask – A mask image. This image can have mode “1”, “L”, or “RGBA”, and must have the same size as the other two images.
# Importing Image module from PIL packagefrom PIL import Image  # creating a image1 object and converting it to mode 'L'im1 = Image.open(r"C:\Users\sadow984\Desktop\c2.PNG").convert('L')  im1.show()
Showing image1:
# Importing Image module from PIL packagefrom PIL import Image  # creating a image1 object and converting it to mode 'L'im2 = Image.open(r"C:\Users\sadow984\Desktop\i2.PNG").convert('L')im2.show()
Showing image2:
# Importing Image module from PIL packagefrom PIL import Image  # creating a image1 object and converting it to mode 'L'mask = Image.open(r"C:\Users\sadow984\Desktop\i3.PNG").convert('L')mask.show()
Showing mask image:
# Importing Image module from PIL packagefrom PIL import Image  # creating a image1 object and converting it to mode 'L'im1 = Image.open(r"C:\Users\sadow984\Desktop\c2.PNG").convert('L')  # creating a image2 object and converting it to mode 'L'im2 = Image.open(r"C:\Users\sadow984\Desktop\i2.PNG").convert('L')  # creating a mask image object and converting it to mode 'L'mask = Image.open(r"C:\Users\sadow984\Desktop\i3.PNG").convert('L')  # compositing all the three imagesim3 = Image.composite(im1, im2, mask)  # to show specified image im3.show()
Output: [the composite image]
sagar0719kumar
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – Find consecutive dates in a list of dates

16 May, 2021
Given a list of dates, the task is to write a Python program to check if all the dates are consecutive in the list.
Input : [datetime(2019, 12, 30), datetime(2019, 12, 31), datetime(2020, 1, 1), datetime(2020, 1, 2), datetime(2020, 1, 3), datetime(2020, 1, 4)]
Output : True
Explanation : All dates are consecutive, from 30 Dec 2019 to 4 January 2020.
Input : [datetime(2019, 12, 29), datetime(2019, 12, 31), datetime(2020, 1, 1), datetime(2020, 1, 2), datetime(2020, 1, 3), datetime(2020, 1, 4)]
Output : False
Explanation : Non consecutive dates.
Method #1 : Using days() + loop
In this, we check consecutive dates by checking days difference from the previous date using days(). The iteration of all dates is done using a loop.
Python3
# Python3 code to demonstrate working of# Test if dates are consecutive# Using days() + loopfrom datetime import datetime, timedelta  # initializing listtest_list = [datetime(2019, 12, 30), datetime(2019, 12, 31),              datetime(2020, 1, 1), datetime(2020, 1, 2),             datetime(2020, 1, 3), datetime(2020, 1, 4)]  # printing original listprint("The original list is : " + str(test_list))  # using loop for iterating all elementsres = Truefor idx in range(1, len(test_list)):      # checking for 1 day time difference    if (test_list[idx] - test_list[idx - 1]).days != 1:        res = False        break  # printing resultprint("Are dates consecutive : " + str(res))
Output:
The original list is : [datetime.datetime(2019, 12, 30, 0, 0), datetime.datetime(2019, 12, 31, 0, 0), datetime.datetime(2020, 1, 1, 0, 0), datetime.datetime(2020, 1, 2, 0, 0), datetime.datetime(2020, 1, 3, 0, 0), datetime.datetime(2020, 1, 4, 0, 0)]
Are dates consecutive : True
Method #2 : Using all() + days()
Similar to the above method, the only difference here is all() is used to check for each day consecution for a more compact solution.
Python3
# Python3 code to demonstrate working of# Test if dates are consecutive# Using all() + days()from datetime import datetime, timedelta  # initializing listtest_list = [datetime(2019, 12, 30), datetime(2019, 12, 31),              datetime(2020, 1, 1), datetime(2020, 1, 2),             datetime(2020, 1, 3), datetime(2020, 1, 4)]  # printing original listprint("The original list is : " + str(test_list))  # using loop for iterating all elementsres = all((test_list[idx] - test_list[idx - 1]).days ==          1 for idx in range(1, len(test_list)))  # printing resultprint("Are dates consecutive : " + str(res))
Output:
The original list is : [datetime.datetime(2019, 12, 30, 0, 0), datetime.datetime(2019, 12, 31, 0, 0), datetime.datetime(2020, 1, 1, 0, 0), datetime.datetime(2020, 1, 2, 0, 0), datetime.datetime(2020, 1, 3, 0, 0), datetime.datetime(2020, 1, 4, 0, 0)]
Are dates consecutive : True
Python datetime-program
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL | LIMIT Clause

06 Nov, 2019
If there are a large number of tuples satisfying the query conditions, it might be resourceful to view only a handful of them at a time.
The LIMIT clause is used to set an upper limit on the number of tuples returned by SQL.
It is important to note that this clause is not supported by all SQL versions.
The LIMIT clause can also be specified using the SQL 2008 OFFSET/FETCH FIRST clauses.
The limit/offset expressions must be a non-negative integer.
Example:Say we have a relation, Student.Student Table:
Queries
SELECT *
FROM Student
LIMIT 5;

Output:
SELECT *
FROM Student
ORDER BY Grade DESC
LIMIT 3;

Output:
The LIMIT operator can be used in situations such as the above, where we need to find the top 3 students in a class and do not want to use any condition statements.
Using LIMIT along with OFFSET
LIMIT x OFFSET y simply means skip the first y entries and then return the next x entries.OFFSET can only be used with ORDER BY clause. It cannot be used on its own.OFFSET value must be greater than or equal to zero. It cannot be negative, else returns error.Queries:
SELECT *
FROM Student
LIMIT 5 OFFSET 2
ORDER BY ROLLNO;

Output:
Using LIMIT ALL
LIMIT ALL implies no limit.
SELECT *
FROM Student
LIMIT ALL;

The above query simply returns all the entries in the table.
This article is contributed by Anannya Uberoi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
guruvishnu_desireddy
ManasChhabra2
SQL-Clauses-Operators
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
User defined function in MATLAB

20 Aug, 2020
Functions let you do a specific task. User defined functions are the functions created by the users according to their needs. This article explains how the user defined function in MATLAB is created.
Syntax : function [a1,...,an] = func(x1,...,xm)func is the function namea1,...,an are outputsx1,...,xm are inputsFunction name is required, whereas input and output arguments are optional.
For making a user defined function in MATLAB, go to Home -> New -> Function. The function template appears as-
function [outputArg1,outputArg2] = untitled(inputArg1,inputArg2)
    % UNTITLED Summary of this function goes here
    % Detailed explanation goes here
    outputArg1 = inputArg1;
    outputArg2 = inputArg2;
end
Change the function name and save the file with the changes made. Save the file either in the current folder or in a folder on the MATLAB search path. The name of the function and the file should be same. For example, to create a function for calculating factorial, the code is:
function f = fact(n)    f = 1;    i = 1;    while i <= n        f = f * i;        i = i + 1;    endend
Save it and it can be run from the command window. The value of the fact() function returned, can also be stored in a variable. Code output for different values of n being passed :
MATLAB
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
System Design Tutorial
ML | Linear Regression
Reinforcement learning
ML | Monte Carlo Tree Search (MCTS)
Docker - COPY Instruction
Supervised and Unsupervised learning
Markov Decision Process
Decision Tree Introduction with example
Getting started with Machine Learning
How to Run a Python Script using Docker?