code-rag-bench/online-tutorials huggingface dataset:
Java Program to set alignment for text in JLabel

The following is an example to set left alignment for JLabel −
import java.awt.Font;
import javax.swing.*;
public class SwingDemo {
   public static void main(String args[]) {
      JFrame frame = new JFrame("Label Demo");
      JLabel label;
      label = new JLabel("Left aligned!", JLabel.LEFT);
      label.setFont(new Font("Verdana", Font.PLAIN, 13));
      frame.add(label);
      frame.setSize(500,300);
      frame.setVisible(true);
   }
}
The following is an example to set center alignment for JLabel −
import java.awt.Font;
import javax.swing.*;
public class SwingDemo {
   public static void main(String args[]) {
      JFrame frame = new JFrame("Label Demo");
      JLabel label;
      label = new JLabel("Center aligned!", JLabel.CENTER);
      label.setFont(new Font("Verdana", Font.PLAIN, 13));
      frame.add(label);
      frame.setSize(500,300);
      frame.setVisible(true);
   }
}
The following is an example to set right alignment for JLabel −
import java.awt.Font;
import javax.swing.*;
public class SwingDemo {
   public static void main(String args[]) {
      JFrame frame = new JFrame("Label Demo");
      JLabel label;
      label = new JLabel("Right aligned!", JLabel.RIGHT);
      label.setFont(new Font("Verdana", Font.PLAIN, 13));
      frame.add(label);
      frame.setSize(500,300);
      frame.setVisible(true);
   }
}
DateTime.ToShortTimeString() Method in C# - GeeksforGeeks

30 Jan, 2019
This method is used to convert the value of the current DateTime object to its equivalent short time string representation.
Syntax: public string ToShortTimeString ();
Return Value: This method returns a string that contains the short time string representation of the current DateTime object.
Below programs illustrate the use of DateTime.ToShortTimeString() Method:
Example 1:
// C# program to demonstrate the// DateTime.ToShortTimeString()// Methodusing System;using System.Globalization;  class GFG {      // Main Method    public static void Main()    {        try {              // creating object of DateTime            DateTime date = new DateTime(2010, 1,                                         1, 4, 0, 15);              // getting ShortTime from DateTime            // using ToShortTimeString() method;            string value = date.ToShortTimeString();              // Display the ShortTime            Console.WriteLine("ShortTime is {0}", value);        }          catch (FormatException e)         {            Console.Write("Exception Thrown: ");            Console.Write("{0}", e.GetType(), e.Message);        }    }}
ShortTime is 04:00

Example 2:
// C# program to demonstrate the// DateTime.ToShortTimeString()// Methodusing System;using System.Globalization;  class GFG {      // Main Method    public static void Main()    {        // calling check() method        check(new DateTime(2010, 1,                     3, 4, 0, 15));          check(new DateTime(2010, 1,                     5, 4, 0, 15));    }      public static void check(DateTime date)    {          // getting ShortTime from DateTime        // using ToShortTimeString() method;        string value = date.ToShortTimeString();          // Display the ShortTime        Console.WriteLine("ShortTime of {0}"+                     " is {1}", date, value);    }}
ShortTime of 01/03/2010 04:00:15 is 04:00
ShortTime of 01/05/2010 04:00:15 is 04:00

Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.datetime.toshorttimestring?view=netframework-4.7.2
CSharp DateTime Struct
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Extension Method in C#
HashSet in C# with Examples
C# | Inheritance
Partial Classes in C#
C# | Generics - Introduction
Top 50 C# Interview Questions & Answers
C# | How to insert an element in an Array?
Switch Statement in C#
Convert String to Character Array in C#
Linked List Implementation in C#
Python | Find indices with None values in given list - GeeksforGeeks

27 Mar, 2019
Many times while working in data science domain we need to get the list of all the indices which are None, so that they can be easily be prepossessed. This is quite a popular problem and solution to it comes quite handy. Let’s discuss certain ways in which this can be done.
Method #1 : Using list comprehension + range()In this method we just check for each index using the range function and store the index if we find that index is None.
# Python3 code to demonstrate# finding None indices in list # using list comprehension + enumerate  # initializing list test_list = [1, None, 4, None, None, 5]  # printing original listprint("The original list : " + str(test_list))  # using list comprehension + enumerate# finding None indices in list res = [i for i in range(len(test_list)) if test_list[i] == None]  # print resultprint("The None indices list is : " + str(res))
The original list : [1, None, 4, None, None, 5]
The None indices list is : [1, 3, 4]

 
Method #2 : Using list comprehension + enumerate()The enumerate function can be used to iterate together the key and value pair and list comprehension can be used to bind all this logic in one line.
# Python3 code to demonstrate# finding None indices in list # using list comprehension + enumerate  # initializing list test_list = [1, None, 4, None, None, 5]  # printing original listprint("The original list : " + str(test_list))  # using list comprehension + enumerate# finding None indices in list res = [i for i, val in enumerate(test_list) if val == None]  # print resultprint("The None indices list is : " + str(res))
The original list : [1, None, 4, None, None, 5]
The None indices list is : [1, 3, 4]

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
Python - motion_blur() in Wand - GeeksforGeeks

18 Oct, 2021
Another kind of blur we can perform in Wand is Motion Blur. In this kind a Gaussia blur is performed in a single linear direction and it appears like image is moving in a linear direction. It takes a new angle parameter. 
Syntax :  
Python3
wand.image.motion_blur(radius= radius_value, sigma= sigma_value,             angle= angle_value, channel = "optional_channel_value")# radius should always be greater than sigma(standard deviation)
Parameter :
 
Image Used :  
Example 1:  
Python3
# import display() to show final imagefrom wand.display import display# import Image from wand.image modulefrom wand.image import Image # read file using Image functionwith Image(filename ="koala.jpeg") as img:     # perform adaptive blur effect using adaptive_blur() function    img.motion_blur(radius = 16, sigma = 8, angle = 90)     # save final image    img.save(filename ="mb_koala.jpeg")     # display final image    display(img)
Output :  
Example 2: increase radius, sigma and changed angle to 45.  
Python3
# import display() to show final imagefrom wand.display import display# import Image from wand.image modulefrom wand.image import Image # read file using Image functionwith Image(filename ="koala.jpeg") as img:     # perform adaptive blur effect using adaptive_blur() function    img.motion_blur(radius = 22, sigma = 10, angle = 45)     # save final image    img.save(filename ="gb_koala.jpeg")     # display final image    display(img)
Output :  
 
gabaa406
Python-wand
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
Python | geometry method in Tkinter - GeeksforGeeks

29 Nov, 2021
Tkinter is a Python module that is used to develop GUI (Graphical User Interface) applications. It comes along with Python, so you do not have to install it using the pip command.
Tkinter provides many methods; one of them is the geometry() method. This method is used to set the dimensions of the Tkinter window and is used to set the position of the main window on the user’s desktop.
Code #1: Tkinter window without using geometry method.  
Python3
# importing only those functions which are neededfrom tkinter import Tk, mainloop, TOPfrom tkinter.ttk import Button  # creating tkinter windowroot = Tk()  # Create Button and add some textbutton = Button(root, text = 'Geeks')# pady is used for giving some padding in y directionbutton.pack(side = TOP, pady = 5)  # Execute Tkinterroot.mainloop()
Output:  
As soon as you run the application, you’ll see the position of the Tkinter window is at the north-west position of the screen and the size of the window is also small as shown in the output.   Code #2:  
Python3
# importing only those functions which# are neededfrom tkinter import Tk, mainloop, TOPfrom tkinter.ttk import Button  # creating tkinter windowroot = Tk()  # creating fixed geometry of the# tkinter window with dimensions 150x200root.geometry('200x150')  # Create Button and add some textbutton = Button(root, text = 'Geeks')button.pack(side = TOP, pady = 5)  # Execute Tkinterroot.mainloop()
Output:  
After running the application, you’ll see that the size of the Tkinter window is changed, but the position on the screen is same.   Code #3:  
Python3
# importing only those functions which# are neededfrom tkinter import Tk, mainloop, TOPfrom tkinter.ttk import Button  # creating tkinter windowroot = Tk()  # creating fixed geometry of the# tkinter window with dimensions 150x200root.geometry('200x150 + 400 + 300')  # Create Button and add some textbutton = Button(root, text = 'Geeks')button.pack(side = TOP, pady = 5)  # Execute Tkinterroot.mainloop()
Output:  
When you run the application, you’ll observe that the position and size both are changed. Now the Tkinter window is appearing at a different position (300 shifted on Y-axis and 400 shifted on X-axis).Note: We can also pass a variable argument in the geometry method, but it should be in the form (variable1) x (variable2); otherwise, it will raise an error. 
abergquist
abhigoya
Python-gui
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Check if element exists in list in Python
sum() function in Python
How to use react-countup module in ReactJS ? - GeeksforGeeks

19 Feb, 2021
In our React app sometimes we want, a number to be displayed in an increasing manner from zero to its original value in these cases react-countup comes into action. It is an npm package we need to install for using countup functionality.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Step 3: After creating the ReactJS application, Install the react-countup modules using the following command:
npm install react-countup
Project structure:
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
App.js
import React from 'react';import CountUp from 'react-countup';  function App() {  return (    <div className="App">      <h1>GEEKSFORGEEKS</h1>      <div style={{fontSize:'150px' }}>        <CountUp          start={0}          end={100000}          duration={3}        />          </div>    </div>  );}  export default App;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
React-Questions
Technical Scripter 2020
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ReactJS useNavigate() Hook
How to set background images in ReactJS ?
Axios in React: A Guide for Beginners
How to create a table in ReactJS ?
How to navigate on path by button click in react router ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
Python - tensorflow.math.reduce_mean() - GeeksforGeeks

11 Aug, 2021
TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning  neural networks.
reduce_mean() is used to find mean of elements across dimensions of a tensor.
Syntax: tensorflow.math.reduce_mean( input_tensor, axis, keepdims, name)
Parameters:
input_tensor: It is numeric tensor to reduce.
axis(optional): It represent the dimensions to  reduce. It’s value should be in range [-rank(input_tensor), rank(input_tensor)). If no value is given for this all dimensions are reduced.
keepdims(optional): It’s default value is False. If it’s set to True it will retain the reduced dimension with length 1.
name(optional): It defines the name for the operation.
Returns: It returns a tensor.
Example 1:
Python3
# importing the libraryimport tensorflow as tf # Initializing the input tensora = tf.constant([1, 2, 3, 4], dtype = tf.float64) # Printing the input tensorprint('Input: ', a) # Calculating resultres = tf.math.reduce_mean(a) # Printing the resultprint('Result: ', res)
Output:
Input:  tf.Tensor([1. 2. 3. 4.], shape=(4, ), dtype=float64)
Result:  tf.Tensor(2.5, shape=(), dtype=float64)
Example 2:
Python3
# importing the libraryimport tensorflow as tf # Initializing the input tensora = tf.constant([[1, 2], [3, 4]], dtype = tf.float64) # Printing the input tensorprint('Input: ', a) # Calculating resultres = tf.math.reduce_mean(a, axis = 1, keepdims = True) # Printing the resultprint('Result: ', res)
Output:
Input:  tf.Tensor(
[[1. 2.]
 [3. 4.]], shape=(2, 2), dtype=float64)
Result:  tf.Tensor(
[[1.5]
 [3.5]], shape=(2, 1), dtype=float64)
varshagumber28
Python Tensorflow-math-functions
Python-Tensorflow
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | Get unique values from a list
Python | os.path.join() method
Defaultdict in Python
Create a directory in Python
Python | Pandas dataframe.groupby()
Java - String toCharArray() Method

This method converts this string to a new character array.
Here is the syntax  of this method −
public char[] toCharArray()

Here is the detail of parameters −
NA
NA
It returns a newly allocated character array, whose length is the length of this string and whose contents are initialized to contain the character sequence represented by this string.
It returns a newly allocated character array, whose length is the length of this string and whose contents are initialized to contain the character sequence represented by this string.
import java.io.*;
public class Test {

   public static void main(String args[]) {
      String Str = new String("Welcome to Tutorialspoint.com");

      System.out.print("Return Value :" );
      System.out.println(Str.toCharArray() );
   }
}
This will produce the following result −
Return Value :Welcome to Tutorialspoint.com


    16 Lectures 
     2 hours 

 Malhar Lathkar

    19 Lectures 
     5 hours 

 Malhar Lathkar

    25 Lectures 
     2.5 hours 

 Anadi Sharma

    126 Lectures 
     7 hours 

  Tushar Kale

    119 Lectures 
     17.5 hours 

 Monica Mittal

    76 Lectures 
     7 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
Addition and Subtraction on TimeDelta objects using Pandas - Python - GeeksforGeeks

29 Aug, 2020
TimeDelta module is used to represent the time in the pandas module and can be used in various ways. Performing operations like addition and subtraction are very important for every language but performing these tasks on dates and time can be very valuable. 
Operations on TimeDelta dataframe or series – 
1) Addition – 
df['Result'] = df['TimeDelta1'] + df['TimeDelta2']
2) Subtraction – 
df['Result'] = df['TimeDelta1'] - df['TimeDelta2']
Return: Return the dataframe after operations is performed.
Example #1 :
In this example, we can see that by using various operations on date and time, we are able to get the addition and subtraction on the dataframe having TimeDelta object values.
Python3
# import pandas and numpyimport pandas as pdimport numpy as np  # Perform addition operationa = pd.Series(pd.date_range('2020-8-10', periods=5, freq='D'))b = pd.Series([pd.Timedelta(days=i) for i in range(5)])  gfg = pd.DataFrame({'A': a, 'B': b})gfg['Result'] = gfg['A'] + gfg['B']  print(gfg)
Output :
            A             B        Result
0 2020-08-10 0 days 2020-08-10
1 2020-08-11 1 days 2020-08-12
2 2020-08-12 2 days 2020-08-14
3 2020-08-13 3 days 2020-08-16
4 2020-08-14 4 days 2020-08-18
Example #2 :
Python3
# import pandas and numpyimport pandas as pdimport numpy as np  # Perform addition operationa = pd.Series(pd.date_range('2020-8-10', periods=4, freq='D'))b = pd.Series([pd.Timedelta(days=i) for i in range(4)])  gfg = pd.DataFrame({'A': a, 'B': b})gfg['Result'] = gfg['A'] - gfg['B']  print(gfg)
Output :
           A             B        Result
0 2020-08-10 0 days 2020-08-10
1 2020-08-11 1 days 2020-08-10
2 2020-08-12 2 days 2020-08-10
3 2020-08-13 3 days 2020-08-10
Python pandas-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 ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Get unique values from a list
Python | Pandas dataframe.groupby()
How to Install and Use BpyTop Resource Monitoring Tool in Linux? - GeeksforGeeks

06 Oct, 2021
It’s just as critical for terminal users to be able to keep track of their system’s resource use. Knowing how much of your system’s resources are being used allows you to make more educated decisions about general system maintenance. Top and htop are two choices, but they only show a few device metrics including CPU and memory use. Bpytop is a terminal-based resource monitor that shows various device resources in an effective and visually appealing manner. It has a game-inspired theme. The python version of bashtop is bpytop.
First, we need to install pip3 using the below command if you already have you can skip this step:
$ sudo apt install python3-pip
Installing pip3
Now you can install BpyTop using pip3 using the below command:
$ sudo pip3 install bpytop
Installing BpyTop using pip3
First, we need to install git using the below command if you already have you can skip this step:
$ sudo apt-get install git
Installing git
Now let’s install BpyTop, clone the package from GitHub to your preferred directory:
git clone https://github.com/aristocratos/bpytop.git
Cloning Bpytop package
Change directory to bpytop:
$ cd bpytop
change directory to bpytop
Now install bpytop using the below command:
$ sudo make install
Installing BpyTop
$ sudo snap install bpytop
Installing BpyTop using snap store
After you’ve installed bpytop with Snap, make sure you grant it the following permissions:
$ sudo snap connect bpytop:mount-observe
$ sudo snap connect bpytop:network-control
$ sudo snap connect bpytop:hardware-observe
$ sudo snap connect bpytop:system-observe
$ sudo snap connect bpytop:process-control
$ sudo snap connect bpytop:physical-memory-observe
Grant all permissions
Now you can access BpyTop simply by using the below command:
$ bpytop
Simply type bpytop
Now BpyTop should be opened:
BpyTop
In a nutshell, the bpytop terminal monitoring tool allows you to get a lot of information about your device. Its ease of use and detailed metrics makes it a great tool and a worthy companion during your conquests. Make friends with it, and you’ll reap the benefits of spades. That said, we appreciate your sticking with us to the end, and we hope the guide was as useful as we hoped.
how-to-install
Linux-Tools
Picked
How To
Installation Guide
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install FFmpeg on Windows?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Set Git Username and Password in GitBash?
How to Create and Setup Spring Boot Project in Eclipse IDE?
How to Install Jupyter Notebook on MacOS?
Installation of Node.js on Linux
How to Install FFmpeg on Windows?
How to Install Pygame on Windows ?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Install Jupyter Notebook on MacOS?
Concatenation Operators in VBScript

VBScript supports the following Concatenation operators −
Assume variable A holds 5 and variable B holds 10 then −
Try the following example to understand the Concatenation operator available in VBScript −
<!DOCTYPE html>
<html>
   <body>
      <script language = "vbscript" type = "text/vbscript">
         Dim a : a = 5
         Dim b : b = 10
         Dim c

         c = a+b 
         Document.write ("Concatenated value:1 is " &c) 'Numeric addition 
         Document.write ("<br></br>")  'Inserting a Line Break for readability
        
         c = a&b 
         Document.write ("Concatenated value:2 is " &c) 'Concatenate two numbers 
         Document.write ("<br></br>")  'Inserting a Line Break for readability
      </script>
   </body>
</html>
When you save it as .html and execute it in Internet Explorer, then the above script will produce the following result −
Concatenated value:1 is 15

Concatenated value:2 is 510

Concatenation can also be used for concatenating two strings. Assume variable A="Microsoft" and variable B="VBScript" then −
Try the following example to understand the Concatenation operator available in VBScript −
<!DOCTYPE html>
<html>
   <body>
      <script language = "vbscript" type = "text/vbscript">
         Dim a : a = "Microsoft"
         Dim b : b = "VBScript"
         Dim c

         c = a+b 
         Document.write ("Concatenated value:1 is " &c) 'Numeric addition 
         Document.write ("<br></br>")  'Inserting a Line Break for readability
        
         c = a&b 
         Document.write ("Concatenated value:2 is " &c) 'Concatenate two numbers 
         Document.write ("<br></br>")  'Inserting a Line Break for readability
      </script>
   </body>
</html>
When you save it as .html and execute it in Internet Explorer, then the above script will produce the following result −
Concatenated value:1 is MicrosoftVBScript

Concatenated value:2 is MicrosoftVBScript
ByteBuffer position() methods in Java with Examples - GeeksforGeeks

27 Jun, 2019
The position(int newPosition) method of java.nio.ByteBuffer Class is used to Sets this buffer’s position. If the mark is defined and larger than the new position then it is discarded.
Syntax:
public ByteBuffer position(int newPosition)
Parameters: This method takes the newPosition as parameter which is the new position value. It must be non-negative and no larger than the current limit.
Return Value: This method returns this buffer.
Below are the examples to illustrate the position() method:
Examples 1:
// Java program to demonstrate// position() method  import java.nio.*;import java.util.*;  public class GFG {      public static void main(String[] args)    {        byte[] barr = { 10, 20, 30, 40 };          // creating object of ByteBuffer        // and allocating size capacity        ByteBuffer bb = ByteBuffer.wrap(barr);          // try to set the position at index 2        // using position() method        bb.position(2);          // Set this buffer mark position        bb.mark();          // try to set the position at index 4        // using position() method        bb.position(4);          // display position        System.out.println("position before reset: "                           + bb.position());          // try to call reset() to restore        // to the position we marked        bb.reset();          // display position        System.out.println("position after reset: "                           + bb.position());    }}
position before reset: 4
position after reset: 2

Examples 2:
// Java program to demonstrate// position() method  import java.nio.*;import java.util.*;  public class GFG {      public static void main(String[] args)    {        // creating object of ByteBuffer        // and allocating size capacity        ByteBuffer bb = ByteBuffer.allocate(4);          // try to set the position at index 1        // using position() method        bb.position(1);          // putting the value of ByteBuffer        // using put() method        bb.put((byte)10);          // try to set the position at index 3        // using position() method        bb.position(3);          // putting the value of ByteBuffer        // using put() method        bb.put((byte)30);          // display position        System.out.println("ByteBuffer: "                           + Arrays.toString(bb.array()));    }}
ByteBuffer: [0, 10, 0, 30]

Reference: https://docs.oracle.com/javase/9/docs/api/java/nio/ByteBuffer.html#position-int-
Java-ByteBuffer
Java-Functions
Java-NIO package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Stream In Java
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java
TypeScript | String slice() Method with example - GeeksforGeeks

18 Jun, 2020
The slice() is an inbuilt function in TypeScript which is used to extracts a section of a string and returns a new string. Syntax: 
string.slice( beginslice [, endSlice] )
Parameter: This method accept two parameter as mentioned above and described below: 
beginSlice – This parameter is the zero-based index at which to begin extraction.
endSlice – This parameter is the zero-based index at which to end extraction.
Return Value: This method returns the index of the regular expression inside the string. Otherwise, it returns -1. 
Below example illustrate the  String slice() method in TypeScriptJS:
Example 1: 
JavaScript
<script>    // Original strings    var str = "Geeksforgeeks - Best Platform";       // use of String slice() Method    var newstr = str.slice(0,14);       console.log(newstr);</script>
Output: 
Geeksforgeeks

Example 2: 
JavaScript
<script>    // Original strings    var str = "Geeksforgeeks - Best Platform";       // use of String slice() Method    var newstr = str.slice(16);       console.log(newstr);</script>
Output: 
Best Platform

TypeScript
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
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
How to print a variable name in C? - GeeksforGeeks

28 Jun, 2021
How to print and store a variable name in string variable?
We strongly recommend you to minimize your browser and try this yourself first
In C, there’s a # directive, also called ‘Stringizing Operator’, which does this magic. Basically # directive converts its argument in a string.
#include <stdio.h>#define getName(var)  #var  int main(){    int myVar;    printf("%s", getName(myVar));    return 0;} 
myVar

We can also store variable name in a string using sprintf() in C.
# include <stdio.h># define getName(var, str)  sprintf(str, "%s", #var)   int main(){    int myVar;    char str[20];    getName(myVar, str);    printf("%s", str);    return 0;} 
myVar

This article is contributed by Abhay Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
C-Macro & Preprocessor
c-puzzle
cpp-macros
C Language
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++
Function Pointer in C
Substring in C++
rand() and srand() in C/C++
fork() in C
std::string class in C++
Enumeration (or enum) in C
Command line arguments in C/C++
Different methods to reverse a string in C/C++
Express.js res.sendStatus() Function - GeeksforGeeks

16 Oct, 2021
The res.sendStatus() function is used to set the response HTTP status code to statusCode and send its string representation as the response body.Syntax: 
res.sendStatus( statusCode )
Parameter: The statusCode parameter describes the HTTP status code.Returns: It returns an Object.Installation of express module:  
You can visit the link to Install express module. You can install this package by using this command. 
npm install express
After installing the express module, you can check your express version in command prompt using the command. 
npm version express
After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command. 
node index.js
Example 1: Filename: index.js 
javascript
var express = require('express');var app = express();var PORT = 3000; // Without middlewareapp.get('/', function(req, res){     // Equivalent to res.status(200).send('OK')    res.sendStatus(200);}); app.listen(PORT, function(err){    if (err) console.log(err);    console.log("Server listening on PORT", PORT);});
Steps to run the program: 
The project structure will look like this:  
Make sure you have installed express module using the following command: 
npm install express
Run index.js file using below command: 
node index.js
Output: 
Server listening on PORT 3000
Now open browser and go to http://localhost:3000/, now check your browser screen and you will see the following output: 
OK
Example 2: Filename: index.js 
javascript
var express = require('express');var app = express();var PORT = 3000; // With middlewareapp.use('/', function(req, res, next){    res.sendStatus(200);    next();}); app.get('/', function(req, res){    res.send();}); app.listen(PORT, function(err){    if (err) console.log(err);    console.log("Server listening on PORT", PORT);});
Run index.js file using below command: 
node index.js
Now open the browser and go to http://localhost:3000/, now check your console and you will see the following output: 
Server listening on PORT 3000
And you will see the following output on your browser screen: 
OK
Reference: https://expressjs.com/en/5x/api.html#res.sendStatus
rs1686740
surindertarika1234
Express.js
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js fs.writeFile() Method
Node.js fs.readFile() Method
How to install the previous version of node.js and npm ?
Difference between promise and async await in Node.js
How to use an ES6 import in Node.js?
Remove elements from a JavaScript Array
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?
Difference between var, let and const keywords in JavaScript
reflect.MakeSlice() Function in Golang with Examples - GeeksforGeeks

03 May, 2020
Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package.The reflect.MakeSlice() Function in Golang is used to create new zero-initialized slice value for the specified slice type, length, and capacity. To access this function, one needs to imports the reflect package in the program.
Syntax:
func MakeSlice(typ Type, len, cap int) Value

Parameters: This function takes the following parameters:
typ : This parameter is the Type.
len: This parameter is the number of elements.
cap: This parameter is the capacity od slice.
Return Value: This function returns a newly created slice.
Below examples illustrate the use of above method in Golang:
Example 1:
// Golang program to illustrate// reflect.MakeMapWithSize() Function     package main     import (    "fmt"    "reflect")    // Main functionfunc main() {           var str []string            var strValue reflect.Value = reflect.ValueOf(&str)       indirectStr := reflect.Indirect(strValue)       valueSlice := reflect.MakeSlice(indirectStr.Type(), 100, 1024)            kind := valueSlice.Kind()       cap := valueSlice.Cap()       length := valueSlice.Len()       fmt.Printf("Type is [%v] with capacity of %v bytes"+              " and length of %v .", kind, cap, length)       }
Output:
Type is [slice] with capacity of 1024 bytes and length of 100 .

Example 2:
// Golang program to illustrate// reflect.MakeMapWithSize() Function    package main    import (    "fmt"    "reflect")   // Main functionfunc main() {           intSlice := make([]int, 0)    mapStringInt := make(map[string]int)       sliceType := reflect.TypeOf(intSlice)    mapType := reflect.TypeOf(mapStringInt)      //use of MakeSlice() method    intSliceReflect := reflect.MakeSlice(sliceType, 0, 0)    mapReflect := reflect.MakeMap(mapType)       v := 100    rv := reflect.ValueOf(v)    intSliceReflect = reflect.Append(intSliceReflect, rv)    intSlice2 := intSliceReflect.Interface().([]int)    fmt.Println(intSlice2)       k := "GeeksforGeeks"    rk := reflect.ValueOf(k)    mapReflect.SetMapIndex(rk, rv)    mapStringInt2 := mapReflect.Interface().(map[string]int)    fmt.Println(mapStringInt2)   }
Output:
[100]
map[GeeksforGeeks:100]

Golang-reflect
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
6 Best Books to Learn Go Programming Language
strings.Replace() Function in Golang With Examples
Arrays in Go
How to Split a String in Golang?
fmt.Sprintf() Function in Golang With Examples
Golang Maps
Slices in Golang
Inheritance in GoLang
Different Ways to Find the Type of Variable in Golang
Interfaces in Golang
parent element method - Selenium Python - GeeksforGeeks

30 Apr, 2020
Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies
This article revolves around how to use parent method in Selenium. parent method is used to get internal reference to the WebDriver instance this element was found from.
element.parent
Example –
<input type="text" name="passwd" id="passwd-id" />
To find an element one needs to use one of the locating strategies, For example,
element = driver.find_element_by_id("passwd-id")
element = driver.find_element_by_name("passwd")
element = driver.find_element_by_xpath("//input[@id='passwd-id']")
Also, to find multiple elements, we can use –
elements = driver.find_elements_by_name("passwd")
Now one can get parent of this element with –
element.parent
Let’s try to get element and its parent method on geeksforgeeksusing parent method.Program –
# import webdriverfrom selenium import webdriver  # create webdriver objectdriver = webdriver.Firefox()  # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/")  # get element element = driver.find_element_by_id("gsc-i-id2")  # get parentprint(element.parent)
Output-
Terminal Output –
Python-selenium
selenium
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
How can I create MySQL stored procedure with INOUT parameter?

Following example will demonstrate MySQL stored procedure with INOUT parameter −
mysql> DELIMITER // ;
mysql> Create PROCEDURE counter(INOUT count INT, IN increment INT)
    -> BEGIN
    -> SET count = count + increment;
    -> END //
Query OK, 0 rows affected (0.03 sec)
Here, ‘count’ is the INOUT parameter, which can store and return values and ‘increment’ is the IN parameter, which accepts the values from user.
mysql> DELIMITER ;
mysql> SET @counter = 0;
Query OK, 0 rows affected (0.00 sec)

mysql> CALL counter(@Counter, 1);
Query OK, 0 rows affected (0.00 sec)

mysql> Select @Counter;
+----------+
| @Counter |
+----------+
| 1        |
+----------+
1 row in set (0.00 sec)

mysql> CALL counter(@Counter, 5);
Query OK, 0 rows affected (0.00 sec)

mysql> Select @Counter;
+----------+
| @Counter |
+----------+
| 6        |
+----------+
1 row in set (0.00 sec)
How to create JSON format with group-concat in MySQL?

You can create JSON format using group_concat() function from MySQL. The syntax is as follows −
SELECT yourColumnName1,
   GROUP_CONCAT(CONCAT('{anytName:"', yourColumnName, '",
anyName:"',yourColunName,'"}')) anyVariableName
   from yourTableName
group by yourColumnName1;
To understand the above syntax, let us first create a table. The query to create a table is as follows −
mysql> create table JsonFormatDemo
   -> (
   -> UserId int,
   -> UserName varchar(100),
   -> UserEmail varchar(100)
   -> );
Query OK, 0 rows affected (0.99 sec)
Insert some records in the table using insert command. The query to insert record is as follows −
mysql> insert into JsonFormatDemo values(101,'John','John@gmail.com');
Query OK, 1 row affected (0.19 sec)

mysql> insert into JsonFormatDemo values(101,'Bob','John@gmail.com');
Query OK, 1 row affected (0.18 sec)

mysql> insert into JsonFormatDemo values(102,'Carol','Carol@gmail.com');
Query OK, 1 row affected (0.12 sec)

mysql> insert into JsonFormatDemo values(103,'Sam','Sam@gmail.com');
Query OK, 1 row affected (0.15 sec)
Display all records from the table using select statement. The query is as follows −
mysql> select *from JsonFormatDemo;
+--------+----------+-----------------+
| UserId | UserName | UserEmail       |
+--------+----------+-----------------+
|    101 | John     | John@gmail.com  |
|    101 | Bob      | John@gmail.com  |
|    102 | Carol    | Carol@gmail.com |
|    103 | Sam      | Sam@gmail.com   |
+--------+----------+-----------------+
4 rows in set (0.00 sec)
The query to create a JSON format with the help of group_concat() function −
mysql> select UserId,
   -> GROUP_CONCAT(CONCAT('{Name:"', UserName, '", Email:"',UserEmail,'"}')) JsonFormat
   -> from JsonFormatDemo
   -> group by UserId;
+--------+----------------------------------------------------------------------------+
| UserId | JsonFormat                                                                 |
+--------+----------------------------------------------------------------------------+
|    101 | {Name:"John", Email:"John@gmail.com"},{Name:"Bob", Email:"John@gmail.com"} |
|    102 | {Name:"Carol", Email:"Carol@gmail.com"}                                    |
|    103 | {Name:"Sam", Email:"Sam@gmail.com"}                                        |
+--------+----------------------------------------------------------------------------+
3 rows in set (0.00 sec)
Cordova - InAppBrowser

This plugin is used for opening web browser inside Cordova app.
We need to install this plugin in command prompt window before we are able to use it.
C:\Users\username\Desktop\CordovaProject>cordova plugin add cordova-plugin-inappbrowser

We will add one button that will be used for opening inAppBrowser window in index.html.
Now let's add event listener for our button in onDeviceReady function in index.js.
document.getElementById("openBrowser").addEventListener("click", openBrowser);
In this step we are creating function that will open browser inside our app. We are assigning it to the ref variable that we can use later to add event listeners.
function openBrowser() {
   var url = 'https://cordova.apache.org';
   var target = '_blank';
   var options = "location = yes"
   var ref = cordova.InAppBrowser.open(url, target, options);
   
   ref.addEventListener('loadstart', loadstartCallback);
   ref.addEventListener('loadstop', loadstopCallback);
   ref.addEventListener('loaderror', loaderrorCallback);
   ref.addEventListener('exit', exitCallback);

   function loadstartCallback(event) {
      console.log('Loading started: '  + event.url)
   }

   function loadstopCallback(event) {
      console.log('Loading finished: ' + event.url)
   }

   function loaderrorCallback(error) {
      console.log('Loading error: ' + error.message)
   }

   function exitCallback() {
      console.log('Browser is closed...')
   }
}
If we press BROWSER button, we will see the following output on screen.
Console will also listen to events. loadstart event will fire when URL is started loading and loadstop will fire when URL is loaded. We can see it in console.
Once we close the browser, exit event will fire.
There are other possible options for InAppBrowser window. We will explain it in the table below.
location
Used to turn the browser location bar on or off. Values are yes or no.
hidden
Used to hide or show inAppBrowser. Values are yes or no.
clearCache
Used to clear browser cookie cache. Values are yes or no.
clearsessioncache
Used to clear session cookie cache. Values are yes or no.
zoom
Used to hide or show Android browser's zoom controls. Values are yes or no.
hardwareback
yes to use the hardware back button to navigate back through the browser history. no to close the browser once back button is clicked.
We can use ref (reference) variable for some other functionalities. We will show you just quick examples of it. For removing event listeners we can use −
ref.removeEventListener(eventname, callback); 

For closing InAppBrowser we can use −
ref.close();

If we opened hidden window, we can show it −
ref.show();

Even JavaScript code can be injected to the InAppBrowser −
var details = "javascript/file/url"
ref.executeScript(details, callback);

The same concept can be used for injecting CSS −
var details = "css/file/url"
ref.inserCSS(details, callback);


    45 Lectures 
     2 hours 

 Skillbakerystudios

    16 Lectures 
     1 hours 

 Nilay Mehta
 Print
 Add Notes
 Bookmark this page
What are variable length (Dynamic) Arrays in Java?

In Java, Arrays are of fixed size. The size of the array will be decided at the time of creation. But if you still want to create Arrays of variable length you can do that using collections like array list.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;

public class AddingItemsDynamically {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the size of the array :: ");
      int size = sc.nextInt();
      String myArray[] = new String[size];
      System.out.println("Enter elements of the array (Strings) :: ");
      for(int i=0; i<size; i++) {
         myArray[i] = sc.next();
      }
      System.out.println(Arrays.toString(myArray));
      ArrayList<String> myList = new ArrayList<String>(Arrays.asList(myArray));
      System.out.println("Enter the element that is to be added:");
      String element = sc.next();
      myList.add(element);
      myArray = myList.toArray(myArray);
      System.out.println(Arrays.toString(myArray));
   }
}
Enter the size of the array ::
3
Enter elements of the array (Strings) ::
Ram
Rahim
Robert
[Ram, Rahim, Robert]
Enter the element that is to be added:
Mahavir
[Ram, Rahim, Robert, Mahavir]
Python | Maximum element in tuple list - GeeksforGeeks

21 Nov, 2019
Sometimes, while working with data in form of records, we can have a problem in which we need to find the maximum element of all the records received. This is a very common application that can occur in Data Science domain. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using max() + generator expressionThis is the most basic method to achieve solution to this task. In this, we iterate over whole nested lists using generator expression and get the maximum element using max().
# Python3 code to demonstrate working of# Maximum element in tuple list# using max() + generator expression  # initialize list test_list = [(2, 4), (6, 7), (5, 1), (6, 10), (8, 7)]  # printing original list print("The original list : " + str(test_list))  # Maximum element in tuple list# using max() + generator expressionres = max(int(j) for i in test_list for j in i)  # printing resultprint("The Maximum element of list is : " + str(res))
The original list : [(2, 4), (6, 7), (5, 1), (6, 10), (8, 7)]
The Maximum element of list is : 10

 
Method #2 : Using max() + map() + chain.from_iterable()The combination of above methods can also be used to perform this task. In this, the extension of finding maximum is done by combination of map() and from_iterable().
# Python3 code to demonstrate working of# Maximum element in tuple list# using max() + map() + chain.from_iterable()from itertools import chain  # initialize list test_list = [(2, 4), (6, 7), (5, 1), (6, 10), (8, 7)]  # printing original list print("The original list : " + str(test_list))  # Maximum element in tuple list# using max() + map() + chain.from_iterable()res = max(map(int, chain.from_iterable(test_list)))  # printing resultprint("The Maximum element of list is : " + str(res))
The original list : [(2, 4), (6, 7), (5, 1), (6, 10), (8, 7)]
The Maximum element of list is : 10

Python tuple-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
*args and **kwargs in Python
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary