code-rag-bench/online-tutorials huggingface dataset:
Get global variable dynamically by name string in JavaScript?

Display in alert by using alert(window()). Following is the syntax −
alert(window['yourVariableName' + 'yourVariableName' + otherVariableName]);
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<script>
   var globalVariablelocal_print100=100;
   print100=1;
   alert(window['globalVariable' + 'local_' + print100]);
</script>
</body>
</html>
To run the above program, save the file name anyName.html(index.html) and right click on the file and select the option open with live server in VS code editor.
C++ Program to Check Prime Number By Creating a Function

A prime number is a whole number that is greater than one and the only factors of a prime number should be one and itself.
Some of the first prime numbers are −
2, 3, 5, 7, 11, 13 ,17
A program to check if a number is prime or not using a function is as follows.
 Live Demo
#include <iostream>
using namespace std;
void isPrime(int n) {
   int i, flag = 0;
   for(i=2; i<=n/2; ++i) {
      if(n%i==0) {
         flag=1;
         break;
      }
   }
   if (flag==0)
   cout<<n<<" is a prime number"<<endl;
   else
   cout<<n<<" is not a prime number"<<endl;
}
int main() {
   isPrime(17);
   isPrime(20);
   return 0;
}
17 is a prime number
20 is not a prime number
The function isPrime() is used to find out if a number is prime or not. There is a loop that runs from 2 to half of n, where n is the number to be determined. Each of the values of the loop divide n. If the remainder of this division is 0, that means n is divisible by a number, not one or itself. So, it is not a prime number and the flag is set to 1. Then break statement is used to exit the loop as shown below −
for(i=2; i<=n/2; ++i) {
   if(n%i==0) {
      flag=1;
      break;
   }
}
If the value of flag remained zero, then the number is a prime number and that is displayed. If the value of flag was changed to one, then the number is not a prime number and that is displayed.
if (flag==0)
cout<<n<<" is a prime number";
else
cout<<n<<" is not a prime number";
The function isPrime() is called from the main() function for the values 17 and 20. This is shown as follows.
isPrime(17);
isPrime(20);
PyQt - Hello World

Creating a simple GUI application using PyQt involves the following steps −
Import QtGui module.
Import QtGui module.
Create an application object.
Create an application object.
A QWidget object creates top level window. Add QLabel object in it.
A QWidget object creates top level window. Add QLabel object in it.
Set the caption of label as “hello world”.
Set the caption of label as “hello world”.
Define the size and position of window by setGeometry() method.
Define the size and position of window by setGeometry() method.
Enter the mainloop of application by app.exec_() method.
Enter the mainloop of application by app.exec_() method.
import sys
from PyQt4 import QtGui

def window():
   app = QtGui.QApplication(sys.argv)
   w = QtGui.QWidget()
   b = QtGui.QLabel(w)
   b.setText("Hello World!")
   w.setGeometry(100,100,200,50)
   b.move(50,20)
   w.setWindowTitle(“PyQt”)
   w.show()
   sys.exit(app.exec_())
	
if __name__ == '__main__':
   window()
The above code produces the following output −

    146 Lectures 
     22.5 hours 

 ALAA EID
 Print
 Add Notes
 Bookmark this page
How to convert 3-digit color code to 6-digit color code using JavaScript ? - GeeksforGeeks

12 Mar, 2021
In this article, we are converting a three-digit color HEX code into a six-digit color HEX code using JavaScript. To solve this problem, first we copy of the individual digits and paster at consecutive position. For example – #34E will be converted into #3344EE and #E90 will be converted into #EE9900.
Steps to convert 3-digit color code to 6-digit color code:
Step 1: The color code is in string format. So, apply the split method on the string. After applying the split method we got an array of elements.
Javascript
<script>  var digit = "39E"  digit = digit.split("")  console.log(digit)  // ["#", "3", "9", "E"]</script>
Output:
["#", "3", "9", "E"]
Step 2: Now apply the map method and iterate over the array and return every item with concatenating to itself and check if the item is “#” then do not return the concatenated result, just return the item.
Javascript
<script>  var digit = "#39E";  digit = digit.split("").map((item)=>{    if(item == "#"){return item}        return item + item;})  console.log(digit)  // ["#", "33", "99", "EE"]</script>
Output:
["#", "33", "99", "EE"]
Step 3: Now use the join method to convert all the array items into a single string.
Javascript
<script>  var digit = "#39E"  digit = digit.split("").map((item)=>{    if(item == "#"){return item}        return item + item;}).join("")  console.log(digit)<script>
Output:
"#3399EE"
Step 4: In the above step, we are converting “#39E” but we can see the first element of this code is “#”, but if the user does not provide the “#” then you have to check if the first element is “#” then concatenate it with the resulting code. And this is our complete code.
Javascript
<script>  var digit = "#39E"  digit = digit.split("").map((item)=>{    if(item == "#"){return item}        return item + item;}).join("")  if(digit[0] != "#"){    digit = "#" + digit;}  console.log(digit)</script>
Output:
#3399EE
javascript-functions
JavaScript-Questions
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
How to get character array from string in JavaScript?
How to remove duplicate elements from JavaScript Array ?
How to get selected value in dropdown list using JavaScript ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between strong and bold tag in HTML - GeeksforGeeks

03 Dec, 2020
HTML strong tag: The strong tag is one of the element of HTML used in formatting HTML texts. It is used to show importance of the text by making it bold or highlighting it semantically.
Syntax:
<strong> Contents... </strong>
HTML bold tag: The bold tag or <b> is also one of the formatting elements of HTML. The text written under <b> tag makes the text bold presentationally to draw attention.
Syntax:
<b> Contents... </b>
The main difference between these two tag is that the strong tag semantically emphasizes on the important word or section of words while the bold tag is just offset text conventionally styled in bold. Below is the code to show this difference.
Example 1:
HTML
<!DOCTYPE html><html>  <head>    <style>        body {            text-align:center;        }        h1 {            color: green;        }    </style></head>  <body>    <h1>GeeksforGeeks</h1>          <p><strong>        This text is important!    </strong></p>          <p><b>This text is bold.</p></body>  </html>                  
Output:
Though there is no difference in the display of both the tags but there is semantical difference between them.
Example 2:
HTML
<!DOCTYPE html><html>  <head>    <title>b tag</title>          <style>        body {            text-align:center;        }        h1 {            color: green;        }    </style></head>  <body>    <h1>GeeksforGeeks</h1>          <p>        Without <strong>internet</strong>         we can not use gfg    </p>          <p>        <b>GeeksforGeeks:</b> A computer         science portal for geeks    </p></body>  </html>                    
Output:
We wanted to show the importance of the word “internet” so we used <strong> tag where as for the word “GeeksforGeeks”, we just simply wanted to format the text in bold.
Supported Browser: The browser supported by <b> and <strong> tag are listed below.
Chrome
Android
Firefox (Gecko)
Firefox Mobile (Gecko)
Internet Explorer (IE)
Edge Mobile
Opera
Opera Mobile
Safari (WebKit)
Safari Mobile
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
HTML-Misc
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to update Node.js and NPM to next version ?
Types of CSS (Cascading Style Sheet)
How to Insert Form Data into Database using PHP ?
CSS to put icon inside an input element in a form
REST API (Introduction)
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
Create Multiple frames with Grid manager using Tkinter - GeeksforGeeks

16 Mar, 2021
Prerequisites: Tkinter
Tkinter can support the creation of more than one widget in the same frame. Not just this it also supports a mechanism to align them relative to each other. One of the easiest ways of aligning the different widgets in the Tkinter is through grid manager. Apart from aligning various widgets, the grid manager can also be used for aligning the numerous frames. 
In this article, we will be discussing the approach of aligning multiple frames with Grid Manager.
For this first the frames needs to be defined, and then they need to be aligned using grid().
Syntax:
frame1=LabelFrame(app, text=”#Text you want to give in frame”)
frame1.grid(row=#Row value, column=#Column value)
LabelFrame() is used to create a frame
grid() is used to apply grid manager to the widgets created
Import module
Create a GUI app using tkinter
Give a title to the app.(optional)
Now, create the first frame, i.e., frame1
Display the frame1 in grid manager by specifying row and column values.
Further, create a widget you wish to get display in the frame1.
Display the widget you made in previous step.
For creating more frames, repeat from steps 4 to 7. Repeat these steps n number of times for creating n number of frames. Don’t forget to change the row value and column value for every frame. You can change the row value and column value of the frames according to the given image.
Finally, make the loop for displaying the GUI app on the screen.
Program:
Python
# Import the library tkinterfrom tkinter import *  # Create a GUI appapp = Tk()  # Give a title to your appapp.title("Vinayak App")  # Constructing the first frame, frame1frame1 = LabelFrame(app, text="Fruit", bg="green",                    fg="white", padx=15, pady=15)  # Displaying the frame1 in row 0 and column 0frame1.grid(row=0, column=0)  # Constructing the button b1 in frame1b1 = Button(frame1, text="Apple")  # Displaying the button b1b1.pack()  # Constructing the second frame, frame2frame2 = LabelFrame(app, text="Vegetable", bg="yellow", padx=15, pady=15)  # Displaying the frame2 in row 0 and column 1frame2.grid(row=0, column=1)  # Constructing the button in frame2b2 = Button(frame2, text="Tomato")  # Displaying the button b2b2.pack()  # Make the loop for displaying appapp.mainloop()
Output:
Picked
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
Python - Convert String to Nested Dictionaries - GeeksforGeeks

14 May, 2020
Sometimes, while working with dictionaries, we can have a problem in which we need to convert a String to nested dictionary, each separator occurrence meaning a new nesting. This is a particular problem but can occur in data domains and day-day programming. Let’s discuss certain way in which this task can be done.
Method : Using loop + recursionThis is way in which this task can be performed. In this, we recur for nesting of dictionary as we encounter a separator occurrence.
# Python3 code to demonstrate working of # Convert String to Nested Dictionaries# Using loop  def helper_fnc(test_str, sep):  if sep not in test_str:    return test_str  key, val = test_str.split(sep, 1)  return {key: helper_fnc(val, sep)}  # initializing stringtest_str = 'gfg_is_best_for_geeks'  # printing original stringprint("The original string is : " + str(test_str))  # initializing separatorsep = '_'  # Convert String to Nested Dictionaries# Using loopres = helper_fnc(test_str, sep)  # printing result print("The nested dictionary is : " + str(res)) 
The original string is : gfg_is_best_for_geeks
The nested dictionary is : {'gfg': {'is': {'best': {'for': 'geeks'}}}}

 
Python dictionary-programs
Python-nested-dictionary
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
Python program to check whether a number is Prime or not - GeeksforGeeks

10 Nov, 2021
Given a positive integer N, The task is to write a Python program to check if the number is prime or not.Definition: A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. The first few prime numbers are {2, 3, 5, 7, 11, ....}.
Examples : 
Input:  n = 11Output: true
Input:  n = 15Output: false
Input:  n = 1Output: false
The idea to solve this problem is to iterate through all the numbers starting from 2 to (N/2) using a for loop and for every number check if it divides N. If we find any number that divides, we return false. If we did not find any number between 2 and N/2 which divides N then it means that N is prime and we will return True.
Below is the Python program to check if a number is prime: 
Python3
# Python program to check if# given number is prime or not  num = 11  # If given number is greater than 1if num > 1:      # Iterate from 2 to n / 2    for i in range(2, int(num/2)+1):          # If num is divisible by any number between        # 2 and n / 2, it is not prime        if (num % i) == 0:            print(num, "is not a prime number")            break    else:        print(num, "is a prime number")  else:    print(num, "is not a prime number")
11 is a prime number
Optimized Method We can do the following optimizations: 
Instead of checking till n, we can check till √n because a larger factor of n must be a multiple of a smaller factor that has been already checked.
Now lets see the code for the first optimization method ( i.e. checking till √n )
Python3
from math import sqrt# n is the number to be check whether it is prime or notn = 1  # no lets check from 2 to sqrt(n)# if we found any facto then we can print as not a prime number  # this flag maintains status whether the n is prime or notprime_flag = 0  if(n > 1):    for i in range(2, int(sqrt(n)) + 1):        if (n % i == 0):            prime_flag = 1            break    if (prime_flag == 0):        print("true")    else:        print("false")else:    print("false")
false
The algorithm can be improved further by observing that all primes are of the form 6k ± 1, with the exception of 2 and 3. This is because all integers can be expressed as (6k + i) for some integer k and for i = -1, 0, 1, 2, 3, or 4; 2 divides (6k + 0), (6k + 2), (6k + 4); and 3 divides (6k + 3). So a more efficient method is to test if n is divisible by 2 or 3, then to check through all the numbers of form 6k ± 1. (Source: wikipedia)
kumarakhilakak
daft
bindusri822
santhoshcharan
vsiddharth365
pulamolusaimohan
Prime Number
Python
Python Programs
School Programming
Prime Number
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
*args and **kwargs in Python
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
Java Program to Get System Name for Windows and Linux Machine - GeeksforGeeks

05 Jul, 2021
We can get the System name for a Windows or Linux machine using the getHostName() method of the InetAddress class of java.net package after getting the IP address of the system using getLocalHost() method of the same class. The class InetAddress gets the IP address of any hostname.  getLocalHost() method of the InetAddress class gets the address of the local host. getHostName() gets the hostname for a given IP address or returns the textual representation of the IP address if the operation is not allowed by the security manager.
Syntax
public String getHostName()
Returns: The address of the host for a given IP address or the textual representation of the IP address if the operation is not allowed.
Example:
Java
// Java program to demonstrate getting// the System name of the user import java.net.InetAddress;public class GFG {    public static void main(String[] args)    {        try {             // get system name            String SystemName                = InetAddress.getLocalHost().getHostName();             // SystemName stores the name of the system            System.out.println("System Name : "                               + SystemName);        }        catch (Exception E) {            System.err.println(E.getMessage());        }    }}
 
 
Output:
 
 
abhishek0719kadiyan
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Generics in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
Iterate through List in Java
Python Program to Check Prime Number - GeeksforGeeks

30 Nov, 2018
Given a positive integer, check if the number is prime or not. A prime is a natural number greater than 1 that has no positive divisors other than 1 and itself. Examples of first few prime numbers are {2, 3, 5,
Examples:
Input:  n = 11
Output: true

Input:  n = 15
Output: false

Input:  n = 1
Output: false

School Method :
# A school method based Python3 # program to check if a number# is prime  def isPrime(n):      # Corner case    if n <= 1:        return False      # Check from 2 to n-1    for i in range(2, n):        if n % i == 0:            return False;      return True  # Driver Program to test above functionprint("true") if isPrime(11) else print("false")print("true") if isPrime(14) else print("false")  # This code is contributed by Smitha Dinesh Semwal
Output:
true
false

Time complexity of this solution is O(n)
Optimized School Method :
# A optimized school method based  # Python3 program to check # if a number is prime         def isPrime(n) :     # Corner cases     if (n <= 1) :         return False    if (n <= 3) :         return True        # This is checked so that we can skip      # middle five numbers in below loop     if (n % 2 == 0 or n % 3 == 0) :         return False        i = 5    while(i * i <= n) :         if (n % i == 0 or n % (i + 2) == 0) :             return False        i = i + 6        return True        # Driver Program      if(isPrime(11)) :     print(" true") else :     print(" false")         if(isPrime(15)) :     print(" true") else :      print(" false")                 # This code is contributed  # by Nikita Tiwari. 
Output:
true
false

Please refer complete article on Primality Test | Set 1 (Introduction and School Method) for more details!
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Convert string dictionary to dictionary
Iterate over characters of a string in Python
Python Program for factorial of a number
Python | Convert set into a list
Python | Convert a list into a tuple
Python program to add two numbers
Python | Check if a variable is string
Add a key:value pair to dictionary in Python
Appending to list in Python dictionary
Python program to find sum of elements in list
How to create a form using Django Forms ?

16 Aug, 2021
Django forms are an advanced set of HTML forms that can be created using python and support all features of HTML forms in a pythonic way. This post revolves around how to create a basic form using various Form Fields and attributes. Creating a form in Django is completely similar to creating a model, one needs to specify what fields would exist in the form and of what type. For example, to input, a registration form one might need First Name (CharField), Roll Number (IntegerField), and so on. 
Illustration of Django Forms using an Example. Consider a project named geeksforgeeks having an app named geeks. 
Refer to the following articles to check how to create a project and an app in Django.  
How to Create a Basic Project using MVT in Django?
How to Create an App in Django ?
In your geeks app make a new file called forms.py where you would be making all your forms. To create a Django form you need to use Django Form Class. Let’s demonstrate it. 
In your forms.py Enter the following, 
Python3
from django import forms # creating a formclass InputForm(forms.Form):     first_name = forms.CharField(max_length = 200)    last_name = forms.CharField(max_length = 200)    roll_number = forms.IntegerField(                     help_text = "Enter 6 digit roll number"                     )    password = forms.CharField(widget = forms.PasswordInput())
Let’s explain what exactly is happening, left side denotes the name of the field and to the right of it, you define various functionalities of an input field correspondingly. A field’s syntax is denoted as 
Syntax : 
Field_name = forms.FieldType(attributes)
Now to render this form into a view, move to views.py and create a home_view as below. 
Python3
from django.shortcuts import renderfrom .forms import InputForm # Create your views here.def home_view(request):    context ={}    context['form']= InputForm()    return render(request, "home.html", context)
In view, one needs to just create an instance of the form class created above in forms.py. Now let’s edit templates > home.html 
HTML
<form action = "" method = "post">    {% csrf_token %}    {{form }}    <input type="submit" value=Submit"></form>
All set to check if the form is working or not let’s visit http://localhost:8000/ 
The form is working properly but visuals are disappointing, Django provides some predefined ways to show forms in a convenient manner. In templates, the following will modify the inputs as, 
{{ form.as_table }} will render them as table cells wrapped in <tr> tags
{{ form.as_p }} will render them wrapped in <p> tags
{{ form.as_ul }} will render them wrapped in <li> tags
One can modify these settings also and show fields as he wants using {{ form.field_name }} but this may alter the normal process of validation if some field is empty and hence needs extraordinary care. More – Django Forms
NaveenArora
ddeevviissaavviittaa
Django-forms
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Finding sum of first n natural numbers in PL/SQL

07 Jul, 2018
Prerequisite – PL/SQL introductionIn PL/SQL code groups of commands are arranged within a block. A block group related declarations or statements. In declare part, we declare variables and between begin and end part, we perform the operations.Given a positive integer n and the task is to find the sum of first n natural number.Examples:
Input: n = 3
Output: 10
      
Input: n = 2
Output: 4

Approach is to take digits form 1 and to n and summing like done below-
Sum of first natural number: 1
Sum of first and second natural number: 1 + 2 = 3
Sum of first, second and third natural number = 1 + 2 + 3 = 6
Below is the required implementation:
--declaration section DECLARE   x NUMBER;   n NUMBER;   i NUMBER;       --function for finding sum   FUNCTION Findmax(n IN NUMBER)     RETURN NUMBER   IS     sums NUMBER := 0;   BEGIN         --for loop for n times iteration     FOR i IN 1..n     LOOP       sums := sums + i*(i+1)/2;     END LOOP;     RETURN sums;   END;   BEGIN         --driver code     n := 4;     x := findmax(n);     dbms_output.Put_line('Sum: '     || x);   END;       --end of Program
Output:
Sum: 20
Time complexity = O(n)
An efficient solution is to use direct formula n(n+1)(n+2)/6
Mathematically, we need to find, Σ ((i * (i + 1))/2), where 1 <= i <= nSo, lets solve this summation,
Sum = Σ ((i * (i + 1))/2), where 1 <= i <= n
    = (1/2) * Σ (i * (i + 1))
    = (1/2) * Σ (i2 + i)
    = (1/2) * (Σ i2 + Σ i)

We know Σ i2 = n * (n + 1) * (2*n + 1) / 6 and 
Σ i = n * ( n + 1) / 2.
Substituting the value, we get,
Sum = (1/2) * ((n * (n + 1) * (2*n + 1) / 6) + (n * ( n + 1) / 2))  
    = n * (n + 1)/2 [(2n + 1)/6 + 1/2]
    = n * (n + 1) * (n + 2) / 6
Below is the required implementation:
--declaration section DECLARE   x NUMBER;   n NUMBER;       --utility function   FUNCTION Findmax(n IN NUMBER)     RETURN NUMBER   IS     z NUMBER;   BEGIN         -- formula for finding sum     z := (n * (n + 1) * (n + 2)) / 6;     RETURN z;   END;   BEGIN     n := 4;     x := findmax(n);     dbms_output.Put_line(' Sum: '     || x);   END;       --end of program
Output:
Sum: 20
Time complexity = O(1)
SQL-PL/SQL
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between Active Attack and Passive Attack

07 Jul, 2022
Active Attacks: Active attacks are the type of attacks in which, The attacker efforts to change or modify the content of messages. Active Attack is danger for Integrity as well as availability. Due to active attack system is always damaged and System resources can be changed. The most important thing is that, In active attack, Victim gets informed about the attack.
Passive Attacks: Passive Attacks are the type of attacks in which, The attacker observes the content of messages or copy the content of messages. Passive Attack is a danger for Confidentiality. Due to passive attack, there is no any harm to the system. The most important thing is that In passive attack, Victim does not get informed about the attack. 
Prerequisite - Types of Security attacks | Active and Passive attacks 
Difference between Active Attack and Passive Attack:
ashushrma378
sayanc170
Information-Security
Computer Networks
Difference Between
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to add/update an attribute to an HTML element using JavaScript?

01 Sep, 2021
We can use two approaches to modify an attribute of an HTML element using JavaScript.Approach 1: We can use the inbuilt setAttribute() function of JavaScript.Syntax:  
var elementVar = document.getElementById("element_id");
elementVar.setAttribute("attribute", "value");
So what basically we are doing is initializing the element in JavaScript by getting its id and then using setAttribute() to modify its attribute.Example: Below is the implementation of above approach.  
html
<!DOCTYPE html><html> <head>    <title>Modify attributes method 1</title>    <script>        function modify() {             //update style attribute of element "heading"             var heading = document.getElementById("heading");            heading.setAttribute("style", "color:green");             //add style attribute to element "tagLine"             var tagLine = document.getElementById("tagLine");            tagLine.setAttribute("style", "color:blue");        }    </script></head> <body>     <h1 style="color:black"        id="heading"        align="center">      GeeksForGeeks  </h1>     <p id="tagLine" align="center"> - Society Of Geeks        <br>        <br>        <button onclick="modify()"> Click to modify </button>    </p> </body> </html>
Output:  
Before clicking the button:  
After clicking the button:  
 
We can modify HTML attributes even without using setAttribute() function as follows :  
document.getElementById("element_id").attribute = attribute_value;
Example: Below is the implementation of above approach:  
html
<!DOCTYPE html><html> <head>    <title>Modify attributes method 2</title>    <script>        function add() {             //get the values of fNum and sNum using getAttribute()             var fNum = Number(document.getElementById("fNum").value);            var sNum = Number(document.getElementById("sNum").value);            var result = fNum + sNum;             //output the result in green colour            var output = "Sum of two numbers is " + result;            document.getElementById("result").style = "color:green";            document.getElementById("result").innerHTML = output;             /*note the way we have updated innerHTML and added style              attribute of "result" element */         }    </script></head> <body>     <h1 style="color:green" align="center">GeeksForGeeks</h1>     <p align="center">        <b>Enter first number :- </b>        <input type="number" id="fNum">        <br>        <br>        <b>Enter second number :- </b>        <input type="number" id="sNum">        <br>        <br>        <button onclick="add()">Add</button>        <b><p id="result" align="center"></p></b>     </p> </body> </html>
Output:  
Before clicking the button:  
After clicking the button:  
 
clintra
JavaScript-Misc
Picked
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL MIN() and MAX()

14 Aug, 2020
SQL MIN() FunctionsThe MIN() function provides the smallest value of the chosen column.MIN() Syntax –SELECT MIN(column_name)
FROM table_name
WHERE condition;
SQL MAX() FunctionsThe MAX() function provides the largest value of the chosen column.MAX() Syntax –SELECT MAX(column_name)
FROM table_name
WHERE condition;

SQL MIN() FunctionsThe MIN() function provides the smallest value of the chosen column.MIN() Syntax –SELECT MIN(column_name)
FROM table_name
WHERE condition;

MIN() Syntax –
SELECT MIN(column_name)
FROM table_name
WHERE condition;

SQL MAX() FunctionsThe MAX() function provides the largest value of the chosen column.MAX() Syntax –SELECT MAX(column_name)
FROM table_name
WHERE condition;

MAX() Syntax –
SELECT MAX(column_name)
FROM table_name
WHERE condition;

Let us assume, we have below table “GeeksTable” :
MIN() Example :The following SQL statement finds the lowest salary product :SELECT MIN(Salary) FROM GeeksTable;Output –2900MAX() Example :The following SQL statement finds the highest salary :SELECT MAX(Price) FROM GeeksTable; Output –8750

MIN() Example :The following SQL statement finds the lowest salary product :SELECT MIN(Salary) FROM GeeksTable;Output –2900
SELECT MIN(Salary) FROM GeeksTable;
Output –
2900
MAX() Example :The following SQL statement finds the highest salary :SELECT MAX(Price) FROM GeeksTable; Output –8750

SELECT MAX(Price) FROM GeeksTable; 
Output –
8750

DBMS-SQL
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
Window functions in SQL
SQL | Sub queries in From Clause
What is Temporary Table in SQL?
SQL using Python
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL Query to Convert VARCHAR to INT
RANK() Function in SQL Server
SQL Query to Compare Two Dates
SQL Query to Convert Rows to Columns in SQL Server
Python | Write multiple files data to master file

06 May, 2019
Given a number of input files in a source directory, write a Python program to read data from all the files and write it to a single master file.
Source directory contains n number of files, and structure is same for all files. The objective of this code is to read all the files one by one and then append the output into a single master file having structure same as source files.
Taking three input files as example, named emp_1.txt, emp_2.txt, emp_3.txt, output will contain data from all the input files.
Input: 




Output: 

 
Method #1: Using os module
import os# list the files in directorylis = os.listdir('D:\\python'                 '\\data_files\\data_files')print(lis)tgt = os.listdir('D:\\python'                 '\\data_files\\target_file')  file_dir ='D:\\python\\data_files\\data_files'out_file = r'D:\\python\\data_files\\target_file\\master.txt'ct = 0  print('target file :', tgt)try:    # check for if file exists    # if yes delete the file     # otherwise data will be appended to existing file    if len(tgt)>0:        os.remove('D:\\python'                  '\\data_files\\target_file\\master.txt')          open(tgt, 'a').close()    else:        # create an empty file        open(tgt, 'a').close()except:    head = open('D:\\python'                '\\data_files\\target_file\\master.txt', 'a+')      line ='empno, ename, sal'    # write header to output    print(head, line)    head.close()    # below loop to write data to output file    for line1 in lis:        f_dir = file_dir+'\\'+line1        # open files in read mode        in_file = open(f_dir, 'r+')          # open output in append mode        w = open(out_file, 'a+')        d = in_file.readline()        d = in_file.readlines()        w.write("\n")        for line2 in d:            print(line2)            w.write(line2)                    ct = ct + 1      w.close()      
Output:
 Method #2: Using pandas
import pandas as pd# pd.read_csv creates dataframesdf1 = pd.read_csv('D:\python\data_files\data_files\emp_1.txt')df2 = pd.read_csv('D:\python\data_files\data_files\emp_2.txt')df3 = pd.read_csv('D:\python\data_files\data_files\emp_3.txt')  frames = [df1, df2, df3]  # concat function concatenates the frames result = pd.concat(frames)# to_csv function writes output to fileresult.to_csv('D:\\python\\data_files'              '\\target_file\\master.txt', encoding ='utf-8', index = False)
Output:
python-utility
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Scala String charAt() method with example

15 Oct, 2019
The charAt() method is utilized to return the character of the index passed in the argument.
Method Definition: char charAt(int index)Return Type: It returns char for the index given in the argument.
Example #1:
// Scala program of charAt()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {        // Creating a String        val m1 = "Nidhi"                  // Applying charAt() method        val result = m1.charAt(2)                  // Displays output        println(result)              }} 
d

Example #2:
// Scala program of charAt()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {        // Creating a String        val m1 = "Nidhi"                  // Applying charAt() method        val result = m1.charAt(0)                  // Displays output        println(result)              }} 
N

shubham_singh
Scala
Scala-Method
Scala-Strings
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Scala Tutorial – Learn Scala with Step By Step Guide
Scala Map
Scala Lists
Scala | Arrays
Enumeration in Scala
Lambda Expression in Scala
How to get the first element of List in Scala
How to Install Scala with VSCode?
Scala String replace() method with example
HashMap in Scala
Java program to find the largest number in an array

To find the largest element of the given array, first of all, sort the array.
Compare the first two elements of the array
If the first element is greater than the second swap them.
Then, compare 2nd and 3rd elements if the second element is greater than the 3rd swap them.
Repeat this till the end of the array.
After sorting an array print the 1st element from the end of the array.
Live Demo
public class ThirdLargestNumberInAnArray {
   public static void main(String args[]){
      int temp, size;
      int array[] = {10, 20, 25, 63, 96, 57};
      size = array.length;

      for(int i = 0; i<size; i++ ){
         for(int j = i+1; j<size; j++){
            if(array[i]>array[j]){
               temp = array[i];
               array[i] = array[j];
               array[j] = temp;
            }
         }
      }
      System.out.println("Third largest element is:: "+array[size-1]);
   }
}
Third largest element is:: 96
You can also sort the elements of the given array using the sort method of the java.util.Arrays class then, print the 1st element from the end of the array.
Live Demo
import java.util.Arrays;
public class LargestNumberSample {
   public static void main(String args[]){
      int array[] = {10, 20, 25, 63, 96, 57};
      int size = array.length;
      Arrays.sort(array);
      System.out.println("sorted Array ::"+Arrays.toString(array));
      int res = array[size-1];
      System.out.println("largest element is ::"+res);
   }
}
sorted Array ::[10, 20, 25, 57, 63, 96]
largest element is ::96
Dart Programming - truncate Method

Returns an integer after discarding any fractional digits.
Number.truncate()

Returns an int without decimal points.
void main() { 
   double n1 = 2.123; 
   var value = n1.truncate(); 
   print("The truncated value of 2.123 = ${value}"); 
} 
It will produce the following output −.
The truncated value of 2.123 = 2 


    44 Lectures 
     4.5 hours 

 Sriyank Siddhartha

    34 Lectures 
     4 hours 

 Sriyank Siddhartha

    69 Lectures 
     4 hours 

 Frahaan Hussain

    117 Lectures 
     10 hours 

 Frahaan Hussain

    22 Lectures 
     1.5 hours 

 Pranjal Srivastava

    34 Lectures 
     3 hours 

 Pranjal Srivastava
 Print
 Add Notes
 Bookmark this page
How to append some text to all paragraphs using jQuery ? - GeeksforGeeks

31 Dec, 2020
In this article, we will append some text to all paragraph elements using jQuery. To append some text to all paragraph elements, we use append() and document.createTextNode() methods.
jQuery append() method is used to insert some content at the end of the selected elements.
Syntax:
$(selector).append( content, function(index, html) )
Example:
HTML
<!DOCTYPE html><html lang="en">  <head>      <!-- Import jQuery cdn library -->    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">    </script>      <script>        $(document).ready(function () {            $("button").click(function () {                $("p").append(document                .createTextNode(" GeeksforGeeks"));            });        });    </script></head>  <body style="text-align: center;">    <h1 style="color: green;">        GeeksforGeeks    </h1>      <h3>        How to append some text to        all paragraphs using jQuery?    </h3>      <p>        Computer Science Portal    </p>      <p>Welcome</p>      <button>Click Here!</button></body>  </html>
Output:
Before Click the Button:
After Click Button:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
CSS-Misc
HTML-Misc
jQuery-Misc
CSS
HTML
JQuery
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Design a web page using HTML and CSS
Form validation using jQuery
Search Bar using HTML, CSS and JavaScript
How to set space between the flexbox ?
How to Create Time-Table schedule using HTML ?
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
How to Insert Form Data into Database using PHP ?
Hide or show elements in HTML using display property
REST API (Introduction)
Dictionary Operations in Data Structure

A dictionary is defined as a general-purpose data structure for storing a group of objects. A dictionary is associated with a set of keys and each key has a single associated value. When
presented with a key, the dictionary will simply return the associated value.
For example, the results of a classroom test could be represented as a dictionary with student's names as keys and their scores as the values:
results = {'Anik' : 75,
'Aftab' :80,
'James' : 85,
'Manisha': 77,
'Suhana' :87,
'Margaret': 82}
Dictionaries typically support so many operations −
retrieve a value (based on language, attempting to retrieve a missing key may provide a default value or throw an exception)
retrieve a value (based on language, attempting to retrieve a missing key may provide a default value or throw an exception)
inserting or updating a value (typically, if the key does not exist in the dictionary, the key-value pair is inserted; if the key already exists, its corresponding value is overwritten with the new one)
inserting or updating a value (typically, if the key does not exist in the dictionary, the key-value pair is inserted; if the key already exists, its corresponding value is overwritten with the new one)
remove or delete a key-value pair
remove or delete a key-value pair
test or verify for existence of a key
test or verify for existence of a key
Most programming languages with dictionaries support iteration over the keys or values in a dictionary. Note that items in a dictionary are unordered, so loops over dictionaries will return items in random order.
MATLAB - Colon Notation

The colon(:) is one of the most useful operator in MATLAB. It is used to create vectors, subscript arrays, and specify for iterations.
If you want to create a row vector, containing integers from 1 to 10, you write −
1:10
MATLAB executes the statement and returns a row vector containing the integers from 1 to 10 −
ans =                                                                           
                                                                                
   1    2    3    4    5    6    7    8    9   10 

If you want to specify an increment value other than one, for example −
100: -5: 50
MATLAB executes the statement and returns the following result −
ans =
   100    95    90    85    80    75    70    65    60    55    50

Let us take another example −
0:pi/8:pi
MATLAB executes the statement and returns the following result −
ans =
   Columns 1 through 7
      0    0.3927    0.7854    1.1781    1.5708    1.9635    2.3562
   Columns 8 through 9
      2.7489    3.1416

You can use the colon operator to create a vector of indices to select rows, columns or elements of arrays.
The following table describes its use for this purpose (let us have a matrix A) −
Create a script file and type the following code in it −
A = [1 2 3 4; 4 5 6 7; 7 8 9 10]
A(:,2)      % second column of A
A(:,2:3)    % second and third column of A
A(2:3,2:3)  % second and third rows and second and third columns
When you run the file, it displays the following result −
A =
      1     2     3     4
      4     5     6     7
      7     8     9    10

ans =
      2
      5
      8

ans =
      2     3
      5     6
      8     9

ans =
      5     6
      8     9


    30 Lectures 
     4 hours 

 Nouman Azam

    127 Lectures 
     12 hours 

 Nouman Azam

    17 Lectures 
     3 hours 

 Sanjeev

    37 Lectures 
     5 hours 

 TELCOMA Global

    22 Lectures 
     4 hours 

 TELCOMA Global

    18 Lectures 
     3 hours 

 Phinite Academy
 Print
 Add Notes
 Bookmark this page
Initialization vs Instantiation in C#

When you assign a value to a variable when it is declared, it is called Initialization.
Here is an example −
int val = 50;

For array initialization, you may need a new keyword, whereas to initialize a variable, you do not need it.
When you create a new object in C# for a class using the new keyword, then it is called instantiation.
Use the new operator to instantiate a class in C#.
Here is an example showing two objects of Student class created using new keyword −
Student s1 = new Student();
Student s2 = new Student();
Check whether the String contains only digit characters in Java

The following is our string.
String str = "4434";
To check whether the above string has only digit characters, try the following if condition that uses matches() method and checks for every character.
if(str.matches("[0-9]+") && str.length() > 2) {
System.out.println("String contains only digits!");
}
 Live Demo
public class Demo {
   public static void main(String []args) {
      String str = "4434";
      if(str.matches("[0-9]+") && str.length() > 2) {
         System.out.println("String contains only digits!");
      }
   }
}
String contains only digits!
Let us see another example.
 Live Demo
public class Demo {
   public static void main(String []args) {
      String str = "5demo9";
      System.out.println("String: "+str);
      if(str.matches("[0-9]+") && str.length() > 2) {
         System.out.println("String contains only digits!");
      } else {
         System.out.println("String contains digits as well as other characters!");
      }
   }
}
String: 5demo9
String contains digits as well as other characters!
Formatted string literals (f-strings) in Python?

Python now provides new way to format strings, called f-strings. This features is available from Python 3.6 under PEP-498. They are so called (f-string) because of the letter ‘f’ prefix with a string. The letter ‘f’ also indicates that these f-strings can be used for formatting.
Below are some of the examples to demonstrates the use of f-strings.
name = 'Rajesh'
age = 13 * 3
fString = f'My name is {name} and my age is {age}'
print(fString)
#We can use Uppercase 'F' instead of lowercase 'f'.
print(F'My name is {name} and my age is {age}')
#As the fString valuation is done, giving another value to the variable will not change fstring value.
name = 'Zack'
age = 44
print(fString)
My name is Rajesh and my age is 39
My name is Rajesh and my age is 39
My name is Rajesh and my age is 39
from datetime import datetime
name = 'Rajesh'
age = 13 * 3
dt = datetime.now()
print(f' Age after ten years will be {age + 10}')
print(f'Name with quotes = {name!r}')
print(f'Default formatted Date = {dt}')
print(f'Modified Date format = {dt: %d/%m/%Y}')
Age after ten years will be 49
Name with quotes = 'Rajesh'
Default formatted Date = 2019-02-11 14:52:05.307841
Modified Date format = 11/02/2019
class Vehicle:
   Model = 0
   Brand = ''
def __init__(self, Model, Brand):
   self.Model = Model
   self.Brand = Brand
def __str__(self):
   return f'E[Model={self.Model}, Brand = {self.Brand}]'
Car = Vehicle (2018, 'Maruti')
print(Car)
print(f'Vehicle: {Car}\nModel is {Car.Model} and Brand is {Car.Brand}')
E[Model=2018, Brand = Maruti]
Vehicle: E[Model=2018, Brand = Maruti]
Model is 2018 and Brand is Maruti
We can call functions in f-strings formatting too.
def Multiply(x,y):
   return x*y
print( f'Multiply(40,20) = {Multiply(40,20)}')
Multiply(40,20) = 800
x = -40.9
print(f' Lambda absolute of (-40.9) is : {(lambda x: abs(x)) (x)}')
print(f' Lambda Square of 2^4 is: {(lambda x: pow(x, 2)) (4)}')
Lambda absolute of (-40.9) is : 40.9
Lambda Square of 24 is: 16