code-rag-bench/online-tutorials huggingface dataset:
wxPython - Create Static Box using Create() method - GeeksforGeeks

08 Jul, 2020
In this article we are going to learn about Static Box in wxPython. A static box is a rectangle drawn around other windows to denote a logical grouping of items.In this article we will create Static Box using two step creation, in order to do that we will use Create() method.
Syntax: wx.StaticBox.Create(parent, id=ID_ANY, label=””, pos=DefaultPosition, size=DefaultSize, style=0, name=StaticBoxNameStr)
Parameters
Return Type: bool
Code Example:
import wx    class FrameUI(wx.Frame):      def __init__(self, parent, title):        super(FrameUI, self).__init__(parent, title = title, size =(300, 200))          # function for in-frame components        self.InitUI()      def InitUI(self):        # parent panel for radio box        pnl = wx.Panel(self)            # initialize static box        self.sb = wx.StaticBox()                 # create static box        self.sb.Create(pnl, 2, label ="Static Box", pos =(20, 20), size =(100, 100))          # set frame in centre        self.Centre()        # set size of frame        self.SetSize((400, 250))        # show output frame        self.Show(True)      # wx App instanceex = wx.App()# Example instanceFrameUI(None, 'RadioButton and RadioBox')ex.MainLoop()
Output Window:
Python wxPython-StaticBox
Python-gui
Python-wxPython
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Reading and Writing to text files in Python
Python Pandas - Extract the quarter of the date from the DateTimeIndex with specific time series frequency

To extract the quarter of the date from the DateTimeIndex with specific time series frequency, use the DateTimeIndex.quarter.
At first, import the required libraries −
import pandas as pd
Create a DatetimeIndex with period 6 and frequency as M i.e. Month. The timezone is Australia/Sydney −
datetimeindex = pd.date_range('2021-10-20 02:30:50', periods=6, tz='Australia/Sydney', freq='2M')

Display DateTimeIndex frequency −
print("DateTimeIndex frequency...\n", datetimeindex.freq)
Get the quarter of the date −
print("\nGet the quarter of the date..\n",datetimeindex.quarter)

Result is based on the following quarters of an year −
Quarter 1 = 1st January to 31st March
Quarter 2 = 1st April to 30th June
Quarter 3 = 1st July to 30th September
Quarter 4 = 1st October to 31st December
Following is the code −
import pandas as pd

# DatetimeIndex with period 6 and frequency as M i.e. Month
# The timezone is Australia/Sydney
datetimeindex = pd.date_range('2021-10-20 02:30:50', periods=6, tz='Australia/Sydney', freq='2M')

# display DateTimeIndex
print("DateTimeIndex...\n", datetimeindex)

# display DateTimeIndex frequency
print("DateTimeIndex frequency...\n", datetimeindex.freq)

# Get the quarter of the date
# Result is based on the following quarters of an year:
# Quarter 1 = 1st January to 31st March
# Quarter 2 = 1st April to 30th June
# Quarter 3 = 1st July to 30th September
# Quarter 4 = 1st October to 31st December
print("\nGet the quarter of the date..\n",datetimeindex.quarter)
This will produce the following code −
DateTimeIndex...
DatetimeIndex(['2021-10-31 02:30:50+11:00', '2021-12-31 02:30:50+11:00',
'2022-02-28 02:30:50+11:00', '2022-04-30 02:30:50+10:00',
'2022-06-30 02:30:50+10:00', '2022-08-31 02:30:50+10:00'],
dtype='datetime64[ns, Australia/Sydney]', freq='2M')
DateTimeIndex frequency...
<2 * MonthEnds>

Get the quarter of the date..
Int64Index([4, 4, 1, 2, 2, 3], dtype='int64')
How to create a breadcrumb navigation with CSS?

Following is the code to create breadcrumb navigation using CSS −
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
   margin: 0px;
   margin-top: 10px;
   padding: 0px;
}
.breadcrumb {
   background-color: rgb(39, 39, 39);
   overflow: auto;
   height: auto;
}
li {
   display: inline-block;
   text-align: center;
   padding: 10px;
   font-size: 17px;
}
.links {
   text-decoration: none;
   color: rgb(178, 137, 253);
}
.links:hover {
   text-decoration: underline;
}
.breadcrumb ul li:before {
   padding: 8px;
   color: white;
   content: "/\00a0";
   text-decoration: none;
}
ul:last-child {
   color: white;
   font-weight: bolder;
   font-family: monospace;
}
</style>
</head>
<body>
<h1>Breadcrumb Navigation Example</h1>
<div class="breadcrumb">
<ul>
<li><a class="links" href="#">Root</a></li>
<li><a class="links" href="#">Home</a></li>
<li><a class="links" href="#">User</a></li>
<li><a class="links" href="#">Desktop</a></li>
<li>Games</li>
</ul>
</div>
<h2>Hover over the links to see effect</h2>
</body>
</html>
The above code will produce the following output −
Create a yellow button (warning) with Bootstrap

Use the .btn-warning class in Bootstrap to create a yellow button that indicates warning in Bootstrap.
You can try to run the following code to implement the .btn-warning class −
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Example</title>
      <link rel = "stylesheet" href = "https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <script src = "https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
   </head>
   <body>
      <button type = "button" class = "btn btn-warning">You are WARNED!</button>
   </body>
</html>
Sort by subdocument in MongoDB

To sort by subdocument, use $sort in MongoDB. Let us create a collection with documents −
> db.demo245.insertOne(
...   {
...      "_id": 101,
...      "deatils": [
...         { "DueDate": new ISODate("2019-01-10"), "Value": 45},
...         {"DueDate": new ISODate("2019-11-10"), "Value": 34 }
...      ]
...   }
...);
{ "acknowledged" : true, "insertedId" : 101 }
> db.demo245.insertOne(
...   {
...      "_id": 102,
...      "details": [
...         { "DueDate": new ISODate("2019-12-11"), "Value": 29},
...         {"DueDate": new ISODate("2019-03-10"), "Value":  78}
...      ]
...   }
...);
{ "acknowledged" : true, "insertedId" : 102 }
Display all documents from a collection with the help of find() method −
> db.demo245.find();
This will produce the following output −
{
   "_id" : 101, "deatils" : [
      { "DueDate" : ISODate("2019-01-10T00:00:00Z"), "Value" : 45 },
      { "DueDate" : ISODate("2019-11-10T00:00:00Z"), "Value" : 34 }
   ]
}
{
   "_id" : 102, "details" : [
      { "DueDate" : ISODate("2019-12-11T00:00:00Z"), "Value" : 29 },
      { "DueDate" : ISODate("2019-03-10T00:00:00Z"), "Value" : 78 } \
   ] 
}
Following is the query to sort by subdocument −
> db.demo245.aggregate([
...   { "$unwind": "$details" },
...   { "$sort": { "_id": 1, "details.Value": -1 } },
...   { "$group": {
...      "_id": "$_id",
...      "details": { "$push": "$details" }
...   }},
...   { "$sort": { "details.Value": -1 } }
...])
This will produce the following output −
{ "_id" : 102, "details" : [ { "DueDate" : ISODate("2019-03-10T00:00:00Z"), "Value" : 78 }, { "DueDate" : ISODate("2019-12-11T00:00:00Z"), "Value" : 29 } ] }
GATE | GATE-CS-2015 (Set 1) | Question 65 - GeeksforGeeks

16 Nov, 2018
Consider the following C function.
int fun1 (int n){   int i, j, k, p, q = 0;   for (i = 1; i<n; ++i)   {      p = 0;      for (j = n; j > 1; j = j/2)         ++p;      for (k = 1; k < p; k = k*2)         ++q;   }   return q;}
Which one of the following most closely approximates the return value of the function fun1?(A) n3(B) n (logn)2(C) nlogn(D) nlog(logn)Answer: (D)Explanation:
int fun1 (int n)
{
   int i, j, k, p, q = 0;

   // This loop runs Θ(n) time
   for (i = 1; i < n; ++i)
   {
      p = 0;

      // This loop runs Θ(Log n) times. Refer this 
      for (j=n; j > 1; j=j/2)
         ++p;
     
      // Since above loop runs Θ(Log n) times, p = Θ(Log n)
      // This loop runs Θ(Log p) times which loglogn
      for (k=1; k < p; k=k*2)
         ++q;
   
   }
   return q;
}
T(n) = n(logn + loglogn)T(n) = n(logn) dominant
But please note here we are return q which lies in loglogn so ans should be T(n) = nloglogn
Refer this for details.Quiz of this Question
GATE-CS-2015 (Set 1)
GATE-GATE-CS-2015 (Set 1)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-IT-2004 | Question 66
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 2010 | Question 24
GATE | GATE CS 2011 | Question 7
GATE | GATE-IT-2004 | Question 71
GATE | GATE-CS-2004 | Question 3
GATE | GATE CS 2019 | Question 27
GATE | GATE-CS-2016 (Set 1) | Question 65
GATE | GATE-CS-2016 (Set 2) | Question 61
GATE | GATE-CS-2004 | Question 69
Java SQL Timestamp getTime() function with examples

06 Mar, 2019
The getTime() function is a part of Timestamp class of Java SQL.The function is used to get the time of the Timestamp object. The function returns time in milliseconds which represents the time in milliseconds after 1st January 1970.
Function Signature:
public long getTime()
Syntax:
ts1.getTime();
Parameters: The function does not require any parameter.
Return value: The function returns long value representing time in milliseconds.
Exception: The function does not throw any exceptions.
Below examples illustrate the use of getTime() function
Example 1: Create a timestamp and use the getTime() to get the time of timestamp object.
// Java program to demonstrate the// use of getTime() function  import java.sql.*;  class GFG {    public static void main(String args[])    {        // Create two timestamp objects        Timestamp ts = new Timestamp(10000);          // Display the timestamp object        System.out.println("Timestamp time : "                           + ts.toString());        System.out.println("Time in milliseconds : "                           + ts.getTime());    }}
Timestamp time : 1970-01-01 00:00:10.0
Time in milliseconds : 10000

Example 2: Create a timestamp and use the getTime() to get the time of timestamp object and set the time before 1st January 1970. The negative long value represents the time before 1st January 1970
// Java program to demonstrate the// use of getTime() function  import java.sql.*;  public class solution {    public static void main(String args[])    {          // Create two timestamp objects        Timestamp ts = new Timestamp(-10000);          // Display the timestamp object        System.out.println("Timestamp time : "                           + ts.toString());          System.out.println("Time in milliseconds : "                           + ts.getTime());    }}
Timestamp time : 1969-12-31 23:59:50.0
Time in milliseconds : -10000

Reference: https:// docs.oracle.com/javase/7/docs/api/java/sql/Timestamp.html
Java - util package
Java-Functions
Java-Sql package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
Stream In Java
ArrayList in Java
Collections in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java
Working of top down parser

12 Oct, 2021
In this article, we are going to cover working of top down parser and will see how we can take input and parse it and also cover some basics of top down. 
Pre-requisite – Parsing  
Top Down Parser :  
In top down technique parse tree constructs from top and input will read from left to right. In top down, In top down parser, It will start symbol from proceed to string.  
It follows left most derivation.  
In top down parser, difficulty with top down parser is if variable contain more than one possibility selecting 1 is difficult.  
Working of Top Down Parser : Let’s consider an example where grammar is given and you need to construct a parse tree by using top down parser technique. 
Example –  
S -> aABe
A -> Abc | b
B -> d
Now, let’s consider the input to read and to construct a parse tree with top down approach. 
 
Input –  
abbcde$
Now, you will see that how top down approach works. Here, you will see how you can generate a input string from the grammar for top down approach.  
First, you can start with S -> a A B e and then you will see input string a in the beginning and e in the end.  
Now, you need to generate abbcde .  
Expand A-> Abc and Expand B-> d.  
Now, You have string like aAbcde and your input string is abbcde.  
Expand A->b.  
Final string, you will get abbcde.  
Given below is the Diagram explanation for constructing top down parse tree. You can see clearly in the diagram how you can generate the input string using grammar with top down approach. 
 
 
sumitgumber28
Compiler Design
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Directed Acyclic graph in Compiler Design (with examples)
Type Checking in Compiler Design
Data flow analysis in Compiler
S - attributed and L - attributed SDTs in Syntax directed translation
Runtime Environments in Compiler Design
Layers of OSI Model
ACID Properties in DBMS
Types of Operating Systems
TCP/IP Model
Normal Forms in DBMS
Plotly with Matplotlib and Chart Studio

This chapter deals with data visualization library titled Matplotlib and online plot maker named Chart Studio.
Matplotlib is a popular Python data visualization library capable of producing production-ready but static plots. you can convert your static matplotlib figures into interactive plots with the help of mpl_to_plotly() function in plotly.tools module.
Following script produces a Sine wave Line plot using Matplotlib’s PyPlot API.
from matplotlib import pyplot as plt
import numpy as np
import math 
#needed for definition of pi
x = np.arange(0, math.pi*2, 0.05)
y = np.sin(x)
plt.plot(x,y)
plt.xlabel("angle")
plt.ylabel("sine")
plt.title('sine wave')
plt.show()
Now we shall convert it into a plotly figure as follows −
fig = plt.gcf()
plotly_fig = tls.mpl_to_plotly(fig)
py.iplot(plotly_fig)
The output of the code is as given below −
Chart Studio is an online plot maker tool made available by Plotly. It provides a graphical user interface for importing and analyzing data into a grid and using stats tools. Graphs can be embedded or downloaded. It is mainly used to enable creating graphs faster and more efficiently.
After logging in to plotly’s account, start the chart studio app by visiting the link https://plot.ly/create. The web page offers a blank work sheet below the plot area. Chart Studio lets you to add plot traces by pushing + trace button.
Various plot structure elements such as annotations, style etc. as well as facility to save, export and share the plots is available in the menu.
Let us add data in the worksheet and add choose bar plot trace from the trace types.
Click in the type text box and select bar plot.
Then, provide data columns for x and y axes and enter plot title.

    12 Lectures 
     53 mins

 Pranjal Srivastava
 Print
 Add Notes
 Bookmark this page
C++ Program for Comb Sort?

The basic idea of comb sort and the bubble sort is same. In other words, comb sort is an improvement on the bubble sort. In the bubble sorting technique, the items are compared with the next item in each phase. But for the comb sort, the items are sorted in a specific gap. After completing each phase, the gap is decreased. The decreasing factor or the shrink factor for this sort is 1.3. It means that after completing each phase the gap is divided by 1.3. Time Complexity is O(n log n) for best case. O(n2/2nP) (p is number of increment) for average case and O(n2) for worst case.
Input − An array of data, and the total number in the array
Output − The sorted Array
Begin
   gap := size
   flag := true
   while the gap ≠ 1 OR flag = true do
      gap = floor(gap/1.3) //the the floor value after division
      if gap < 1 then
         gap := 1
      flag = false
      for i := 0 to size – gap -1 do
         if array[i] > array[i+gap] then
            swap array[i] with array[i+gap]
            flag = true;
      done
   done
End
include<iostream>
#include<algorithm>
using namespace std;
void display(int *array, int size){
   for(int i = 0; i<size; i++)
      cout << array[i] << " ";
   cout << endl;
}
void combSort(int *array, int size){
   int gap = size; //initialize gap size with size of array
   bool flag = true;
   while(gap != 1 || flag == true){
      gap = (gap*10)/13; //minimize gap by shrink factor
      if(gap<1)
         gap = 1;
      flag = false;
      for(int i = 0; i<size-gap; i++){ //compare elements with gap
         if(array[i] > array[i+gap]){
            swap(array[i], array[i+gap]);
            flag = true;
         }
      }
   }
}
int main(){
   int n;
   cout << "Enter the number of elements: ";
   cin >> n;
   int arr[n]; //create an array with given number of elements
   cout << "Enter elements:" << endl;
   for(int i = 0; i<n; i++){
      cin >> arr[i];
   }
   cout << "Array before Sorting: ";
   display(arr, n);
   combSort(arr, n);
   cout << "Array after Sorting: ";
   display(arr, n);
}
Enter the number of elements: 10
Enter elements:
108 96 23 74 12 56 85 42 13 47
Array before Sorting: 108 96 23 74 12 56 85 42 13 47
Array after Sorting: 12 13 23 42 47 56 74 85 96 108
How do we create multiline comments in Python?

Comment is a piece of text in a computer program that is meant to be a programmer-readable explanation or annotation in the source code and not ignored by compiler/interpreter. In Python script, the symbol # indicates start of comment line.
C like block comment (/* .. */) is not available in Python. If more than one consecutive line are to be commented, # symbol must be put at beginning of each line
##comment1
##comment2
##comment3
 print ("Hello World")
A triple quoted multi-line string is also treated as comment if it is not a docstring of a function or class.
'''
comment1
comment2
comment3
'''
 print ("Hello World")
How to compare float and double in C++?

Comparing floats and double variables depends on what your end goal is. If you want a runnable function without going too much in details and won't have a problem in some inaccurate calculations you can use the following function −
#include<iostream>
using namespace std;

// Define the error that you can tolerate
#define EPSILON 0.000001

bool areSame(double a, double b) {
   return fabs(a - b) < EPSILON;
}

int main() {
   double a = 1.005;
   double b = 1.006;
   cout << areSame(a, a);
   cout << areSame(a, b);
}
This will give the output −
1
0
This function takes your tolerance for error and checks if the threshold is greater than the difference between the numbers you're comparing. If you need something much more accurate, you're better off reading this excellent blog       post:https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/
Python String isupper() Method

Python string  method isupper() checks whether all the case-based characters (letters) of the string are uppercase.
Following is the syntax for isupper() method −
str.isupper()

NA
NA
This method returns true if all cased characters in the string are uppercase and there is at least one cased character, false otherwise.
The following example shows the usage of isupper() method.
#!/usr/bin/python

str = "THIS IS STRING EXAMPLE....WOW!!!"; 
print str.isupper()

str = "THIS is string example....wow!!!";
print str.isupper()
When we run above program, it produces following result −
True
False


    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
Arduino - Connecting Switch

Pushbuttons or switches connect two open terminals in a circuit. This example turns on the LED on pin 2 when you press the pushbutton switch connected to pin 8.
Pull-down resistors are used in electronic logic circuits to ensure that inputs to Arduino settle at expected logic levels if external devices are disconnected or are at high-impedance. As nothing is connected to an input pin, it does not mean that it is a logical zero. Pull down resistors are connected between the ground and the appropriate pin on the device.
An example of a pull-down resistor in a digital circuit is shown in the following figure. A pushbutton switch is connected between the supply voltage and a microcontroller pin. In such a circuit, when the switch is closed, the micro-controller input is at a logical high value, but when the switch is open, the pull-down resistor pulls the input voltage down to the ground (logical zero value), preventing an undefined state at the input.
The pull-down resistor must have a larger resistance than the impedance of the logic circuit, or else it might pull the voltage down too much and the input voltage at the pin would remain at a constant logical low value, regardless of the switch position.
You will need the following components −
1 × Arduino UNO board
1 × 330 ohm resistor
1 × 4.7K ohm resistor (pull down)
1 × LED
Follow the circuit diagram and make the connections as shown in the image given below.
Open the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open a new sketch File by clicking on New.
// constants won't change. They're used here to
// set pin numbers:
const int buttonPin = 8; // the number of the pushbutton pin
const int ledPin = 2; // the number of the LED pin
// variables will change:
int buttonState = 0; // variable for reading the pushbutton status

void setup() {
   // initialize the LED pin as an output:
   pinMode(ledPin, OUTPUT);
   // initialize the pushbutton pin as an input:
   pinMode(buttonPin, INPUT);
}

void loop() {
   // read the state of the pushbutton value:
   buttonState = digitalRead(buttonPin);
   // check if the pushbutton is pressed.
   // if it is, the buttonState is HIGH:
   if (buttonState == HIGH) {
      // turn LED on:
      digitalWrite(ledPin, HIGH);
   } else {
      // turn LED off:
      digitalWrite(ledPin, LOW);
   }
}
When the switch is open, (pushbutton is not pressed), there is no connection between the two terminals of the pushbutton, so the pin is connected to the ground (through the pull-down resistor) and we read a LOW. When the switch is closed (pushbutton is pressed), it makes a connection between its two terminals, connecting the pin to 5 volts, so that we read a HIGH.
LED is turned ON when the pushbutton is pressed and OFF when it is released.

    65 Lectures 
     6.5 hours 

 Amit Rana

    43 Lectures 
     3 hours 

 Amit Rana

    20 Lectures 
     2 hours 

 Ashraf Said

    19 Lectures 
     1.5 hours 

 Ashraf Said

    11 Lectures 
     47 mins

 Ashraf Said

    9 Lectures 
     41 mins

 Ashraf Said
 Print
 Add Notes
 Bookmark this page
How to create an unordered list with disc bullets in HTML?

To create unordered list in HTML, use the <ul> tag. The unordered list starts with the <ul> tag. The list item starts with the <li> tag and will be marked as disc, square, circle, etc. The default is bullets, which is small black circles.
For creating an unordered list with circle bullets, use CSS property list-style-type. We will be using the style attribute. The style attribute specifies an inline style for an element. The attribute is used with the HTML <ul> tag, with the CSS property list-style-type to add circle bullets to an unordered list.
 Just keep in mind, the usage of style attribute overrides any style set globally. It will override any style set in the HTML <style> tag or external style sheet.
 
You can try to run the following code to create an unordered list with disc bullets in HTML −
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>HTML Unordered List</title>
   </head>
   <body>
      <h1>Developed Countries</h1>
      <p>The list of developed countries:</p>
      <ul style="list-style-type:disc">
         <li>US</li>
         <li>Australia</li>
         <li>New Zealand</li>
      </ul>
   </body>
</html>
Java Program to check if a Float is Infinite or Not a Number(NAN)

To check if a Float is isInfinite, use the isInfinite() method and to check for NAN, use the isNaN() method.
 Live Demo
public class Demo {
   public static void main(String[] args) {
      float value1 = (float) 1 / 0;
      boolean res1 = Float.isInfinite(value1);
      System.out.println("Checking for isInfinite? = "+res1);
      float value2 = (float) Math.sqrt(9);
      boolean res2 = Float.isNaN(value2);
      System.out.println("Checking for isNan? = "+res2);
   }
}
Checking for isInfinite? = true
Checking for isNan? = false
Drawing a network graph with networkX and Matplotlib

To draw a network graph with networkx and matplotlib, plt.show() −
Set the figure size and adjust the padding between and around the subplots.
Set the figure size and adjust the padding between and around the subplots.
Make an object for a dataframe with the keys, from and to.
Make an object for a dataframe with the keys, from and to.
Get a graph containing an edgelist.
Get a graph containing an edgelist.
Draw a graph (Step 3) using draw() method with some node properties.
Draw a graph (Step 3) using draw() method with some node properties.
To display the figure, use show() method.
To display the figure, use show() method.
import pandas as pd
import networkx as nx
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
df = pd.DataFrame({'from': ['A', 'B', 'C', 'A'], 'to': ['D', 'A', 'E', 'C']})
G = nx.from_pandas_edgelist(df, 'from', 'to')
nx.draw(G, with_labels=True, node_size=100, alpha=1, linewidths=10)
plt.show()
Patching Array in C++

Suppose we have an array nums and one number. We can add elements in the array, such that any number in range [1, n] (both are inclusive) can be formed by the sum of some elements in the array. We have to find the minimum number of required patches. So when the array is like [1,4] and given number is n = 7, then output will be 1, as initially the nums are [1], [4] and [1,4] = 5, now if we add 2 into array, then the nums will be [1], [2], [4], [1,2], [1,4],[2,4], [1,2,4], so the sum values will be 1, 2, 4, 3, 5, 6, 7 respectively.
To solve this, we will follow these steps −
req := 1, i := 0, ret := 0
req := 1, i := 0, ret := 0
while req <= n, do −if i < size of nums and nums[i] <= req, then,req = req + nums[i]increase i by 1Otherwisereq = req + reqincrease ret by 1
while req <= n, do −
if i < size of nums and nums[i] <= req, then,req = req + nums[i]increase i by 1
if i < size of nums and nums[i] <= req, then,
req = req + nums[i]
req = req + nums[i]
increase i by 1
increase i by 1
Otherwisereq = req + reqincrease ret by 1
Otherwise
req = req + req
req = req + req
increase ret by 1
increase ret by 1
return ret
return ret
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int minPatches(vector<int>& nums, int n) {
      long long int req = 1;
      int i = 0;
      int ret = 0;
      while(req <= n){
         if(i < nums.size() && nums[i] <= req){
            req += nums[i];
            i++;
         } else {
            req += req;
            ret++;
         }
      }
      return ret;
   }
};
main(){
   Solution ob;
   vector<int> v = {1,4};
   cout << (ob.minPatches(v, 7));
}
{1,4}
1
How does the Java “foreach” loop work?

JDK 1.5 introduced a new for loop known as foreach loop or enhanced for loop, which enables you to traverse the complete array sequentially without using an index variable. 
public class ArrayUsingForEach {
   public static void main(String[] args) {
      double[] myList = {1.9, 2.9, 3.4, 3.5};
      // Print all the array elements
      for (double element: myList) {
         System.out.println(element);
      }
   }
}
Output
1.9
2.9
3.4
3.5
Get the first element from a Sorted Set in Java

To create a Sorted Set, firstly create a Set.
Set<Integer> s = new HashSet<Integer>();
Add elements to the above set.
int a[] = {77, 23, 4, 66, 99, 112, 45, 56, 39, 89};
Set<Integer> s = new HashSet<Integer>();
try {
   for(int i = 0; i < 5; i++) {
      s.add(a[i]);
    }
After that, use TreeSet class to sort.
TreeSet sorted = new TreeSet<Integer>(s);
Get the first element, using the first() method −
System.out.println("\nFirst element of the sorted set = "+ (Integer)sorted.first());
The following is the code to get the first element from a Sorted Set in Java.
 Live Demo
import java.util.*;
public class Demo {
   public static void main(String args[]) {
      int a[] = {77, 23, 4, 66, 99, 112, 45, 56, 39, 89};
      Set<Integer> s = new HashSet<Integer>();
      try {
         for(int i = 0; i < 5; i++) {
            s.add(a[i]);
         }
         System.out.println(s);
         TreeSet sorted = new TreeSet<Integer>(s);
         System.out.println("Sorted list = ");
         System.out.println(sorted);
         System.out.println("\nFirst element of the sorted set = "+ (Integer)sorted.first());
      } catch(Exception e) {}
   }
}
[66, 99, 4, 23, 77]
Sorted list =
[4, 23, 66, 77, 99]
First element of the sorted set = 4
What is the difference between super and this, keywords in Java?

The this is a keyword in Java which is used as a reference to the object of the current class. Using it you can −
Differentiate the instance variables from local variables if they have same names, within a constructor or a method.
Call one type of constructor (parametrized constructor or default) from other in a class. It is known as explicit constructor invocation.
class Superclass {
   int age;
   Superclass(int age) {
      this.age = age;
   }
   public void getAge() {
      System.out.println("The value of the variable named age in super class is: " +age);
   }
}
The super is a keyword in Java which is used as a reference to the object of the super class. Like the this keyword −
It is used to differentiate the members of superclass from the members of subclass, if they have same names.
It is used to invoke the superclass constructor from subclass.
 Live Demo
class Superclass {
   int age;
      Superclass(int age) {
      this.age = age;
   }
   public void getAge() {
      System.out.println("The value of the variable named age in super class is: " +age);
   }
}
public class Subclass extends Superclass {
   Subclass(int age) {
      super(age);
   }
   public static void main(String argd[]) {
      Subclass s = new Subclass(24);
      s.getAge();
   }
}
The value of the variable named age in super class is: 24
MySQL query to find sum of fields with same column value?

Use GROUP BY clause for this. Let us first create a table −
mysql> create table sumOfFieldsDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> ClientSerialNumber varchar(100),
   -> ClientCost int
   -> );
Query OK, 0 rows affected (0.50 sec)
Following is the query to insert some records in the table using insert command −
mysql> insert into sumOfFieldsDemo(ClientSerialNumber,ClientCost) values('1111',450);
Query OK, 1 row affected (0.16 sec)
mysql> insert into sumOfFieldsDemo(ClientSerialNumber,ClientCost) values('2222',550);
Query OK, 1 row affected (0.15 sec)
mysql> insert into sumOfFieldsDemo(ClientSerialNumber,ClientCost) values('3333',150);
Query OK, 1 row affected (0.64 sec)
mysql> insert into sumOfFieldsDemo(ClientSerialNumber,ClientCost) values('3333',250);
Query OK, 1 row affected (0.12 sec)
mysql> insert into sumOfFieldsDemo(ClientSerialNumber,ClientCost) values('2222',1000);
Query OK, 1 row affected (0.10 sec)
mysql> insert into sumOfFieldsDemo(ClientSerialNumber,ClientCost) values('1111',1000);
Query OK, 1 row affected (0.16 sec)
mysql> insert into sumOfFieldsDemo(ClientSerialNumber,ClientCost) values('1111',500);
Query OK, 1 row affected (0.17 sec)
mysql> insert into sumOfFieldsDemo(ClientSerialNumber,ClientCost) values('4444',100);
Query OK, 1 row affected (0.17 sec)
Following is the query to display all records from the table using select statement −
mysql> select * from sumOfFieldsDemo;
This will produce the following output −
+----+--------------------+------------+
| Id | ClientSerialNumber | ClientCost |
+----+--------------------+------------+
| 1  | 1111               | 450        |
| 2  | 2222               | 550        |
| 3  | 3333               | 150        |
| 4  | 3333               | 250        |
| 5  | 2222               | 1000       |
| 6  | 1111               | 1000       |
| 7  | 1111               | 500        |
| 8  | 4444               | 100        |
+----+--------------------+------------+
8 rows in set (0.00 sec)
Here is the query to find sum of fields with same column value −
mysql> select Id,ClientSerialNumber,SUM(ClientCost) AS TotalSum
   -> from sumOfFieldsDemo
   -> group by ClientSerialNumber;
This will produce the following output −
+----+--------------------+----------+
| Id | ClientSerialNumber | TotalSum |
+----+--------------------+----------+
| 1  | 1111               | 1950     |
| 2  | 2222               | 1550     |
| 3  | 3333               | 400      |
| 8  | 4444               | 100      |
+----+--------------------+----------+
4 rows in set (0.00 sec)
How to plot values with log scales on x and y axis or on a single axis in R?

We can plot numerical values in R with many scales and that includes log scale as well. Also, it is possible to plot the values with log scales on both the axes. In base R, the best way to do this is defining the axes values with decimal representation as shown in the below examples with well-defined log.
Consider the below vector −
 Live Demo
set.seed(555)
x<-sample(1:9,10,replace=TRUE)
x
[1] 4 8 7 5 6 1 9 2 1 8
Creating plot of x with log scale on both, x and y axis −
plot(x,xlim=c(0.000001,10),ylim=c(0.000001,10),log="xy")
Creating plot of x with log scale on y axis only −
plot(x,xlim=c(0.000001,10),ylim=c(0.000001,10),log="y")

Creating plot of x with log scale on x axis only −
plot(x,xlim=c(0.000001,10),ylim=c(0.000001,10),log="x")
Climbing Stairs in C++

There are n stairs. One person will go to 1st to nth stairs. Maximum how many stairs he/she can cross in one step is also given. With this information, we have to find possible ways to go to the nth stairs. Let us consider one can cross a maximum two stairs in each step. So we can find recursive relations to solve this problem. One can move to nth stair, either from (n-1)th stair or from (n-2)th stair. So ways(n) = ways(n-1) + ways(n-2).
Suppose the number of stairs, say 10, the maximum number of stairs that can be jumped in one step, say 2, then the output will be 89 possible ways.
To solve this, follow these steps −
define array count of size same as stair number
count[0] := 1
for i := 2 to stair -1, docount[i] := 0for j = 1 to i and j <= max; docount[i] := count[i] + count[i - j]
count[i] := 0
for j = 1 to i and j <= max; docount[i] := count[i] + count[i - j]
count[i] := count[i] + count[i - j]
return count[stair - 1]
Let us see the implementation to get better understanding
 Live Demo
#include<iostream>
using namespace std;
int stairClimbWays(int stair, int max){
   int count[stair]; //fill the result stair using bottom up manner
   count[0] = 1; //when there are 0 or 1 stair, 1 way to climb
   count[1] = 1;
   for (int i=2; i<stair; i++){ //for stair 2 to higher
      count[i] = 0;
      for(int j=1; j<=max && j<=i; j++)
         count[i] += count[i-j];
   }
   return count[stair-1];
}
int countWays(int stair, int max){ //person can climb 1,2,...max stairs at a time
   return stairClimbWays(stair+1, max);
}
int main (){
   int stair, max;
   cout << "Enter number of stairs: "; cin >> stair;
   cout << "Enter max stair a person can climb: "; cin >> max;
   cout << "Number of ways to reach: " << countWays(stair, max);
}
Stairs = 10
Max stairs a person can climb: 2
Enter number of stairs: 10
Enter max stair a person can climb: 2
Number of ways to reach: 89
Search an element of Vector in Java

An element of a Vector can be searched using the method java.util.ArrayList.indexOf(). This method returns the index of the first occurrence of the element that is specified. If the element is not available in the Vector, then this method returns -1.
A program that demonstrates this is given as follows:
 Live Demo
import java.util.Vector;
public class Demo {
   public static void main(String args[]) {
      Vector vec = new Vector(5);
      vec.add(4);
      vec.add(1);
      vec.add(7);
      vec.add(9);
      vec.add(2);
      vec.add(8);
      System.out.println("The Vector elements are: " + vec);
      System.out.println("The index of element 9 in Vector is: " + vec.indexOf(9));
      System.out.println("The index of element 5 in Vector is: " + vec.indexOf(5));
   }
}
The output of the above program is as follows:
The Vector elements are: [4, 1, 7, 9, 2, 8]
The index of element 9 in Vector is: 3
The index of element 5 in Vector is: -1
Now let us understand the above program.
The Vector is created. Then Vector.add() is used to add the elements to the Vector. Vector.indexOf() returns the index of the first occurrence of elements 9 and 5 and that is displayed. A code snippet which demonstrates this is as follows:
Vector vec = new Vector(5);
vec.add(4);
vec.add(1);
vec.add(7);
vec.add(9);
vec.add(2);
vec.add(8);
System.out.println("The Vector elements are: " + vec);
System.out.println("The index of element 9 in Vector is: " + vec.indexOf(9));
System.out.println("The index of element 5 in Vector is: " + vec.indexOf(5));
Selenium WebDriver StaleElementReferenceException.

We have StaleElementReferenceException in Selenium webdriver. As the name suggests, the word stale refers to something which is not new and perished. There may be a scenario in which an element which was present in DOM previously is now no longer available due to modification in DOM.
In such a condition, if we try to access that element then StaleElementReferenceException is thrown. This type of exception is encountered due to the below reasons −
The element is not present in the DOM any more.
The element is not present in the DOM any more.
The element has been removed totally.
The element has been removed totally.
There are certain ways we can prevent a StaleElementReferenceException as described below −
We can reload the webpage and try to interact with the same element.
driver.navigate().refresh();
driver.findElement(By.id("txt")).sendKeys("Selenium");
We can add a try catch block and interact with the same element. Here with for loop, there shall be five attempts. If the element is identified before the five attempts, there shall be exit from the loop.
for(int k=0; k<=5;k++){
   try{
      driver.findElement(By.id("txt")).sendKeys("Selenium");
      break;
   }
   catch(Exception exp){
      System.out.println(exp.message());
   }
}
To prevent a StaleElementReferenceException we can add the explicit wait [synchronization] to wait for the element till the element is rendered in DOM with the help of the expected condition presenceOfElementLocated.
w.until(ExpectedConditions.presenceOfElementLocated(By.name("presence")));
JavaScript - Array indexOf() Method

JavaScript array indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.
Its syntax is as follows −
array.indexOf(searchElement[, fromIndex]);

searchElement − Element to locate in the array.
searchElement − Element to locate in the array.
fromIndex − The index at which to begin the search. Defaults to 0, i.e. the whole array will be searched. If the index is greater than or equal to the length of the array, -1 is returned.
fromIndex − The index at which to begin the search. Defaults to 0, i.e. the whole array will be searched. If the index is greater than or equal to the length of the array, -1 is returned.
Returns the index of the found element.
This method is a JavaScript extension to the ECMA-262 standard; as such it may not be present in other implementations of the standard. To make it work, you need to add the following code at the top of your script.
if (!Array.prototype.indexOf) {
   Array.prototype.indexOf = function(elt /*, from*/) {
      var len = this.length;
      
      var from = Number(arguments[1]) || 0;
      from = (from < 0)
      ? Math.ceil(from)
      : Math.floor(from);
      
      if (from < 0)
      from += len;
      
      for (; from < len; from++) {
         if (from in this &&
         this[from] === elt)
         return from;
      }
      return -1;
   };
}
Try the following example.
<html>
   <head>
      <title>JavaScript Array indexOf Method</title>
   </head>
   
   <body>   
      <script type = "text/javascript">
         if (!Array.prototype.indexOf) {
            Array.prototype.indexOf = function(elt /*, from*/) {
               var len = this.length;
               
               var from = Number(arguments[1]) || 0;
               from = (from < 0)
               ? Math.ceil(from)
               : Math.floor(from);
               
               if (from < 0)
               from += len;
               
               for (; from < len; from++) {
                  if (from in this &&
                  this[from] === elt)
                  return from;
               }
               return -1;
            };
         }
         var index = [12, 5, 8, 130, 44].indexOf(8);
         document.write("index is : " + index ); 
         
         var index = [12, 5, 8, 130, 44].indexOf(13);
         document.write("<br />index is : " + index ); 
      </script>      
   </body>
</html>
index is : 2
index is : -1 


    25 Lectures 
     2.5 hours 

 Anadi Sharma

    74 Lectures 
     10 hours 

 Lets Kode It

    72 Lectures 
     4.5 hours 

 Frahaan Hussain

    70 Lectures 
     4.5 hours 

 Frahaan Hussain

    46 Lectures 
     6 hours 

 Eduonix Learning Solutions

    88 Lectures 
     14 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page
Shell Script To Check That Input Only Contains Alphanumeric Characters

09 Apr, 2021
If you want an input which contains only alphanumeric characters i.e. 1-9 or a-z lower case as well as upper case characters, We can make use of regular expression or Regex in short in a Shell Script to verify the input.
Example:
Input: Geeksforgeeks
Output: True

Explanation: Here all the inputted data are alphanumeric

Input: Geeks@for@geeks
Output: False

Explanation: @ is not alphanumeric
Here our task is to write a script to take inputs a variable, and it checks that the input string from start to end has only numbers or alphabets(lower or upper case). If there are any other special characters the condition in the while loop will evaluate to false and hence the while loop will get executed, and it inputs the variable again, and then it again checks for the while loop condition of alphanumeric characters. The loop will continue until the user inputs only alphanumeric and non-empty string or number. \
#!/bin/bash

# Input from user
read -p "Input : " inp


# While loop for alphanumeric characters and a non-zero length input
while [[ "$inp" =~ [^a-zA-Z0-9] || -z "$inp" ]]
do        
   echo "The input contains special characters."     
   echo "Input only alphanumeric characters."     
   
   
# Input from user
   read -p "Input : " inp
   
   
#loop until the user enters only alphanumeric characters.
done
echo "Successful Input"
Output:
Bash Script Output
The following screenshot of the test case of the code is executed, and it only accepts non-empty alphanumeric input. It even rejects an empty input and other characters excluding alphabets and numbers. The following code is a regular expression to check for numbers or alphabets from start(^) till the end($) and a condition of empty input ( -z stands for the length of zero). So, the shell script will prompt the user again and again until he/she inputs an alphanumeric character.
Picked
Shell Script
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
numpy.flipud() in Python

28 Mar, 2022
The numpy.flipud() function flips the array(entries in each column) in up-down direction, shape preserved. Syntax: 
numpy.flipud(array)
Parameters : 
array : [array_like]Input array, we want to flip
Return : 
Flipped array in up-down direction.
Python
# Python Program illustrating# numpy.flipud() method import numpy as geek array = geek.arange(8).reshape((2,2,2))print("Original array : \n", array) # flipud : means flip up-downprint("\nFlipped array : \n", geek.flipud(array))
Output : 
Original array : 
 [[[0 1]
  [2 3]]

 [[4 5]
  [6 7]]]

Flipped array : 
 [[[4 5]
  [6 7]]

 [[0 1]
  [2 3]]]
References : https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.flipud.html#numpy.flipud 
Note : These codes won’t run on online IDE’s. So please, run them on your systems to explore the working.
This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@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.
vinayedula
Python numpy-arrayManipulation
Python-numpy
Misc
Python
Misc
Misc
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
time.NewTimer() Function in Golang With Examples

21 Apr, 2020
In Go language, time packages supplies functionality for determining as well as viewing time. The NewTimer() function in Go language is used to create a new Timer that will transmit the actual time on its channel at least after duration “d”. Moreover, this function is defined under the time package. Here, you need to import the “time” package in order to use these functions.
Syntax:
func NewTimer(d Duration) *Timer

Here, *Timer is a pointer to the Timer.
Return Value: It returns a channel that notifies how long a timer will have to wait.
Example 1:
// Golang program to illustrate the usage of// NewTimer() function  // Including main packagepackage main  // Importing fmt and timeimport (    "fmt"    "time")  // Main functionfunc main() {      // Calling NewTimer method    newtimer := time.NewTimer(5 * time.Second)      // Notifying the channel    <-newtimer.C      // Printed after 5 seconds    fmt.Println("Timer is inactivated")}
Output:
Timer is inactivated

Here, the above output is printed after 5 seconds of running the code, as after that stated time the channel is being notified that the timer is inactivated.
Example 2:
// Golang program to illustrate the usage of// NewTimer() function  // Including main packagepackage main  // Importing fmt and timeimport (    "fmt"    "time")  // Main functionfunc main() {      // Calling NewTimer method    newtimer := time.NewTimer(time.Second)      // Notifying channel under go function    go func() {        <-newtimer.C          // Printed when timer is fired        fmt.Println("timer inactivated")    }()      // Calling stop method to stop the    // timer before inactivation    stoptimer := newtimer.Stop()      // If the timer is stopped then the    // below string is printed    if stoptimer {        fmt.Println("The timer is stopped!")    }      // Calling sleep method to stop the    // execution at last    time.Sleep(4 * time.Second)}
Output:
The timer is stopped!

In the above method, the timer is being stopped before inactivating as here the stop method is being called to stop the timer. And at last, the program is exited using sleep method.
GoLang-time
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.