code-rag-bench/online-tutorials huggingface dataset:
How to instantiate Struct Pointer Address Operator in Golang?

20 Aug, 2021
As pointers are the special variables that are used to store the memory address of another variable whereas, the struct is user-defined data type that consists of different types. A struct is mainly a holder for all other data types. By using a pointer to a struct we can easily manipulate/access the data assigned to a struct. To use pointer to a struct we use “&” i.e, address operator. In Go lang, by using pointers to a struct we can access the fields of a struct without de-referencing them explicitly.
Example: Here we have defined one struct names as “shape” and we are passing the values to the field of this struct. Also, we are printing the value of the struct using pointers.
Go
// Golang program to show how to instantiate// Struct Pointer Address Operatorpackage main import "fmt" type shape struct {    length  int    breadth int    color   string} func main() {     // Passing all the parameters    var shape1 = &shape{10, 20, "Green"}     // Printing the value struct is holding    fmt.Println(shape1)     // Passing only length and color value    var shape2 = &shape{}    shape2.length = 10    shape2.color = "Red"     // Printing the value struct is holding    fmt.Println(shape2)     // Printing the length stored in the struct    fmt.Println(shape2.length)     // Printing the color stored in the struct    fmt.Println(shape2.color)     // Passing only address of the struct    var shape3 = &shape{}     // Passing the value through a pointer    // in breadth field of the variable    // holding the struct address    (*shape3).breadth = 10     // Passing the value through a pointer    // in color field of the variable    // holding the struct address    (*shape3).color = "Blue"     // Printing the values stored    // in the struct using pointer    fmt.Println(shape3)}
Output:
&{10 20 Green}
&{10 0 Red}
10
Red
&{0 10 Blue}
 
singghakshay
Golang-Pointers
Golang-Program
Picked
Go Language
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Rexx - substr String

This method gets a sub string from a particular string.
substr(string1,index,count) 

string1 − The source string.
string1 − The source string.
index − The starting index position for the sub string.
index − The starting index position for the sub string.
count − The number of characters for the sub string.
count − The number of characters for the sub string.
Returns the sub-string.
/* Main program */ 
a = "Hello World" 
say substr(a,2,3) 
When we run the above program, we will get the following result.
Python Program to Print matrix in antispiral form

06 Jan, 2022
Given a 2D array, the task is to print matrix in anti spiral form:Examples:  
Output: 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 
Input : arr[][4] = {1, 2, 3, 4
                    5, 6, 7, 8
                    9, 10, 11, 12
                    13, 14, 15, 16};
Output : 10 11 7 6 5 9 13 14 15 16 12 8 4 3 2 1

Input :arr[][6] = {1, 2, 3, 4, 5, 6
                  7, 8, 9, 10, 11, 12
                  13, 14, 15, 16, 17, 18};
Output : 11 10 9 8 7 13 14 15 16 17 18 12 6 5 4 3 2 1
 
The idea is simple, we traverse matrix in spiral form and put all traversed elements in a stack. Finally one by one elements from stack and print them.  
Python 3
# Python 3 program to print# matrix in anti-spiral formR = 4C = 5  def antiSpiralTraversal(m, n, a):    k = 0    l = 0      # k - starting row index    # m - ending row index    # l - starting column index    # n - ending column index    # i - iterator     stk = []      while (k <= m and l <= n):                  # Print the first row         # from the remaining rows         for i in range(l, n + 1):            stk.append(a[k][i])        k += 1          # Print the last column         # from the remaining columns         for i in range(k, m + 1):            stk.append(a[i][n])        n -= 1          # Print the last row        # from the remaining rows         if ( k <= m):            for i in range(n, l - 1, -1):                stk.append(a[m][i])            m -= 1          # Print the first column         # from the remaining columns         if (l <= n):            for i in range(m, k - 1, -1):                stk.append(a[i][l])            l += 1              while len(stk) != 0:        print(str(stk[-1]), end = " ")        stk.pop()  # Driver Codemat = [[1, 2, 3, 4, 5],       [6, 7, 8, 9, 10],       [11, 12, 13, 14, 15],       [16, 17, 18, 19, 20]];  antiSpiralTraversal(R - 1, C - 1, mat)  # This code is contributed# by ChitraNayal
Output:  
12 13 14 9 8 7 6 11 16 17 18 19 20 15 10 5 4 3 2 1 
Please refer complete article on Print matrix in antispiral form for more details!
Matrix
Python
Python Programs
School Programming
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PyQt5 – How to auto resize Label | adjustSize QLabel

26 Mar, 2020
During the designing of the GUI (Graphical User Interface) application there is a need to display plain text as information where label is used, but sometimes information text could be large or much smaller and it is difficult to use resize() method so have to auto adjust the size of the label according to the text, in order to do so adjustSize() method can be used.
adjustSize() method will change the size of label according to the length of the text, if the length is less it will decrease the length and height of the widget and vice versa.
Syntax : label.adjustSize()
Argument : It takes no argument.
Code :
# importing the required libraries  from PyQt5.QtWidgets import * from PyQt5 import QtCorefrom PyQt5.QtGui import * import sys  class Window(QMainWindow):    def __init__(self):        super().__init__()            # set the title        self.setWindowTitle("Label")          # setting  the geometry of window        self.setGeometry(0, 0, 400, 300)          # creating a label widget        self.label_1 = QLabel("== Normal Label ====", self)          # moving position        self.label_1.move(100, 100)          # setting up border        self.label_1.setStyleSheet("border: 1px solid black;")          # creating a label widget        self.label_2 = QLabel("====== Adjusted label =====", self)          # moving position        self.label_2.move(100, 150)          # setting up border        self.label_2.setStyleSheet("border: 1px solid black;")          # adjusting the size of label        self.label_2.adjustSize()            # show all the widgets        self.show()    # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to set FlowLayout for JFrame in Java?

To set FlowLayout for a frame, use the Container. At first, set a JFrame −
JFrame frame = new JFrame();
Now, use Container and set the layout as FlowLayout−
Container container
container = frame.getContentPane();
container.setLayout(new FlowLayout());
The following is an example to set FlowLayout for JFrame −
package my;
import java.awt.Container;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
public class SwingDemo {
   public static void main(String[] val) {
      JFrame frame = new JFrame();
      Container container;
      JButton btn;
      frame.setBounds(20, 20, 15, 15);
      container = frame.getContentPane();
      container.setLayout(new FlowLayout());
      btn = new JButton("Submit");
      JCheckBox checkBox1 = new JCheckBox("Graduate");
      JCheckBox checkBox2 = new JCheckBox("Post-Graduate");
      container.add(btn);
      container.add(checkBox1);
      container.add(checkBox2);
      frame.setVisible(true);
      frame.setSize(550, 400);
      frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
   }
}
How to check if the PyMongo Cursor is Empty?

10 Jul, 2020
MongoDB is an open source NOSQL database, and is implemented in C++. It is a document oriented database implementation that stores data in structures called Collections (group of MongoDB documents). PyMongo is a famous open source library that is used for embedded MongoDB queries. PyMongo is widely used for interacting with a MongoDB database as python is powerful language for data analysis and data science.
When a given collection is queried using pymongo using the .find() method, the return value is an object of type PyMongo.cursor.Cursor Class and it contains the documents matching the query. PyMongo cursor would be empty in the case the query made returns no result. If you want to get the individual documents you need to use the .find_one() method. To check is the cursor object is empty or not several approaches can be followed – 
Approach 1: The cursor returned is an iterable, thus we can convert it into a list. If the length of the list is zero (i.e. List is empty), this implies the cursor is empty as well.
Sample Database:
Example: 
Python3
import pymongo  connection = pymongo.MongoClient()db = connection.GFGcol = db.lecture  # This is a cursor instancecur = col.find()     results = list(cur)  # Checking the cursor is empty# or notif len(results)==0:    print("Empty Cursor")else:    print("Cursor is Not Empty")    print("Do Stuff Here")
Output:
Cursor is Not Empty
Do Stuff Here
Approach 2: Another way is to use the .count() method that returns the number of matching documents for the query. if the return value for .count() is 0, then the cursor is empty
Example:
Python3
import pymongo    connection = pymongo.MongoClient()db = connection.GFGcol = db.lecture  # This is a cursor instancecur = col.find()  if cur.count()==0:    print("Empty Cursor")else:    print("Cursor is Not Empty")    print("Do Stuff Here")
Output:
Cursor is Not Empty
Do Stuff Here
Python-mongoDB
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Iterate over a list in Python
How to iterate through Excel rows in Python?
Enumerate() in Python
Rotate axis tick labels in Seaborn and Matplotlib
Python Dictionary
Deque in Python
Stack in Python
Queue in Python
Read a file line by line in Python
Defaultdict in Python
Validate the size of input=file in HTML5?

You can try to run the following code to validate the size of input type file:
<!DOCTYPE html>
   <html>
      <head>
         <script src="http://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
      </head>
      <body>
         <form >
            <input type="file" id="myfile" data-max-size="32154" />
            <input type="submit"/>
         </form>
         <script>
            $(function(){
               $('form').submit(function(){
                  var val = true;
   
                  $('input[type=file][data-max-size]').each(function(){
                  if(typeof this.files[0] !== 'undefined'){
                     var max = parseInt($(this).attr('max-size'),10),
                     mySize = this.files[0].size;
                     val = max > mySize;
                     return val;
                  }
               });
               return val;
            });
         });
      </script>
   </body>
</html>
Optional filter() method in Java with examples

30 Jul, 2019
The filter() method of java.util.Optional class in Java is used to filter the value of this Optional instance by matching it with the given Predicate, and then return the filtered Optional instance. If there is no value present in this Optional instance, then this method returns an empty Optional instance.
Syntax:
public Optional<T> 
  filter(Predicale<T> predicate)

Parameters: This method accepts predicate as parameter of type Predicate to filter an Optional instance with this.
Return value: This method returns the filtered Optional instance. If there is no value present in this Optional instance, then this method returns an empty Optional instance.
Exception: This method throws NullPointerException if the specified predicate is null.
Below programs illustrate filter() method:Program 1:
// Java program to demonstrate// Optional.filter() method  import java.util.*;  public class GFG {      public static void main(String[] args)    {          // create a Optional        Optional<Integer> op            = Optional.of(9456);          // print value        System.out.println("Optional: "                           + op);          // filter the value        System.out.println("Filtered value "                           + "for odd or even: "                           + op                                 .filter(num                                         -> num % 2 == 0));    }}
Optional: Optional[9456]
Filtered value for odd or even: Optional[9456]

Program 2:
// Java program to demonstrate// Optional.filter() method  import java.util.*;  public class GFG {      public static void main(String[] args)    {          // create a Optional        Optional<Integer> op            = Optional.empty();          // print value        System.out.println("Optional: "                           + op);          try {              // filter the value            System.out.println("Filtered value "                               + "for odd or even: "                               + op                                     .filter(num                                             -> num % 2 == 0));        }        catch (Exception e) {            System.out.println(e);        }    }}
Optional: Optional.empty
Filtered value for odd or even: Optional.empty

Reference: https://docs.oracle.com/javase/9/docs/api/java/util/Optional.html#filter-java.util.function.Predicate-
Java - util package
Java-Functions
Java-Optional
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JavaScript Course | Printing Hello World in JavaScript

03 Jan, 2022
Previous article: JavaScript Course | What is JavaScript? 
Whenever we write javascript we make use of the ‘script’ tag. We know what a normal HTML document is made up of. The ‘script’ tag is used to write javascript code and this ‘script’ tag is either placed inside the ‘head’ tag or inside the ‘body’ tag. 
Example: 
HTML
<!DOCTYPE HTML><html><head>  <title></title>  <!-- Script tag can also be placed here --></head><body>        <p>Before the script...</p>      <!-- Script tag inside the body -->  <script>    // write the javascript code inside it  </script>        <p>...After the script.</p>      </body></html>
We can put the script tag inside the ‘head’ or ‘body’ tag. Though it should be noted that each choice of putting the ‘script’ tag has its own consequences. For now, you can put the script tag anywhere you want.
Printing Hello World In order to print the famous ‘Hello World’ sentence to the screen, we can make use of different methods that javascript provides. Most common are: 
console.log()
document.write()
alert()
Each of the above method have different ways of outputting the content. Though ‘document.write()’ is used when we want to print the content onto the document which is the HTML Document. Also ‘console.log()’ is mainly used when we are debugging javascript code and same thing with ‘alert()’.
Example:  
Javascript
<script>// using console.logconsole.log('Hello World');</script>
Hit Ctrl+Shift+J to see the output in the browser console. 
Output: 
Example: 
Javascript
<script>// using document.writedocument.write('Hello World');</script>
Output: 
Hello World
Example: 
Javascript
<script>// using alertalert('Hello World');</script>
Output: 
Supported Browser:
Google Chrome
Microsoft Edge
Firefox
Opera
Safari
Next article: JavaScript Course | Understanding Code Structure in JavaScript 
surinderdawra388
ysachin2314
JavaScript-Course
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
How to append HTML code to a div using JavaScript ?
Difference Between PUT and PATCH Request
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Python | Pandas dataframe.corrwith()

16 May, 2020
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandasis one of those packages and makes importing and analyzing data much easier.
Pandas dataframe.corrwith() is used to compute pairwise correlation between rows or columns of two DataFrame objects. If the shape of two dataframe object is not same then the corresponding correlation value will be a NaN value.
Syntax: DataFrame.count(axis=0, level=None, numeric_only=False)
Parameters:other : DataFrameaxis : 0 or ‘index’ to compute column-wise, 1 or ‘columns’ for row-wisedrop : Drop missing indices from result, default returns union of all
Returns: correls : Series
Note: The correlation of a variable with itself is 1.
Example #1: Use corrwith() function to find the correlation among two dataframe objects along the column axis
# importing pandas as pdimport pandas as pd  # Creating the first dataframedf1 = pd.DataFrame({"A":[1, 5, 7, 8],                     "B":[5, 8, 4, 3],                    "C":[10, 4, 9, 3]})  # Creating the second dataframe df2 = pd.DataFrame({"A":[5, 3, 6, 4],                    "B":[11, 2, 4, 3],                    "C":[4, 3, 8, 5]})  # Print the first dataframeprint(df1, "\n")  # Print the second dataframeprint(df2)
Now find the correlation among the columns of the two data frames along the row axis.
# To find the correlation among the# columns of df1 and df2 along the column axisdf1.corrwith(df2, axis = 0)
Output :The output series contains the correlation between the three columns of two dataframe objects respectively. Example #2: Use corrwith() function to find the correlation among two dataframe objects along the row axis
# importing pandas as pdimport pandas as pd  # Creating the first dataframedf1 = pd.DataFrame({"A":[1, 5, 7, 8],                    "B":[5, 8, 4, 3],                    "C":[10, 4, 9, 3]})  # Creating the second dataframe df2 = pd.DataFrame({"A":[5, 3, 6, 4],                    "B":[11, 2, 4, 3],                     "C":[4, 3, 8, 5]})  # To find the correlation among the# columns of df1 and df2 along the row axisdf1.corrwith(df2, axis = 1)
Output :
The output series contains the correlation between the four rows of two data frame objects respectively.
jaikishan6
AtharvaShirode
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
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
Iterate over a list in Python
Convert integer to string in Python
How to add/remove values in the array in PowerShell?

An array is always a fixed size. To add value to the array, you need to create a new copy of the array and add value to it. To do so, you simply need to use += operator.
For example, you have an existing array as given below.
$array = 1,2,3,4,5
To add value “Hello” to the array, we will use += sign.
$array += "Hello"
Now, we will check the output of the array.
We have another method to add value to the array. By Add() operation of the array.
$array.Add("Hi")
When you use the above method to add a variable in the given array, you will get below error.
Exception calling "Add" with "1" argument(s): "Collection was of a fixed size."
At line:1 char:1
+ $array.Add("Hi")
+ ~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : NotSupportedException

This is because the array size is fixed. You can check if the array is a fixed size or not by using the below method.
$array.IsfixedSize
When you check the type of this array, it is an object, not the list.
To deal with the above problem, we need to use System.Collection.ArrayList instead.
When you check the type of this array, it will be an array list.
So from the array list, we can add or remove items.
$array.Add("Hello")
$array.Remove("Delta")
Difference Between Virtual and Pure Virtual Function

In this post, we will understand the difference between virtual and pure virtual functions.
It has its own definition inside the class.
It has its own definition inside the class.
The base class can override a virtual function.
The base class can override a virtual function.
It doesn’t have a derived class.
It doesn’t have a derived class.
virtual funct_name(parameter_list) {. . . . .};
It doesn’t have a definition.
It doesn’t have a definition.
If a class has at least one virtual function, it can be declared abstract.
If a class has at least one virtual function, it can be declared abstract.
The derived class has to override the pure virtual function to use it.
The derived class has to override the pure virtual function to use it.
A pure virtual function is specified by placing "= 0" in its declaration
A pure virtual function is specified by placing "= 0" in its declaration
virtual funct_name(parameter_list)=0;
Following is an example −
class Box {
   public:
   // pure virtual function
   virtual double getVolume() = 0;
   private:
   double length; // Length of a box
   double breadth; // Breadth of a box
   double height; // Height of a box
};
Aptitude - Speed and Distance

Speed = Distance⁄Time
Time = Distance⁄Speed
P km/hr = (P x 5⁄18)m/sec
P m/sec = (P x 18⁄5)km/hr

If the ratio of the speeds of P and Q is p:q, then the ratio of the times taken by them to cover the same distance is
1⁄p:1⁄q or q : p

The average speed of the journey is 

(2pq⁄p+q)km/hr

if a man covers a certain distance at p km/hr and an equal distance at q km/hr

    87 Lectures 
     22.5 hours 

 Programming Line
 Print
 Add Notes
 Bookmark this page
LESS - Import Directives

The @import directive is used to import the files in the code. It spreads the LESS code over different files and allows to maintain the structure of code easily. You can put the @import statements anywhere in the code.
For instance, you can import the file by using @import keyword as @import "file_name.less".
You can use the @import statements depending on the different file extensions such as −
If you are using .css extension, then it will be considered as CSS and the @import statement remains as it is.
If you are using .css extension, then it will be considered as CSS and the @import statement remains as it is.
If it contains any other extension, then it will be considered as LESS and will be imported.
If it contains any other extension, then it will be considered as LESS and will be imported.
If there is no LESS extension, then it will appended and included as imported LESS file.
If there is no LESS extension, then it will appended and included as imported LESS file.
@import "style";      // imports the style.less
@import "style.less"; // imports the style.less
@import "style.php";  // imports the style.php as a less file
@import "style.css";  // it will kept the statement as it is
The following example demonstrates the use of variable in the SCSS file −
<!doctype html>
   <head>
      <title>Import Directives</title>
      <link rel = "stylesheet" href = "style.css" type = "text/css" />
   </head>

   <body>
      <h2>Example of Import Directives</h2>
      <p class = "myline">Welcome to Tutorialspoint...</p>
   </body>
</html>
Next, create the import_dir.less file.
.myline {
   font-size: 20px;
}
Now, create the style.less file.
@import "http://www.tutorialspoint.com/less/import_dir.less";
.myline {
   color:#FF0000;
}
The import_dir.less file will get imported into style.less file from the path https://www.tutorialspoint.com/less/import_dir.less.
You can compile the style.less to style.css by using the following command −
lessc style.less style.css

Execute the above command; it will create the style.css file automatically with the following code −
.myline {
   font-size: 20px;
}

.myline {
   color: #FF0000;
}
Follow these steps to see how the above code works −
Save the above html code in the import_directives.html file.
Save the above html code in the import_directives.html file.
Open this HTML file in a browser, the following output will get displayed.
Open this HTML file in a browser, the following output will get displayed.

    20 Lectures 
     1 hours 

 Anadi Sharma

    44 Lectures 
     7.5 hours 

 Eduonix Learning Solutions

    17 Lectures 
     2 hours 

 Zach Miller

    23 Lectures 
     1.5 hours 

 Zach Miller

    34 Lectures 
     4 hours 

 Syed Raza

    31 Lectures 
     3 hours 

 Harshit Srivastava
 Print
 Add Notes
 Bookmark this page
CSS | translate3d() Function - GeeksforGeeks

07 Aug, 2019
The translate3d() function is an inbuilt function which is used to reposition an element in 3D space.
Syntax:
translate3d( tx, ty, tz )
Parameters: This function accepts three parameters as mentioned above and described below:
tx: This parameter holds the length of translation corresponding to x-axis. This parameter holds the value in form of number or percentage.
ty: This parameter holds the length of translation corresponding to y-axis. This parameter holds the value in form of number or percentage.
tz: This parameter holds the length of translation corresponding to z-axis. This parameter holds the value in form of numbers only.
Below examples illustrate the translate3d() function in CSS:
Example 1:
<!DOCTYPE html><html>  <head>    <title>      CSS translate3d() function  </title>    <style>        body {            text-align: center;        }                  h1 {            color: green;        }                  .translate3d_image {            transform: translate3d(100px, 0, 0);        }    </style></head>  <body>    <h1>GeeksforGeeks</h1>    <h2>CSS translate3d() function</h2>      <h4>Original Image</h4>    <img src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png"          alt="GeeksforGeeks logo">    <br>      <h4>Translated image</h4>    <img class="translate3d_image"          src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png"          alt="GeeksforGeeks logo"></body>  </html>
Output:
Example 2:
<!DOCTYPE html> <html> <head>     <title>CSS translate3d() function</title>     <style>         body {            text-align:center;        }        h1 {            color:green;        }        .GFG {            font-size:35px;            font-weight:bold;            color:green;        }        .geeks {            transform: translate3d(100px, 20px, 0);        }    </style> </head>   <body>     <h1>GeeksforGeeks</h1>    <h2>CSS translate3d() function</h2>          <h4>Original Element</h4>    <div class="GFG">Welcome to GeeksforGeeks</div>          <h4>Translated Element</h4>    <div class="GFG geeks">Welcome to GeeksforGeeks</div> </body> </html>
Output:
Supported Browsers: The browsers supported by translate3d() function are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
CSS-Functions
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Design a web page using HTML and CSS
Form validation using jQuery
Search Bar using HTML, CSS and JavaScript
How to style a checkbox using CSS?
How to fetch data from localserver database and display on HTML table using PHP ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Angular Libraries For Web Developers
Convert a string to an integer in JavaScript
Apache Presto - split(string,delimiter)

presto:default> select split('apache presto','e') as string_split; 
   string_split 
------------------- 
 [apach,  pr, sto] 


    46 Lectures 
     3.5 hours 

 Arnab Chakraborty

    23 Lectures 
     1.5 hours 

 Mukund Kumar Mishra

    16 Lectures 
     1 hours 

 Nilay Mehta

    52 Lectures 
     1.5 hours 

 Bigdata Engineer

    14 Lectures 
     1 hours 

 Bigdata Engineer

    23 Lectures 
     1 hours 

 Bigdata Engineer
 Print
 Add Notes
 Bookmark this page
Create an ordered list in HTML

The HTML <ol> tag is used for creating an ordered list. You can try to run the following code to create an ordered list using the <ol> tag −
The HTML <ol> tag supports the following additional attributes −
You can try to run the following code to create an ordered list using the <ol> tag −
<!DOCTYPE html>
<html>
   <head>
      <title>HTML ol Tag</title>
   </head>
   <body>
      <p>Programming Languages:</p>
      <ol>
         <li>Java</li>
         <li>C++</li>
         <li>C</li>
      </ol>
   </body>
</html>
Python | Pandas series.cummax() to find Cumulative maximum of a series - GeeksforGeeks

20 Nov, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas Series.cummax() is used to find Cumulative maximum of a series. In cumulative maximum, the length of returned series is same as input series and every element is equal to the greater one between current element and previous element.
Syntax: Series.cummax(axis=None, skipna=True)
Parameters:axis: 0 or ‘index’ for row wise operation and 1 or ‘columns’ for column wise operation.skipna: Skips NaN addition for elements after the very next one if True.
Return type: Series
Example #1:In this example, a series is created from a Python list. The list also contains a Null value and the skipna parameter is kept default, that is True.
# importing pandas module import pandas as pd     # importing numpy module import numpy as np     # making list of values values = [3, 4, np.nan, 7, 2, 0]     # making series from list series = pd.Series(values)     # calling method cummax = series.cummax()     # display cummax
Output:
0    3.0
1    4.0
2    NaN
3    7.0
4    7.0
5    7.0
dtype: float64
Explanation: Cummax is comparison of current value with previous value. The first element is always equal to first of caller series.
3
4  (4>3)
NaN (Since NaN cannot be compared to integer values)
7  (7>4)
7  (7>2)
7  (7>0)

 Example #2: Keeping skipna = False
In this example, a series is created just like in the above example. But the skipna parameter is kept False. Hence NULL values won’t be ignored and it would be compared every time on it’s occurrence.
# importing pandas module import pandas as pd     # importing numpy module import numpy as np     # making list of values values = [9, 4, 33, np.nan, 0, 1, 76, 5]     # making series from list series = pd.Series(values)     # calling method cummax = series.cummax(skipna = False)     # display cummax 
Output:
0     9.0
1     9.0
2    33.0
3     NaN
4     NaN
5     NaN
6     NaN
7     NaN
dtype: float64
Explanation: Just like in the above example, maximum of current and previous values were stored at every position until NaN occurred. Since NaN compared with anything returns NaN and skipna parameter is kept False, the cumulative maximum after its occurrence is NaN due to comparison of all the values with NaN.
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Python String | replace()
Reading and Writing to text files in Python
sum() function in Python
PHP array_key_exists() Function

01 Dec, 2021
In this article, we will see how to get the array key using the array_key_exists() function in PHP, & will also see its implementation through the example. The array_key_exists() is an inbuilt function of PHP that is used to check whether a specific key or index is present inside an array or not. The function returns true if the specified key is found in the array otherwise returns false. The required key while specifying the array, is skipped then it will generate the integer value for the key, starting from 0 that will be incremented by 1 for each value.
Pre-requisite: PHP array_keys() Function
Syntax:
boolean array_key_exists($index, $array)
Parameters: This function takes 2 arguments and is described below:
$index: This parameter is mandatory and refers to the key that is needed to be searched for in an input array.
$array: This parameter is mandatory and refers to the original array in which we want to search the given key $index.
Return Value: This function returns a boolean value i.e., TRUE and FALSE depending on whether the key is present in the array or not respectively.
Note: Nested keys will return the FALSE result. 
Example 1: The below programs illustrates the array_key_exists() function in PHP. Here, we will see how we can find a key inside an array that holds key_value pair.
PHP
<?php     // PHP function to illustrate the use    // of array_key_exists()    function Exists($index, $array)    {        if (array_key_exists($index, $array))        {            echo "Found the Key";        }        else        {            echo "Key not Found";        }    }    $array = array(        "ram" => 25,        "krishna" => 10,        "aakash" => 20,        "gaurav"    );    $index = "aakash";    print_r(Exists($index, $array));?>
Output:
Found the Key
If no key_value pair exits, as shown in the below case, then the array takes the default keys i.e. numeric keys starting from zero, into consideration and returns true as far as the $index limit ranges.
Example: This example illustrates the array_key_exists() function in PHP by specifying the particular $index value.
PHP
<?php     // PHP function to illustrate the use of    // array_key_exists()    function Exists($index, $array)    {        if (array_key_exists($index, $array))        {            echo "Found the Key";        }        else        {            echo "Key not Found";        }    }      $array = array(        "ram",        "krishna",        "aakash",        "gaurav"    );    $index = 2;    print_r(Exists($index, $array));?>
Output:
Found the Key
Reference: http://php.net/manual/en/function.array-key-exists.php
surinderdawra388
bhaskargeeksforgeeks
PHP-array
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Resize JPEG Image in PHP ?

27 May, 2020
Why do we need to resize images?In a website, often, we need to scale an image to fit a particular section. Sometimes, it becomes necessary to scale down any image of random size to fit a cover photo section or profile picture section. Also, we need to show a thumbnail of a bigger image. In those cases, it’s not feasible to manually resize the image always.
One way to solve the above problem is to use the following method where we need to just set the width and height attributes on the image tag in our HTML.
<img src="check.jpg" height="100" width="100" alt="Image resize">
The problem with this is that the entire image is downloaded from the server and it is shown in the decreased size within the browser. This means the same amount of bandwidth is required to show the image in the smaller size that would have been required in case of the original size.
Using PHP to resize the image on server end: We will be henceforth using PHP to decrease the image dimension and render it so that a smaller size is only downloaded on the client end and not the original image. To achieve this we will be using the imagecopyresampled() function in PHP.
The imagecopyresampled() function is used to copy and resize an image or part of the image with resampling.
Syntax:
bool imagecopyresampled( resource $dst_image, resource $src_image,
                  int $dst_x, int $dst_y, int $src_x, int $src_y,
                  int $dst_w, int $dst_h, int $src_w, int $src_h )
Parameters: This function accepts a rectangular area from $src_image of width $src_w and height $src_h at position ($src_x, $src_y) and place it in a rectangular area of $dst_image of width $dst_w and height $dst_h at position ($dst_x, $dst_y).
Example: This example uses imagecopyresampled() function to resize the image.
<?php  // The file concerned$filename = 'check.jpg';  // Maximum width and height$width = 100;$height = 100;  // File typeheader('Content-Type: image/jpg');  // Get new dimensionslist($width_orig, $height_orig) = getimagesize($filename);  $ratio_orig = $width_orig/$height_orig;  if ($width/$height > $ratio_orig) {    $width = $height*$ratio_orig;} else {    $height = $width/$ratio_orig;}  // Resampling the image $image_p = imagecreatetruecolor($width, $height);$image = imagecreatefromjpeg($filename);  imagecopyresampled($image_p, $image, 0, 0, 0, 0,        $width, $height, $width_orig, $height_orig);  // Display of output imageimagejpeg($image_p, null, 100);  ?>
Output:
Original Image:
Output Image:
PHP-Misc
Picked
PHP
PHP Programs
Web Technologies
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to fetch data from localserver database and display on HTML table using PHP ?
Difference between HTTP GET and POST Methods
Different ways for passing data to view in Laravel
PHP | file_exists( ) Function
PHP | Ternary Operator
How to call PHP function on the click of a Button ?
How to fetch data from localserver database and display on HTML table using PHP ?
PHP | Ternary Operator
How to create admin login page using PHP?
How to send an email using PHPMailer ?
Python Program for Program to calculate area of a Tetrahedron

16 Jun, 2022
A Tetrahedron is simply a pyramid with a triangular base. It is a solid object with four triangular faces, three on the sides or lateral faces, one on the bottom or the base and four vertices or corners. If the faces are all congruent equilateral triangles, then the tetrahedron is called regular. The volume of the tetrahedron can be found by using the following formula :
Volume = a3/(6√2)
Examples :
Input : side = 3
Output : 3.18


Input : side = 20
Output : 942.81
Python3
# Python code to find the volume of a tetrahedronimport mathdef vol_tetra(side):    volume = (side ** 3 / (6 * math.sqrt(2)))    return round(volume, 2) # Driver Codeside = 3vol = vol_tetra(side)print(vol)
Output :
3.18
Time complexity: O(1)
Auxiliary Space: O(1)
Please refer complete article on Program to calculate area of a Tetrahedron for more details!
hasani
area-volume-programs
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Binary Search (Recursive and Iterative)
Python program to find second largest number in a list
Iterate over characters of a string in Python
Python | Convert set into a list
Python program to interchange first and last elements in a list
Appending to list in Python dictionary
Python | Convert a list into a tuple
Add a key:value pair to dictionary in Python
C++ default constructor | Built-in types - GeeksforGeeks

29 May, 2017
Predict the output of following program?
#include <iostream>using namespace std;  int main() {     cout << int() << endl;   return 0;}
A constructor without any arguments or with default values for every argument, is treated as default constructor. It will be called by the compiler when in need (precisely code will be generated for default constructor based on need).
C++ allows even built-in type (primitive types) to have default constructors. The function style cast int() is analogous to casting 0 to required type. The program prints 0 on console.
The initial content of the article triggered many discussions, given below is consolidation.
It is worth to be cognizant of reference vs. value semantics in C++ and the concept of Plain Old Data types. From Wiki, primitive types and POD types have no user-defined copy assignment operator, no user-defined destructor, and no non-static data members that are not themselves PODs. Moreover, a POD class must be an aggregate, meaning it has no user-declared constructors, no private nor protected non-static data, no base classes and no virtual functions.
An excerpt (from a mail note) from the creator of C++, “I think you mix up ‘actual constructor calls’ with conceptually having a constructor. Built-in types are considered to have constructors”.
The code snippet above mentioned int() is considered to be conceptually having constructor. However, there will not be any code generated to make an explicit constructor call. But when we observe assembly output, code will be generated to initialize the identifier using value semantics. For more details refer section 8.5 of this document.
Thanks to Prasoon Saurav for initiating the discussion, providing various references and correcting lacuna in my understanding.
Contributed by Venki. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
References:
The C++ Programming Language, 3e.Latest C++ standard – working draft section 8.5.
The C++ Programming Language, 3e.
Latest C++ standard – working draft section 8.5.
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multidimensional Arrays in C / C++
Left Shift and Right Shift Operators in C/C++
fork() in C
Core Dump (Segmentation fault) in C/C++
Function Pointer in C
Vector in C++ STL
Inheritance in C++
Initialize a vector in C++ (6 different ways)
Map in C++ Standard Template Library (STL)
C++ Classes and Objects
Find K Closest Points to the Origin in C++

Suppose we have a set of points. Our task is to find K points which are closest to the origin. Suppose the points are (3, 3), (5, -1) and (-2, 4). Then the closest two (K = 2) points are (3, 3), (-2, 4).
To solve this problem, we will sort the list of points based on their Euclidean distance, after that take the top most K elements from the sorted list. Those are the K nearest points.
 Live Demo
#include<iostream>
#include<algorithm>
using namespace std;
class Point{
   private:
   int x, y;
   public:
   Point(int x = 0, int y = 0){
      this->x = x;
      this->y = y;
   }
   void display(){
      cout << "("<<x<<", "<<y<<")";
   }
   friend bool comparePoints(Point &p1, Point &p2);
};
bool comparePoints(Point &p1, Point &p2){
   float dist1 = (p1.x * p1.x) + (p1.y * p1.y);
   float dist2 = (p2.x * p2.x) + (p2.y * p2.y);
   return dist1 < dist2;
}
void closestKPoints(Point points[], int n, int k){
   sort(points, points+n, comparePoints);
   for(int i = 0; i<k; i++){
      points[i].display();
      cout << endl;
   }
}
int main() {
   Point points[] = {{3, 3},{5, -1},{-2, 4}};
   int n = sizeof(points)/sizeof(points[0]);
   int k = 2;
   closestKPoints(points, n, k);
}
(3, 3)
(-2, 4)
C++ program to find two numbers with sum and product both same as N

In this tutorial, we will be discussing a program to find two numbers (say ‘a’ and ‘b’) such that both
a+b = N and a*b = N are satisfied.
Eliminating ‘a’ from both the equations, we get a quadratic equation in ‘b’ and ‘N’ i.e
b2 - bN + N = 0
This equation will have two roots which will give us the value of both ‘a’ and ‘b’. Using the determinant method to find the roots, we get the value of ‘a’ and ‘b’ as,
a=(N−N∗N−4N)/2b=(N+N∗N−4N)/2
 Live Demo
#include <iostream>
//header file for the square root function
#include <math.h>
using namespace std;
int main() {
   float N = 12,a,b;
   cin >> N;
   //using determinant method to find roots
   a = (N + sqrt(N*N - 4*N))/2;
   b = (N - sqrt(N*N - 4*N))/2;
   cout << "The two integers are :" << endl;
   cout << "a - " << a << endl;
   cout << "b - " << b << endl;
   return 0;
}
The two integers are :
a - 10.899
b - 1.10102
Copy char array to string in Java

Use the valueOf() method in Java to copy char array to string. You can also use the copyValueOf() method, which represents the character sequence in the array specified. Here, you can specify the part of array to be copied.
Let us first create a character array.
char[] arr = { 'p', 'q', 'r', 's' };
The method valueOf() will convert the entire array into a string.
String str = String.valueOf(arr);
The following is an example.
 Live Demo
public class Demo {
   public static void main(String []args) {
      char[] arr = { 'p', 'q', 'r', 's' };
      String str = String.valueOf(arr);
      System.out.println(str);
   }
}
Pqrs
Let us see another example that use copyValueOf() method that convert char array to string.
 Live Demo
public class Demo {
   public static void main(String []args) {
      char[] arr = { 'p', 'q', 'r', 's' };
      String str = String.copyValueOf(arr, 1, 2);
      System.out.println(str);
   }
}
Qr
How to extract a single column of an R data frame as a data frame?

Generally, we extract columns as a vector from an R data frame but sometimes we might need a column as a data frame, therefore, we can use as.data.frame to extract columns that we want to extract as a data frame with single square brackets. The purpose behind this could be merging the column with another data frame.
Consider the below data frame −
set.seed(9)
x1<-rnorm(20)
x2<-rnorm(20,0.2)
x3<-rnorm(20,0.5)
x4<-rnorm(20,2.5)
x5<-rpois(20,5)
x6<-runif(20,2,5)
df<-data.frame(x1,x2,x3,x4,x5,x6)
df
      x1       x2       x3       x4       x5       x6
1 -0.76679604 1.95699294 -0.30845634 2.7812222 5 3.087890
2 -0.81645834 0.38225214 -1.51938169 1.2972914 8 3.559316
3 -0.14153519 -0.06688875 -0.23872407 2.9651637 3 2.710724
4 -0.27760503 1.12642163 0.88288656 2.8520164 8 3.417152
5 0.43630690 -0.49333188 2.23086367 1.9101438 5 2.520602
6 -1.18687252 2.88199007 0.29691805 1.6464000 8 4.958743
7 1.19198691 0.42252448 -0.49639735 2.2532679 8 4.302067
8 -0.01819034 -0.50667241 -0.80653629 4.0393386 6 3.447421
9 -0.24808460 0.61721325 -0.49783160 3.0460777 2 2.992220
10 -0.36293689 0.56955678 -0.06502873 4.0649619 4 2.563962
11 1.27757055 -0.71376435 2.25205784 2.7496702 5 3.204598
12 -0.46889715 -0.11691475 -0.04777135 0.5375814 4 2.962441
13 0.07105410 1.24905921 -0.35852571 1.6909398 7 2.752308
14 -0.26603845 0.36811181 0.54929453 2.0013149 5 3.582086
15 1.84525720 0.23144021 0.29995552 2.8051218 3 4.365315
16 -0.83944966 -0.81033054 -0.60395445 2.2107928 3 3.258313
17 -0.07744806 0.58275153 0.74058804 3.9577142 2 2.204786
18 -2.61770553 -0.61969653 0.88111362 3.3737555 9 3.329696
19 0.88788403 0.56171109 2.73045895 1.5470440 7 4.025269
20 -0.70749145 0.29337136 1.69920239 2.4683245 4 4.254372
Extracting some columns as a separate data frames −
x2 <-as.data.frame(df[,2])
x2
df[, 2]
1 1.95699294
2 0.38225214
3 -0.06688875
4 1.12642163
5 -0.49333188
6 2.88199007
7 0.42252448
8 -0.50667241
9 0.61721325
10 0.56955678
11 -0.71376435
12 -0.11691475
13 1.24905921
14 0.36811181
15 0.23144021
16 -0.81033054
17 0.58275153
18 -0.61969653
19 0.56171109
20 0.29337136
is.data.frame(x2)
[1] TRUE
x5 <-as.data.frame(df[,5])
x5
df[, 5]
1 5
2 8
3 3
4 8
5 5
6 8
7 8
8 6
9 2
10 4
11 5
12 4
13 7
14 5
15 3
16 3
17 2
18 9
19 7
20 4
is.data.frame(x5)
[1] TRUE
x3 <-as.data.frame(df[,3])
x3
df[, 3]
1 -0.30845634
2 -1.51938169
3 -0.23872407
4 0.88288656
5 2.23086367
6 0.29691805
7 -0.49639735
8 -0.80653629
9 -0.49783160
10 -0.06502873
11 2.25205784
12 -0.04777135
13 -0.35852571
14 0.54929453
15 0.29995552
16 -0.60395445
17 0.74058804
18 0.88111362
19 2.73045895
20 1.69920239
is.data.frame(x3)
[1] TRUE