code-rag-bench/online-tutorials huggingface dataset:
Data Structures | Linked List | Question 1

05 Jan, 2013
What does the following function do for a given Linked List with first node as head?
void fun1(struct node* head)
{
  if(head == NULL)
    return;
  
  fun1(head->next);
  printf("%d  ", head->data);
}

(A) Prints all nodes of linked lists(B) Prints all nodes of linked list in reverse order(C) Prints alternate nodes of Linked List(D) Prints alternate nodes in reverse orderAnswer: (B)
 
Explanation: fun1() prints the given Linked List in reverse manner. For Linked List 1->2->3->4->5, fun1() prints 5->4->3->2->1. See https://www.geeksforgeeks.org/practice-questions-for-linked-list-and-recursion/
Data Structures
Data Structures-Linked List
Linked Lists
Data Structures
Data Structures
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Gulp - Cleaning Unwanted Files

In this chapter, you will learn how to clean generated files. As we are automatically generating the files, make sure that unnecessary files should be deleted before running your build. This procedure is called cleaning. The del plugin can be used for this purpose.
In your command line install the plugin by entering the following command.
npm install del --save-dev

In your configuration file gulpfile.js, declare the dependencies as shown in the following command.
var del = require('del');

Next, create a task as shown in the following code.
gulp.task('clean:build', function() {
   return del.sync('build');
});

The above task will clean entire build. The clean task clears any image catches and removes any old files present in build.
It is possible to clean only specific file or folder and leave some of them untouched as illustrated in the following code.
gulp.task('clean:build', function() {
   //return del.sync('build');
   return del([
      'build/temp/',
      // instructs to clean temp folder
      '!build/package.json'
      // negate to instruct not to clean package.json file ]);
});
In the above task, only the temp folder will be cleaned leaving package.json untouched.
 Print
 Add Notes
 Bookmark this page
Mark different color points on matplotlib

03 Jun, 2020
Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack.
In this article, the task is to mark different color points in a graph based on a condition that the values of the elements of the list say x is less than or equal to 7 should be colored in blue and those greater should be colored magenta. The idea is to plot a graph having points grouped under one condition in different colors, basically to group the clusters in one color. For this, we run a loop for all values of x and assign a color value to the corresponding value of x. A list will be made of blue and magenta colors specifying the color at the ith index.
Below is the implementation.
import  numpy as npimport matplotlib.pyplot as plt    # values of xx = np.array([1, 2, 3, 4, 5,              6, 7, 8, 9, 10])  # values of yy = np.array([10, 9, 8, 7, 6, 5,              4, 3, 2, 1])  # empty list, will hold color value# corresponding to xcol =[]  for i in range(0, len(x)):    if x[i]<7:        col.append('blue')      else:        col.append('magenta')   for i in range(len(x)):          # plotting the corresponding x with y     # and respective color    plt.scatter(x[i], y[i], c = col[i], s = 10,                linewidth = 0)        plt.show()
Output:
Python-matplotlib
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
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | Delete items from dictionary while iterating

16 May, 2022
A dictionary in Python is an ordered collection of data values. Unlike other Data Types that hold only a single value as an element, a dictionary holds the key: value pairs. Dictionary keys must be unique and must be of an immutable data type such as a: string, integer or tuple.
Note: In Python 2 dictionary keys were unordered. As of Python 3, they are ordered.
Let’s see how to delete items from a dictionary while iterating over it. 
Method #1: Using del() method  
Python3
# Creating a dictionarymyDict = {1: 'Geeks', 2: 'For', 3: 'Geeks'} # Iterating through the keysfor key in myDict.keys():    if key == 2:        del myDict[key] # Modified Dictionaryprint(myDict)
Output:
{1: 'Geeks', 3: 'Geeks'}
The above code works fine for Python2, (as in that version dictionary keys were unordered). But if we run it with Python3, it throws the following error:  
for key in myDict.keys():
RuntimeError: dictionary changed size during iteration
This runtime error says changing the size of the dictionary during iteration is not allowed (but it is possible). Now, let’s see all the different ways we can delete items from the dictionary while iterating. 
Method #2: Creating a List of Keys to delete
Here we use a list comprehension to build a list of all the keys that need to be deleted and then iterate through each key in that list deleting them:
Python3
# Creating a dictionarymyDict = {1: 'Geeks', 2: 'For', 3: 'Geeks'} # Using a list comprehension to make a list of the keys to be deleted# (keys having value in 3.)delete = [key for key in myDict if key == 3] # delete the key/sfor key in delete:    del myDict[key] # Modified Dictionaryprint(myDict)
Output: 
{1: 'Geeks', 2: 'For'}
Or if you’re new to list comprehensions:
We can build up the list of keys to delete using a for loop for that do create a list delete and add keys of all the values we want to delete. 
Python
# Creating a dictionarymyDict = {1: 'Geeks', 2: 'For', 3: 'Geeks'} # create a list of keys to deletedelete = []for key in myDict:    if key == 3:        delete.append(key) for i in delete:    del myDict[i] # Modified Dictionaryprint(myDict)
Method #3: Using list(myDict)  
Python3
# Creating a dictionarymyDict = {1: 'Geeks', 2: 'For', 3: 'Geeks'} # Iterating through the list of keysfor key in list(myDict):    if key == 2:        del myDict[key] # Modified Dictionaryprint(myDict)
Output: 
{1: 'Geeks', 3: 'Geeks'}
sreemo207
raedali480145
Python dictionary-programs
python-dict
Python
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to create Non-Rectangular Header using HTML & CSS ?

25 Mar, 2021
In this article, we are going to create a Non-Rectangular-header using the basics of HTML and CSS.
Approach:
Create a header using <header> tag.
Create a div for adding the content for the header.
Use clip-path() function to give a particular shape to the header.
HTML Code:
Create an HTML file (index.html).
Link the CSS file that provides all the animation’s effect on HTML. The CSS file is linked inside the head section of the webpage.
Coming to the body section of our HTML code.Create a header tag.Create a div tag and assign the class to it.Add a heading and paragraph to that particular div.
Create a header tag.
Create a div tag and assign the class to it.
Add a heading and paragraph to that particular div.
HTML
<!DOCTYPE html><html lang="en">  <head>    <title>Document</title>    <link rel="stylesheet" href="style.css"></head>  <body>    <header>        <div class="main_box">            <h1>Geeks For Geeks</h1>            <p>A computer science portal for geeks</p>        </div>    </header></body>  </html>
CSS Code: The following code added inside “style.css” file and used in the HTML code. CSS is used to give different types of animations and effects to HTML page so that it is interactive to all users.
Restore all the browser effects.
Use classes and ids to give effects to HTML elements.
Use CSS clip-path() function to give a particular shape to the header.
style.css
*{    margin: 0;    padding: 0;    box-sizing: border-box;}  body{    background-color: #000;}  header{    height: 65vh;    background-color: rgb(37, 142, 8);    clip-path:    polygon(0 0, 100% 0, 100% 50vh,         80% 60vh, 60% 50vh, 40% 60vh,         20% 50vh, 0 60vh);    border-radius: 10em;}  .main_box{    position: absolute;    top: 25%;    left: 50%;    text-align: center;    transform: translate(-50%,-50%);}  h1{    font-size: 3.85em;    margin: 0.25em;}  p{    font-size: 2em;}
Combining the above two sections (HTML and CSS) of codes and run it on the browser.
Output:
CSS-Properties
CSS-Questions
HTML-Attributes
HTML-Questions
HTML-Tags
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a Tribute Page using HTML & CSS
How to set space between the flexbox ?
Build a Survey Form using HTML and CSS
Design a web page using HTML and CSS
Form validation using jQuery
REST API (Introduction)
Hide or show elements in HTML using display property
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Design a Tribute Page using HTML & CSS
Python – Round Off Dictionary Values to K decimals

01 Aug, 2020
Given Dictionary with float values perform round off to K of all the values.
Input : {“Gfg” : 54.684034, “is” : 76.324334, “Best” : 28.43524}, K = 2Output : {“Gfg” : 54.68, “is” : 76.32, “Best” : 28.43}Explanation : Values rounded till 2.
Input : {“Gfg” : 54.684034, “is” : 76.324334, “Best” : 28.43524}, K = 1Output : {“Gfg” : 54.6, “is” : 76.3, “Best” : 28.4}Explanation : Values rounded till 1.
Method #1 : Using loop + round()
This is one of the ways in which this task can be performed. In this, we iterate for all the values, and perform round off to nearest K values using round().
Python3
# Python3 code to demonstrate working of # Round Off Dictionary Values to K decimals# Using loop + round()  # initializing dictionarytest_dict = {"Gfg" : 54.684034, "is" : 76.324334, "Best" : 28.43524}  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # initializing K K = 3  # loop to iterate for values res = dict()for key in test_dict:          # rounding to K using round()    res[key] = round(test_dict[key], K)  # printing result print("Values after round off : " + str(res)) 
The original dictionary is : {'Gfg': 54.684034, 'is': 76.324334, 'Best': 28.43524}
Values after round off : {'Gfg': 54.684, 'is': 76.324, 'Best': 28.435}


Method #2 : Using dictionary comprehension + round()
This is yet another way in which this task can be performed. In this we performed similar task using above functionality, the difference being usage of dictionary comprehension to provide one-line solution.
Python3
# Python3 code to demonstrate working of # Round Off Dictionary Values to K decimals# Using dictionary comprehension + round()  # initializing dictionarytest_dict = {"Gfg" : 54.684034, "is" : 76.324334, "Best" : 28.43524}  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # initializing K K = 3  # Encapsulating solution using single comprehensionres = {key : round(test_dict[key], K) for key in test_dict}  # printing result print("Values after round off : " + str(res)) 
The original dictionary is : {'Gfg': 54.684034, 'is': 76.324334, 'Best': 28.43524}
Values after round off : {'Gfg': 54.684, 'is': 76.324, 'Best': 28.435}

Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Search in Rotated Sorted Array in Python

Consider we have an array sorted in ascending order, and that is rotated at some pivot unknown to you beforehand. For example, [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]. We have given a target value to the search. If we can get it in the array, then return its index, otherwise return -1. We can assume no duplicate exists in the array. So if the array is like [4,5,6,7,0,1,2], then the output will be 4. as the index of this element is present at index 4.
To solve this, we will follow these steps −
low := 0 and high := length of array
while low < highfind mid as mid := low + (high - low)/2if arr[mid] = target, then return midif arr[low] <= arr[mid]if target >= arr[low] and target < arr[mid], then high := mid, otherwise low := mid + 1otherwiseif target <= arr[high - 1] and target > arr[mid], then low := mid + 1, otherwise high := mid
find mid as mid := low + (high - low)/2
if arr[mid] = target, then return mid
if arr[low] <= arr[mid]if target >= arr[low] and target < arr[mid], then high := mid, otherwise low := mid + 1
if target >= arr[low] and target < arr[mid], then high := mid, otherwise low := mid + 1
otherwiseif target <= arr[high - 1] and target > arr[mid], then low := mid + 1, otherwise high := mid
if target <= arr[high - 1] and target > arr[mid], then low := mid + 1, otherwise high := mid
return -1
Let us see the following implementation to get better understanding −
 Live Demo
class Solution(object):
   def search(self, nums, target):
      low = 0
      high = len(nums)
      while low<high:
         mid = low + (high-low)//2
         if nums[mid] == target:
            return mid
         if nums[low]<=nums[mid]:
            if target >=nums[low] and target <nums[mid]:
               high = mid
            else:
               low = mid+1
         else:
            if target<=nums[high-1] and target>nums[mid]:
               low = mid+1
            else:
               high = mid
      return -1
ob1 = Solution()
print(ob1.search([4,5,6,7,8,0,1,2], 0))
[4,5,6,7,0,1,2]
0
5
Python | Pandas Series.dt.day_name

20 Mar, 2019
Series.dt can be used to access the values of the series as datetimelike and return several properties. Pandas Series.dt.day_name() function return the day names of the DateTimeIndex with specified locale.
Syntax: Series.dt.day_name(*args, **kwargs)
Parameter :locale : Locale determining the language in which to return the day name. Default is English locale.
Returns : Index of day names.
Example #1: Use Series.dt.day_name() function to return the day names of the underlying datetime data in the given series object. Return the names of the day in English language.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(['2012-12-31 08:45', '2019-1-1 12:30', '2008-02-2 10:30',                '2010-1-1 09:25', '2019-12-31 00:00'])  # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5']  # set the indexsr.index = idx  # Convert the underlying data to datetime sr = pd.to_datetime(sr)  # Print the seriesprint(sr)
Output :
Now we will use Series.dt.day_name() function to return the names of the day of each timestamp in the given series object.
# return day name in englishresult = sr.dt.day_name(locale = 'English')  # print the resultprint(result)
Output :
As we can see in the output, the Series.dt.day_name() function has successfully returned the names of the day in the specified language.
Example #2 : Use Series.dt.day_name() function to return the day names of the underlying datetime data in the given series object. Return the names of the day in French language.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(pd.date_range('2012-12-31 09:45', periods = 5, freq = 'Q',                            tz = 'Europe / Berlin'))  # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5']  # set the indexsr.index = idx  # Print the seriesprint(sr)
Output :
Now we will use Series.dt.day_name() function to return the names of the day of each timestamp in the given series object.
# return day name in frenchresult = sr.dt.day_name(locale = 'French')  # print the resultprint(result)
Output :
As we can see in the output, the Series.dt.day_name() function has successfully returned the names of the day in the specified language.
Python pandas-series-datetime
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
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 | Get unique values from a list
Python | datetime.timedelta() function
How to vertically and horizontally align flexbox to center ?

14 May, 2021
As we already know, flexbox is a model and not just a CSS property.The below image shows a box with two axis, one is Main Axis (i.e. horizontal axis) and Cross Axis (i.e. vertical axis). And for aligning a flexbox in the centre, both horizontally and vertically, we are going to need to work on both of this axis.  
So, first of all, we need to remember two CSS properties here, and they are:  
justify-content
align-items
The first property, i.e. justify-content, is to align any HTML element on main axis, which is the horizontal axis. And the second property is to align any HTML element on a cross-axis, which is the vertical axis.So, to align an HTML element in the centre of the screen, both horizontally and vertically, we will have to set the value for both of these properties to ‘center’.Syntax:  
.gfg-box {
    display: flex;
    justify-content: center;
    align-items: center;
}
Example:  
html
<!DOCTYPE html><html lang="en"> <head>    <meta charset="UTF-8">    <title>Flexbox</title>    <style>        html,        body {            margin: 0;            padding: 0;            height: 100%;        }         .gfg-box {            display: flex;            justify-content: center;            align-items: center;            height: 100%;        }         .box {            padding: 8px 35px;            font-size: 30px;            color: green;            border: 10px solid green;        }    </style></head> <body>     <div class="gfg-box">        <div class="box">            <h1>GeeksforGeeks</h1>        </div>    </div> </body> </html>
Output:  
Note: The ‘height’ property should have the value of ‘100%’ in ‘HTML’, ‘body’ and ‘gfg-box’.To know more about flexbox and all its properties, refer to this article. 
ysachin2314
CSS-Properties
HTML5
Picked
CSS
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Types of CSS (Cascading Style Sheet)
How to set space between the flexbox ?
Design a Tribute Page using HTML & CSS
How to position a div at the bottom of its container using CSS?
How to Upload Image into Database and Display it using PHP ?
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
LinkedList indexOf() method in Java

10 Dec, 2018
The Java.util.LinkedList.indexOf(Object element) method is used to check and find the occurrence of a particular element in the list. If the element is present then the index of the first occurrence of the element is returned otherwise -1 is returned if the list does not contain the element.
Syntax:
LinkedList.indexOf(Object element)
Parameters: The parameter element is of the type LinkedList. It specifies the element whose occurrence is needed to be checked in the LinkedList.
Return Value: The method returns the index or position of the first occurrence of the element in the list else -1 if the element is not present in the list. The returned value is of integer type.
Below program illustrate the Java.util.LinkedList.indexOf() method:
// Java code to illustrate indexOf()import java.io.*;import java.util.LinkedList;  public class LinkedListDemo {   public static void main(String args[]) {        // Creating an empty LinkedList      LinkedList<String> list = new LinkedList<String>();        // Use add() method to add elements in the list      list.add("Geeks");      list.add("for");      list.add("Geeks");      list.add("10");      list.add("20");        // Displaying the list      System.out.println("LinkedList:" + list);              // The first position of an element       // is returned      System.out.println("The first occurrence of Geeks is at index:"                                               + list.indexOf("Geeks"));      System.out.println("The first occurrence of 10 is at index: "                                                 + list.indexOf("10"));     }}
LinkedList:[Geeks, for, Geeks, 10, 20]
The first occurrence of Geeks is at index: 0
The first occurrence of 10 is at index: 3

Java - util package
Java-Collections
Java-Functions
java-LinkedList
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
Collections in Java
Stream In Java
Multidimensional Arrays in Java
Stack Class in Java
Singleton Class in Java
Set in Java
Scanner and nextChar() in Java

19 Oct, 2016
Scanner class in Java supports nextInt(), nextLong(), nextDouble() etc. But there is no nextChar() (See this for examples)
To read a char, we use next().charAt(0). next() function returns the next token/word in the input as a string and charAt(0) function returns the first character in that string.
// Java program to read character using Scanner // classimport java.util.Scanner;public class ScannerDemo1{    public static void main(String[] args)    {        // Declare the object and initialize with        // predefined standard input object        Scanner sc = new Scanner(System.in);           // Character input        char c = sc.next().charAt(0);           // Print the read value        System.out.println("c = "+c);    }}
Input :
g
Output :
c = g
This article is contributed by Piyush Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Generate a Self-Signed Certificate with OpenSSL in Linux? - GeeksforGeeks

27 Feb, 2020
TLS (Transport Layer Security) is a secured protocol which is currently in trend. It can see used on top of the HTTP and application layer. The primary use of this protocol is to set up secure communication between web applications and servers. TLS protocol can also be used for secure email transfer, messaging and voice over IP.
Why SSL/TLS secure certificate?
Everyone wants a save website and secured payment gateways so that any kind of username, password and one-time password can not be used by a third party. SSL is a secure way of surfing the internet and it is used to protect our sensitive data. SSL/TLS is required to protect your websites.
Use of SSL/TLS secure certificate
We can use SSL/TLS secure certificate to establish an encrypted way of communication between you and the only recipient that you want to convey a message. We need a secure network packets so that it can not be accessed by third party. Here comes the role of the SSL/TLS secure certificate who can provide us the proper authentications while transferring network packets.
With the help of below command, we can generate our SSL certificate
openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365
This certificate is valid only for 365 days. Most of the parameters are fixed in this command like req, keyout and out. The private key name is up to your choice but it is required and the same for certificate as well. Below are the following steps that have to be followed to create this certificate.
Step 1: In this step, one should provide a password that is always required when you set up a connection with your server. One will not able to see the password while writing the password.
Step 2: In this step, one has to provide the country name with the starting two letters of your country.
Step 3: In this step one has to provide the full name of the state.
Step 4: In this step, one has to provide the organization name in which you are working or an organization for which this certificate is used for.
Step 5: In this step one has to provide the email address of your organization or if you are working as an individual one can give your email address.
After all the above steps are to be followed to make an SSL certificate and private key.
Private Key Generated:
SSL Certificate Generated:
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
scp command in Linux with Examples
mv command in Linux with examples
Docker - COPY Instruction
SED command in Linux | Set 2
chown command in Linux with Examples
nohup Command in Linux with Examples
Named Pipe or FIFO with example C program
Thread functions in C/C++
uniq Command in LINUX with examples
Start/Stop/Restart Services Using Systemctl in Linux
What is a block statement in JavaScript?

A block statement groups zero or more statements. In languages other than JavaScript, it is known as a compound statement.
Here’s the syntax −
{
   //List of statements
}
Variables with a block get scoped to the containing function. Block statement never introduce scope and using var to declare variables don’t have block scope.
var a = 20; {
   var b = 40;
}
Now, when you will print the value of a, it will print 40, not 20. This is because variable declared with a var within the block has the same scope like var before the block.
var a = 20; {
   var a = 40;
}
// this prints 40
document.write(a);
SciPy Matlab Arrays

We know that NumPy provides us with methods to persist the data in readable formats for 
Python.
But SciPy provides us with interoperability with Matlab as well.
SciPy provides us with the module scipy.io, which has functions for working with 
Matlab arrays.
The savemat() function allows us to export data in 
Matlab format.
The method takes the following parameters:

filename - the file name for saving data.
mdict - a dictionary containing the data.
do_compression - a boolean value that specifies whether to compress the 
result or not. Default False.

filename - the file name for saving data.
mdict - a dictionary containing the data.
do_compression - a boolean value that specifies whether to compress the 
result or not. Default False.
Export the following array as variable name "vec" to a mat file:
Note: The example above saves a file name "arr.mat" on your computer.
To open the file, check out the "Import Data from Matlab Format" example below:
The loadmat() function allows us to import data from a 
Matlab file.
The function takes one required parameter:

filename - the file name of the saved data.

It will return a structured array whose keys are the variable names, and the corresponding values are the variable values.
Import the array from following mat file.:



 {
   '__header__': b'MATLAB 5.0 MAT-file Platform: nt, Created on: Tue Sep 22 13:12:32 2020',
   '__version__': '1.0',
   '__globals__': [],
   'vec': array([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]])
 }


Use the variable name "vec" to display only the array from the matlab data:



 [[0 1 2 3 4 5 6 7 8 9]]


Note: We can see that the array originally was 1D,
but on extraction it has increased one dimension.
In order to resolve this we can pass an additional argument squeeze_me=True:



 [0 1 2 3 4 5 6 7 8 9]


Insert the missing method to export data in Matlab format:
from scipy import io
import numpy as np

arr = np.arange(10)

io.('arr.mat', {"vec": arr})

Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
How to align JLabel text vertically top in Java?

Use the setVerticalAlignment() method to align JLabel text vertically to the top:
JLabel label = label.setVerticalAlignment(JLabel.TOP);
The following is an example to align JLabel text vertically to the top:
import java.awt.Color;
import java.awt.Font;
import javax.swing.*;
import javax.swing.border.Border;
public class SwingDemo {
   public static void main(String args[]) {
      JFrame frame = new JFrame("Demo");
      JLabel label;
      label = new JLabel("This is demo label!");
      label.setFont(new Font("Verdana", Font.PLAIN, 14));
      label.setVerticalAlignment(JLabel.TOP);
      Border border = BorderFactory.createLineBorder(Color.ORANGE);
      label.setBorder(border);
      frame.add(label);
      frame.setSize(600,300);
      frame.setVisible(true);
   }
}
How to create filename containing date or time in Python - GeeksforGeeks

31 Aug, 2021
Prerequisite: DateTime module
In this article, we are going to see how to create filenames with dates or times using Python. 
For this, we will use the DateTime module. First, import the module and then get the current time with datetime.now() object. Now convert it into a string and then create a file with the file object like a regular file is created using file handling concepts in python.
Example 1: Creating text file containing date/time 
Python3
# import modulefrom datetime import datetime  # get current date and timecurrent_datetime = datetime.now()print("Current date & time : ", current_datetime)  # convert datetime obj to stringstr_current_datetime = str(current_datetime)  # create a file object along with extensionfile_name = str_current_datetime+".txt"file = open(file_name, 'w')  print("File created : ", file.name)file.close()
Output:
Current date & time : 2021-08-19 13:17:48.408908
File created :  2021-08-19 13:17:48.408908.txt
Any type of file can be created in this manner if the required extension is provided correctly.
Example 2:  Creating CSV file containing date/time 
Python3
# import modulefrom datetime import datetime  # get current date and timecurrent_datetime = datetime.now()print("Current date & time : ", current_datetime)  # convert datetime obj to stringstr_current_datetime = str(current_datetime)  # create a file object along with extensionfile_name = str_current_datetime+".csv"file = open(file_name, 'w')  print("File created : ", file.name)file.close()
Output:
Current date & time :  2021-08-19 13:19:29.667423
File created :  2021-08-19 13:19:29.667423.csv
Picked
Python datetime-program
Python file-handling-programs
python-csv
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
How to use “not in” query with C# LINQ?

Except operator are designed to allow you to query data which supports the IEnumerable<T< interface. Since all LINQ query expressions, and most LINQ queries, return IEnumerable<T<, these operators are designed to allow you to perform set operations on the results of a LINQ query.
The Except operator shows all the items in one list minus the items in a second list
class Program{
   static void Main(string[] args){
      var listA = Enumerable.Range(1, 6);
      var listB = new List<int> { 3, 4 };
      var listC = listA.Except(listB);
      foreach (var item in listC){
         Console.WriteLine(item);
      }
      Console.ReadLine();
   }
}
Here in the above example we have 2 list and we are fetching only those result from the list A which are not present in listb
1
2
5
6
Using Sql like syntax
static void Main(string[] args){
   var listA = Enumerable.Range(1, 6);
   var listB = new List<int> { 3, 4 };
   var listC = from c in listA
   where !listB.Any(o => o == c)
   select c;
   foreach (var item in listC){
      Console.WriteLine(item);
   }
   Console.ReadLine();
}
1
2
5
6
How to create a Custom Dialog box on iOS App using Swift?

To create a dialog box in swift we’ll make use of UIAlertController which is an important part of UIKit. We’ll do this with help of an iOS application and a sample project.
First of all, we’ll create an empty project, then inside its default view controller, we’ll perform the following operations.
We’ll create an UIAlertController object.
let alert = UIAlertController.init(title: title, message: description, preferredStyle: .alert)
We’ll create an action
let okAction = UIAlertAction.init(title: "Ok", style: .default) { _ in
   print("You tapped ok")
   //custom action here.
}
We’ll add the action to the alert and present it
alert.addAction(okAction)
self.present(alert, animated: true, completion: nil)
Now we’ll convert this to a function −
func createAlert(withTitle title:String,andDescription description: String) {
   let alert = UIAlertController.init(title: title, message: description, preferredStyle: .alert)
   let okAction = UIAlertAction.init(title: "Ok", style: .default) {
       _ in print("You tapped ok")
      //custom action here.
   }
   alert.addAction(okAction)
   self.present(alert, animated: true, completion: nil)
}
we’ll now call the function in our viewWillLayoutSubviews method, and this is how it looks when we run this on a device.
override func viewWillLayoutSubviews() {
   self.createAlert(withTitle: "This is an alert", andDescription: "Enter your description here.")
}
This produces the result as shown below.
Subarrays with K Different Integers in C++

Suppose we have an array A of positive integers, we can call a good subarray (contiguous) of A, if the number of different integers in that subarray is exactly K. So, if the array is like [1,2,3,1,2] has 3 different integers: 1, 2, and 3. We have to find the number of good subarrays of A.
So, if the input is like [1,2,3,1,4] and K = 3, then the output will be 4, as it can form three subarrays with exactly four distinct integers, these are [1,2,3], [1,2,3,1], [2,3,1], [3,1,4].
To solve this, we will follow these steps −
Define a function atMost(), this will take an array a and variable k,
Define a function atMost(), this will take an array a and variable k,
Define one set current
Define one set current
j := 0, ans := 0, n := size of a
j := 0, ans := 0, n := size of a
Define one map m
Define one map m
for initialize i := 0, when i < size of a, update (increase i by 1), do −if m[a[i]] is zero, increase m[a[i]] by 1 then −while k < 0, do −if decrease m[a[j]] by 1 and m[a[i]] is zero, then −(increase k by 1)(increase j by 1)x := ((i - j) + 1)ans := ans + x
for initialize i := 0, when i < size of a, update (increase i by 1), do −
if m[a[i]] is zero, increase m[a[i]] by 1 then −while k < 0, do −if decrease m[a[j]] by 1 and m[a[i]] is zero, then −(increase k by 1)(increase j by 1)
if m[a[i]] is zero, increase m[a[i]] by 1 then −
while k < 0, do −if decrease m[a[j]] by 1 and m[a[i]] is zero, then −(increase k by 1)(increase j by 1)
while k < 0, do −
if decrease m[a[j]] by 1 and m[a[i]] is zero, then −(increase k by 1)
if decrease m[a[j]] by 1 and m[a[i]] is zero, then −
(increase k by 1)
(increase k by 1)
(increase j by 1)
(increase j by 1)
x := ((i - j) + 1)
x := ((i - j) + 1)
ans := ans + x
ans := ans + x
return ans
return ans
From the main method do the following −
From the main method do the following −
return atMost(a, k) - atMost(a, k - 1);
return atMost(a, k) - atMost(a, k - 1);
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int subarraysWithKDistinct(vector<int>& a, int k) {
      return atMost(a, k) - atMost(a, k - 1);
   }
   int atMost(vector <int>& a, int k){
      set <int> current;
      int j = 0;
      int ans = 0;
      int n = a.size();
      unordered_map <int, int> m;
      for(int i = 0; i < a.size(); i++){
         if(!m[a[i]]++) k--;
         while(k < 0){
            if(!--m[a[j]])
            k++;
            j++;
         }
         int x = ((i - j) + 1);
         ans += x;
      }
      return ans;
   }
};
main(){
   Solution ob;
   vector<int> v = {1,2,3,1,4};
   cout << (ob.subarraysWithKDistinct(v, 3));
}
{1,2,3,1,4}, 3
4
Select all text in a Text widget using Python 3 with tkinter

Tkinter text widgets are used for creating text fields that contain multiline user input. It has many inbuilt functions and methods which can be invoked to perform certain operations on text widgets. In contrast, let us assume that we have written a bunch of context in the text widget and if we want to select all the text, then we can use tag_add(tag, range) to select the text and add tag and tag_configure(tag, options) to style the tag property.
#Import tkinter library
from tkinter import *
#Create an instance of tkinter frame
win = Tk()
#Set the geometry
win.geometry("750x200")
def select_text():
   text.tag_add("start", "1.0","end")
   text.tag_configure("start",background="black", foreground= "white")
#Create a Text Widget
text= Text(win)
text.insert(INSERT, "Python is an interpreted, high-level and generalpurpose
programming language. Python's design philosophy emphasizes
code readability with its notable use of significant indentation")
text.pack()
#Create a button to select all the text in the text widget
button= Button(win, text= "Select", background= "gray71", command=select_text)
button.pack(pady=20, side= TOP)
win.mainloop()
Executing the above code will display a window with a button "Select" which can be used to select all the content written in the text widget.
Now, click the "Select" button to select all the text in the widget.
Area of Reuleaux Triangle?

Here we will see how to calculate the area of Reuleaux Triangle like below. The Reuleaux Triangle has one equilateral triangle inside it. Suppose its height is h, this shape is made by the intersection of three circles.
There are three circular sectors. The area of each sector is −
Since the area of the equilateral triangle is added three times, then we have to subtract them. So the final area is −
#include <iostream>
#include <cmath>
using namespace std;
float areaReuleaux(float h) {
   if (h < 0) //if h is negative it is invalid
   return -1;
   float area = ((3.1415 - sqrt(3)) * h * h)/2;
   return area;
}
int main() {
   float height = 6;
   cout << "Area of Reuleaux Triangle: " << areaReuleaux(height);
}
Area of Reuleaux Triangle: 25.3701
What is the MySQL error: “Data too long for column”?

The “Data too long for column” error occurs when you insert more data for a column that does not have the capability to store that data.
For Example - If you have data type of varchar(6) that means it stores only 6 characters. Therefore, if you will give more than 6 characters, then it will give an error.
Let us create a table to understand the error. The query to create a table is as follows −
mysql> create table DataToolongDemo
  −> (
  −> Name varchar(10)
   −> );
Query OK, 0 rows affected (0.55 sec)
Above, we have created a table successfully. We have set a field “Name” with “varchar(10). Now, if we will give more than 10 characters, an error will generate.
The error is as follows −
mysql> insert into DataToolongDemo values('Carol Taylor');
ERROR 1406 (22001): Data too long for column 'Name' at row 1
To rectify the above error, you can set the type to longtext. The query is as follows to change type to longtext, since currently the type is “varchar” −
mysql> alter table DataToolongDemo change Name Name longtext;
Query OK, 0 rows affected (2.22 sec)
Records: 0 Duplicates: 0 Warnings: 0
Now if you will insert same record, then no error will get generated −
mysql> insert into DataToolongDemo values('Carol Taylor');
Query OK, 1 row affected (0.11 sec)
Display all records from the table with the help of select statement. The query is as follows −
mysql> select *from DataToolongDemo;
The following is the output −
+--------------+
| Name         |
+--------------+
| Carol Taylor |
+--------------+
1 row in set (0.00 sec)
How do I center text horizontally and vertically in a TextView of Android?

This example demonstrates about How do I center text horizontally and vertically in a TextView of Android
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:layout_margin="16dp">
   <TextView
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:gravity="center_vertical"
      android:text="Text in Center Vertical" />
   <TextView
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:gravity="center_horizontal"
      android:text="Text in Center Horizontal" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
package app.com.sample;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
   }
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
Click here to download the project code.
JavaScript | Object Prototypes - GeeksforGeeks

01 Mar, 2019
JavaScript prototypes are used to accessing properties and methods of objects. Inherited properties are originally defined in the prototype or parent object. The Date object is inherited from Date.prototype, Array object inherits from Array.prototype etc. The prototypes may be used to add new properties and methods to the existing objects and object constructor.
Syntax:
Object.prototype
Example 1: This example adding new property to the object.
<!DOCTYPE html><html>  <head>    <title>        JavaScript Object Prototypes    </title></head>  <body>    <h1>GeeksforGeeks</h1>          <h2>JavaScript Object Prototypes</h2>          <p id="GFG"></p>          <script>        function Student(a, b) {            this.name = a;            this.id = b;        }                  Student.prototype.age = 12;                  var s1 = new Student("Dinesh", 1234567);                  document.getElementById("GFG").innerHTML = s1.name +                " is " + s1.age + " years old.";     </script></body>  </html>                    
Output:
Example 2: This example adding new method to the object.
<!DOCTYPE html><html>  <head>    <title>        JavaScript Object Prototypes    </title></head>  <body>    <h1>GeeksforGeeks</h1>          <h2>JavaScript Object Prototypes</h2>          <p id="GFG"></p>          <!-- Script to add new method -->    <script>        function Student(a, b) {            this.name = a;            this.id = b;        }                  Student.prototype.details = function() {            return this.name + " " + this.id        };                  var s1 = new Student("Dinesh", 1234567);                  document.getElementById("GFG").innerHTML                = s1.details();     </script></body>  </html>                    
Output:
javascript-object
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to Open URL in New Tab using JavaScript ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Int32.MaxValue Field in C# with Examples - GeeksforGeeks

08 Apr, 2019
The MaxValue field or property of Int32 Struct is used to represent the maximum value of Int32. The value of this field is constant means that the user cannot change the value of this field. The value of this field is 2147483647. Its hexadecimal value is 0x7FFFFFFF. It is used to avoid the OverflowException while converting to an Int32 value.
Syntax:
public const int MaxValue = 2147483647;
Return Value: This field always returns 2147483647.
Example:
// C# program to illustrate the// Int32.MaxValue fieldusing System;  class GFG {      // Main Method    static public void Main()    {        // display the Maximum value         // of Int32 struct        Console.WriteLine("Maximum Value is: "+                                Int32.MaxValue);          // Taking an array of long i.e Int64 data type        long[]num = {347, 49458, 345348534650436656};          // taking variable of Int32 type        int mynum;                  foreach(long n in num){              if(n >= Int32.MinValue && n <= Int32.MaxValue)            {                  // using the method of Convert class                mynum = Convert.ToInt32(n);                                  Console.WriteLine("Conversion is Possible.");            }            else            {                Console.WriteLine("Not Possible");            }        }              }}
Output:
Maximum Value is: 2147483647
Conversion is Possible.
Conversion is Possible.
Not Possible

Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.int32.maxvalue?view=netframework-4.7.2
CSharp-Int32-Struct
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Delegates
C# | Abstract Classes
Difference between Ref and Out keywords in C#
Extension Method in C#
C# | Class and Object
C# | Constructors
C# | String.IndexOf( ) Method | Set - 1
C# | Replace() Method
Introduction to .NET Framework
C# | Data Types