code-rag-bench/online-tutorials huggingface dataset:
Sorting a vector in C++

Sorting a vector in C++ can be done by using std::sort(). It is defined in<algorithm> header. To get a stable sort std::stable_sort is used. It is exactly like sort() but maintains the relative order of equal elements. Quicksort(), mergesort() can also be used, as per requirement.
Begin
   Decalre v of vector type.
      Initialize some values into v in array pattern.
   Print “Elements before sorting”.
   for (const auto &i: v)
      print all the values of variable i.
   Print “Elements after sorting”.
   Call sort(v.begin(), v.end()) function to sort all the elements of the v vector.
   for (const auto &i: v)
      print all the values of variable i.
End.
This is a simple example of sorting a vector in c++:
 Live Demo
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
   vector<int> v = { 10, 9, 8, 6, 7, 2, 5, 1 };
   cout<<"Elements before sorting"<<endl;
   for (const auto &i: v)
      cout << i << ' '<<endl;
      cout<<"Elements after sorting"<<endl;
      sort(v.begin(), v.end());
   for (const auto &i: v)
      cout << i << ' '<<endl;
   return 0;
}
Elements before sorting
10
9
8
6
7
2
5
1
Elements after sorting
1
2
5
6
7
8
9
10
Format percentage with MessageFormat class in Java

To format message with percentage fillers in Java, we use the MessageFormat class. The MessageFormat class gives us a way to produce concatenated messages which are not dependent on the language. The MessageFormat class extends the Serializable and Cloneable interfaces.
Declaration - The java.text.MessageFormat class is declared as follows −
public class MessageFormat extends Format
The  MessageFormat.format(pattern, params) method formats the message and fills in the missing parts using the objects in the params array matching up the argument numbers and the array indices.
The format method has two arguments, a pattern and an array of arguments. The pattern contains placeholder in {} curly braces which have a index that indicate the position in the array where the value of the argument is stored, a number argument indicating that the filler is a number and a percent parameter indicating that the number is percent representing percentage. They are as follows −
String message = MessageFormat.format("{0,number,percent} passed and {1,number,percent} failed", obj);
Let us see a program to format the message with percentage fillers −
 Live Demo
import java.text.MessageFormat;
public class Example {
   public static void main(String[] args) throws Exception {
      Object[] obj = new Object[] { new Double(40.56), new Double(59.44)};
      String message = MessageFormat.format("{0,number,percent} passed and {1,number,percent} ailed", obj);
      System.out.println(message);
   }
}
The output is as follows −
4,056% passed and 5,944% failed
Font Awesome - Brand icons

This chapter explains the usage of Font Awesome Brand icons. Assume that custom is the CSS class name where we defined the size and color, as shown in the example given below.
<html>
   <head>
      <link rel = "stylesheet" href = "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.min.css">

      <style>
         i.custom {font-size: 2em; color: gray;}
      </style>
		
   </head>
	
   <body>
      <i class = "fa fa-adjust custom"></i>
   </body>
	
</html>
The following table shows the usage and the results of Font Awesome Brand icons. Replace the <body> tag of the above program with the code given in the table to get the respective outputs −

    26 Lectures 
     2 hours 

 Neha Gupta

    20 Lectures 
     2 hours 

 Asif Hussain

    43 Lectures 
     5 hours 

 Sharad Kumar

    411 Lectures 
     38.5 hours 

 In28Minutes Official

    71 Lectures 
     10 hours 

 Chaand Sheikh

    207 Lectures 
     33 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page
PyQt5 QSpinBox - Setting size increment - GeeksforGeeks

28 May, 2020
In this article we will see how we can set the size increment of spin box or not. Size increment is used when spin box size is changeable with the main window size. Base size is used to calculate a proper spin box size if the spin box defines sizeIncrement. By default, for a newly-created spin box, this property contains a size with zero width and height.
Below is the formula for getting new spin box size when main window get bigger.
width = baseSize().width() + i * sizeIncrement().width()
height = baseSize().height() + j * sizeIncrement().height()

Here i, j are the size increment in the main window

In order to do this we use setSizeIncrement method with the spin box object.
Syntax : spin_box.setSizeIncrement(base, height)
Argument : It takes two integer as argument
Return : It returns None
Below is the implementation
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys    class Window(QMainWindow):      def __init__(self):        super().__init__()          # setting title        self.setWindowTitle("Python ")          # setting geometry        self.setGeometry(100, 100, 600, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()          # method for widgets    def UiComponents(self):        # creating spin box        self.spin = QSpinBox(self)          # setting geometry to spin box        self.spin.setGeometry(100, 100, 250, 40)          # setting range to the spin box        self.spin.setRange(0, 9)          # setting prefix to spin        self.spin.setPrefix("PREFIX ")          # setting suffix to spin        self.spin.setSuffix(" SUFFIX")          # setting size increment        self.spin.setSizeIncrement(10, 10)           # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python PyQt-SpinBox
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
Display an Icon from Image Sprite using CSS

The main advantage of using image sprite is to reduce the number of http requests that makes our site’s load time faster.
Following is the code for displaying an icon from image sprite using CSS −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
body {
   font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.twitter,.facebook {
   background: url(sprites_64.png) no-repeat;
   display:inline-block;
   width: 64px;
   height: 64px;
   margin:10px 4px;
}
.facebook {
   background-position: 0 -148px;
}
</style>
</head>
<body>
<h1>Image Sprite example</h1>
<a class="twitter"></a>
<a class="facebook"></a>
</body>
</html>
The above code will produce the following output −
Jump Game in Python

Suppose we have an array of non-negative integers; we are initially positioned at the first index of the array. Each element in the given array represents out maximum jump length at that position. We have to determine if we are able to reach the last index or not. So if the array is like [2,3,1,1,4], then the output will be true. This is like jump one step from position 0 to 1, then three step from position 1 to the end.
Let us see the steps −
n := length of array A – 1
for i := n – 1, down to -1if A[i] + i > n, then n := i
if A[i] + i > n, then n := i
return true when n = 0, otherwise false
Let us see the following implementation to get better understanding −
 Live Demo
class Solution(object):
   def canJump(self, nums):
      n = len(nums)-1
      for i in range(n-1,-1,-1):
         if nums[i] + i>=n:
            n = i
      return n ==0
ob1 = Solution()
print(ob1.canJump([2,3,1,1,4]))
[2,3,1,1,4]
True
Remove Trailing Zero in MySQL?

Use trim() function to remove trailing zeroz in MySQL. Following is the syntax −
select trim(yourColumnName)+0 As anyAliasName from yourTableName;
Let us first create a table −
mysql> create table removeTrailingZero
   -> (
   -> Number DECIMAL(10,4)
   -> );
Query OK, 0 rows affected (0.83 sec)
Following is the query to insert some records in the table using insert command −
mysql> insert into removeTrailingZero values(10.789);
Query OK, 1 row affected (0.19 sec)

mysql> insert into removeTrailingZero values(89.90);
Query OK, 1 row affected (0.18 sec)

mysql> insert into removeTrailingZero values(8999.70);
Query OK, 1 row affected (0.20 sec)

mysql> insert into removeTrailingZero values(0.40);
Query OK, 1 row affected (0.23 sec)

mysql> insert into removeTrailingZero values(0.0);
Query OK, 1 row affected (0.16 sec)
Following is the query to display all records from the table using select statement −
mysql> select * from removeTrailingZero;
This will produce the following output −
+-----------+
| Number    |
+-----------+
| 10.7890   |
| 89.9000   |
| 8999.7000 |
| 0.4000    |
| 0.0000    |
+-----------+
5 rows in set (0.00 sec)
Following is the query to remove trailing zeros −
mysql> select trim(Number)+0 As WithoutTrailingZero from removeTrailingZero;
This will produce the following output −
+---------------------+
| WithoutTrailingZero |
+---------------------+
| 10.789              |
| 89.9                |
| 8999.7              |
| 0.4                 |
| 0                   |
+---------------------+
5 rows in set (0.00 sec
Can we create an object of an abstract class in Java?

No, we can't create an object of an abstract class. But we can create a reference variable of an abstract class. The reference variable is used to refer to the objects of derived classes (subclasses of abstract class).
An abstract class means hiding the implementation and showing the function definition to the user is known as Abstract class. A Java abstract class can have instance methods that implement a default behavior if we know the requirement and partially implementation we can go for an abstract class.
Live Demo
abstract class Diagram {
   double dim1;
   double dim2;
   Diagram(double a, double b) {
      dim1 = a;
      dim2 = b;
   }
      // area is now an abstract method
      abstract double area();
}
class Rectangle extends Diagram {
   Rectangle(double a, double b) {
      super(a, b);
   }
   // override area for rectangle
   double area() {
      System.out.println("Inside Area for Rectangle.");
      return dim1 * dim2;
   }
}
class Triangle extends Diagram {
   Triangle(double a, double b) {
      super(a, b);
   }
   // override area for triangle
   double area() {
      System.out.println("Inside Area for Triangle.");
      return dim1 * dim2 / 2;
   }
}
public class Test {
   public static void main(String args[]) {
      // Diagram d = new Diagram(10, 10); // illegal now
      Rectangle r = new Rectangle(9, 5);
      Triangle t = new Triangle(10, 8);
      Diagram diagRef; // This is OK, no object is created
      diagRef = r;
      System.out.println("Area of Rectangle is: " + diagRef.area());
      diagRef = t;
      System.out.println("Area of Triangle is:" + diagRef.area());
   }
}
In the above example, we cannot create the object of type Diagram but we can create a reference variable of type Diagram. Here we created a reference variable of type Diagram and the Diagram class reference variable is used to refer to the objects of the class Rectangle and Triangle.
Inside Area for Rectangle.
Area of Rectangle is: 45.0
Inside Area for Triangle.
Area of Triangle is:40.0
What are the undecidable problems in TOC?

The problems for which we can’t construct an algorithm that can answer the problem correctly in the infinite time are termed as Undecidable Problems in the theory of computation (TOC).
A problem is undecidable if there is no Turing machine that will always halt an infinite amount of time to answer as ‘yes’ or ‘no’.
Examples
The examples of undecidable problems are explained below. Here, CFG refers to Context Free Grammar.
Whether two CFG L and M equal − Since, we cannot determine all the strings of any CFG, we can predict that two CFG are equal or not.
Whether two CFG L and M equal − Since, we cannot determine all the strings of any CFG, we can predict that two CFG are equal or not.
Given a context-free language, there is no Turing machine (TM) that will always halt an infinite amount of time and give an answer to whether language is ambiguous or not.
Given a context-free language, there is no Turing machine (TM) that will always halt an infinite amount of time and give an answer to whether language is ambiguous or not.
Given two context-free languages, there is no Turing machine that will always halt an infinite amount of time and give an answer whether two context-free languages are equal or not.
Given two context-free languages, there is no Turing machine that will always halt an infinite amount of time and give an answer whether two context-free languages are equal or not.
Whether CFG will generate all possible strings of the input alphabet (∑*) is undecidable.
Whether CFG will generate all possible strings of the input alphabet (∑*) is undecidable.
Halting Problem
The Halting problem is the most famous of the undecidable problems.
Consider the code
num=1;
while(num=0)
{
   num=num+1;
}
It counts up forever since it will never equal 0. This is an example of the halting problem.
Note: Every context-free language is decidable.
Some of the other undecidable problems are:
Totality problem − It decide whether an arbitrary TM halts on all inputs. This is equivalent to the problem of whether a program can ever enter an infinite loop, for any input. It differs from the halting problem, which asks whether it enters an infinite loop for a particular input.
Equivalence problem − It decide whether two TMs accept the same language. This is equivalent to the problem of whether two programs compute the same output for every input.
Create an Exception Logging Decorator in Python - GeeksforGeeks

08 May, 2020
Prerequisites: Decorators in Python, Logging in Python
Logging helps you to keep track of the program/application you run. It stores the outputs/errors/messages/exceptions anything you want to store. Program executions can be debugged with the help of print statements during the runtime of code. But the code is not elegant and not a good practice. Logging is a standard process an application to follow to store the process in a log file that would help to analyze/debug in the future/unexpected situations.
For a logger, we have different levels of logging a message. As the article is limited to exception logging, we will go with the ‘INFO’ level log message which helps us to check if the code is working as expected. If there is an exception, it will store exception into the log file using logger object logger.exception(“some exception raised”)
Below is the implementation.
import loggingfrom functools import wraps     def create_logger():           #create a logger object    logger = logging.getLogger('exc_logger')    logger.setLevel(logging.INFO)          #create a file to store all the     # logged exceptions    logfile = logging.FileHandler('exc_logger.log')          fmt = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'    formatter = logging.Formatter(fmt)          logfile.setFormatter(formatter)    logger.addHandler(logfile)          return logger     logger = create_logger()  # you will find a log file# created in a given pathprint(logger)     def exception(logger):          # logger is the logging object    # exception is the decorator objects     # that logs every exception into log file    def decorator(func):                  @wraps(func)        def wrapper(*args, **kwargs):                          try:                return func(*args, **kwargs)                          except:                issue = "exception in "+func.__name__+"\n"                issue = issue+"-------------------------\                ------------------------------------------------\n"                logger.exception(issue)            raise                                 return wrapper    return decorator     @exception(logger)def divideStrByInt():    return "krishna"/7  # Driver Codeif __name__ == '__main__':    divideStrByInt()   
Output:
Python Decorators
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Selecting rows in pandas DataFrame based on conditions
Check if element exists in list in Python
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
How to call a method after a delay in Swift(iOS)?

In this post, we will be seeing how you can delay a method call using Swift. Here we will be seeing how you can achieve the same in two ways,
So let’s get started,
We will be seeing both the example in Playground,
Step 1 − Open Xcode → New Playground.
In the first approach, we will be using asyncAfter(deadline: execute:) instance method, which Schedules a work item for execution at the specified time and returns immediately.
You can read more about it here https://developer.apple.com/documentation/dispatch/dispatchqueue/2300020-asyncafter
Step 2 − Copy the below code in Playground and run,
func functionOne() {
   let delayTime = DispatchTime.now() + 3.0
   print("one")
   DispatchQueue.main.asyncAfter(deadline: delayTime, execute: {
      hello()
   })
}
func hello() {
   print("text")
} functionOne()
Here we are creating one function functionOne, where first we are declaring delay time which is 3 Seconds. Then we are using asyncAfter where we are giving the delay time as a parameter and asking to execute hello() function after 3 seconds.
If we run the above program first “one” prints then after 3 seconds “text” prints.
In the second approach, we are going to use NSTimer,
You can copy the below code in your Xcode→Single View application
class ViewController: UIViewController {
   override func viewDidLoad() {
      super.viewDidLoad()
      print("one")
      Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(ViewController.hello), userInfo: nil, repeats: false)
   }
   @objc func hello() {
      print("text")
   }
}
Run the application, you will see the same output, one is printed and after 3 seconds text is printed.
How To Convert Python Dictionary To JSON?

08 Nov, 2021
JSON stands for JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called json. To use this feature, we import the JSON package in Python script. The text in JSON is done through quoted-string which contains a value in key-value mapping within { }. It is similar to the dictionary in Python.Note: For more information, refer to Read, Write and Parse JSON using Python 
Function Used:  
json.dumps()  
json.dump()  
Syntax: json.dumps(dict, indent)Parameters:  
dictionary – name of dictionary which should be converted to JSON object.  
indent – defines the number of units for indentation  
Syntax: json.dump(dict, file_pointer)Parameters:  
dictionary – name of dictionary which should be converted to JSON object.  
file pointer – pointer of the file opened in write or append mode.  
 
Example 1:
Python3
import json       # Data to be written dictionary ={   "id": "04",   "name": "sunil",   "department": "HR"}       # Serializing json  json_object = json.dumps(dictionary, indent = 4) print(json_object)
{
    "id": "04",
    "name": "sunil",
    "department": "HR"
}
Output:
{
    "department": "HR",
    "id": "04",
    "name": "sunil"
}
Example 2:
Python3
import json    # Data to be writtendictionary ={    "name" : "sathiyajith",    "rollno" : 56,    "cgpa" : 8.6,    "phonenumber" : "9976770500"}    with open("sample.json", "w") as outfile:    json.dump(dictionary, outfile)
Output: 
sagar0719kumar
prachisoda1234
Python json-programs
Python-json
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Lodash _.fromQuery() Method

30 Sep, 2020
The Lodash _.fromQuery() method is used to convert the given URL Query String into an equivalent JavaScript object.
Syntax:
_.fromQuery( URL_Query);
Parameters: This method accepts a single parameter as mentioned above and described below:
URL_Query: This method takes a URL Query String to convert into JavaScript object.
Return Value: This method returns the equivalent JavaScript Object.
Note: This will not work in normal JavaScript because it requires the lodash.js contrib library to be installed. Lodash.js contrib library can be installed using npm install lodash-contrib –save.
Example 1:
Javascript
// Defining lodash contrib variable var _ = require('lodash-contrib');   var s  = _.fromQuery("https://geeksforgeeks.org/path/to/page?name=ferret&color=purple");     console.log("The generated JavaScript Object is : ", s);
Output:
The generated JavaScript Object is :
Object {
color: "purple" ,
https://geeksforgeeks.org/path/to/page?name: "ferret"
}

Example 2:
Javascript
// Defining lodash contrib variable var _ = require('lodash-contrib');   var s  = _.fromQuery("https://practice.geeksforgeeks.org/courses/?ref=gfg_header");    console.log("The generated JavaScript Object is : ", s);
Output:
The generated JavaScript Object is :
Object {https://practice.geeksforgeeks.org/courses/?ref: "gfg_header"}

JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Lodash _.groupBy() Method
JavaScript | Promises
Difference Between PUT and PATCH Request
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
REST API (Introduction)
How to fetch data from an API in ReactJS ?
Python | Dictionary has_key()

12 Apr, 2022
Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only a single value as an element, Dictionary holds key: value pair.
Note: has_key() method was removed in Python 3. Use the in operator instead.
In Python Dictionary, has_key() method returns true if specified key is present in the dictionary, else returns false. 
Syntax: dict.has_key(key)Parameters:
key – This is the Key to be searched in the dictionary.
Returns: Method returns true if a given key is available in the dictionary, otherwise it returns a false.
Example #1:  
Python
# Python program to show working# of has_key() method in Dictionary # Dictionary with three itemsDictionary1 = {'A': 'Geeks', 'B': 'For', 'C': 'Geeks'} # Dictionary to be checkedprint("Dictionary to be checked: ")print(Dictionary1) # Use of has_key() to check# for presence of a key in Dictionaryprint(Dictionary1.has_key('A'))print(Dictionary1.has_key('For'))
Output: 
Dictionary to be checked: 
{'A': 'Geeks', 'C': 'Geeks', 'B': 'For'}
True
False
Example #2:  
Python
# Python program to show working# of has_key() method in Dictionary # Dictionary with three itemsDictionary2 = {1: 'Welcome', 2: 'To', 3: 'Geeks'} # Dictionary to be checkedprint("Dictionary to be checked: ")print(Dictionary2) # Use of has_key() to check# for presence of a key in Dictionaryprint(Dictionary2.has_key(1))print(Dictionary2.has_key('To'))
Output: 
Dictionary to be checked: 
{1: 'Welcome', 2: 'To', 3: 'Geeks'}
True
False
Note : dict.has_key() has removed from Python 3.x
has_key() has been removed in Python 3. in operator is used to check whether a specified key is present or not in a Dictionary.
Example:  
Python3
# Python Program to search a key in Dictionary# Using in operator dictionary = {1: "Geeks", 2: "For", 3: "Geeks"} print("Dictionary: {}".format(dictionary)) # Return True if Present.if 1 in dictionary: # or "dictionary.keys()"    print(dictionary[1])else:    print("{} is Absent".format(1))  # Return False if not Present.if 5 in dictionary.keys():    print(dictionary[5])else:    print("{} is Absent".format(5))
Output: 
Dictionary: {1:"Geeks",2:"For",3:"Geeks"}
Geeks
5 is Absent 
Vikku_Sharma
victorbitman
nagulans
python-dict
Python-dict-functions
Python
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python - Tkinter Canvas

The Canvas is a rectangular area intended for drawing pictures or other complex layouts. You can place graphics, text, widgets or frames on a Canvas.
Here is the simple syntax to create this widget −
w = Canvas ( master, option=value, ... )

master − This represents the parent window.
master − This represents the parent window.
options − Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas.
options − Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas.
bd
Border width in pixels. Default is 2.
bg
Normal background color.
confine
If true (the default), the canvas cannot be scrolled outside of the scrollregion.
cursor
Cursor used in the canvas like arrow, circle, dot etc.
height
Size of the canvas in the Y dimension.
highlightcolor
Color shown in the focus highlight.
relief
Relief specifies the type of the border. Some of the values are SUNKEN, RAISED, GROOVE, and RIDGE.
scrollregion
A tuple (w, n, e, s) that defines over how large an area the canvas can be scrolled, where w is the left side, n the top, e the right side, and s the bottom.
width
Size of the canvas in the X dimension.
xscrollincrement
If you set this option to some positive dimension, the canvas can be positioned only on multiples of that distance, and the value will be used for scrolling by scrolling units, such as when the user clicks on the arrows at the ends of a scrollbar.
xscrollcommand
If the canvas is scrollable, this attribute should be the .set() method of the horizontal scrollbar.
yscrollincrement
Works like xscrollincrement, but governs vertical movement.
yscrollcommand
If the canvas is scrollable, this attribute should be the .set() method of the vertical scrollbar.
The Canvas widget can support the following standard items −
arc − Creates an arc item, which can be a chord, a pieslice or a simple arc.
coord = 10, 50, 240, 210
arc = canvas.create_arc(coord, start=0, extent=150, fill="blue")

image − Creates an image item, which can be an instance of either the BitmapImage or the PhotoImage classes.
filename = PhotoImage(file = "sunshine.gif")
image = canvas.create_image(50, 50, anchor=NE, image=filename)

line − Creates a line item.
line = canvas.create_line(x0, y0, x1, y1, ..., xn, yn, options)

oval − Creates a circle or an ellipse at the given coordinates. It takes two pairs of coordinates; the top left and bottom right corners of the bounding rectangle for the oval.
oval = canvas.create_oval(x0, y0, x1, y1, options)

polygon − Creates a polygon item that must have at least three vertices.
oval = canvas.create_polygon(x0, y0, x1, y1,...xn, yn, options)

Try the following example yourself −
import Tkinter

top = Tkinter.Tk()

C = Tkinter.Canvas(top, bg="blue", height=250, width=300)

coord = 10, 50, 240, 210
arc = C.create_arc(coord, start=0, extent=150, fill="red")

C.pack()
top.mainloop()
When the above code is  executed, it produces the following result −
How to pass a json object as a parameter to a python function?

We have this code below which will the given json object as a parameter to a python function.
import json
json_string = '{"name":"Rupert", "age": 25, "desig":"developer"}'
print type (json_string)
def func(strng):
    a =json.loads(strng)
    print type(a)
    for k,v in a.iteritems():
           print k,v
    print dict(a)      
func(json_string)
<type 'str'>
<type 'dict'>
desig developer
age 25
name Rupert
{u'desig': u'developer', u'age': 25, u'name': u'Rupert'}
Parsing Time in Golang

08 Jun, 2020
Parsing time is to convert our time to Golang time object so that we can extract information such as date, month, etc from it easily. We can parse any time by using time.Parse function which takes our time string and format in which our string is written as input and if there is no error in our format, it will return a Golang time object.
Examples:
Input : "2018-04-24"
Output : 2018-04-24 00:00:00 +0000 UTC

Input : "04/08/2017"
Output : 2017-04-08 00:00:00 +0000 UTC

Code:
// Golang program to show the parsing of timepackage main  import (    "fmt"    "time")  func main() {      // The date we're trying to     // parse, work with and format    myDateString := "2018-01-20 04:35"    fmt.Println("My Starting Date:\t", myDateString)      // Parse the date string into Go's time object    // The 1st param specifies the format,    // 2nd is our date string    myDate, err := time.Parse("2006-01-02 15:04", myDateString)    if err != nil {        panic(err)    }      // Format uses the same formatting style    // as parse, or we can use a pre-made constant    fmt.Println("My Date Reformatted:\t", myDate.Format(time.RFC822))      // In YY-MM-DD    fmt.Println("Just The Date:\t\t", myDate.Format("2006-01-02"))}
Output:
My Starting Date:     2018-01-20 04:35
My Date Reformatted:     20 Jan 18 04:35 UTC
Just The Date:         2018-01-20

GoLang-time
Picked
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
strings.Replace() Function in Golang With Examples
fmt.Sprintf() Function in Golang With Examples
Arrays in Go
Golang Maps
How to Split a String in Golang?
Interfaces in Golang
Slices in Golang
Different Ways to Find the Type of Variable in Golang
How to Parse JSON in Golang?
How to Trim a String in Golang?
Plotting graph using seaborn in python.

Plotly's Python graphing library makes interactive, publication-quality graphs online. this graph is mainly used when we want to make line plots, scatter plots, area charts, bar charts, error bars, box plots, histograms, heatmaps, subplots, multiple-axes, polar charts, and bubble charts.
Seaborn is a library for making statistical graphics in Python. It is built on top of matplotlib and it is integrated with pandas data structures.
1. We import seaborn, which is the only library necessary for this simple example.
import seaborn as sns

2. We apply the default default seaborn theme, scaling, and color palette.
sns.set()

3. We load one of the example datasets.
tips = sns.load_dataset("tips")

4. We draw a faceted scatter plot with multiple semantic variables.
# This Python program will illustrate scatter plot with Seaborn
# importing modules
import matplotlib.pyplot as plt
import seaborn as sns
# values for x-axis 
x=['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] 
# valueds for y-axis 
y=[10.5, 12.5, 11.4, 11.2, 9.2, 14.5, 10.1] 
# plotting with seaborn
my_plot = sns.stripplot(x, y);
# assigning x-axis and y-axis labels
my_plot.set(xlabel ='Day Names', ylabel ='Turn Over (In Million Dollars)') 
# assigning plot title
plt.title('Scatter Plot'); 
# function to show plot 
plt.show()
Lodash _.lowerCase() Method - GeeksforGeeks

07 Sep, 2020
Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc.
The _.lowerCase() method is used to convert the given string, as space separated words, to lower case.
Syntax:
_.lowerCase([string=''])

Parameters: This method accepts single parameter as mentioned above and described below:
string: This parameter holds the string that need to convert into lower case.
Return Value: This method returns the lower cased string.
Example 1:
Javascript
const _ = require('lodash');   var str1 = _.lowerCase("GEEKS FOR GEEKS");console.log(str1);  var str2 = _.lowerCase("GFG--Geeks");console.log(str2);
Output:
"geeks for geeks"
"gfg geeks"

Example 2:
Javascript
const _ = require('lodash');   var str1 = _.lowerCase("GEEKS__FOR__GEEKS");console.log(str1);  var str2 = _.kebabCase("G4G--geeks--GEEKS");console.log(str2);  var str3 = _.kebabCase("GEEKS-----FOR_____Geeks");console.log(str3);
Output:
"geeks for geeks"
"g-4-g-geeks-geeks"
"geeks-for-geeks"

JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Differences between Functional Components and Class Components in React
Convert a string to an integer in JavaScript
Hide or show elements in HTML using display property
Set the value of an input field in JavaScript
How to calculate the number of days between two dates in javascript?
Express.js express.Router() Function
Installation of Node.js on Linux
How to set input type date in dd-mm-yyyy format using HTML ?
Differences between Functional Components and Class Components in React
How to create footer to stay at the bottom of a Web page?
How to access a NumPy array by column - GeeksforGeeks

29 May, 2021
Accessing a NumPy based array by a specific Column index can be achieved by the indexing. Let’s discuss this in detail.
NumPy follows standard 0 based indexing.
Row and column in NumPy are similar to Python List
Examples:
Given array : 1 13 6
              9  4 7
              19 16 2

Input: print(NumPy_array_name[ :,2])

# printing 2nd column
Output: [6 7 2]

Input: x =  NumPy_array_name[ :,1]
       print(x)

# storing 1st column into variable x
Output:  [13 4 16]
Method #1: Selection using slices
Syntax :
For column : numpy_Array_name[  : ,column] 
For row : numpy_Array_name[ row, :  ]
Python3
# Python code to select row and column# in NumPy import numpy as np array = [[1, 13, 6], [9, 4, 7], [19, 16, 2]] # defining arrayarr = np.array(array) print('printing array as it is')print(arr) print('printing 0th row')print(arr[0, :]) print('printing 2nd column')print(arr[:, 2]) # multiple columns or rows can be selected as wellprint('selecting 0th and 1st row simultaneously')print(arr[:,[0,1]])
 Output :
printing array as it is
[[ 1 13  6]
 [ 9  4  7]
 [19 16  2]]
printing 0th row
[ 1 13  6]
printing 2nd column
[6 7 2]
selecting 0th and 1st row simultaneously
[[ 1 13]
 [ 9  4]
 [19 16]]
 
Method #2: Using Ellipsis
Syntax :
For column : numpy_Array_name[...,column]
For row : numpy_Array_name[row,...]
where ‘...‘ represents no of elements in the given row or column 
Note: This is not a very practical method but one must know as much as they can.
Python3
# program to select row and column# in numpy using ellipsis import numpy as np # defining arrayarray = [[1, 13, 6], [9, 4, 7], [19, 16, 2]] # converting to numpy arrayarr = np.array(array) print('printing array as it is')print(arr) print('selecting 0th column')print(arr[..., 0]) print('selecting 1st row')print(arr[1, ...])
Output :
printing array as it is
[[ 1 13  6]
 [ 9  4  7]
 [19 16  2]]
selecting 0th column
[ 1  9 19]
selecting 1st row
[9 4 7]
ireshaupulie
Python numpy-Indexing
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
*args and **kwargs in Python
Check if element exists in list in Python
Convert integer to string in Python
C# StartsWith() Method

The StartsWith() method in C# is used to determine whether the beginning of this string instance matches the specified string.
public bool StartsWith (string val);
Above, val is the string to compare.
 Live Demo
using System;
public class Demo {
   public static void Main() {
      string str = "JohnAndJacob";
      Console.WriteLine("String = "+str);
      Console.WriteLine("Does String begins with J? = "+str.StartsWith("J"));
      char[] destArr = new char[20];
      str.CopyTo(1, destArr, 0, 4);
      Console.Write(destArr);
   }
}
This will produce the following output -
String = JohnAndJacob
Does String begins with J? = True
ohnA
Let us now see another example -
 Live Demo
using System;
public class Demo {
   public static void Main(String[] args) {
      string str1 = "Akon";
      string str2 = "Eminem";
      Console.WriteLine("String 1 = "+str1);
      Console.WriteLine("HashCode of String 1 = "+str1.GetHashCode());
      Console.WriteLine("Does String1 begins with E? = "+str1.StartsWith("E"));
      Console.WriteLine("\nString 2 = "+str2);
      Console.WriteLine("HashCode of String 2 = "+str2.GetHashCode());
      Console.WriteLine("Does String2 begins with E? = "+str2.StartsWith("E"));
      Console.WriteLine("\nString 1 is equal to String 2? = {0}", str1.Equals(str2));
   }
}
This will produce the following output -
String 1 = Akon
HashCode of String 1 = 416613838
Does String1 begins with E? = False
String 2 = Eminem
HashCode of String 2 = 40371907
Does String2 begins with E? = True
String 1 is equal to String 2? = False
How to copy a collection from one database to another in MongoDB?

In MongoDB, the command does not exist to copy a collection from one database to another. To achieve it, use the below concept −
db.yourCollectionName.find().forEach(function(yourVariableName){
   db.getSiblingDB('yourDestinationDatabase')['yourCollectionName'].insert(yourVariableName);
});
Let us create a collection in the test database and copy this collection to another database with the name „sample‟.
To understand the above syntax, let us create a collection with the document. The query to create a collection with a document is as follows −
<test>
> use test
switched to db test
> db.copyThisCollectionToSampleDatabaseDemo.insertOne({"User_Id":101,"UserName":"Larr
y"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c77ad622386c62d05142a67")
}
> db.copyThisCollectionToSampleDatabaseDemo.insertOne({"User_Id":102,"UserName":"Maxwell"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c77ad6e2386c62d05142a68")
}
> db.copyThisCollectionToSampleDatabaseDemo.insertOne({"User_Id":103,"UserName":"Robert"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c77ad7c2386c62d05142a69")
}
Display all documents from a collection with the help of find() method. The query is as follows −
> db.copyThisCollectionToSampleDatabaseDemo.find().pretty();
The following is the output −
{
   "_id" : ObjectId("5c77ad622386c62d05142a67"),
   "User_Id" : 101,
   "UserName" : "Larry"
}
{
   "_id" : ObjectId("5c77ad6e2386c62d05142a68"),
   "User_Id" : 102,
   "UserName" : "Maxwell"
}
{
   "_id" : ObjectId("5c77ad7c2386c62d05142a69"),
   "User_Id" : 103,
   "UserName" : "Robert"
}
Let us check the sample database has a collection with the name “copyThisCollectionToSampleDatabaseDemo” or not.
The query is as follows −
<sample>
> use sample;
switched to db sample
> show collections;
The following is the output −
deleteDocuments
deleteDocumentsDemo
deleteInformation
employee
internalArraySizeDemo
sourceCollection
updateInformation
userInformation
So, there is no collection with name “copyThisCollectionToSampleDatabaseDemo”.
Now we will copy the above collection from a test database to sample database. The query is as follows −
> use test;
switched to db test
> db.copyThisCollectionToSampleDatabaseDemo.find().forEach(function(send){
db.getSiblingDB('sample')['copyThisCollectionToSampleDatabaseDemo'].insert(send); });
Now let us check once again the collection is copied or not successfully in the sample database.
The query is as follows −
> use sample;
switched to db sample
> show collections;
The following is the output −
copyThisCollectionToSampleDatabaseDemo
deleteDocuments
deleteDocumentsDemo
deleteInformation
employee
internalArraySizeDemo
sourceCollection
updateInformation
userInformation
Look at the sample output, the collection “copyThisCollectionToSampleDatabaseDemo” is present in the sample database while it is present in the test database also.
Creating an index on a nested MongoDB field?

You can use dot(.) notation for this. Let us first create a collection with documents −
> db.createIndexOnNestedFieldDemo.insertOne(
   {"UserDetails":{"UserPersonalDetails":{"UserFirstName":"John","UserLastName":"Smith"}}});
   {
      "acknowledged" : true,
      "insertedId" : ObjectId("5ce929c778f00858fb12e916")
   }
>
> db.createIndexOnNestedFieldDemo.insertOne( {"UserDetails":{"UserPersonalDetails":{"UserFirstName":"Chris","UserLastName":"Brown"}}});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ce929d678f00858fb12e917")
}
> db.createIndexOnNestedFieldDemo.insertOne( {"UserDetails":{"UserPersonalDetails":{"UserFirstName":"David","UserLastName":"Miller"}}});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ce929e378f00858fb12e918")
}
Following is the query to display all documents from a collection with the help of find() method −
> db.createIndexOnNestedFieldDemo.find().pretty();
This will produce the following output −
{
   "_id" : ObjectId("5ce929c778f00858fb12e916"),
   "UserDetails" : {
      "UserPersonalDetails" : {
         "UserFirstName" : "John",
         "UserLastName" : "Smith"
      }
   }
}
{
   "_id" : ObjectId("5ce929d678f00858fb12e917"),
   "UserDetails" : {
      "UserPersonalDetails" : {
         "UserFirstName" : "Chris",
         "UserLastName" : "Brown"
      }
   }
}
{
   "_id" : ObjectId("5ce929e378f00858fb12e918"),
   "UserDetails" : {
      "UserPersonalDetails" : {
         "UserFirstName" : "David",
         "UserLastName" : "Miller"
      }
   }
}
Following is the query to create an index on a nested field −
>db.createIndexOnNestedFieldDemo.createIndex({"UserDetails.UserPersonalDetails.UserLastName":1});
This will produce the following output −
{
   "createdCollectionAutomatically" : false,
   "numIndexesBefore" : 1,
   "numIndexesAfter" : 2,
   "ok" : 1
}
What are the DDL commands in DBMS?

Data definition language (DDL) is a language that allows the user to define the data and their relationship to other types of data.
Data Definition language statements work with the structure of the database table.
Various data types used in defining columns in a database table
Various data types used in defining columns in a database table
Integrity and value constraints
Integrity and value constraints
Viewing, modifying and removing a table structure
Viewing, modifying and removing a table structure
The Data Definition Languages (DDL) Commands are as follows −
Create − It is used to create a new table or a new database.
Create − It is used to create a new table or a new database.
Alter − It is used to alter or change the structure of the database table.
Alter − It is used to alter or change the structure of the database table.
Drop − It is used to delete a table, index, or views from the database.
Drop − It is used to delete a table, index, or views from the database.
Truncate − It is used to delete the records or data from the table, but its structure remains as it is.
Truncate − It is used to delete the records or data from the table, but its structure remains as it is.
Rename − It is used to rename an object from the database.
Rename − It is used to rename an object from the database.
When you create a table, you have to specify the following −
Table name.
Table name.
Name of each column.
Name of each column.
Data type of each column.
Data type of each column.
Size of each column.
Size of each column.
When a table is created, each column in the table is assigned a data type.
Some of the important data types are as follows −
Varchar2
Varchar2
Char
Char
Number
Number
Let’s see each DDL command with an example.
Create
It is used to create a new table or a new database.
An example of the create command is as follows −
create table student(stdname varchar(20) , branch varchar(20),college varchar(20), age number, telephone number, address varchar(20));
A student table is created with the fields given below −
Alter
It is used to alter or change the structure of the database table
An example of the alter command is as follows −
ALTER TABLE student ADD birthdate DATETIME
Drop
It is used to delete a table, index, or views from the database.
An example of the drop command is as follows −
 DROP TABLE student
When and where static blocks are executed in java?

A static block is a block of code with a static keyword. In general, these are used to initialize the static members. JVM executes static blocks before the main method at the time of class loading.
 Live Demo
public class MyClass {
   static{
      System.out.println("Hello this is a static block");
   }
   public static void main(String args[]){
      System.out.println("This is main method");
   }
}
Hello this is a static block
This is main method
JVM first looks for the main method (at least the latest versions) and then, starts executing the program including static block. Therefore, you cannot execute a static block without main method.
 Live Demo
public class Sample {
   static {
      System.out.println("Hello how are you");
   }
}
Since the above program doesn’t have a main method, if you compile and execute it you will get an error message.
C:\Sample>javac StaticBlockExample.java
C:\Sample>java StaticBlockExample
Error: Main method not found in class StaticBlockExample, please define the main
method as: public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application
If you want to execute static block you need to have Main method and, static blocks of the class get executed before main method.
 Live Demo
public class StaticBlockExample {
   static {
      System.out.println("This is static block");
   }
   public static void main(String args[]){
      System.out.println("This is main method");
   }
}
This is static block
This is main method
C++ Vector Library - resize() Function

The C++ function std::vector::resize() changes the size of vector. If n is smaller than current size then extra elements are destroyed.
If n is greater than current container size then new elements are inserted at the end of vector.
If val is specified then new elements are initialed with val.
Following is the declaration for std::vector::resize() function form std::vector header.
void resize (size_type n, value_type val = value_type());

void resize (size_type n);
void resize (size_type n, const value_type& val);

n − New container size.
n − New container size.
val − Initial value for container elements.
val − Initial value for container elements.
None.
If reallocation fails then bad_alloc exception is thrown.
Linear i.e. O(n)
The following example shows the usage of std::vector::resize() function.
#include <iostream>
#include <vector>

using namespace std;

int main(void) {
   vector<int> v;

   cout << "Initial vector size = " << v.size() << endl;

   v.resize(5, 10);
   cout << "Vector size after resize = " << v.size() << endl;

   cout << "Vector contains following elements" << endl;
   for (int i = 0; i < v.size(); ++i)
      cout << v[i] << endl;

   return 0;
}
Let us compile and run the above program, this will produce the following result −
Initial vector size = 0
Vector size after resize = 5
Vector contains following elements
10
10
10
10
10

 Print
 Add Notes
 Bookmark this page