code-rag-bench/online-tutorials huggingface dataset:
Java Program to convert String to Boolean

To convert String to Boolean, use the parseBoolean() method in Java. The parseBoolean() parses the string argument as a boolean. The boolean returned represents the value true if the string argument is not null and is equal, ignoring case, to the string "true".
Firstly, declare a string.
String str = "false";
Now, use the Boolean.parseBoolean() method to convert the above declared String to Boolean.
boolean bool = Boolean.parseBoolean(str);
Let us now see the complete example to learn how to convert String to Boolean.
 Live Demo
public class Demo {
   public static void main(String[] args) {
      // string
      String str = "false";
      // string to boolean
      boolean bool = Boolean.parseBoolean(str);
      // returned boolean value
      System.out.println(bool);
   }
}
false
Python 3 - os.remove() Method

The method remove() removes the file path. If the path is a directory, OSError is raised.
Following is the syntax for remove() method −
os.remove(path)

path − This is the path, which is to be removed.
This method does not return any value.
The following example shows the usage of remove() method.
# !/usr/bin/python3
import os, sys
os.chdir("d:\\tmp")

# listing directories
print ("The dir is: %s" %os.listdir(os.getcwd()))

# removing
os.remove("test.java")

# listing directories after removing path
print ("The dir after removal of path : %s" %os.listdir(os.getcwd()))
When we run the above program, it produces the following result −
The dir is: [
   'Applicationdocs.docx', 'book.zip', 'foo.txt', 'home', 
   'Java Multiple Inheritance.htm', 'Java Multiple Inheritance_files', 
   'java.ppt', 'ParallelPortViewer', 'test.java'
]
The dir after removal of path : [
   'Applicationdocs.docx', 'book.zip', 'foo.txt', 'home', 
   'Java Multiple Inheritance.htm', 'Java Multiple Inheritance_files', 
   'java.ppt', 'ParallelPortViewer'
]


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
How to run multiple async tasks and waiting for them all to complete in C#?

The Task.WaitAll blocks the current thread until all other tasks have completed execution.
The Task.WhenAll method is used to create a task that will complete if and only if all the other tasks have complete. In the 1st example, we could see that when using Task.WhenAll the task complete is executed before the other tasks are completed. This means that Task.WhenAll doesn’t block the execution. And in the 2nd example, we could see that when using Task.WaitAll the task complete is executed only after all the other tasks are completed. This means that Task.WaitAll block the execution.
static void Main(string[] args){
   Task task1 = new Task(() =>{
      for (var i = 0; i < 5; i++){
         Console.WriteLine("Task 1 - iteration {0}", i);
         Task.Delay(1000);
      }
      Console.WriteLine("Task 1 complete");
   });
   Task task2 = new Task(() =>{
      for (var i = 0; i < 5; i++){
         Console.WriteLine("Task 2 - iteration {0}", i);
         Task.Delay(1000);
      }
      Console.WriteLine("Task 2 complete");
   });
   task1.Start();
   task2.Start();
   Console.WriteLine("Waiting for tasks to complete.");
   Task.WhenAll(task1, task2);
   Console.WriteLine("Both Tasks Completed.");
   Console.ReadLine();
}
Waiting for tasks to complete.
Both Tasks Completed.
Task 1 - iteration 0
Task 2 - iteration 0
Task 2 - iteration 1
Task 2 - iteration 2
Task 2 - iteration 3
Task 1 - iteration 1
Task 1 - iteration 2
Task 1 - iteration 3
Task 1 - iteration 4
Task 1 complete
Task 2 - iteration 4
Task 2 complete
static void Main(string[] args){
   Task task1 = new Task(() =>{
      for (var i = 0; i < 5; i++){
         Console.WriteLine("Task 1 - iteration {0}", i);
         Task.Delay(1000);
      }
      Console.WriteLine("Task 1 complete");
   });
   Task task2 = new Task(() =>{
      for (var i = 0; i < 5; i++){
         Console.WriteLine("Task 2 - iteration {0}", i);
         Task.Delay(1000);
      }
      Console.WriteLine("Task 2 complete");
   });
   task1.Start();
   task2.Start();
   Console.WriteLine("Waiting for tasks to complete.");
   Task.WaitAll(task1, task2);
   Console.WriteLine("Both Tasks Completed.");
   Console.ReadLine();
}
Waiting for tasks to complete.
Task 1 - iteration 0
Task 2 - iteration 0
Task 1 - iteration 1
Task 1 - iteration 2
Task 1 - iteration 3
Task 1 - iteration 4
Task 1 complete
Task 2 - iteration 1
Task 2 - iteration 2
Task 2 - iteration 3
Task 2 - iteration 4
Task 2 complete
Both Tasks Completed
reference_wrapper in C++

In C++ the reference_wrapper is a class template that helps by wrapping a reference in a copy constructible and copy assignable object of type T. The instances of std::reference_wrapper are basically objects, but they can be converted into T&. So we can use as argument with the functions that take the underlying type by reference.
#include <iostream>
#include <functional>
using namespace std;
int main () {
   char a = 'h', b = 'e', c = 'l', d = 'l', e = 'o' , f = 'W', g = 'o', h = 'r', i = 'l', j = 'd';
   reference_wrapper<char> ref[] = {a, b, c, d, e, f, g, h, i, j}; //creating reference array
   for (char& s : ref)
      cout << s;
   cout <<endl;
   return 0;
}
soumyadeep@soumyadeep-VirtualBox:~$ ./a.out
helloWorld
soumyadeep@soumyadeep-VirtualBox:~$
How to Count Variable Numbers of Arguments in C?

In this section we will see how to count number of arguments in case of variable number of arguments in C.
The C supports ellipsis. This is used to take variable number of arguments to a function. User can count the arguments by using one of the three different ways.
By passing the first argument as count of the parameters
By passing the first argument as count of the parameters
By passing last argument as NULL.
By passing last argument as NULL.
Using the logic like printf() or scanf() where the first argument has the placeholders for other arguments.
Using the logic like printf() or scanf() where the first argument has the placeholders for other arguments.
In the following program, we will total
number of variable of arguments passed.
#include<stdio.h>
#include <stdarg.h>
int get_avg(int count, ...) {
   va_list ap;
   int i;
   int sum = 0;
   va_start(ap, count); //va_start used to start before accessing arguments
   for(i = 0; i < count; i++) {
      sum += va_arg(ap, int);
   }
   va_end(ap); //va_end used after completing access of arguments
   return sum;
}
main() {
   printf("Total variable count is: %f", get_avg(5, 8, 5, 3, 4, 6));
}
Total variable count is: 5
Powershell - Backtick

Backtick (`) operator is also called word-wrap operator. It allows a command to be written in multiple lines. It can be used for new line (`n) or tab (`t) in sentences as well. See the examples below −
Get-Service * | Sort-Object ServiceType `
| Format-Table Name, ServiceType, Status -AutoSize
It will become 
Get-Service * | Sort-Object ServiceType | Format-Table Name, ServiceType, Status -AutoSize
Verify the output as
Name                                                   ServiceType  Status
----                                                   -----------  ------
MSSQLServerADHelper100                             Win32OwnProcess Stopped
ntrtscan                                           Win32OwnProcess Running
...

Use of new line and tab.
> Write-host "Title Subtitle"
Title Subtitle

> Write-host "Title `nSubtitle"
Title 
Subtitle

> Write-host "Title `tSubtitle"
Title   Subtitle

    15 Lectures 
     3.5 hours 

 Fabrice Chrzanowski

    35 Lectures 
     2.5 hours 

 Vijay Saini

    145 Lectures 
     12.5 hours 

 Fettah Ben
 Print
 Add Notes
 Bookmark this page
Unix Socket - Ports and Services

When a client process wants to a connect a server, the client must have a way of identifying the server that it wants to connect. If the client knows the 32-bit Internet address of the host on which the server resides, it can contact that host. But how does the client identify the particular server process running on that host?
To resolve the problem of identifying a particular server process running on a host, both TCP and UDP have defined a group of well-known ports.
For our purpose, a port will be defined as an integer number between 1024 and 65535. This is because all port numbers smaller than 1024 are considered well-known -- for example, telnet uses port 23, http uses 80, ftp uses 21, and so on.
The port assignments to network services can be found in the file /etc/services. If you are writing your own server then care must be taken to assign a port to your server. You should make sure that this port should not be assigned to any other server.
Normally it is a practice to assign any port number more than 5000. But there are many organizations who have written servers having port numbers more than 5000. For example, Yahoo Messenger runs on 5050, SIP Server runs on 5060, etc.
Here is a small list of services and associated ports. You can find the most updated list of internet ports and associated service at IANA - TCP/IP Port Assignments.
Unix provides the following functions to fetch service name from the /etc/services file.
struct servent *getservbyname(char *name, char *proto) − This call takes service name and protocol name, and returns the corresponding port number for that service.
struct servent *getservbyname(char *name, char *proto) − This call takes service name and protocol name, and returns the corresponding port number for that service.
struct servent *getservbyport(int port, char *proto) − This call takes port number and protocol name, and returns the corresponding service name.
struct servent *getservbyport(int port, char *proto) − This call takes port number and protocol name, and returns the corresponding service name.
The return value for each function is a pointer to a structure with the following form −
struct servent {
   char  *s_name;
   char  **s_aliases;
   int   s_port;
   char  *s_proto;
};
Here is the description of the member fields −
TCP
UDP

    129 Lectures 
     23 hours 

 Eduonix Learning Solutions

    5 Lectures 
     4.5 hours 

 Frahaan Hussain

    35 Lectures 
     2 hours 

 Pradeep D

    41 Lectures 
     2.5 hours 

 Musab Zayadneh

    46 Lectures 
     4 hours 

 GUHARAJANM

    6 Lectures 
     4 hours 

 Uplatz
 Print
 Add Notes
 Bookmark this page
C++ Program to Perform String Matching Using String Library

Here we will see how the string library functions can be used to match strings in C++. Here we are using the find() operation to get the occurrences of the substring into the main string. This find() method returns the first location where the string is found. Here we are using this find() function multiple times to get all of the matches.
If the item is found, this function returns the position. But if it is not found, it will return string::npos.
Input: The main string “aabbabababbbaabb” and substring “abb”
Output: The locations where the substrings are found. [1, 8, 13]
Input − The main string and the substring to check
Output − The positions of the substring in the main string
pos := 0
while index = first occurrence of sub_str into the str in range pos to end of the string, do
   print the index as there is a match
   pos := index + 1
done
 Live Demo
#include<iostream>
using namespace std;
main() {
   string str1 = "aabbabababbbaabb";
   string str2 = "abb";
   int pos = 0;
   int index;
   while((index = str1.find(str2, pos)) != string::npos) {
      cout << "Match found at position: " << index << endl;
      pos = index + 1; //new position is from next element of index
   }
}
Match found at position: 1
Match found at position: 8
Match found at position: 13
Parsing incoming requests in express.js

To receive some data in http request , lets add a form on url path ‘/add-username’:
app.use('/add-username', (req, res,next)=>{
   res.send('<form action="/post-username" method="POST"> <input type="text" name="username"> <button    type="submit"> Send </button> </form>');
});
For parsing the http request, we requires a third party library body-parser: It’s a production required dependency
npm install –save body-parser
express js provides middleware use function to include a body parser before adding middleware.
const http = require('http');

const express = require('express');
const bodyParser = require('body-parser');

const app = express();

app.use(bodyParser.urlencoded({extended: false}));
the use(0 function shown above uses next() function by default so http request gets passed to next middleware without any trouble.
The above parser is useful for parsing simple form data like input text etc. but for parsing files, json we will use different parsers.
Now, parsing request is simpler than core node.js way of writing code.
Express.js provides a property body inside the http request which will return request data.
Console output: on localhost: 3000/add-username
data: tutorials point
redirecting request is easy with response has a function redirect.
Complete App.js file is shown here −
const http = require('http');
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({extended: false}));
app.use('/', (req, res,next)=>{
   next();
});
app.use('/add-username', (req, res,next)=>{
   res.send('<form action="/post-username" method="POST"> <input type="text" name="username"> <button    type="submit"> Send </button> </form>');
});
app.use('/post-username', (req, res, next)=>{
   console.log('data: ', req.body.username);
   res.redirect('/');
});
app.use('/', (req, res,next)=>{
   res.send('<h1> first midleware: Hello Tutorials Point </h1>');
});
const server = http.createServer(app);
server.listen(3000);
After installing any third party library, nodemon should be restarted manually to take effect of new library instead of relying on auto restart of nodemon which might not work properly.
Ternary Operator in Python?

Many programming languages support ternary operator, which basically define a conditional expression.
Similarly the ternary operator in python is used to return a value based on the result of a binary condition. It takes binary value(condition) as an input, so it looks similar to an “if-else” condition block. However, it also returns a value so behaving similar to a function.
[on_true] if [expression] else [on_false]
Let’s write one simple program, which compare two integers -
a. Using python if-else statement -
>>> x, y = 5, 6
>>> if x>y:
   print("x")
else:
   print("y")
y
b. Using ternary operator
>>> x, y = 5, 6
>>> print("x" if x> y else "y")
y
With ternary operator, we are able to write code in one line. So python basically first evaluates the condition, if true – evaluate the first expression else evaluates the second condition.
>>> def find_max(a,b):
return a if (a>b) else b
>>> find_max(5, 6)
6
Below are different ways to implement ternary operator.
a. Using Python Tuples
>>> a, b = random(), random()
>>> (b, a) [a>b]
0.5497848117028667
Above is equivalent to -
>>> (b, a) [True]
0.5065247098746795
But if you are confused with value returned is of ‘a’ or ‘b’. Let’ rewrite above code.
>>> (f"b:{b}", f"a:{a}") [a>b]
'b:0.5497848117028667'
b. Using Python dictionaries
>>> a, b = random(), random()
>>> {False: f"b:{b}", True: f"a:{a}"}[a>b]
'a:0.8089581560973976'
We can interchange the key-value pair -
>>> {True: f"a:{a}", False: f"b:{b}"}[a>b]
'a:0.8089581560973976'
c. Using Lambdas
We can use python lambda function to act as a ternary operator -
>>> (lambda: f"a:{a}", lambda: f"b:{b}")[a>b]()
'b:0.6780078581465793'
Let’s try chaining these operators -
>>> from random import random
>>> x = random()
>>> "Less than zero" if x<0 else "between 0 and 5" if a>=0 and a<=5 else "Greather than five"
'between 0 and 5'
Let’s check the actual value of x -
>>> x
0.08009251123993566
How to retrieve a specific number of lines from files in PowerShell?

To retrieve the specific number of lines from the beginning or the end of the file, you first need to get the content of the file using Get-Content and then need to pipeline the -First for retrieving the number of files from the beginning and -Last to retrieve the number of lines from the bottom.
Check the below example of retrieving the content of the first 10 lines.
Get-Content D:\Temp\PowerShellaliases.txt -First 10
PS C:\WINDOWS\system32> Get-Content D:\Temp\PowerShellaliases.txt -First 10
CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Alias           % -> ForEach-Object
Alias           ? -> Where-Object
Alias           ac -> Add-Content
Alias           asnp -> Add-PSSnapin
Alias           cat -> Get-Content
Alias           cd -> Set-Location
Alias           CFS -> ConvertFrom-String                          3.1.0.0    Microsoft.PowerShell.Utility
To get the content of the last 10 lines from the file.
Get-Content D:\Temp\PowerShellaliases.txt -Last 10
PS C:\WINDOWS\system32> Get-Content D:\Temp\PowerShellaliases.txt -Last 10
Alias           swmi -> Set-WmiInstance
Alias           tee -> Tee-Object
Alias           trcm -> Trace-Command
Alias           type -> Get-Content
Alias           wget -> Invoke-WebRequest
Alias           where -> Where-Object
Alias           wjb -> Wait-Job
Alias           write -> Write-Output
How to validate data using Cerberus in python

The Cerberus module in python provides powerful yet lightweight data validation functions. It is designed in such a way that you can extend it to various applications and custom validations.
We first define a schema and then validate the data against the scheme and check if it matches the provided conditions or not. If not, accurate errors are thrown to display where it went wrong.
Various conditions can be applied at once to the data field for validation.
In order to use Cerberus, you must first install it, as it does not come packaged with Python.
In order to download and install it, we use the pip package manager.
Launch your terminal and use the command below.
pip install Cerberus
Once you have successfully downloaded and installed the Cerberus library, you must import it’s validator module into your Python script.
from cerberus import Validator
And that’s it. You are all set to start validating data.
First, we must create a schema.
schema = {'numbers': {'type': 'integer'}}
v = Validator(schema)
This means, in a python dictionary, the numbers field must contain only integers.
data = {'numbers': 5}
The above is the data that we need to validate.
if v.validate(data):
   print("Data is valid")
else:
   print("Data is invalid")
This validates the data against the scheme we had created earlier.
from cerberus import Validator
schema = {'numbers': {'type': 'integer'}}
v = Validator(schema)
data = {'numbers': 5}
if v.validate(data):
   print("Data is valid")
else:
   print("Data is invalid")
Data is valid .
from cerberus import Validator
v = Validator()
v.schema = {'ID': {'required': True, 'type': 'number'},
'age': {'type': 'integer'}}
if v.validate({'age': 60}):
   print('Data is valid')
else:
   print('Data is invalid')
   print(v.errors)
Data is invalid, {'ID': ['required field']}
from cerberus import Validator
v = Validator()
v.schema = {'name': { 'type': 'string', 'minlength': 5},
'age': {'type': 'integer', 'min': 18, 'max': 65}}
if v.validate({'name': 'VJ', 'age': 16}):
   print('Data is valid')
else:
   print('Data is invalid')
   print(v.errors)
Data is invalid
{'age': ['min value is 18'], 'name': ['min length is 5']}
And that’s it, you can now validate dictionaries, json files, etc in a similar way using the Cerberus library.
You have learnt to validate data using the Cerberus library with your own custom made schema.
Using this method, you can validate json files, data extracted from an API, etc.
We validated data mainly in order to avoid errors while building a database or while working on data analysis.
You can even automate validating data and build a dynamic website based on the same.
jQuery - clone( ) Method

The clone( ) method clones matched DOM Elements and select the clones.
This is useful for moving copies of the elements to another location in the DOM.
Here is the simple syntax to use this method −
selector.clone( )

Here is the description of all the parameters used by this method −
NA
NA
Following is a simple example a simple showing the usage of this method −
<html>
   <head>
      <title>The jQuery Example</title>
      <script type = "text/javascript" 
         src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
      </script>
		
      <script type = "text/javascript" language = "javascript">
         $(document).ready(function() {
            $("div").click(function () {
               $(this).clone().insertAfter(this);
            });
         });
      </script>
		
      <style>
         .div{ margin:10px;padding:12px; border:2px solid #666; width:60px;}
      </style>
   </head>
	
   <body>
      <p>Click on any square below to see the result:</p>
		
      <div class = "div" style = "background-color:blue;"></div>
      <div class = "div" style = "background-color:green;"></div>
      <div class = "div" style = "background-color:red;"></div>
   </body>
</html>
This will produce following result −
Click on any square below to see the result −

    27 Lectures 
     1 hours 

 Mahesh Kumar

    27 Lectures 
     1.5 hours 

 Pratik Singh

    72 Lectures 
     4.5 hours 

 Frahaan Hussain

    60 Lectures 
     9 hours 

 Eduonix Learning Solutions

    17 Lectures 
     2 hours 

 Sandip Bhattacharya

    12 Lectures 
     53 mins

 Laurence Svekis
 Print
 Add Notes
 Bookmark this page
How to list all users who are currently logged into the Linux system?


To check information about users who are currently logged into the system, we use the who command in the Linux system.
The who command is used to display the users logged into the system. The who command related to the w command that is used to display information about the users currently on the machine and their processes.
The general syntax of the who command is as follows −
who [OPTION]... [ FILE | ARGUMENT1 ARGUMENT2 ]
Brief description of options available in the who command.
To displays the name of users currently logged in, terminal line numbers, login time of the users in the system, and remote hostname of the user in the Linux system, we use the who command without any options and arguments as shown below.
vikash@tutorialspoint:~$ who
vikash :0 2021-01-11 09:40 (:0)
To enhance the output and print information in standard input, we use -H option with the who command as shown in below.
vikash@tutorialspoint:~$ who -H
NAME LINE TIME COMMENT
vikash :0 2021-01-11 09:40 (:0)
To display the last booted time of the Linux/Unix system using the terminal, we use -b or --
boot option with the who command as shown below.
vikash@tutorialspoint:~$ who –boot
System boot 2021-01-11 09:37
Or
vikash@tutorialspoint:~$ who -b
System boot 2021-01-11 09:37
To display the current login user in the Linux system, we use the whoami command without any option and arguments as shown below.
vikash@tutorialspoint:~$ whoami
vikash
To display more information about the command, we use --help option with the who command as shown in below.
$ who --help
Swing Examples - Sorting Table By Headers

Following example showcase how to create a sortable table by headers in a Java Swing application.
We are using the following APIs.
JTable(Object[][] data, String[] columnNames) − To create a table.
JTable(Object[][] data, String[] columnNames) − To create a table.
JTable().setAutoCreateRowSorter(true) − To add a default sort on each header of the table.
JTable().setAutoCreateRowSorter(true) − To add a default sort on each header of the table.
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;

public class SwingTester {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;

   public SwingTester(){
      prepareGUI();
   }
   public static void main(String[] args){
      SwingTester swingControlDemo = new SwingTester();      
      swingControlDemo.showTableDemo();
   }
   private void prepareGUI(){
      mainFrame = new JFrame("Java Swing Examples");
      mainFrame.setSize(500,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new JLabel("", JLabel.CENTER);        
      statusLabel = new JLabel("",JLabel.CENTER);    
      statusLabel.setSize(350,100);

      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }
   private void showTableDemo(){
      headerLabel.setText("Control in action: JTable"); 

      String[] columnNames = {"Name", "Salary"};
      Object[][] data = {
         {"Ramesh Raman", 5000},
         {"Shabbir Hussein", 7000}
      };
      JTable table = new JTable(data, columnNames);
	  table.setAutoCreateRowSorter(true);
      JScrollPane scrollPane = new JScrollPane(table);
      scrollPane.setSize(300, 300);
      table.setFillsViewportHeight(true);
      controlPanel.add(scrollPane);      
      mainFrame.setVisible(true);     
   } 
}
 Print
 Add Notes
 Bookmark this page
How to reverse the bars of a bar plot a using ggplot2 in R?

The bars of a bar plot are generally vertical from bottom to top but we can reverse them as well. Although, this is not a normal practice but we can do it if we want to. For this purpose, we will have to reverse the values on the Y-axis, as a result the bars will be reversed. It can be achieved by using scale_y_continuous.
Consider the below data frame −
Salary_Group <-c("A","B","C","D","E")
Attendance <-c(78,82,90,95,85)
df <-data.frame(Salary_Group,Attendance)
df
Salary_Group Attendance
1 A 78
2 B 82
3 C 90
4 D 95
5 E 85
Creating a simple bar plot −
library(ggplot2)
ggplot(df,aes(Salary_Group,Attendance))+geom_bar(stat="identity")
Reversing the bars of the plot −
ggplot(df,aes(Salary_Group,Attendance))+geom_bar(stat="identity")+scale_y_continuous(trans="reverse")
Java Program to set JComboBox in JOptionPane

Let us first crate a ComboBox and add items to it −
Object[] sports = { "Football", "Cricket", "Squash", "Baseball", "Fencing", "Volleyball", "Basketball" };
JComboBox comboBox = new JComboBox(sports);
Now, add the combo box to the JOptionPane −
JOptionPane.showMessageDialog(null, comboBox, "Fav Sports", JOptionPane.QUESTION_MESSAGE);
The following is an example to set JComboBox in JOptionPane −
package my;
import java.awt.GridBagLayout;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class SwingDemo {
   public static void main(String[] args) throws Exception {
      JPanel panel = new JPanel(new GridBagLayout());
      Object[] sports = { "Football", "Cricket", "Squash", "Baseball", "Fencing", "Volleyball", "Basketball" };
      JComboBox comboBox = new JComboBox(sports); comboBox.setSelectedIndex(1);
      JOptionPane.showMessageDialog(null, comboBox, "Fav Sports",
      JOptionPane.QUESTION_MESSAGE);
      panel.add(comboBox);
   }
}
Be default, we have set index i.e. “Cricket”. You can select any of the options now from the ComboBox set −
\DeclareMathOperator - Tex Command

\DeclareMathOperator - allows you to define your own operator names.
{ \DeclareMathOperator #1 #2  }
\DeclareMathOperator command allows you to define your own operator names; they are subsequently typeset using the proper font and spacing.

myOp(x)

myOp(x)


\text{myOp}(x)

myOp(x)


\DeclareMathOperator {\myOp}{myOp}
\myOp(x)


myOp⁡(x)


\myOp_a^b(x)

myOpab⁡(x)



myOp(x)

myOp(x)


myOp(x)
\text{myOp}(x)

myOp(x)


\text{myOp}(x)
\DeclareMathOperator {\myOp}{myOp}
\myOp(x)


myOp⁡(x)


\DeclareMathOperator {\myOp}{myOp}
\myOp(x)

\myOp_a^b(x)

myOpab⁡(x)


\myOp_a^b(x)

    14 Lectures 
     52 mins

 Ashraf Said

    11 Lectures 
     1 hours 

 Ashraf Said

    9 Lectures 
     1 hours 

 Emenwa Global, Ejike IfeanyiChukwu

    29 Lectures 
     2.5 hours 

 Mohammad Nauman

    14 Lectures 
     1 hours 

 Daniel Stern

    15 Lectures 
     47 mins

 Nishant Kumar
 Print
 Add Notes
 Bookmark this page
SAS - Chi Square

A chi-square test is used to examine the association between two categorical variables. It can be used to test both extent of dependence and extent of independence between Variables. SAS uses PROC FREQ along with the option chisq to determine the result of Chi-Square test.
The basic syntax for applying PROC FREQ for Chi-Square test in SAS is −
PROC FREQ DATA = dataset;
TABLES variables 
/CHISQ TESTP = (percentage values);

Following is the description of the parameters used −
Dataset is the name of the dataset.
Dataset is the name of the dataset.
Variables are the variable names of the dataset use in chi-square test.
Variables are the variable names of the dataset use in chi-square test.
Percentage Values in the TESTP statement represent the percentage of levels of the variable.
Percentage Values in the TESTP statement represent the percentage of levels of the variable.
In the below example we consider a chi-square test on the variable named type in the dataset SASHELP.CARS. This variable has six levels and we assign percentage to each level as per the design of the test.
proc freq data = sashelp.cars;
tables type 
/chisq 
testp = (0.20 0.12 0.18 0.10 0.25 0.15);
run;

When the above code is executed, we get the following result −
We also get the bar chart showing the deviation of the variable type as shown in the following screenshot.
Two way Chi-Square test is used when we apply the tests to two variables of the dataset.
In the below example we apply chi-square test on two variables named type and origin. The result shows the tabular form of all combinations of these two variables.
proc freq data = sashelp.cars;
tables type*origin 
/chisq 
;
run;

When the above code is executed, we get the following result −

    50 Lectures 
     5.5 hours 

 Code And Create

    124 Lectures 
     30 hours 

 Juan Galvan

    162 Lectures 
     31.5 hours 

 Yossef Ayman Zedan

    35 Lectures 
     2.5 hours 

 Ermin Dedic

    167 Lectures 
     45.5 hours 

 Muslim Helalee
 Print
 Add Notes
 Bookmark this page
PHP Indexed Arrays

There are two ways to create indexed arrays:
The index can be assigned automatically (index 
always starts at 0), like this:
or the index can be assigned manually:
The following example creates an indexed array named $cars, assigns three 
elements to it, and then prints a text containing the array values:
To loop through and print all the values of an indexed array, you could use a for loop, like this:
For a complete reference of all array functions, go to our complete PHP Array Reference.
The reference contains a brief description, and examples of use, for each function!
Output the second item in the $fruits array.
$fruits = array("Apple", "Banana", "Orange");
echo ;

We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
C# Program to Get Tomorrow's Date Using TimeSpan Method - GeeksforGeeks

06 Dec, 2021
TimeSpan is a struct that is used to represent time interval which is used to measure the positive and negative number of minutes, hours, days. It is also used to represent the time of the day only when the time is unrelated to some specified date. In this article, we will find tomorrow’s date using the TimeSpan struct.
Syntax:
TimeSpan variable_name = new TimeSpan();
We can get the day, month, and year of a particular date using the following methods:
datetime.Day: It is used to find the day represented by this instance.
datetime.Month: It is used to find the month of the date represented by this instance.
datetime.Year: It is used to find the year of the date represented by this instance.
Example:
C#
// C# program to find tomorrow's date// Using TimeSpan Methodusing System;  class GFG{  static void Main(){          // Add todays date with timespan of 1 to get    // tomorrow date    DateTime tomorrowDate = DateTime.Now + new TimeSpan(1, 0, 0, 0);          // Displaying day, month and year of tomorrow's date    Console.WriteLine("tomorrow Date: {0}/{1}/{2}",                      tomorrowDate.Day, tomorrowDate.Month,                      tomorrowDate.Year);}}
Output:
tomorrow Date: 30/11/2021
Explanation: In the above example, first of all, we find tomorrow’s date by adding today’s date with the timespan of 1. Here, we get today’s date using the DateTime.Now method. Display tomorrow’s date with month, and year in DD/MM/YY format.
Picked
C#
C# Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Destructors in C#
Extension Method in C#
HashSet in C# with Examples
Top 50 C# Interview Questions & Answers
C# | How to insert an element in an Array?
Convert String to Character Array in C#
Socket Programming in C#
Program to Print a New Line in C#
Getting a Month Name Using Month Number in C#
Program to find absolute value of a given number
Delete all elements in an array field in MongoDB?

You can use $set operator for this. The syntax is as follows −
db.yourCollectionName.update({}, { $set : {"yourFieldName": [] }} , {multi:true} );
To understand the above syntax, let us create a collection with the document. The query to create a collection with a document is as follows −
> db.deleteAllElementsInArrayDemo.insertOne({"InstructorName":"Larry","InstructorTechnicalSubject":["Java","MongoDB"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8fb971d3c9d04998abf00e")
}
> db.deleteAllElementsInArrayDemo.insertOne({"InstructorName":"Mike","InstructorTechnicalSubject":["C","C++","Python"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8fb98ad3c9d04998abf00f")
}
Display all documents from a collection with the help of find() method. The query is as follows −
> db.deleteAllElementsInArrayDemo.find().pretty();
The following is the output −
{
   "_id" : ObjectId("5c8fb971d3c9d04998abf00e"),
   "InstructorName" : "Larry",
   "InstructorTechnicalSubject" : [
      "Java",
      "MongoDB"
   ]
}
{
   "_id" : ObjectId("5c8fb98ad3c9d04998abf00f"),
   "InstructorName" : "Mike",
   "InstructorTechnicalSubject" : [
      "C",
      "C++",
      "Python"
   ]
}
Here is the query to delete all elements in the array field −
> db.deleteAllElementsInArrayDemo.update({}, { $set : {"InstructorTechnicalSubject": [] }} , {multi:true} );
WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 })
Let us now check all the documents from a collection using find(). The query is as follows −
> db.deleteAllElementsInArrayDemo.find().pretty();
The following is the output. We have deleted all the elements of the “InstructorTechnicalSubject” array field:
{
   "_id" : ObjectId("5c8fb971d3c9d04998abf00e"),
   "InstructorName" : "Larry",
   "InstructorTechnicalSubject" : [ ]
}
{
   "_id" : ObjectId("5c8fb98ad3c9d04998abf00f"),
   "InstructorName" : "Mike",
   "InstructorTechnicalSubject" : [ ]
}
SortedSet iterator() method in Java with Examples - GeeksforGeeks

30 Sep, 2019
The java.util.SortedSet.iterator() method is used to return an iterator of the same elements as the set. The elements are returned in random order from what present in the set.
Syntax:
Iterator iterate_value = sortedSetInstance.iterator();

Parameters: The function does not take any parameter.
Return Value: The method iterates over the elements of the set and returns the values(iterators).
Note: The iterator() method in SortedSet is inherited from the Set interface in Java.
Below program illustrate the java.util.Set.iterator() method:
// Java code to illustrate iterator()  import java.util.*;  public class SortedSetDemo {    public static void main(String args[])    {          // Creating an empty Set        SortedSet<String> set            = new TreeSet<String>();          // Use add() method to        // add elements into the Set        set.add("Welcome");        set.add("To");        set.add("Geeks");        set.add("4");        set.add("Geeks");          // Displaying the Set        System.out.println("SortedSet: "                           + set);          // Creating an iterator        Iterator value = set.iterator();          // Displaying the values after        // iterating through the iterator        System.out.println("The iterator values are: ");        while (value.hasNext()) {            System.out.println(value.next());        }    }}
SortedSet: [4, Geeks, To, Welcome]
The iterator values are: 
4
Geeks
To
Welcome

Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Set.html#iterator()
Java - util package
Java-Functions
Java-SortedSet
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Hashtable in Java
Constructors in Java
Different ways of Reading a text file in Java
Comparator Interface in Java with Examples
Java Math random() method with Examples
HashMap containsKey() Method in Java
How to Create Array of Objects in Java?
Convert Double to Integer in Java
Iterating over ArrayLists in Java
Generating random numbers in Java
Repeated Substring Pattern in C++

Suppose we have a non-empty string. We have to check whether it can be constructed by taking a substring of it and appending multiple times of the substring. The string consists of lowercase English letters only and its length will not exceed 10000. So if the input is like “abaabaaba”, then answer will be true, as this is created using “aba”
To solve this, we will follow these steps −
We will use the dynamic programming approach.
Define an array DP of size n. n is the size of the string
i := 1 and j := 0
while i < nif str[i] == str[j], then DP[i] := j + 1, increase i and j by 1otherwiseif j > 0, then j := DP[j – 1]else dp[i] := 0, and increase i by 1
if str[i] == str[j], then DP[i] := j + 1, increase i and j by 1
otherwiseif j > 0, then j := DP[j – 1]else dp[i] := 0, and increase i by 1
if j > 0, then j := DP[j – 1]
else dp[i] := 0, and increase i by 1
if DP[n – 1] is not 0 and n % (n – DP[n – 1]) == 0return true
return true
otherwise return false
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   void printVector(vector <int> v){
      for(int i = 0; i < v.size(); i++)cout << v[i] << " ";
      cout << endl;
   }
   bool repeatedSubstringPattern(string s) {
      int n = s.size();
      vector <int> dp(n);
      int i = 1;
      int j = 0;
      while(i < n){
         if(s[i] == s[j]){
            dp[i] = j+1;
            i++;
            j++;
         } else {
            if(j > 0){
               j = dp[j-1];
            } else {
               dp[i] = 0;
               i++;
            }
         }
      }
      return dp[n - 1] && n % (n - dp[n-1]) == 0;
   }
};
main(){
   Solution ob;
   string res = (ob.repeatedSubstringPattern("abaabaaba"))? "true" : "fasle";
   cout << res;
}
"abaabaaba"
true
Numpy size() function | Python - GeeksforGeeks

29 Jul, 2021
In Python, numpy.size() function count the number of elements along a given axis.
Syntax: numpy.size(arr, axis=None)Parameters: arr: [array_like] Input data. axis: [int, optional] Axis(x,y,z) along which the elements(rows or columns) are counted. By default, give the total number of elements in a arrayReturns: [int] Return the number of elements along a given axis.  
Code #1 :  
Python3
# Python program explaining# numpy.size() method # importing numpyimport numpy as np # Making a random arrayarr = np.array([[1, 2, 3, 4], [5, 6, 7, 8]]) # By default, give the total number of elements.print(np.size(arr))
8
 
Code #2 : 
Python3
# Python program explaining# numpy.size() method # importing numpyimport numpy as np # Making a random arrayarr = np.array([[1, 2, 3, 4], [5, 6, 7, 8]]) # count the number of elements along the axis.# Here rows and columns are being treated# as elements #gives no. of rows along x-axisprint(np.size(arr, 0)) #gives no. of columns along y-axisprint(np.size(arr, 1))
2
4
 
VarunPandey
adimish98
kalrap615
arorakashish0911
Python-numpy
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
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Reading and Writing to text files in Python
sum() function in Python
Create a Pandas DataFrame from Lists
How to drop one or multiple columns in Pandas Dataframe
Creating a Proxy Webserver in Python

A proxy server sits in between the client and the actual server. It receives the requests from the client, send it to the actual server, and on receiving the response from the actual server it sends the response back to the client. There are many reasons to use the proxy like hiding the server’s IP address, performance improvement or increasing security etc. In this article we will see how we can create a simple proxy server using python.
The three modules SimpleWebSocketServer,, SimpleHTTPSServer and urllib can be used to achieve this. Below we see how we create python class using the methods available in this module and pass the instance of that class to SimpleWebSocketServer. Then we get the server up and running by using the server forever method available with the class.
import SimpleWebSocketServer
import SimpleHTTPSServer
import urllib
PORT = 9012
class JustAProxy(SimpleHTTPSServer.SimpleWebSocketServer):
   def do_GET(self):
      url=self.path[1:]
      self.send_response(200)
      self.end_headers()
      self.copyfile(urllib.urlopen(url), self.wfile)
httpd = SimpleWebSocketServer.SimpleWebSocketServer('localhost',PORT,JustAProxy)
print ("Proxy Srever at" , str(PORT))
httpd.serveforever()
Running the above code gives us the following result −
Proxy Srever at 9012
3D Bubble chart using Plotly in Python - GeeksforGeeks

10 Jul, 2020
Plotly is a Python library that is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library.
A bubble chart can be created using the scatter_3d() method of plotly.express class. A bubble chart is a data visualization which helps to displays multiple circles (bubbles) in a 3d dimensional plot as same in 3d scatter plot. A bubble chart is primarily used to depict and show relationships between numeric variables.
Example 1: Using Iris dataset
Python3
import plotly.express as px    df = px.data.iris()fig = px.scatter_3d(df, x='sepal_width',                    y='sepal_length',                     z='petal_width',                    size='petal_length',                     color='species')  fig.show()
Output:
Example 2: Using tips dataset
Python3
import plotly.express as px    df = px.data.tips()fig = px.scatter_3d(df, x='total_bill',                    y='day', z='time',                    size='tip', color='sex')  fig.show()
Output:
It can be edited using the color option of the Scatter3D() method of graph_objects class. Let’s look at the below example for a better understanding of the topic.
Example:
Python3
import plotly.express as pximport plotly.graph_objects as go    df = px.data.tips()  fig = go.Figure(go.Scatter3d(    x = df['total_bill'],    y = df['time'],    z = df['day'],    mode = 'markers',    marker = dict(        color = df['tip'],        size = df['total_bill'],        colorscale=[[0, 'rgb(15, 10, 172)'],                     [.3, 'rgb(150, 255, 255)'],                     [1, 'rgb(100, 10, 100)']]        )))  fig.show()
Output:
Python-Plotly
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Taking input in Python
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
How to set a tooltip to each column of a JTableHeader in Java?

A JTableHeader is a subclass of JComponent class, When we create a JTable object, the constructor creates a new JTableHeader object to manage the table component's header. A JTable supplies a setTableHeader() method that establishes the table header component's JTableHeader object and a getTableHeader() method that returns a reference to the table header component's JTableHeader object. We can set a tooltip text to each column of a JTableHeader by overriding the getToolTipText() method of JTableHeader class.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
public class JTableHeaderToolTipTest extends JPanel {
   private DefaultTableModel dmodel;
   private JTable table;
   private JScrollPane jsp;
   public JTableHeaderToolTipTest() {
      setLayout(new BorderLayout());
      String[] headers = {"Name", "Age", "Contact Number", "City"};
      String[] toolTips = {"Name of Emp", "Age of Emp", "Contact Number of Emp","City of Emp"};
      dmodel = new DefaultTableModel(headers, 4);
      table = new JTable(dmodel);
      ToolTipHeader tooltipHeader = new ToolTipHeader(table.getColumnModel());
      tooltipHeader.setToolTipStrings(toolTips);
      table.setTableHeader(tooltipHeader);
      jsp = new JScrollPane(table);
      add(jsp, BorderLayout.CENTER);
   }
   public static void main(String[] args) {
      JFrame frame = new JFrame("JTableHeaderToolTip Test");
      frame.getContentPane().add(new JTableHeaderToolTipTest(), BorderLayout.CENTER);
      frame.setSize(400, 250);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }
}
// implementation code to set a tooltip text to each column of JTableHeader
class ToolTipHeader extends JTableHeader {
   String[] toolTips;
   public ToolTipHeader(TableColumnModel model) {
      super(model);
   }
   public String getToolTipText(MouseEvent e) {
      int col = columnAtPoint(e.getPoint());
      int modelCol = getTable().convertColumnIndexToModel(col);
      String retStr;
      try {
         retStr = toolTips[modelCol];
      } catch (NullPointerException ex) {
         retStr = "";
      } catch (ArrayIndexOutOfBoundsException ex) {
         retStr = "";
      }
      if (retStr.length() < 1) {
         retStr = super.getToolTipText(e);
      }
      return retStr;
   }
   public void setToolTipStrings(String[] toolTips) {
      this.toolTips = toolTips;
   }
}