code-rag-bench/online-tutorials huggingface dataset:
Erlang - Atoms

An atom is a literal, a constant with name. An atom is to be enclosed in single quotes (') if it does not begin with a lower-case letter or if it contains other characters than alphanumeric characters, underscore (_), or @.
The following program is an example of how atoms can be used in Erlang. This program declares 3 atoms, atom1, atom_1 and ‘atom 1’ respectively. So you can see the different ways an atom can be declared.
-module(helloworld). 
-export([start/0]). 

start() -> 
   io:fwrite(atom1), 
   io:fwrite("~n"), 
   io:fwrite(atom_1), 
   io:fwrite("~n"), 
   io:fwrite('atom 1'), 
   io:fwrite("~n").
The output of the above program would be follows −
atom1
atom_1
atom 1

Let’s see some of the methods available in Erlang to work with atoms.
is_atom
This method is used to determine if a term is indeed an atom.
atom_to_list
This method is used to convert an atom to a list.
list_to_atom
This method is used to convert a list item to an atom.
atom_to_binary
This method is used to convert an atom to a binary value.
binary_to_atom
This method is used to convert a binary value to an atom value.
 Print
 Add Notes
 Bookmark this page
numpy.ravel_multi_index() function | Python - GeeksforGeeks

22 Apr, 2020
numpy.ravel_multi_index() function converts a tuple of index arrays into an array of flat indices, applying boundary modes to the multi-index.
Syntax : numpy.ravel_multi_index(multi_index, dims, mode = ‘raise’, order = ‘C)Parameters :multi_index : [tuple of array_like] A tuple of integer arrays, one array for each dimension.dims : [tuple of ints] The shape of array into which the indices from multi_index apply.mode : [{‘raise’, ‘wrap’, ‘clip’}, optional] Specifies how out-of-bounds indices are handled. Can specify either one mode or a tuple of modes, one mode per index.‘raise’ – raise an error (default)‘wrap’ – wrap around‘clip’ – clip to the rangeIn ‘clip’ mode, a negative index that would normally wrap will clip to 0 instead.order : [{‘C’, ‘F’}, optional] Determines whether the multi-index should be viewed as indexing in row-major (C-style) or column-major (Fortran-style) order.
Return : [ndarray] An array of indices into the flattened version of an array of dimensions dims.
Code #1 :
# Python program explaining# numpy.ravel_multi_index() function  # importing numpy as geek import numpy as geek  arr = geek.array([[3, 6, 6], [4, 5, 1]])  gfg = geek.ravel_multi_index(arr, (7, 6))  print(gfg) 
Output :
[22 41 37]

 Code #2 :
# Python program explaining# numpy.ravel_multi_index() function  # importing numpy as geek import numpy as geek  arr = geek.array([[3, 6, 6], [4, 5, 1]])  gfg = geek.ravel_multi_index(arr, (7, 6), order = 'F')  print(gfg) 
Output :
[31 41 13]

 Code #3 :
# Python program explaining# numpy.ravel_multi_index() function  # importing numpy as geek import numpy as geek  arr = geek.array([[3, 6, 6], [4, 5, 1]])  gfg = geek.ravel_multi_index(arr, (7, 6), mode = 'clip')  print(gfg) 
Output :
[22 41 37]

Python numpy-arrayManipulation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Create a directory in Python
Python | Pandas dataframe.groupby()
Program to list of candidates who have got majority vote in python

Suppose we have a list of numbers called nums where each number represents a vote to a candidate. We have to find the ids of the candidates that have greater than floor(n/3) votes, in non-decreasing order.
So, if the input is like nums = [3, 2, 6, 6, 6, 6, 7, 7, 7, 7, 7], then the output will be [6, 7], as 6 and 7 have 40% of the votes.
To solve this, we will follow these steps −
ans := a new empty set
sort the list nums
i := 0
n := size of nums
while i < size of nums, doif occurrences of nums[i] in nums > (n / 3), theninsert nums[i] into ansi := i + (n / 3)
if occurrences of nums[i] in nums > (n / 3), theninsert nums[i] into ans
insert nums[i] into ans
i := i + (n / 3)
return ans in sorted order
Let us see the following implementation to get better understanding −
Live Demo
class Solution:
   def solve(self, nums):
      ans = set([])
      nums.sort()
      i = 0
      n = len(nums)
      while i < len(nums):
         if nums.count(nums[i]) > n // 3:
            ans.add(nums[i])
         i += n // 3
      return sorted(list(ans))
ob = Solution()
nums = [3, 2, 6, 6, 6, 6, 7, 7, 7, 7, 7]
print(ob.solve(nums))
[3, 2, 6, 6, 6, 6, 7, 7, 7, 7, 7]
[6, 7]
Remove all values from HashMap in Java

To remove all values from HashMap, use the clear() method.
First, let us create a HashMap.
HashMap hm = new HashMap();
Add some elements to the HashMap
hm.put("Wallet", new Integer(700));
hm.put("Belt", new Integer(600));
hm.put("Backpack", new Integer(1200));
Now, remove all the elements
hm.clear();
The following is an example to remove all values from HashMap.
 Live Demo
import java.util.*;
public class Demo {
   public static void main(String args[]) {
      // Create hash map
      HashMap hm = new HashMap();
      hm.put("Wallet", new Integer(700));
      hm.put("Belt", new Integer(600));
      hm.put("Backpack", new Integer(1200));
      System.out.println("Map = "+hm);
      hm.clear();
      System.out.println("Map after removing all the elements (blank)= "+hm);
   }
}
The following is the output
Map = {Backpack=1200, Belt=600, Wallet=700}
Map after removing all the elements (blank)= {}
How to dynamically add/remove/update labels in a Tkinter window?

We can use the Tkinter Label widget to display text and images. By configuring the label widget, we can dynamically change the text, images, and other properties of the widget.
To dynamically update the Label widget, we can use either config(**options) or an inline configuration method such as for updating the text, we can use Label["text"]=text; for removing the label widget, we can use pack_forget() method.
# Import the required libraries
from tkinter import *
from tkinter import ttk
from PIL import ImageTk, Image

# Create an instance of tkinter frame or window
win=Tk()

# Set the size of the window
win.geometry("700x350")

def add_label():
   global label
   label=Label(win, text="1. A Newly created Label", font=('Aerial 18'))
   label.pack()

def remove_label():
   global label
   label.pack_forget()

def update_label():
   global label
   label["text"]="2. Yay!! I am updated"

# Create buttons for add/remove/update the label widget
add=ttk.Button(win, text="Add a new Label", command=add_label)
add.pack(anchor=W, pady=10)

remove=ttk.Button(win, text="Remove the Label", command=remove_label)
remove.pack(anchor=W, pady=10)

update=ttk.Button(win, text="Update the Label", command=update_label)
update.pack(anchor=W, pady=10)

win.mainloop()
Running the above code will display a window with some buttons in it. Each button can be used to update/remove or add a label in the application.
Upon clicking the "Update the Label" button, the label will get updated as follows −
How to create a Vertical menu bar in Java?

Let us create a MenuBar −
JMenuBar menuBar = new JMenuBar();
Now, set its layout to create a Vertical Menu Bar with GridLayout −
menuBar.setLayout(new GridLayout(0,1));
The following is an example to create a Vertical menu bar in Java −
package my;
import java.awt.GridLayout;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
public class SwingDemo {
   public static void main(final String args[]) {
      JFrame frame = new JFrame("MenuBar Demo");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      JMenuBar menuBar = new JMenuBar();
      menuBar.setLayout(new GridLayout(0,1));
      JMenu fileMenu = new JMenu("File");
      fileMenu.setMnemonic(KeyEvent.VK_F);
      menuBar.add(fileMenu);
      JMenuItem menuItem1 = new JMenuItem("New", KeyEvent.VK_N);
      fileMenu.add(menuItem1);
      JMenuItem menuItem2 = new JMenuItem("Open File", KeyEvent.VK_O);
      fileMenu.add(menuItem2);
      JMenu editMenu = new JMenu("Edit");
      editMenu.setMnemonic(KeyEvent.VK_E);
      menuBar.add(editMenu);
      JMenuItem menuItem3 = new JMenuItem("Cut", KeyEvent.VK_C);
      editMenu.add(menuItem3);
      JMenu sourceMenu = new JMenu("Source");
      sourceMenu.setMnemonic(KeyEvent.VK_S);
      menuBar.add(sourceMenu);
      JMenu refactorMenu = new JMenu("Refactor");
      refactorMenu.setMnemonic(KeyEvent.VK_R);
      menuBar.add(refactorMenu);
      JMenu navigateMenu = new JMenu("Navigate");
      navigateMenu.setMnemonic(KeyEvent.VK_A);
      menuBar.add(navigateMenu);
      menuBar.revalidate();
      frame.setJMenuBar(menuBar);
      frame.setSize(550, 350);
      frame.setVisible(true);
   }
}
This will produce the following output −
HTML - keygen Tag

The HTML <keygen> tag is used to process Web forms with certificate management systems. The element generates a secure key and submits the public key.
<!DOCTYPE html>
<html>

   <head>
      <title>HTML keygen Tag</title>
   </head>

   <body>
      <form>
         <keygen name = "random_key" challenge = "0987654321">
         <input name = "firstname" value = "first name">
      </form>
   </body>

</html>
This will produce the following result −
This tag supports all the global attributes described in HTML Attribute Reference
The HTML <keygen> tag also supports the following additional attributes −
This tag supports all the event attributes described in − HTML Events Reference

    19 Lectures 
     2 hours 

 Anadi Sharma

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    18 Lectures 
     1.5 hours 

 Frahaan Hussain

    57 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)

    54 Lectures 
     6 hours 

 DigiFisk (Programming Is Fun)

    45 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)
 Print
 Add Notes
 Bookmark this page
Match the elements of an array in a MySQL query

Let us first create a table table −
mysql> create table DemoTable1523
   -> (
   -> Id int,
   -> Value int
   -> );
Query OK, 0 rows affected (0.76 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1523 values(1,56);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable1523 values(2,78);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable1523 values(1,34);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable1523 values(2,45);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable1523 values(1,99);
Query OK, 1 row affected (0.10 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1523;
This will produce the following output −
+------+-------+
| Id   | Value |
+------+-------+
|    1 |    56 |
|    2 |    78 |
|    1 |    34 |
|    2 |    45 |
|    1 |    99 |
+------+-------+
5 rows in set (0.00 sec)
Following is the query to match the elements of array. Here, we are selecting id with matching values 34, 99, and 56 −
mysql> select Id from DemoTable1523
   -> where Value IN ('34','99','56')
   -> group by Id
   -> having count(*)=3;
This will produce the following output −
+------+
| Id   |
+------+
|    1 |
+------+
1 row in set (0.00 sec)
W3.CSS - Modal Dialog

W3.CSS can be used to display a customizable modal dialog box instead of the standard JavaScript alert.
It uses w3-row and w3-col style classes to define rows and columns respectively.
modal-dialog
Represents the main parent window to define a dialog box.
w3-modal-dialog
Represents the dialog content container.
w3-modal-content
Represents dialog contents.
<html>
   <head>
      <title>The W3.CSS Modal dialog</title>
      <meta name = "viewport" content = "width = device-width, initial-scale = 1">
      <link rel = "stylesheet" href = "https://www.w3schools.com/lib/w3.css">
   </head>
   
   <body class = "w3-container">
      <h2>Modal dialog Demo</h2>
      <a class = "w3-btn w3-teal" href = "#model-dialog">Open a Modal dialog</a>
      <div id = "model-dialog" class = "w3-modal">
         <div class = "w3-modal-dialog">
            <div class = "w3-modal-content w3-card-8">
               <header class = "w3-container w3-teal">
                  <a href = "#" class = "w3-closebtn">×</a>
                  <h2>TutorialsPoint</h2>
               </header>
               <div class = "w3-container">
                  <p>Hello World!</p>
               </div>
               <footer class = "w3-container w3-teal">
                  <p>@TutorialsPoint.COM</p>
               </footer>
            </div>
         </div>
      </div>
   </body>
</html>
Verify the result.
MomentJS - Day of week

This method will get/set the day of the week. It takes input from 0-6, where 0 is for Sunday and 6 as Saturday. If the value is greater than the range, it will fall in the next week. You can set the day of week using number or string.
moment().day(Number|String);
moment().day();
moment().days(Number|String);
moment().days();

var m = moment().day(); // gives 4 for thursday
var d = moment().day(0); //shows sunday
var a = moment().day('Monday'); //set the day of week to monday
var k = moment().day(10); //since it greater than 0-6 it sets to the next week and outputs Wed.
var o = moment().day(-5); // since the value is -ve it will set for last week
This gets or sets the day of the week according to the locale.
moment().weekday(Number);
moment().weekday();

As per the locale, if Sunday is set as the first day of week, you will have to set moment.weekday(0) to Sunday. If Monday is the first day of week you will see moment.weekday(0) to set as Monday.
The working of it remains same as day of week where if greater than range it will set to next week , if -ve value it will go for last week.
var m = moment().weekday();
var d = moment().weekday(4);
var a = moment().weekday('Monday');
var k = moment().weekday(10);
var o = moment().weekday(-5);
This method will set / get the day of week as per ISO where 1 is Monday and 7 is Sunday. So the range is 1-7 and anything greater than the range will fall in the next week and less than the range will fall in the last week.
moment().isoWeekday(Number);
moment().isoWeekday();

var m = moment().isoWeekday();
var d = moment().isoWeekday(4);
var a = moment().isoWeekday('Monday');
var k = moment().isoWeekday(10);
var o = moment().isoWeekday(-5);
 Print
 Add Notes
 Bookmark this page
Sort in C++ Standard Template Library (STL)

Here we will see how to use the sort() function of C++ STL to sort an array So if the array is like A = [52, 14, 85, 63, 99, 54, 21], then the output will be [14 21 52 54 63 85 99]. To sort we will use the sort() function, that is present in the header file <algorithm>. The code is like below −
 Live Demo
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
   int arr[] = {52, 14, 85, 63, 99, 54, 21};
   int n = sizeof(arr) / sizeof(arr[0]);
   cout << "Array before sorting: ";
   for (int i = 0; i < n; i++)
      cout << arr[i] << " ";
   sort(arr, arr + n);
   cout << "\nArray after sorting: ";
   for (int i = 0; i < n; i++)
      cout << arr[i] << " ";
}
Array before sorting: 52 14 85 63 99 54 21
Array after sorting: 14 21 52 54 63 85 99
Getting console.log output from Chrome with Selenium Python API bindings.

We can get console.log output from Chrome with Selenium Python API bindings. We will perform this with the DesiredCapabilities class. We shall enable the logging from the browser with DesiredCapabilities.Chrome setting.
We have to pass this browser capability to the driver object by passing it as a parameter to the Chrome class. To enable logging we shall set the property goog:loggingPrefs of the browser to 'browser':'ALL'.
Syntax:dc = DesiredCapabilities.CHROME
dc['goog:loggingPrefs'] = { 'browser':'ALL' }
driver = webdriver.Chrome(desired_capabilities=dc)
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import
DesiredCapabilities
#set browser log
dc = DesiredCapabilities.CHROME
dc['goog:loggingPrefs'] = { 'browser':'ALL' }
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe",
desired_capabilities=dc)
#launch browser
driver.get ("https://www.tutorialspoint.com/index.htm")
#obtain with get_log()
for e in driver.get_log('browser'):
   print(e)
driver.quit()
Returning a value even if there is no result in a MySQL query?

You can use IFNULL() function from MySQL to return a value even if there is not result. Let us create a table. Te query to create a table.
mysql> create table IfNullDemo
   −> (
   −> Id int,
   −> Name varchar(100)
   −> );
Query OK, 0 rows affected (0.60 sec)
Insert some records in the table with the help of insert command. The query is as follows −
mysql> insert into IfNullDemo values(1,'John');
Query OK, 1 row affected (0.18 sec)

mysql> insert into IfNullDemo values(200,'Sam');
Query OK, 1 row affected (0.21 sec)

mysql> insert into IfNullDemo values(204,'Carol');
Query OK, 1 row affected (0.14 sec)

mysql> insert into IfNullDemo values(510,'Johnson');
Query OK, 1 row affected (0.18 sec)
Display all records from the table with the help of select statement. The query is as follows −
mysql> select *from IfNullDemo;
The following is the output −
+------+---------+
| Id   | Name    |
+------+---------+
|   1 | John     |
| 200 | Sam      |
| 204 | Carol    |
| 510 | Johnson  |
+------+---------+
4 rows in set (0.00 sec)
Let us first return a value for TRUE condition −
The query is as follows −
mysql> select ifnull((select Id from IfNullDemo where Id = 200),'No Result Found') As ResultFound;
The following is the output −
+-------------+
| ResultFound |
+-------------+
| 200         |
+-------------+
1 row in set (0.00 sec)
Now, let us return a value if there is no result using the IFNULL method. The query is as follows −
mysql> select ifnull((select Id from IfNullDemo where Id = 400),'No Result Found') As ResultFound;
The following is the output −
+-----------------+
| ResultFound     |
+-----------------+
| No Result Found |
+-----------------+
1 row in set (0.00 sec)
Reverse Linked List II in C++


Suppose we have a linked list. We have to reverse the nodes from position m to n. We have to do it in one pass. So if the list is [1,2,3,4,5] and m = 2 and n = 4, then the result will be [1,4,,3,2,5]
Let us see the steps −
There will be two methods, the reverseN() and reverseBetween(). The reverseBetween() will work as main method.
define one link node pointer called successor as null
The reverseN will work as follows −
if n = 1, then successor := next of head, and return head
last = reverseN(next of head, n - 1)
next of (next of head) = head, and next of head := successor, return last
the reverseBetween() method will be like −
if m = 1, then return reverseN(head, n)
next of head := reverseBetween(next of head, m – 1, n – 1)
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class ListNode{
   public:
      int val;
      ListNode *next;
      ListNode(int data){
         val = data;
         next = NULL;
      }
   };
   ListNode *make_list(vector<int> v){
      ListNode *head = new ListNode(v[0]);
      for(int i = 1; i<v.size(); i++){
         ListNode *ptr = head;
         while(ptr->next != NULL){
            ptr = ptr->next;
         }
         ptr->next = new ListNode(v[i]);
      }
      return head;
   }
   void print_list(ListNode *head){
      ListNode *ptr = head;
      cout << "[";
      while(ptr){
         cout << ptr->val << ", ";
         ptr = ptr->next;
      }
      cout << "]" << endl;
 }
 class Solution {
   public:
      ListNode* successor = NULL;
      ListNode* reverseN(ListNode* head, int n ){
         if(n == 1){
            successor = head->next;
            return head;
         }
         ListNode* last = reverseN(head->next, n - 1);
         head->next->next = head;
         head->next = successor;
         return last;
      }
      ListNode* reverseBetween(ListNode* head, int m, int n) {
      if(m == 1){
            return reverseN(head, n);
      }
      head->next = reverseBetween(head->next, m - 1, n - 1);
            return head;
   }
 };
main(){
   Solution ob;
   vector<int> v = {1,2,3,4,5,6,7,8};
   ListNode *head = make_list(v);
   print_list(ob.reverseBetween(head, 2, 6));
}
[1,2,3,4,5,6,7,8]
2
6
[1, 6, 5, 4, 3, 2, 7, 8, ]
Add Interactive Slider to Bokeh Plots - GeeksforGeeks

28 Jul, 2021
Bokeh is an interactive Data visualization library of Python. It can be used to create interactive plots, dashboards, and data applications. Widgets are nothing but additional visual elements that you can add to your plots to interactively control your Bokeh document. There are various types of widgets such as button, div, spinner, slider, etc. In this article, we will learn about the slider widget in bokeh.
The Bokeh slider can be configured with start and end values, a step size, an initial value, and a title. Basically, you need to import the Slider widget from bokeh.models.
Syntax:
from bokeh.models import CustomJS, Slider
Slider() function can be used to create a slider.
Syntax:
Slider(start=0, end=10, value=1, step=.1, title=”Stuff”)
Parameter:
start: It represents the sliders starting value.
end:It represents the sliders ending value.
value: It represents the current value of the slider.
step: It represents the interval through which the slider moves.
title: It represents the title of the slider widget.
Now add callback functionality using CustomJS which is called when on_change event occurs.
Syntax:
js_on_change(“value”, CustomJS(code=”””.... “””))
js_on_change is a callback function that is called when slider on_change event occurs. and customJS(code=”””   “””) represents the code that is to be executed once the event occurs. Now call the callback function using the slider object and create a layout of all the elements you want to display on the browser.
Example: Creating a slider using bokeh
Python
from bokeh.layouts import columnfrom bokeh.models import ColumnDataSource, Slider, CustomJSfrom bokeh.plotting import figure, output_file, showimport numpy as np  x = np.linspace(0, 10, 500)y = np.sin(x)  source = ColumnDataSource(data=dict(x=x, y=y))  # Create plots and widgetsplot = figure()  plot.line('x', 'y', source=source, line_width=3, line_alpha=0.5)  # Create Slider objectslider = Slider(start=0, end=6, value=2,                step=0.2, title='Number of points')  # Adding callback codecallback = CustomJS(args=dict(source=source, val=slider),                    code="""    const data = source.data;    const freq = val.value;    const x = data['x'];    const y = data['y'];   for (var i = 0; i < x.length; i++) {        y[i] = Math.sin(freq*x[i]);    }          source.change.emit();""")  slider.js_on_change('value', callback)  # Arrange plots and widgets in layoutslayout = column(slider, plot)  output_file('exam.html')  show(layout)
Output:
Picked
Python-Bokeh
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Box Plot in Python using Matplotlib
Bar Plot in Matplotlib
Python | Get dictionary keys as a list
Python | Convert set into a list
Ways to filter Pandas DataFrame by column values
Python - Call function from another file
loops in python
Multithreading in Python | Set 2 (Synchronization)
Python Dictionary keys() method
Python Lambda Functions
Variable length arguments for Macros in C

We know that we can use variable length arguments for functions in C. For that we have to use ellipsis (...). Similarly for macros, we can use variable length arguments. Here also we have to include ellipsis, The ‘__VA_ARGS__’ is used to handle variable length arguments. Concatenation operator ‘##’ is used to concatenate the variable arguments.
In this example, the Macro will take variable length argument like the printf() or scanf() function. In this macro, we will print the filename, line number, and error messages. The first argument is pr. This is used to determine the priority i.e. whether it is normal info string or error
#include <stdio.h>
#define INFO 1
#define ERR 2
#define STD_OUT stdout
#define STD_ERR stderr
#define LOG_MESSAGE(pr, strm, msg, ...) do {\
   char *str;\
   if (pr == INFO)\
      str = "INFORMATION";\
   else if (pr == ERR)\
      str = "ERROR";\
      fprintf(strm, "[%s] : %s : %d : "msg" \n", \
      str, __FILE__, __LINE__, ##__VA_ARGS__);\
} while (0)
int main(void) {
   char *s = "Test String";
   LOG_MESSAGE(ERR, STD_ERR, "Unable to open the file"); //here normal message will be printed
   LOG_MESSAGE(INFO, STD_OUT, "%s is passed as argument", s); //pass string argument
   LOG_MESSAGE(INFO, STD_OUT, "%d + %d = %d", 14, 16, (14 + 16)); //Provide integer
}
[ERROR] : D:\text.c : 21 : Unable to open the file
[INFORMATION] : D:\text.c : 23 : Test String is passed as argument
[INFORMATION] : D:\text.c : 25 : 14 + 16 = 30
Class getResourceAsStream() method in Java with Examples - GeeksforGeeks

27 Dec, 2019
The getResourceAsStream() method of java.lang.Class class is used to get the resource with the specified resource of this class. The method returns the specified resource of this class in the form of InputStream object.
Syntax:
public InputStream getResourceAsStream(String resourceName)

Parameter: This method accepts a parameter resourceName which is the resource to get.
Return Value: This method returns the specified resource of this class in the form of InputStream objects.
Exception This method throws:
NullPointerException if name is null
Below programs demonstrate the getResourceAsStream() method.
Example 1:
// Java program to demonstrate// getResourceAsStream() method  import java.util.*;  public class Test {      public Object obj;      public static void main(String[] args)        throws ClassNotFoundException    {          // returns the Class object for this class        Class myClass = Class.forName("Test");          System.out.println("Class represented by myClass: "                           + myClass.toString());          String resourceName = "obj";          // Get the resource of myClass        // using getResourceAsStream() method        System.out.println(            resourceName + " resource of myClass: "            + myClass.getResourceAsStream(resourceName));    }}
Class represented by myClass: class Test
obj resource of myClass: null

Example 2:
// Java program to demonstrate// getResourceAsStream() method  import java.util.*;  class Main {      private Object obj;      public static void main(String[] args)        throws ClassNotFoundException, NoSuchFieldException    {          // returns the Class object for this class        Class myClass = Class.forName("Main");          System.out.println("Class represented by myClass: "                           + myClass.toString());          String resourceName = "obj";          try {            // Get the resource of myClass            // using getResourceAsStream() method            System.out.println(                resourceName + " resource of myClass: "                + myClass.getResourceAsStream(resourceName));        }        catch (Exception e) {            System.out.println(e);        }    }}
Class represented by myClass: class Main
obj resource of myClass: null

Reference: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#getResourceAsStream-java.lang.String-
Java-Functions
Java-lang package
Java.lang.Class
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Initialize an ArrayList in Java
Object Oriented Programming (OOPs) Concept in Java
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Multidimensional Arrays in Java
Stack Class in Java
Stream In Java
Singleton Class in Java
Set in Java
C library function - toupper()

The C library function int toupper(int c) converts lowercase letter to uppercase.
Following is the declaration for toupper() function.
int toupper(int c);
c − This is the letter to be converted to uppercase.
c − This is the letter to be converted to uppercase.
This function returns uppercase equivalent to c, if such value exists, else c remains unchanged. The value is returned as an int value that can be implicitly casted to char.
The following example shows the usage of toupper() function.
#include <stdio.h>
#include <ctype.h>

int main () {
   int i = 0;
   char c;
   char str[] = "Tutorials Point";
   
   while(str[i]) {
      putchar (toupper(str[i]));
      i++;
   }
   
   return(0);
}
Let us compile and run the above program to produce the following result −
TUTORIALS POINT


    12 Lectures 
     2 hours 

 Nishant Malik

    12 Lectures 
     2.5 hours 

 Nishant Malik

    48 Lectures 
     6.5 hours 

 Asif Hussain

    12 Lectures 
     2 hours 

 Richa Maheshwari

    20 Lectures 
     3.5 hours 

 Vandana Annavaram

    44 Lectures 
     1 hours 

 Amit Diwan
 Print
 Add Notes
 Bookmark this page
Determinant of a Matrix in C++ Program

In this tutorial, we are going to learn how to find the determinant of a matrix.
Let's see the steps to find the determinant of a matrix.
Initialize the matrix.
Initialize the matrix.
Write a function to find the determinant of the matrix.If the size of the matrix is 1 or 2, then find the determinant of the matrix. It's a straightforward thing.Initialize variables for determinant, submatrix, sign.Iterate from 1 to the size of the matrix N.Find the submatrix for the current matrix element.All the elements that are not in the current element row and columnAdd the product of the current element and its cofactor to the determinant.Alter the sign.
Write a function to find the determinant of the matrix.
If the size of the matrix is 1 or 2, then find the determinant of the matrix. It's a straightforward thing.
If the size of the matrix is 1 or 2, then find the determinant of the matrix. It's a straightforward thing.
Initialize variables for determinant, submatrix, sign.
Initialize variables for determinant, submatrix, sign.
Iterate from 1 to the size of the matrix N.
Iterate from 1 to the size of the matrix N.
Find the submatrix for the current matrix element.All the elements that are not in the current element row and column
Find the submatrix for the current matrix element.
All the elements that are not in the current element row and column
All the elements that are not in the current element row and column
Add the product of the current element and its cofactor to the determinant.
Add the product of the current element and its cofactor to the determinant.
Alter the sign.
Alter the sign.
Print the determinant of the matrix.
Print the determinant of the matrix.
Let's see the code.
 Live Demo
#include <bits/stdc++.h>
using namespace std;
#define N 3
void subMatrix(int mat[N][N], int temp[N][N], int p, int q, int n) {
   int i = 0, j = 0;
   // filling the sub matrix
   for (int row = 0; row < n; row++) {
      for (int col = 0; col < n; col++) {
         // skipping if the current row or column is not equal to the current
         // element row and column
         if (row != p && col != q) {
            temp[i][j++] = mat[row][col];
            if (j == n - 1) {
               j = 0;
               i++;
            }
         }
      }
   }
}
int determinantOfMatrix(int matrix[N][N], int n) {
   int determinant = 0;
   if (n == 1) {
      return matrix[0][0];
   }
   if (n == 2) {
      return (matrix[0][0] * matrix[1][1]) - (matrix[0][1] * matrix[1][0]);
   }
   int temp[N][N], sign = 1;
   for (int i = 0; i < n; i++) {
      subMatrix(matrix, temp, 0, i, n);
      determinant += sign * matrix[0][i] * determinantOfMatrix(temp, n - 1);
      sign = -sign;
   }
   return determinant;
}
int main() {
   int mat[N][N] = {{2, 1, 3}, {6, 5, 7}, {4, 9, 8}};
   cout << "Determinant: " << determinantOfMatrix(mat, N) << endl;
   return 0;
}
If you execute the above program, then you will get the following result.
Determinant: 36
If you have any queries in the tutorial, mention them in the comment section.
Lex Program to print the total characters, white spaces, tabs in the given input file

30 Apr, 2019
Lex is a computer program that generates lexical analyzers. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language.
The commands for executing the lex program are:
lex abc.l (abc is the file name)
cc lex.yy.c -lfl
./a.out

Let’s see Lex program to print the total characters, white spaces, tabs in the given input file.
Below is the implementation:
/* Lex program to print the total characters, white spaces, tabs in the given input file.*/  %{    int n, w, c;    %}% %\n { n++; }[^ \n\t] +{    w++;    c = c + yyleng;}.c++;% % int yywrap(void){    return 1;}    main(){    extern FILE* yyin;    yyin = fopen("input.txt", "r");    yylex();    printf("Line= %d word=%d total char=%d \n", n, w, c);}
Input:
Output:
Lex program
C Programs
Compiler Design
GBlog
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Replace a Element in Java ArrayList?

27 Jul, 2021
To replace an element in Java ArrayList, set() method of java.util. An ArrayList class can be used. The set() method takes two parameters-the indexes of the element which has to be replaced and the new element. The index of an ArrayList is zero-based. So, to replace the first element, 0 should be the index passed as a parameter.
Declaration:
public Object set(int index, Object element)
Return Value: The element which is at the specified index
Exception Throws: IndexOutOfBoundsException This occurs when the index is out of range.
index < 0 or index >= size()
Implementation:
Here we will be proposing out 2 examples wherein one of them we will be setting the index within bound and in the other, we will be setting the index out of bounds. 
Example 1: Where Index is Within Bound 
Java
// Java program to demonstrate set() Method of ArrayList// Where Index is Within Bound // Importing required classesimport java.io.*;import java.util.*; // Main classclass GFG {   // Main driver method  public static void main(String[] args) {     // Try block to check for exceptions    try {       // Creating an object of Arraylist class      ArrayList<String> list = new ArrayList<>();        // Adding elements to the List      // using add() method       // Custom input elements      list.add("A");      list.add("B");      list.add("C");      list.add("D");       // Print all the elements added in the above object      System.out.println(list);       // 2 is the index of the element "C".      //"C" will be replaced by "E"      list.set(2, "E");       // Printing the newly updated List      System.out.println(list);     }     // Catch block to handle the exceptions    catch (Exception e) {       // Display the exception on the console      System.out.println(e);    }  }}
[A, B, C, D]
[A, B, E, D]

 Example 2: Where Index is Out of Bound
Java
// Java program to demonstrate set() Method of ArrayList// Where Index is Out of Bound // Importing required classesimport java.io.*;import java.util.*; // Main classclass GFG {   // Main driver method  public static void main(String[] args) {     // Try block to check for exceptions    try {       // Creating an object of Arraylist class      ArrayList<String> list = new ArrayList<>();        // Adding elements to the List      // using add() method       // Custom input elements      list.add("A");      list.add("B");å      list.add("C");      list.add("D");       // Print all the elements added in the above object      System.out.println(list);              // Settijg the element at the 6 th index which      // does not exist in our input list object      list.set(6);         // Printing the newly updated List      System.out.println(list);    }     // Catch block to handle the exceptions    catch (Exception e) {       // Display the exception on the console      System.out.println(e);    }  }}
Output:
comrade
Java-ArrayList
Java-Collections
Picked
Java
Java Programs
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2009 | Question 60 - GeeksforGeeks

28 Jun, 2021
Let R and S be relational schemes such that R={a,b,c} and S={c}. Now consider the following queries on the database:
IV) SELECT R.a, R.b
       FROM R,S
            WHERE R.c=S.c
Which of the above queries are equivalent?(A) I and II(B) I and III(C) II and IV(D) III and IVAnswer: (A)Explanation: I and II describe the division operator in Relational Algebra and Tuple Relational Calculus respectively. See Page 3 of this and slide numbers 9,10 of this for more details.Quiz of this Question
GATE-CS-2009
GATE-GATE-CS-2009
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-IT-2004 | Question 66
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 2011 | Question 65
GATE | GATE-CS-2004 | Question 3
GATE | GATE-CS-2006 | Question 49
GATE | GATE CS 2011 | Question 7
GATE | GATE-IT-2004 | Question 71
GATE | GATE CS 2019 | Question 27
GATE | GATE-CS-2016 (Set 1) | Question 65
Compaction in Operating System
Convert CSV to list in R - GeeksforGeeks

16 May, 2021
In this article, we will discuss how to convert the content of the CSV file to list in R Programming Language.
CSV Used:
In this method, the file is first read into the R program and then one by one using for loop the columns are extracted and converted to list explicitly using list() function.
Example :
R
df=read.csv("item.csv")  lst1=list()    for(i in 1:ncol(df)) {        lst1[[i]] <- df[ , i]    }  names(lst1)=colnames(df)  print(lst1)  
Output :
In this method, the file is first read and then each column is extracted one by one explicitly with the name of the column. Then using the list method, all the extracted columns are converted to a list using list() in one go. Here names of the extracted columns is given as comma-separated values to list() to get the required functionality.
Example :
R
df=read.csv('item.csv')  a=df$idb=df$itemc=df$quantityd=df$pricee=df$boughtf=df$forenoong=df$afternoonh=df$X  lst=list(a,b,c,d,e,f,g,h)  names(lst)=colnames(df)  print(lst)
Output :
R List-Programs
R-CSV
R-List
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
How to filter R dataframe by multiple conditions?
Convert Matrix to Dataframe in R
What is the maximum length of MySQL VARCHAR column?

Actually VARCHAR data type stores variable-length character data in single byte and multibyte character Syntax for this data type is VARCHAR(n),where n is the maximum number of characters and it must be specified while creating the table. Before MySQL 5.03 the value of n can be in the range of 0 to 255 but in and after MySQL 5.03 the value can be in the range of 0 to 65,535.
The maximum number of characters stored in VARCHAR depends upon maximum row size and character set used. If we are using ASCII character set then it can store 65,535 characters because ASCII would use 1 byte per character. On the other hand, if we are using utf8 character set then the character limit would be of 21,844 because utf8 will use 3 bytes per characters. Maximum row size limit is 65,535 bytes which means that including all columns it must not be more than 65,535 bytes.
mysql> Create Table var_test(FName Varchar(32765) NOT NULL, LName Varchar(32766)
       NOT NULL);
       Query OK, 0 rows affected (0.25 sec)
The query above created a table with two columns, FName Varchar(32765) and LName Varchar(32766). Hence the total length would be 32765+2+32766+2=65535(2 bytes are used each column for storing length).
mysql> Create Table var_test1(FName varchar(32766) NOT NULL, LName Varchar(32766)
       NOT NULL);
       ERROR 1118 (42000): Row size too large. The maximum row size for the used
       table
       type, not counting BLOBs, is 65535. You have to change some columns to TEXT
       or BLOBs
Now, on increasing the length by 1 byte MySQL returns an error as shown in the query above.
asin() and atan() functions in C/C++ with Example - GeeksforGeeks

30 Oct, 2020
In C++, asin() and atan() is a predefined function used for mathematical calculations. math.h is the header file required for various mathematical functions. All the functions available in this library take double as an argument and return double as the result.
asin()
asin() function is used to find the arc sine of a number means give a sin value to this function it will return the angle in radian corresponding to that value. In trigonometrics, arc sine is the inverse operation of sine. Note: The argument passed to this function must be in the range of [-1, 1] and asin() function returns the values in the range of [-?/2, ?/2].Syntax:  
double asin(double k)

Parameters:
k is the value whose corresponding angle we have to find. 
CPP
// CPP code to illustrate// the use of asin function#include <bits/stdc++.h>using namespace std; #define PI 3.14159265 int main(){    double k, ret, val;     // Take any value between [-1, 1]    k = 0.5;    // asin() returns value in the range of [-?/2,?/2]    ret = asin(k);    val = (ret * 180) / PI;    cout << "The arcsine of " << k << " is " << ret         << " radians or " << val << " degrees";     return 0;}
Output: 
The arcsine of 0.5 is 0.523599 radians or 30 degrees 
atan()
atan() function is used to find the arc tangent of a number means gives a tangent value to this function it will return the angle in radians corresponding to that value. arc tangent is the inverse operation of tangent. This function accepts all the real numbers and atan() function returns the values in the range of [-?/2, ?/2].Syntax:  
double atan(double k)

Parameters:
k is the value whose corresponding angle we have to find.

CPP
// CPP code to illustrate// the use of atan function#include <bits/stdc++.h>using namespace std; #define PI 3.14159265 int main(){    double k, ret, val;     // Take any value    k = 1.0;    ret = atan(k);    val = (ret * 180) / PI;    cout << "The arctangent of " << k << " is " << ret         << " radians or " << val << " degrees";     return 0;}
Output: 
The arctangent of 1 is 0.785398 radians or 45 degrees 
badger_666
CPP-Library
cpp-math
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Inheritance in C++
Map in C++ Standard Template Library (STL)
Constructors in C++
C++ Classes and Objects
Socket Programming in C/C++
Bitwise Operators in C/C++
Operator Overloading in C++
Multidimensional Arrays in C / C++
Copy Constructor in C++
Virtual Function in C++
How to iterate json array – JavaScript?

To iterate JSON array, use the JSON.parse().
Following is the code −
var apiValues =
   [
      '{"name": "John", "scores": [78, 89]}',
      '{"name": "David", "scores": [58, 98]}',
      '{"name": "Bob", "scores": [56, 79]}',
      '{"name": "Mike", "scores": [94, 91]}'
   ];
var parseJSONObject = apiValues.map(obj => JSON.parse(obj));
console.log("The original String : ", apiValues);
console.log("The JSON Objects : ", parseJSONObject);
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo252.js.
This will produce the following output on console −
PS C:\Users\Amit\javascript-code> node demo252.js
The original String :  [
   '{"name": "John", "scores": [78, 89]}',
   '{"name": "David", "scores": [58, 98]}',
   '{"name": "Bob", "scores": [56, 79]}',
   '{"name": "Mike", "scores": [94, 91]}'
]
The JSON Objects :  [
   { name: 'John', scores: [ 78, 89 ] },
   { name: 'David', scores: [ 58, 98 ] },
   { name: 'Bob', scores: [ 56, 79 ] },
   { name: 'Mike', scores: [ 94, 91 ] }
]
How to get an attribute value in jQuery?

To get an attribute value in jQuery is quite easy. For this, use the jQuery attr() method. You can try to run the following code to learn how to get an attribute value in jQuery −
Live Demo
<html>

   <head>
      <title>jQuery Example</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

      <script>
      $(document).ready(function(){
         $("button").click(function(){
            alert($("img").attr("height"));
         });
      });
      </script>
   </head>
   
   <body>
      <img src="/green/images/logo.png" alt="logo" width="350" height="120"><br>
      <button>Get the height</button>
   </body>
   
</html>
MySQL regular expression to update a table with column values including string, numbers and special characters

For this, use UPDATE command along with REGEXP. Let us first create a table −
mysql> create table DemoTable2023
   -> (
   -> StreetNumber varchar(100)
   -> );
Query OK, 0 rows affected (0.59 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable2023 values('7');
Query OK, 1 row affected (0.17 sec)

mysql> insert into DemoTable2023 values('1');
Query OK, 1 row affected (0.14 sec)

mysql> insert into DemoTable2023 values('AUS-100');
Query OK, 1 row affected (0.15 sec)

mysql> insert into DemoTable2023 values('US-101');
Query OK, 1 row affected (0.11 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable2023;
This will produce the following output −
+--------------+
| StreetNumber |
+--------------+
| 7            |
| 1            |
| AUS-100      |
| US-101       |
+--------------+
4 rows in set (0.00 sec)
Here is the query to update a table using a regular expression −
mysql> update DemoTable2023
   -> set StreetNumber=concat('Street',StreetNumber)
   -> where StreetNumber regexp'^[0-9]{1,2}$';
Query OK, 2 rows affected (0.19 sec)
Rows matched: 2 Changed: 2 Warnings: 0
Let us check the table records once again −
mysql> select *from DemoTable2023;
This will produce the following output −
+--------------+
| StreetNumber |
+--------------+
| Street7      |
| Street1      |
| AUS-100      |
| US-101       |
+--------------+
4 rows in set (0.00 sec)
C# Multiple Local Variable Declarations

In C#, you can use the comma to declare more than one local variable in a statement. The following displays the same −
int a = 20, b = 70, c = 40, d = 90;
Let us see an example in which we are declaring multiple local variables. Below four variable is declared and initialized in the same statement.
Live Demo
using System;
class Demo {
   static void Main() {
      int a = 20, b = 70, c = 40, d = 90;
      Console.WriteLine("{0} {1} {2} {3}", a, b, c, d);
   }
}
20 70 40 90
C# Files

The File class from the 
System.IO namespace, allows us to work with files:
using System.IO;  // include the System.IO namespace

File.SomeFileMethod();  // use the file class with methods

The File class has many useful methods for creating and getting information 
about files. 
For example:
For a full list of File methods, go to Microsoft .Net File Class Reference.
In the 
following example, we use the WriteAllText() method 
to create a file named "filename.txt" and write some content to it. Then we use the ReadAllText() 
method to read the contents of the file:
using System.IO;  // include the System.IO namespace

string writeText = "Hello World!";  // Create a text string
File.WriteAllText("filename.txt", writeText);  // Create a file and write the content of writeText to it

string readText = File.ReadAllText("filename.txt");  // Read the contents of the file
Console.WriteLine(readText);  // Output the content

The output will be:
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.