code-rag-bench/online-tutorials huggingface dataset:
C++ Program to Compare Binary and Sequential Search

Binary Search and Sequential or Linear Search both are used in computer programming to search an element. The time complexity of Binary Search is O(log(n)) and Sequential Search is O(n).
Begin
   Algorithm for Binary Search:
   BinarySearch() function with ‘arr’ the array of data and ‘n’ the number of values, start and end index, iteration count and element to be searched in the argument list.
   Increment iteration counter and compare the item value with the a[mid].
   If item < a[mid] choose first half otherwise second half to proceed further.
   Return iteration value on successful search.
End
#include<iostream>
using namespace std;
int BinarySearch(int a[], int start, int end, int item, int iter) {
   int i, mid;
   cout<<"\niteration "<<iter+1;
   iter++;
   mid = start + (end-start+1)/2;
   if(item > a[end] || item < a[start] || mid == end) {
      cout<<"\nNot found";
      return iter;
   } else if(item == a[mid]) {
      cout<<"\n item found at "<<mid<<" index.";
      return iter;
   } else if(item == a[start]) {
      cout<<"\n item found at "<<start<<" index.";
      return iter;
   } else if(item == a[end]) {
      cout<<"\n item found at "<<end<<" index.";
      return iter;
   } else if(item > a[mid])
         BinarySearch(a, mid, 9, item, iter);
      else
         BinarySearch(a, start, mid, item, iter);
   }
   int LinearSearch(int a[], int n, int item) {
      int i;
      for(i = 0; i < n; i++) {
         cout<<"\niteration "<<i+1;
         if(a[i] == item) {
            cout<<"\n item found at "<<i<<" index.";
         return i+1;
      }
   }
   cout<<"\nNot found";
}
int main() {
   int n, i, B, L, a[10]={2, 7, 14, 24, 26, 35, 38, 41, 49, 53};
   cout<<"\nEnter the element to be searched: ";
   cin>>n;
   cout<<"\n\n\t\t\tBinary Search :";
   B = BinarySearch(a, 0, 9, n, 0);
   cout<<"\n\n\t\t\tLinear Search :";
   L = LinearSearch(a, 10, n);
   if(L > B)
      cout<<"\n\nBinary search is better for this search.";
   else if(L < B)
      cout<<"\n\nLinear search is better for this search.";
   else
      cout<<"\n\nBoth are equally efficient for this search.";
   return 0;
}
Enter the element to be searched: 7
Binary Search :
iteration 1
iteration 2
iteration 3
iteration 4
item found at 1 index.
Linear Search :
iteration 1
iteration 2
item found at 1 index.
Linear search is better for this search.
Enter the element to be searched: 53
Binary Search :
iteration 1
item found at 9 index.
Linear Search :
iteration 1
iteration 2
iteration 3
iteration 4
iteration 5
iteration 6
iteration 7
iteration 8
iteration 9
iteration 10
item found at 9 index.
Binary search is better for this search.
Enter the element to be searched: 1
Binary Search :
iteration 1
Not found
Linear Search :
iteration 1
iteration 2
iteration 3
iteration 4
iteration 5
iteration 6
iteration 7
iteration 8
iteration 9
iteration 10
Not found
Binary search is better for this search.
How to use map() to Create Lists in ReactJS ? - GeeksforGeeks

23 Jul, 2021
An array in JavaScript comes with a plethora of functions to work with. A map() is one such function that is used to create a list of objects by calling a function on each element of the array. In React, we can use the map() function to map a list of values to a list of components.
Let’s see how we can create a list in react using a simple project. The project has a list of fruit names, and we will change them into a list of components rendered in the browser.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:npx create-react-app listmapdemo 
Step 1: Create a React application using the following command:
npx create-react-app listmapdemo
 
Step 2: After creating your project folder i.e. listmapdemo, move to it using the following command:cd listmapdemo
Step 2: After creating your project folder i.e. listmapdemo, move to it using the following command:
cd listmapdemo
Project Structure: It will look like the following.
Project Structure
Example: While creating components using the map, react expects a key prop passed to each component being built. It will still render if the key is not passed, but you will see a warning from React about it in the console. In the App.js file, we have defined a list of fruits which is then mapped to a list of divs.
App.js
import React from "react"  function App() {    // Declared an array of items  const fruits = [    'Apple',    'Mango',    'Banana',    'GFG'  ];    // Some styling for the items  const styles = {    backgroundColor: 'white',    width: '50px',    marginBottom: '10px',    padding: '10px',    color: 'green',    boxShadow: 'rgb(0,0,0,0.44) 0px 5px 5px',  };    return <>    {      /*  This maps each array item to a div adds      the style declared above and return it */      fruits.map(fruit => <div key={fruit}             style={styles}>{fruit}</div>)    }  </>;}  export default App;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Explanation: We declared a list of fruits that will be used to render divs. The styles object contains CSS styles for each item, it simply adds some margin, padding and some shadow. Finally, the App function returns a list of divs that are returned by calling map() on the fruits array. We added the styles object to the style attribute of each div.
kapoorsagar226
Picked
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ReactJS useNavigate() Hook
Axios in React: A Guide for Beginners
How to set background images in ReactJS ?
How to create a table in ReactJS ?
How to navigate on path by button click in react router ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
PyQt5 QListWidget – Setting Selection Behaviour - GeeksforGeeks

06 Aug, 2020
In this article we will see how we can set the selection behavior of the QListWidget. QListWidget is a convenience class that provides a list view with a classic item-based interface for adding and removing items. QListWidget uses an internal model to manage each QListWidgetItem in the list. Selection behavior describes how user can select the item, it can be row or it can be column or it can be single item.
In order to do this we will use setSelectionBehavior method with the list widget object.
Syntax : list_widget.setSelectionBehavior(behaviour)
Argument : It takes behaviour object 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, 500, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()          # method for components    def UiComponents(self):          # creating a QListWidget        list_widget = QListWidget(self)          # setting geometry to it        list_widget.setGeometry(50, 70, 150, 60)          # list widget items        item1 = QListWidgetItem("PyQt5 Geeks for Geeks")        item2 = QListWidgetItem("B")        item3 = QListWidgetItem("C")          # adding items to the list widget        list_widget.addItem(item1)        list_widget.addItem(item2)        list_widget.addItem(item3)          # setting selection behaviour        list_widget.setSelectionBehavior(QAbstractItemView.SelectItems)          # setting word wrap property        list_widget.setWordWrap(True)          # creating a label        label = QLabel("GeesforGeeks", self)          # setting geometry to the label        label.setGeometry(230, 80, 280, 80)          # making label multi line        label.setWordWrap(True)        # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python PyQt-QListWidget
Python-gui
Python-PyQt
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 Convert Python Dictionary To JSON?
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Get unique values from a list
Python | Pandas dataframe.groupby()
Tryit Editor v3.7

Tryit basic HTML headings
Groovy - isEmpty()

Returns true if this List contains no elements.
boolean isEmpty() 

None
True or false depending on whether the list is empty or not.
Following is an example of the usage of this method −
class Example { 
   static void main(String[] args) { 
      def lst = [11, 12, 13, 14]; 
      def emptylst = [];
		
      println(lst.isEmpty()); 
      println(emptylst.isEmpty()); 
   } 
}
When we run the above program, we will get the following result −
false 
true


    52 Lectures 
     8 hours 

 Krishna Sakinala

    49 Lectures 
     2.5 hours 

 Packt Publishing
 Print
 Add Notes
 Bookmark this page
CherryPy - ToolBox

Within CherryPy, built-in tools offer a single interface to call the CherryPy library. The tools defined in CherryPy can be implemented in the following ways −
From the configuration settings
As a Python decorator or via the special _cp_config attribute of a page handler
As a Python callable that can be applied from within any function
The purpose of this tool is to provide basic authentication to the application designed in the application.
This tool uses the following arguments −
Let us take an example to understand how it works −
import sha
import cherrypy

class Root:
@cherrypy.expose
def index(self):

return """
<html>
   <head></head>
   <body>
      <a href = "admin">Admin </a>
   </body>
</html>
""" 

class Admin:

@cherrypy.expose
def index(self):
return "This is a private area"

if __name__ == '__main__':
def get_users():
# 'test': 'test'
return {'test': 'b110ba61c4c0873d3101e10871082fbbfd3'}
def encrypt_pwd(token):

return sha.new(token).hexdigest()
   conf = {'/admin': {'tools.basic_auth.on': True,
      tools.basic_auth.realm': 'Website name',
      'tools.basic_auth.users': get_users,
      'tools.basic_auth.encrypt': encrypt_pwd}}
   root = Root()
root.admin = Admin()
cherrypy.quickstart(root, '/', config=conf)
The get_users function returns a hard-coded dictionary but also fetches the values from a database or anywhere else. The class admin includes this function which makes use of an authentication built-in tool of CherryPy. The authentication encrypts the password and the user Id.
The basic authentication tool is not really secure, as the password can be encoded and decoded by an intruder.
The purpose of this tool is to provide memory caching of CherryPy generated content.
This tool uses the following arguments −
The purpose of this tool is to decode the incoming request parameters.
This tool uses the following arguments −
Let us take an example to understand how it works −
import cherrypy
from cherrypy import tools

class Root:
@cherrypy.expose
def index(self):

return """ 
<html>
   <head></head>
   <body>
      <form action = "hello.html" method = "post">
         <input type = "text" name = "name" value = "" />
         <input type = ”submit” name = "submit"/>
      </form>
   </body>
</html>
"""

@cherrypy.expose
@tools.decode(encoding='ISO-88510-1')
def hello(self, name):
return "Hello %s" % (name, )
if __name__ == '__main__':
cherrypy.quickstart(Root(), '/')
The above code takes a string from the user and it will redirect the user to "hello.html" page where it will be displayed as “Hello” with the given name.
The output of the above code is as follows −
hello.html

 Print
 Add Notes
 Bookmark this page
Construct a Turing Machine for language L = {a^n b^m c^nm where n >=0 and m >= 0} - GeeksforGeeks

12 Jun, 2020
Prerequisite – Turing Machine
The language L = {anbmcnm | n >= 0 and m>=0} represents a kind of language where we use only 3 symbols, i.e., a, b and c. In the beginning language has n number of a’s followed by m number of b’s and then n*m number of c’s. Any such string which falls in this category will be accepted by this language.
Examples:
Input : abbcc
Output : YES

Input : abbbcc
Output : NO

Input :  or empty string
Output : YES 
Basic Representation :
Start of Computation :The tape contains the input string w, the tape head is on the leftmost symbol of w, and the Turing machine is in the start state Q0.
Basic Idea :The tape head reads the leftmost symbol of w, which is a and at start only we will make it Blank. Then we will traverse to make leftmost b a $ and replace rightmost c by a Blank, we will do this zigzag pattern of replacing b by $ and c by Blank till all b are not replaced by $.After this we will traverse back in left direction till we get leftmost a and replacing all $ by b in the traversal. After this we have reduced our string into form an-1bmcnm-m so we can figure if all a’s are replaced by blankand if the string belongs to Language L then there will be no c’s left hence it will get accepted.
Meanings of symbols used:R, L – direction of movement of one unit on either side.B-Blank,a, b, c -symbols whose combination string is to be tested.$-Temporarily symbol to replace b.
Working Procedure :
Step-1:We first replace leftmost a by Blank and then traverse to replace leftmost b by $ and rightmost c by Blank.Repeat this step from state Q1 till there is no more b left.
Step-2:After replacing all b by $ we have also replaced m rightmost c’s with Blanks and then we will traverse back to left most a and replace all $ by b’s.After this step if check the string it is now reduced to an-1bmcnm-m form.Now we will repeat from step 1 till all a’s are not made Blank.
Step-3:So after all a’s are made blank and if the string belonged to Language L then 0 c’s must be left which we check at state Q0 and Q6 as only b’s will be left and after which if Blank is found then all c’s must have been replace by Blank as we where making c’s Blank from rightmost end of the string.
Step-4:So if we get a Blank symbol at state Q6 the the string is accepted at final state Q7. Also if the string was empty then it will also be accepted as Blank symbol input at state Q0 then it will got to state Q7 and gets accepted.
Theory of Computation & Automata
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Chomsky Hierarchy in Theory of Computation
Converting Context Free Grammar to Chomsky Normal Form
Introduction of Pushdown Automata
Construct Pushdown Automata for given languages
How to identify if a language is regular or not
Introduction of Theory of Computation
Simplifying Context Free Grammars
Closure properties of Regular languages
Closure Properties of Context Free Languages
Recursive and Recursive Enumerable Languages in TOC
CICS - ENDBR

When we have finished reading a file sequentially, we terminate the browse using the ENDBR command. It tells the CICS that the browse is being terminated.
Following is the syntax of the ENDBR command −
EXEC CICS ENDBR
   FILE ('name')
END-EXEC.

 Print
 Add Notes
 Bookmark this page
Python | Tokenizing strings in list of strings

29 Apr, 2019
Sometimes, while working with data, we need to perform the string tokenization of the strings that we might get as an input as list of strings. This has a usecase in many application of Machine Learning. Let’s discuss certain ways in which this can be done.
Method #1 : Using list comprehension + split()
We can achieve this particular task using list comprehension to traverse for each strings from list of strings and split function performs the task of tokenization.
# Python3 code to demonstrate# Tokenizing strings in list of strings# using list comprehension + split()  # initializing listtest_list = ['Geeks for Geeks', 'is', 'best computer science portal']  # printing original listprint("The original list : " + str(test_list))  # using list comprehension + split()# Tokenizing strings in list of stringsres = [sub.split() for sub in test_list]  # print resultprint("The list after split of strings is : " + str(res))
The original list : [‘Geeks for Geeks’, ‘is’, ‘best computer science portal’]The list after split of strings is : [[‘Geeks’, ‘for’, ‘Geeks’], [‘is’], [‘best’, ‘computer’, ‘science’, ‘portal’]]
 
Method #2 : Using map() + split()This is yet another method in which this particular task can be solved. In this method, we just perform the similar task as above, just we use map function to bind the split logic to the entire list.
# Python3 code to demonstrate# Tokenizing strings in list of strings# using map() + split()  # initializing listtest_list = ['Geeks for Geeks', 'is', 'best computer science portal']  # printing original listprint("The original list : " + str(test_list))  # using map() + split()# Tokenizing strings in list of stringsres = list(map(str.split, test_list))  # print resultprint("The list after split of strings is : " + str(res))
The original list : [‘Geeks for Geeks’, ‘is’, ‘best computer science portal’]The list after split of strings is : [[‘Geeks’, ‘for’, ‘Geeks’], [‘is’], [‘best’, ‘computer’, ‘science’, ‘portal’]]
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
UGC-NET | UGC NET CS 2017 Jan – III | Question 72

03 Apr, 2018
A neuron with 3 inputs has the weight vector [0.2 –0.1 0.1]T and a bias θ = 0. If the input vector is X = [0.2 0.4 0.2]T then the total input to the neuron is :(A) 0.20(B) 1.0(C) 0.02(D) –1.0Answer: (C)Explanation:
Given:
 weight vector(WT) = [0.2 –0.1 0.1]T 
   input vector(X) = [0.2 0.4 0.2]T
                Θ  = 0
f(x) = WT*X + Θ
i.e. = [0.2 –0.1 0.1] *  [0.2 0.4 0.2] + 0
     = [0.2 * 0.2 – 0.1 * 0.4 + 0.1 * 0.2] + 0
     = 0.02
So, option (C) is correct.Quiz of this Question
UGC-NET
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
UGC-NET | UGC NET CS 2016 Aug - III | Question 32
UGC-NET | UGC NET CS 2015 Jun - III | Question 64
UGC-NET | UGC NET CS 2015 Jun - III | Question 35
UGC-NET | UGC NET CS 2015 Jun - III | Question 33
UGC-NET | UGC NET CS 2015 Jun - II | Question 1
UGC-NET | UGC NET CS 2015 Jun - III | Question 34
UGC-NET | UGC NET CS 2015 Jun - III | Question 31
UGC-NET | UGC NET CS 2018 July - II | Question 26
UGC-NET | UGC NET CS 2016 July – III | Question 32
UGC-NET | UGC NET CS 2018 July - II | Question 21
Python | Denoising of colored images using opencv

14 Jan, 2019
Denoising of an image refers to the process of reconstruction of a signal from noisy images. Denoising is done to remove unwanted noise from image to analyze it in better form. It refers to one of the major pre-processing steps. There are four functions in opencv which is used for denoising of different images.
Syntax: cv2.fastNlMeansDenoisingColored( P1, P2, float P3, float P4, int P5, int P6)
Parameters:P1 – Source Image ArrayP2 – Destination Image ArrayP3 – Size in pixels of the template patch that is used to compute weights.P4 – Size in pixels of the window that is used to compute a weighted average for the given pixel.P5 – Parameter regulating filter strength for luminance component.P6 – Same as above but for color components // Not used in a grayscale image.
Below is the implementation:
# importing librariesimport numpy as npimport cv2from matplotlib import pyplot as plt  # Reading image from folder where it is storedimg = cv2.imread('bear.png')  # denoising of image saving it into dst imagedst = cv2.fastNlMeansDenoisingColored(img, None, 10, 10, 7, 15)  # Plotting of source and destination imageplt.subplot(121), plt.imshow(img)plt.subplot(122), plt.imshow(dst)  plt.show()
Output:
Image-Processing
OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Drop duplicate rows in PySpark DataFrame

16 Dec, 2021
In this article, we are going to drop the duplicate rows by using distinct() and dropDuplicates() functions from dataframe using pyspark in Python. 
Let’s create a sample Dataframe
Python3
# importing moduleimport pyspark # importing sparksession from# pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving# an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list  of employee datadata = [["1", "sravan", "company 1"],        ["2", "ojaswi", "company 1"],        ["3", "rohith", "company 2"],        ["4", "sridevi", "company 1"],        ["1", "sravan", "company 1"],        ["4", "sridevi", "company 1"]] # specify column namescolumns = ['Employee ID', 'Employee NAME', 'Company'] # creating a dataframe from the# lists of datadataframe = spark.createDataFrame(data, columns) print('Actual data in dataframe')dataframe.show()
Output:
Distinct data means unique data. It will remove the duplicate rows in the dataframe
Syntax: dataframe.distinct()
where, dataframe is the dataframe name created from the nested lists using pyspark
Python3
print('distinct data after dropping duplicate rows') # display distinct datadataframe.distinct().show()
Output:
We can use the select() function along with distinct function to get distinct values from particular columns
Syntax: dataframe.select([‘column 1′,’column n’]).distinct().show()
Python3
# display distinct data in Employee# ID and Employee NAMEdataframe.select(['Employee ID', 'Employee NAME']).distinct().show()
Output:
Syntax: dataframe.dropDuplicates()
where, dataframe is the dataframe name created from the nested lists using pyspark
Python3
# remove duplicate data using# dropDuplicates()functiondataframe.dropDuplicates().show()
Output:
Python program to remove duplicate values in specific columns
Python3
# remove duplicate data using# dropDuplicates() function in# two columnsdataframe.select(['Employee ID', 'Employee NAME']                ).dropDuplicates().show()
Output:
sagar0719kumar
Picked
Python-Pyspark
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stack.ToArray() Method in C#

04 Feb, 2019
This method(comes under System.Collections namespace) is used to copy a Stack to a new array. The elements are copied onto the array in last-in-first-out (LIFO) order, similar to the order of the elements returned by a succession of calls to Pop. This method is an O(n) operation, where n is Count.
Syntax:
public virtual object[] ToArray ();

Return Type: This method returns a new array of type System.Object containing copies of the elements of the Stack.
Below given are some examples to understand the implementation in a better way:
Example 1:
// C# code to illustrate the// Stack.ToArray() Methodusing System;using System.Collections;  class GFG {      // Driver code    public static void Main()    {          // Creating a Stack        Stack myStack = new Stack();          // Inserting the elements into the Stack        myStack.Push("Geeks");        myStack.Push("Geeks Classes");        myStack.Push("Noida");        myStack.Push("Data Structures");        myStack.Push("GeeksforGeeks");          // Converting the Stack into array        Object[] arr = myStack.ToArray();          // Displaying the elements in array        foreach(Object str in arr)        {            Console.WriteLine(str);        }    }}
GeeksforGeeks
Data Structures
Noida
Geeks Classes
Geeks

Example 2:
// C# code to illustrate the// Stack.ToArray() Methodusing System;using System.Collections;  class GFG {      // Driver code    public static void Main()    {          // Creating a Stack        Stack myStack = new Stack();          // Inserting the elements into the Stack        myStack.Push(2);        myStack.Push(3);        myStack.Push(4);        myStack.Push(5);        myStack.Push(6);          // Converting the Stack into array        Object[] arr = myStack.ToArray();          // Displaying the elements in array        foreach(Object i in arr)        {            Console.WriteLine(i);        }    }}
6
5
4
3
2

Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.stack.toarray?view=netframework-4.7.2
CSharp-Collections-Namespace
CSharp-Collections-Stack
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between Abstract Class and Interface in C#
C# Dictionary with examples
C# | How to check whether a List contains a specified element
C# | Arrays of Strings
Introduction to .NET Framework
C# | IsNullOrEmpty() Method
String.Split() Method in C# with Examples
C# | Multiple inheritance using interfaces
Differences Between .NET Core and .NET Framework
C# | Delegates
What is TYPE_SCROLL_SENSITIVE ResultSet in JDBC?

This represents is a scrollable ResultSet i.e. the cursor moves in forward or backward directions. This type of ResultSet is sensitive to the changes that are made in the database i.e. the modifications done in the database are reflected in the ResultSet.
Which means if we have established a connection with a database using a JDBC program and retrieved a ResultSet holding all the records in a table named SampleTable. Meanwhile, if we have added some more records to the table (after retrieving the ResultSet), these recent changes will be reflected in the ResultSet object we previously obtained.
Following is an example which demonstrates how to create the TYPE_SCROLL_SENSITIVE result set.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
public class ScrollSensitive {
   public static void main(String[] args) throws Exception {
      //Registering the Driver
      DriverManager.registerDriver(new com.mysql.jdbc.Driver());
      //Getting the connection
      String url = "jdbc:mysql://localhost/testdb";
      Connection con = DriverManager.getConnection(url, "root", "password");
      //Creating a Statement object
      Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
      stmt.setFetchSize(1);
   }
}
How to use Django Field Choices ?

03 Nov, 2019
Django Field Choices. According to documentation Field Choices are a sequence consisting itself of iterables of exactly two items (e.g. [(A, B), (A, B) ...]) to use as choices for some field. For example, consider a field semester which can have options as { 1, 2, 3, 4, 5, 6 } only. Choices limits the input from the user to the particular values specified in models.py. If choices are given, they’re enforced by model validation and the default form widget will be a select box with these choices instead of the standard text field. Choices can be any sequence object – not necessarily a list or tuple.
The first element in each tuple is the actual value to be set on the model, and the second element is the human-readable name.For example,
SEMESTER_CHOICES = (
    ("1", "1"),
    ("2", "2"),
    ("3", "3"),
    ("4", "4"),
    ("5", "5"),
    ("6", "6"),
    ("7", "7"),
    ("8", "8"),
)

Let us create a choices field with above semester in our django project named geeksforgeeks.
from django.db import models  # specifying choices  SEMESTER_CHOICES = (    ("1", "1"),    ("2", "2"),    ("3", "3"),    ("4", "4"),    ("5", "5"),    ("6", "6"),    ("7", "7"),    ("8", "8"),)  # declaring a Student Model  class Student(models.Model):      semester = models.CharField(        max_length = 20,        choices = SEMESTER_CHOICES,        default = '1'        )
Let us check in admin panel how semester is created.One can also collect your available choices into named groups that can be used for organizational purposes:
MEDIA_CHOICES = [
    ('Audio', (
            ('vinyl', 'Vinyl'),
            ('cd', 'CD'),
        )
    ),
    ('Video', (
            ('vhs', 'VHS Tape'),
            ('dvd', 'DVD'),
        )
    ),
    ('unknown', 'Unknown'),
]

The first element in each tuple is the name to apply to the group. The second element is an iterable of 2-tuples, with each 2-tuple containing a value and a human-readable name for an option. Grouped options may be combined with ungrouped options within a single list (such as the unknown option in this example).For each model field that has choices set, Django will add a method to retrieve the human-readable name for the field’s current value. See get_FOO_display() in the database API documentation.
Django-models
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Iterate over a list in Python
Python Classes and Objects
Convert integer to string in Python
How to insert DATE in MySQL table with TRIGGERS?

Let us first create a table −
mysql> create table DemoTable1584
   -> (
   -> DueDate datetime
   -> );
Query OK, 0 rows affected (1.79 sec)
Here is the query to insert DATE in a MySQL −
mysql> create trigger insertDate before insert on DemoTable1584
   ->  for each row set new.DueDate=curdate();
Query OK, 0 rows affected (0.22 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1584 values();
Query OK, 1 row affected (0.66 sec)
mysql> insert into DemoTable1584 values();
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable1584 values();
Query OK, 1 row affected (0.07 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1584;
This will produce the following output −
+---------------------+
| DueDate             |
+---------------------+
| 2019-10-18 00:00:00 |
| 2019-10-18 00:00:00 |
| 2019-10-18 00:00:00 |
+---------------------+
3 rows in set (0.00 sec)
How to Install Numpy on MacOS?

22 Sep, 2021
In this article, we will learn how to install Numpy in Python on MacOS. NumPy is a library for the Python programming language, adding support for large, multi-dimensional arrays and matrices, along with a large collection of high-level mathematical functions to operate on these arrays.
Follow the below steps to install the Numpy package on macOS using pip:
Step 1: Install the latest Python3 in MacOS
Step 2: Check if pip3 and python3 are correctly installed.
python3 --version
pip3 --version
Step 3: Upgrade your pip to avoid errors during installation.
pip3 install --upgrade pip
Step 4: Enter the following command to install Numpy  using pip3.
pip3 install numpy 
Follow the below steps to install the Numpy package on macOS using the setup.py file:
Step 1: Download the latest source package of Numpy for python3 from here.
curl https://files.pythonhosted.org/packages/3a/be/650f9c091ef71cb01d735775d554e068752d3ff63d7943b26316dc401749/numpy-1.21.2.zip > numpy.tar.gz
Step 2: Extract the downloaded package using the following command.
tar -xzvf numpy.tar.gz
Step 3: Go inside the folder and Enter the following command to install the package.
Note: You must have developer tools for XCode MacOS installed in your system
cd numpy-1.21.2
python3 setup.py install
Make the following import in your python terminal to verify if the installation has been done properly:
import numpy
If there is any error while importing the module then is not installed properly.
Blogathon-2021
how-to-install
Picked
Blogathon
How To
Installation Guide
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to break a loop in JavaScript?

The break statement is used to break a loop and continue executing the code, which is after the loop.
You can try to run the following code to break a loop in JavaScript
Live Demo
<!DOCTYPE html>
<html>
   <body>
      <p id="test"></p>
      <script>
         var text = "";
         var i;

         for (i = 0; i < 5; i++) {
            if (i === 2) {
               break;
            }
            text += "Value: " + i + "<br>";
         }
         document.getElementById("test").innerHTML = text;
      </script>
   </body>

</html>
Value: 0
Value: 1
Sequential Digits in C++

Suppose we have an integer, that has sequential digits if and only if each digit in the number is one more than the previous digit. We have to find a sorted list of all the integers in the range [low, high] inclusive that have sequential digits. So if the low = 100 and high = 300, then the output will be [123,234]
To solve this, we will follow these steps −
create one array res
for i in range 1 to nfor j := 1, until j + i – 1 <= 9x := 0for k in range 0 to i – 1x := 10x + (j + k)if low < x and x <= high, then insert x into ans
for j := 1, until j + i – 1 <= 9x := 0for k in range 0 to i – 1x := 10x + (j + k)if low < x and x <= high, then insert x into ans
x := 0
for k in range 0 to i – 1x := 10x + (j + k)
x := 10x + (j + k)
if low < x and x <= high, then insert x into ans
return ans
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<auto> v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
      cout << v[i] << ", ";
   }
   cout << "]"<<endl;
}
class Solution {
   public:
   vector<int> sequentialDigits(int low, int high) {
      vector <int> ans;
      for(int i = 1; i <= 9; i++){
         for(int j = 1; j + i - 1 <= 9; j++){
            int x = 0;
            for(int k = 0; k < i; k++){
               x = (x*10) + (j + k);
            }
            if(low <= x && x <= high){
               ans.push_back(x);
            }
         }
      }
      return ans;
   }
};
main(){
   Solution ob;
   print_vector(ob.sequentialDigits(500, 5000));
}
500
5000
[567, 678, 789, 1234, 2345, 3456, 4567, ]
How to Assign Default Value for Struct Field in Golang?

22 Jun, 2020
Default values can be assigned to a struct by using a constructor function. Rather than creating a structure directly, we can use a constructor to assign custom default values to all or some of its members.
Example 1:
// Golang program to assign// default values to a struct // using constructor functionpackage main  import (    "fmt")  // declaring a student structtype Student struct{          // declaring struct variables    name string    marks int64    age int64}  // constructor functionfunc(std *Student) fill_defaults(){      // setting default values    // if no values present    if std.name == "" {        std.name = "ABC"    }          if std.marks == 0 {        std.marks = 40    }          if std.age == 0 {        std.age = 18    }}  // main functionfunc main() {      // creating a struct where    // only the name is initialised    std1 := Student{name: "Vani"}          // printing the struct     // with no default values    fmt.Println(std1)          // this will assign default values     // to non-initialised valiables    // in struct std1    std1.fill_defaults()          // printing after assigning    // defaults to struct variables    fmt.Println(std1)          // creating a struct where    // age and marks are initialised    std2 := Student{age: 19, marks: 78}          // assigning default name    std2.fill_defaults()          // printing after assigning     // default name to struct    fmt.Println(std2)      }
Output:
{Vani 0 0}
{Vani 40 18}
{ABC 78 19}

Another way of assigning default values to structs is by using tags. Tags can only be used for string values only and can be implemented by using single quotes(”).
Example 2:
// Golang program to assign// default values to a struct // using tags  package main  import (    "fmt"    "reflect")  // declaring a person structtype Person struct {      // setting the default value     // of name to "geek"      name string `default:"geek"`   }  func default_tag(p Person) string {      // TypeOf returns type of     // interface value passed to it      typ := reflect.TypeOf(p)      // checking if null string      if p.name == "" {                  // returns the struct field         // with the given parameter "name"            f, _ := typ.FieldByName("name")                  // returns the value associated         // with key in the tag string        // and returns empty string if         // no such key in tag            p.name = f.Tag.Get("default")      }        return fmt.Sprintf("%s", p.name)}  // main functionfunc main(){      // prints out the default name     fmt.Println("Default name is:", default_tag(Person{}))}
Output:
Default name is: geek

Golang-Program
Picked
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Golang Maps
Interfaces in Golang
Data Types in Go
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?
Pointers in Golang
Channel in Golang
How to iterate over an Array using for loop in Golang?
JavaScript - Nested Functions

Prior to JavaScript 1.2, function definition was allowed only in top level global code, but JavaScript 1.2 allows function definitions to be nested within other functions as well. Still there is a restriction that function definitions may not appear within loops or conditionals. These restrictions on function definitions apply only to function declarations with the function statement.
As we'll discuss later in the next chapter, function literals (another feature introduced in JavaScript 1.2) may appear within any JavaScript expression, which means that they can appear within if and other statements.
Try the following example to learn how to implement nested functions.
<html>
   <head>
      <script type = "text/javascript">
         <!--
            function hypotenuse(a, b) {
               function square(x) { return x*x; }
               return Math.sqrt(square(a) + square(b));
            }
            function secondFunction() {
               var result;
               result = hypotenuse(1,2);
               document.write ( result );
            }
         //-->
      </script>
   </head>
   
   <body>
      <p>Click the following button to call the function</p>
      
      <form>
         <input type = "button" onclick = "secondFunction()" value = "Call Function">
      </form>
      
      <p>Use different parameters inside the function and then try...</p>
   </body>
</html>
Click the following button to call the function
Use different parameters inside the function and then try...
2D vector in C++ with user defined size

A vector of a vector is called 2D vector.
Begin
   Declare a variable v to the 2D vector type.
   Initialize values to the vector v.
   Print “the 2D vector is:”.
   for (int i = 0; i < v.size(); i++)
      for (int j = 0; j < v[i].size(); j++)
         print the value of 2D vector v[i][j].
End.
 Live Demo
#include <iostream>
#include <vector> //header file for 2D vector in C++
using namespace std;
int main() {
   vector<vector<int> > v{ { 4,5, 3, 10 }, // initializing 2D vector with values.
   { 2, 7, 11 },
   { 3, 2, 1, 12 } };
   cout<<"the 2D vector is:"<<endl;
   for (int i = 0; i < v.size(); i++) { // printing the 2D vector.
      for (int j = 0; j < v[i].size(); j++)
      cout << v[i][j] << " ";
      cout << endl;
   }
   return 0;
}
the 2D vector is: 
4 5 3 10
2 7 11 
3 2 1 12
Tri-Surface Plot in Python using Matplotlib

11 Nov, 2021
A Tri-Surface Plot is a type of surface plot, created by triangulation of compact surfaces of finite number of triangles which cover the whole surface in a manner that each and every point on the surface is in triangle. The intersection of any two triangles results in void or a common edge or vertex. This type of plot is created where the evenly sampled grids are restrictive and inconvenient to plot. Generally Tri-Surface plots are created by calling ax.plot_trisurf() function of matplotlib library. Some of the attributes of the function are listed below:
Example 1: Let’s create a basic Tri-Surface plot using the ax.plot_trisurf() function. 
Python3
# Import librariesfrom mpl_toolkits import mplot3dimport numpy as npimport matplotlib.pyplot as plt  # Creating datasetz = np.linspace(0, 50000, 100)x = np.sin(z)y = np.cos(z) # Creating figurefig = plt.figure(figsize =(14, 9))ax = plt.axes(projection ='3d') # Creating plotax.plot_trisurf(x, y, z,                linewidth = 0.2,                antialiased = True); # show plotplt.show()
Output : 
Example 2 : For better understanding Let’s take another example. 
Python3
# Import librariesfrom mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as np   # Creating radii and anglesr = np.linspace(0.125, 1.0, 100) a = np.linspace(0, 2 * np.pi,                100,                endpoint = False)    # Repeating all angles for every radius a = np.repeat(a[..., np.newaxis], 100, axis = 1)    # Creating datasetx = np.append(0, (r * np.cos(a))) y = np.append(0, (r * np.sin(a)))   z = (np.sin(x ** 4) + np.cos(y ** 4))   # Creating figurefig = plt.figure(figsize =(16, 9)) ax = plt.axes(projection ='3d')  # Creating color mapmy_cmap = plt.get_cmap('hot')   # Creating plottrisurf = ax.plot_trisurf(x, y, z,                         cmap = my_cmap,                         linewidth = 0.2,                         antialiased = True,                         edgecolor = 'grey') fig.colorbar(trisurf, ax = ax, shrink = 0.5, aspect = 5)ax.set_title('Tri-Surface plot') # Adding labelsax.set_xlabel('X-axis', fontweight ='bold')ax.set_ylabel('Y-axis', fontweight ='bold')ax.set_zlabel('Z-axis', fontweight ='bold')     # show plotplt.show()
Output: 
 
singghakshay
anikakapoor
Matplotlib Artist-class
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
tuple() Function in Python

23 Oct, 2020
The tuple() function is a built-in function in Python that can be used to create a tuple.
A tuple is an immutable sequence type.
Syntax:
tuple(iterable)  

Parameters: This function accepts a single parameter iterable (optional). It is an iterable(list, range etc..) or an iterator object. If an iterable is passed, the corresponding tuple is created. If the iterable is not passed, empty tuple is created .
Returns: It does not returns any-thing but creates a tuple.
Error and Exception: It returns a TypeError, if an iterable is not passed.
Below programs illustrate tuple() function in Python:Program 1: Program demonstrating the use of tuple() function
# Python3 program demonstrating# the use of tuple() function  # when parameter is not passedtuple1 = tuple()print(tuple1)  # when an iterable(e.g., list) is passedlist1= [ 1, 2, 3, 4 ] tuple2 = tuple(list1)print(tuple2)  # when an iterable(e.g., dictionary) is passeddict = { 1 : 'one', 2 : 'two' } tuple3 = tuple(dict)print(tuple3)  # when an iterable(e.g., string) is passedstring = "geeksforgeeks" tuple4 = tuple(string)print(tuple4)
Output:
()
(1, 2, 3, 4)
(1, 2)
('g', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'g', 'e', 'e', 'k', 's')

Program 2: Program demonstrating the TypeError
# Python3 program demonstrating # the TypeError in tuple() function  # Error when a non-iterable is passedtuple1 = tuple(1) print(tuple1)
Output:
Traceback (most recent call last):
  File "/home/eaf759787ade3942e8b9b436d6c60ab3.py", line 5, in 
    tuple1=tuple(1) 
TypeError: 'int' object is not iterable
Akanksha_Rai
Python-Functions
python-tuple
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
HTTP status codes | Informational Responses

31 Oct, 2019
The HTTP status codes are used to indicate that any specific HTTP request has successfully completed or not. The HTTP status codes are categorized into five sections those are listed below:
Informational responses (100–199)
Successful responses (200–299)
Redirects (300–399)
Client errors (400–499)
Server errors (500–599)
There are four Informational Responses those are Continue, Switching Protocols, Processing, and Early Hints. All of them are described below:
100 Continue: The HTTP 100 Continue Informational Response status code is used to inform the client that till now everything is OKAY with the request. If the work is done then the client will ignore it if it’s not done yet then the client will proceed with the other requests. The server needs to send a final response when the request has been completed.When the request contains the Expect header field that includes 100-continue expectation, the 100 response indicates that the server waiting to receive the request payload body. The client does not need to send the request-header with the 100-continue expectation. If it does not wish to send a request body.Status:100 Continue
100 Continue
101 Switching Protocols: The HTTP 101 Switching Protocol Informational Response status code is used to indicate the protocols that are going to switch for the client request which includes the upgrade request header for the protocols. This status code can be used with the WebSockets.Status:101 Switching ProtocolsExample: Performing with the websockets.HTTP/1.1 101 Switching Protocols
Upgrade: websocket 
Connection: Upgrade
Status:
101 Switching Protocols
Example: Performing with the websockets.
HTTP/1.1 101 Switching Protocols
Upgrade: websocket 
Connection: Upgrade
102 Processing: The 102 Processing Informational Response status code is used to indicate that the server received the request and working on the request but in response, there is nothing till now.
103 Early Hints: The 103 Early Hints Informational Response status code is used with the link header to allow the User-Agent to reloading the resources when the server is preparing a response. So basically when the server is working on to prepare the response then, the 103 Early Hints forcefully reloading the resources so the server can have few times on preparing a response.Status:103 Early Hints
103 Early Hints
Supported Browsers: The browsers compatible with the HTTP status codes Informational Responses are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
HTTP- response-status-codes
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js fs.readFileSync() Method
How to set the default value for an HTML <select> element ?
How do you run JavaScript script through the Terminal?
Node.js | fs.writeFileSync() Method
ReactJS setState()
Difference between var, let and const keywords in JavaScript
How to set space between the flexbox ?
How to create footer to stay at the bottom of a Web page?
Differences between Functional Components and Class Components in React
JavaScript | promise resolve() Method
How to get the thread ID from a thread in C#?

A thread is defined as the execution path of a program. Each thread defines a unique
flow of control. If your application involves complicated and time-consuming
operations, then it is often helpful to set different execution paths or threads, with
each thread performing a particular job.
Threads are lightweight processes. One common example of use of thread is
implementation of concurrent programming by modern operating systems. Use of
threads saves wastage of CPU cycle and increase efficiency of an application.
In C#, the System.Threading.Thread class is used for working with threads. It allows creating and accessing individual threads in a multithreaded application. The first thread to be executed in a process is called the main thread.
When a C# program starts execution, the main thread is automatically created. The
threads created using the Thread class are called the child threads of the main thread.
You can access a thread using the CurrentThread property of the Thread class.
class Program{
   public static void Main(){
      Thread thr;
      thr = Thread.CurrentThread;
      thr.Name = "Main thread";
      Console.WriteLine("Name of current running " + "thread: {0}", Thread.CurrentThread.Name);
      Console.WriteLine("Id of current running " + "thread: {0}", Thread.CurrentThread.ManagedThreadId);
      Console.ReadLine();
   }
}
Name of current running thread: Main thread
Id of current running thread: 1