code-rag-bench/online-tutorials huggingface dataset:
How to change the text of a label using JavaScript ?

21 Jul, 2021
Given an HTML document and the task is to change the text of a label using JavaScript.
What is a label ?The <label>tag is used to provide a usability improvement for mouse users i.e, if a user clicks on the text within the <label> element, it toggles the control.
Approach:
Create a label element and assign an id to that element.
Define a button that is used to call a function. It acts as a switch to change the text in the label element.
Define a javaScript function, that will update the label text.
Use the innerHTML property to change the text inside the label. The innerHTML property sets or returns the HTML content of an element.
Example 1: This example implements the above approach.
<!DOCTYPE html><html>  <head>    <title>        How to change the text of        a label using JavaScript ?    </title></head>  <body style="text-align:center;">          <h1 style="color:green;">        GeeksforGeeks    </h1>      <h4>        Click on the button to change        the text of a label    </h4>      <label id = "GFG">        Welcome to GeeksforGeeks    </label>          <br>          <button onclick="myGeeks()">        Click Here!    </button>      <script>        function myGeeks() {            document.getElementById('GFG').innerHTML                = 'A computer science portal for geeks';        }    </script></body>  </html>      
Output:
Before Click on the Button:
After Click on the Button:
Example 2: This example changes the text of a label using JavaScript.
<!DOCTYPE html><html>  <head>    <title>        How to change the text of        a label using JavaScript ?    </title></head>  <body style="text-align:center;">          <h1 style="color:green;">        GeeksforGeeks    </h1>      <h4>        Click on the button to change        the text of a label    </h4>      <label id = "GFG">        Welcome to GeeksforGeeks    </label>          <br>          <button onclick="myGeeks()">        Click Here!    </button>      <script>        function myGeeks() {            var x = document.getElementById("GFG");                          if (x.innerHTML === "Welcome to GeeksforGeeks") {                x.innerHTML = "A computer science portal for geeks";            } else {                x.innerHTML = "Welcome to GeeksforGeeks";            }        }    </script></body>  </html>
Output:
Before Click on the Button:
After Click on the Button:
JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.
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.
Python program for multiplication and division of complex number

30 Jan, 2020
Given two complex numbers. The task is to multiply and divide them.
Multiplication of complex number: In Python complex numbers can be multiplied using * operator
Examples:
Input: 2+3i, 4+5i 
Output: Multiplication is : (-7+22j) 

Input: 2+3i, 1+2i
Output: Multiplication is : (-4+7j) 

# Python program to demonstrate# multiplication of complex numbers    def mulComplex( z1, z2):    return z1*z2         # driver codez1 = complex(2, 3)z2 = complex(4, 5)    print("Multiplication is :", mulComplex(z1,z2))
Output:
Multiplication is : (-7+22j)

Division of complex number: In Python, complex numbers can be divided using the / operator.
Examples:
Input: 2+3i, 4+5i
Output: Division  is : (0.5609756097560976+0.0487804878048781j)

Input: 2+3i, 1+2i
Output: Division is :(1.6-0.2j) 

# Python program to demonstrate# division of complex numbers    def divComplex( z1, z2):    return z1 / z2  # driver code  z1 = complex(2, 3)z2 = complex(4, 5)  print( "Division is :", (divComplex(z1, z2))
Output:
Division is : (0.5609756097560976+0.0487804878048781j)

python-utility
Technical Scripter 2019
Python Programs
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ColorMaps in Seaborn HeatMaps

25 Nov, 2020
Colormaps are used to visualize heatmaps effectively and easily. One might use different sorts of colormaps for different kinds of heatmaps. In this article, we will look at how to use colormaps while working with seaborn heatmaps.
Sequential Colormaps: We use sequential colormaps when the data values(numeric) goes from high to low and only one of them is important for the analysis. 
Example of sequential colormaps:
sns.palplot(sns.color_palette("Greens",12))

Sequential color palette
sns.palplot(sns.color_palette("Blues",12))

Sequential color palette
Note that we have used sns.color_palette() to construct a colormap and sns.palplot() to display the colors present in the colormap. The following example shows how to implement a sequential colormap on a seaborn heatmap.
Example:
Python3
import seaborn as snsimport numpy as np    np.random.seed(0)  # generates random valuesdata = np.random.rand(12, 12)  # creating a colormapcolormap = sns.color_palette("Greens")  # creating a heatmap using the colormapax = sns.heatmap(data, cmap=colormap)
Output:
Heatmap with a sequential colormap
Since “Greens” is an inbuilt colormap in seaborn, can also directly pass “Greens” to the cmap argument:
Python3
import seaborn as snsimport numpy as np    np.random.seed(0)  data = np.random.rand(12, 12)ax = sns.heatmap(data, cmap="Greens")
Output:
Heatmap with a sequential colormap
Note that our colormap now has a continuous color intensity unlike the one before which had a discrete intensity of green for a range of values. Here is a closer look at both of the colormaps generated in the above-mentioned heatmaps:
Discrete(left) and Continuous(right) Colormaps
Diverging Colormaps: They are used to represent numeric values that go from high to low(and vice-versa), and both high and low values are of interest.
Here are some diverging colormaps present in seaborn:
sns.palplot(sns.color_palette("PiYG", 12))

Diverging color palette
sns.palplot(sns.color_palette("coolwarm", 12))

Example: The following example shows how to implement a diverging colormap on a seaborn heatmap.
Python3
import seaborn as snsimport numpy as np    np.random.seed(0)  data = np.random.rand(12, 12)ax = sns.heatmap(data, cmap="PiYG")
Output:
Python-Seaborn
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Spam bot using PyAutoGUI

02 Feb, 2021
PyAutoGUI is a Python module that helps us automate the key presses and mouse clicks programmatically. In this article we will learn to develop a spam bot using PyAutoGUI.
Spamming – Refers to sending unsolicited messages to large number of systems over the internet. 
This mini-project can be used for many real-life applications like:
Remind your friends or relatives to do a particular task after every particular time interval
Can be used for advertisement purpose
In this article we will show the working of spam bot on telegram, but the code can also work for WhatsApp, Instagram etc. i.e. anywhere we find a text field it will work the same way.
Approach
Import module
Add delay of 2 second in the execution of the program
Create mechanism to generate text messages. typewrite() function of pyautogui helps to write the text and sleep function helps us specify the particular time interval (in seconds) after which the next instruction has to be executed. datetime.datetime.now() function helps the user keep a track of when the message was sent.
Syntax:
typewriter(“<message>”)
Execute code
Follow these simple steps to develop a spam bot using python:
Example:
Python3
import pyautogui, time, datetime  time.sleep(2)  while True:        # to display the time at which the message is sent     print(datetime.datetime.now())    pyautogui.typewrite("Reminder: Drink water!")     pyautogui.press("enter")    time.sleep(31)      print(datetime.datetime.now())      pyautogui.typewrite("Reminder: Take medicine!")    pyautogui.press("enter")    time.sleep(31)      print(datetime.datetime.now())      pyautogui.typewrite("Reminder: Take the dog for a walk!")    pyautogui.press("enter")    time.sleep(31)      print(datetime.datetime.now())      pyautogui.typewrite("Reminder: Drink water!")    pyautogui.press("enter")    time.sleep(31)      print(datetime.datetime.now())      pyautogui.typewrite("Reminder: Drink water!")    pyautogui.press("enter")    time.sleep(31)
Output:  
Date and time at which the message was sent 
Python-projects
Python-PyAutoGUI
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
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
Python | Get unique values from a list
Python | datetime.timedelta() function
PHP sizeof() Function

02 Dec, 2021
In this article, we will see how to get the length of the array using the sizeof() function in PHP. The sizeof() function is a built-in function in PHP and is used to count the number of elements present in an array or any other countable object.
Syntax:
int sizeof(array, mode);
Parameter: This function accepts 2 parameters which are described below:
array: This parameter represents the array containing elements that we need to count.
mode: This is an optional parameter and specifies the mode of the function. It can take two different values as shown below: 0: It is the default, does not count all elements of multidimensional arrays1: It Counts the array recursively (counts all the elements of multidimensional arrays)
0: It is the default, does not count all elements of multidimensional arrays
1: It Counts the array recursively (counts all the elements of multidimensional arrays)
Return Value: This function returns an integer value as shown in the syntax which represents the number of elements present in the array.
We will understand the concept of the sizeof() function through the examples.
Example 1: This example illustrates the count of the number of elements in the one-dimensional array.
PHP
<?php   // input array   $a=array(1,2,3,4,5,6);    // getting total number of elements   // present in the array.   $result = sizeof($a);    print($result);?>
Output:
6
Example: This example illustrates the counting the number of elements in the multi-dimensional array.
PHP
<?php  $array = array('name' => array('Geeks', 'For', 'Geeks'),                'article' => array('sizeof', 'function', 'PHP'));   // Recursive count  echo sizeof($array, 1);   // Normal count  echo sizeof($array);?>
Output:
8
2
Reference: http://php.net/manual/en/function.sizeof.php
shubham_singh
bhaskargeeksforgeeks
PHP-array
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to convert array to string in PHP ?
PHP | Converting string to Date and DateTime
Comparing two dates in PHP
How to receive JSON POST with PHP ?
How to get parameters from a URL string in PHP?
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
File Searching using Python

21 Feb, 2022
There may be many instances when you want to search a system.Suppose while writing an mp3 player you may want to have all the ‘.mp3’ files present. Well here’s how to do it in a simple way. This code searches all the folders in the file it’s being run. If you want some other kinds of files just change the extension. 
Python3
# Python code to search .mp3 files in current# folder (We can change file type/name and path# according to the requirements.import os # This is to get the directory that the program# is currently running in.dir_path = os.path.dirname(os.path.realpath(__file__)) for root, dirs, files in os.walk(dir_path):    for file in files:         # change the extension from '.mp3' to        # the one of your choice.        if file.endswith('.mp3'):            print (root+'/'+str(file))
os is not an external library in python. So I feel this is the simplest and the best way to do this.This article is contributed by soumith kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
avtarkumar719
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Python Program for Sum the digits of a given number

11 Aug, 2021
Given a number and the task is to find sum of digits of this number in Python. Examples:  
Input : n = 87 Output : 15 Input : n = 111 Output : 3
 Below are the methods to sum of the digits. Method-1: Using str() and int() methods.: The str() method is used to convert the number to string. The int() method is used to convert the string digit to an integer. 
Convert the number to string and iterate over each digit in the string and after converting each digit to integer and add to the sum of the digits in each iteration. 
Python3
# Python program to# compute sum of digits in # number.   # Function to get sum of digits def getSum(n):        sum = 0    for digit in str(n):       sum += int(digit)          return sum   n = 12345print(getSum(n))
Output:
15
Method-2: Using sum() methods.: The sum() method is used to sum of numbers in the list.
Convert the number to string using str() and strip the string and convert to list of number using strip() and map() method resp. Then find the sum using the sum() method.
Python3
# Python program to# compute sum of digits in # number.   # Function to get sum of digits def getSum(n):         strr = str(n)    list_of_number = list(map(int, strr.strip()))    return sum(list_of_number)   n = 12345print(getSum(n))
Output:
15
Method-3: Using General Approach: 
Get the number
Declare a variable to store the sum and set it to 0
Repeat the next two steps till the number is not 0
Get the rightmost digit of the number with help of remainder ‘%’ operator by dividing it with 10 and add it to sum.
Divide the number by 10 with help of ‘//’ operator
Print or return the sum
A. Iterative Approach:
Python3
# Python 3 program to# compute sum of digits in # number.   # Function to get sum of digits def getSum(n):        sum = 0    while (n != 0):               sum = sum + (n % 10)        n = n//10           return sum   n = 12345print(getSum(n))
Output:
15
B. Recursive Approach:
Python3
# Python program to compute# sum of digits in number.   def sumDigits(no):    return 0 if no == 0 else int(no % 10) + sumDigits(int(no / 10))    # Driver coden = 12345print(sumDigits(n))
Output:
15
sagar0719kumar
Picked
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python | Split string into list of characters
Touch module in Python

21 Apr, 2020
In Python, the Touch module is used to create any file on any specified directory. The touch module is equivalent to linux command ‘touch‘ or to the windows’ cmd command ‘ type null > ‘.
Installation:
This module does not come built-in with Python. To install this module type the below command in the terminal.
pip install touch
Example 1: In this example, we will create a file inside a same directory.
import touch  touch.touch("success.java")
Output:
Example 2: In this example, we will create a file in a different directory. Here we create a file in “testm” folder.
import touch  touch.touch("testm / success2.java")
Output:
Example 3: In this example, we will create a multiple files at the same time. For this, we need to pass the file name in a list.
import touch  touch.touch(["testm / success100.java", "success10.cpp"])
Output:
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What does the @ prefix do on string literals in C#?

The @prefix states hat you don't need to escape special characters in the string following to the symbol.
The following statement
@"D:\new"
is equal to:
"D:\\new"
The @ prefix is also used if you want to have large strings and want it to be displayed across multiple lines. The following is an example showing multi-line string −
 Live Demo
using System;

namespace Demo {

   class Program {

      static void Main(string[] args) {
         string str = @"Welcome User,
         Kindly wait for the image to
         load";

         Console.WriteLine(str);
      }
   }
}
Welcome User,
Kindly wait for the image to
load
Sqoop - List Tables

This chapter describes how to list out the tables of a particular database in MySQL database server using Sqoop. Sqoop list-tables tool parses and executes the ‘SHOW TABLES’ query against a particular database. Thereafter, it lists out the present tables in a database.
The following syntax is used for Sqoop list-tables command.
$ sqoop list-tables (generic-args) (list-tables-args) 
$ sqoop-list-tables (generic-args) (list-tables-args)
The following command is used to list all the tables in the userdb database of MySQL database server.
$ sqoop list-tables \
--connect jdbc:mysql://localhost/userdb \
--username root
If the command is executes successfully, then it will display the list of tables in the userdb database as follows.
...
13/05/31 16:45:58 INFO manager.MySQLManager: Preparing to use a MySQL streaming resultset.

emp
emp_add
emp_contact


    50 Lectures 
     4 hours 

 Navdeep Kaur
 Print
 Add Notes
 Bookmark this page
Hadoop – getmerge Command

29 Jun, 2020
Hadoop -getmerge command is used to merge multiple files in an HDFS(Hadoop Distributed File System) and then put it into one single output file in our local file system.
We want to merge the 2 files present inside are HDFS i.e. file1.txt and file2.txt, into a single file output.txt in our local file system.
Step 1: Let’s see the content of file1.txt and file2.txt that are available in our HDFS. You can see the content of File1.txt in the below image:
Content of File2.txt
In this case, we have copied both of these files inside my HDFS in Hadoop_File folder. If you don’t know how to make the directory and copy files to HDFS then follow below command to do so.
Making Hadoop_Files directory in our HDFShdfs dfs -mkdir /Hadoop_File
hdfs dfs -mkdir /Hadoop_File
Copying files to HDFShdfs dfs -copyFromLocal /home/dikshant/Documents/hadoop_file/file1.txt /home/dikshant/Documents/hadoop_file/file2.txt /Hadoop_File
hdfs dfs -copyFromLocal /home/dikshant/Documents/hadoop_file/file1.txt /home/dikshant/Documents/hadoop_file/file2.txt /Hadoop_File
Below is the Image showing this file inside my /Hadoop_File directory in HDFS.
Step 2: Now it’s time to use -getmerge command to merge these files into a single output file in our local file system for that follow the below procedure.
Syntax:
hdfs dfs -getmerge -nl /path1 /path2 ..../path n /destination
-nl is used for adding new line. this will add a new line between the content of these n files. In this case we have merge it to /hadoop_file folder inside my /Documents folder.
hdfs dfs -getmerge -nl /Hadoop_File/file1.txt /Hadoop_File/file2.txt /home/dikshant/Documents/hadoop_file/output.txt
Now let’s see whether the file get merged in output.txt file or not.
In the above image, you can easily see that the file is merged successfully in our output.txt file.
Hadoop
Hadoop
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Concept of Isolates in Dart

20 Jul, 2020
Dart was traditionally designed to create single-page applications. And we also know that most computers, even mobile platforms, have multi-core CPUs. To take advantage of all those cores, developers traditionally use shared-memory threads running concurrently. However, shared-state concurrency is error-prone and can lead to complicated code. Instead of threads, all Dart code runs inside of isolates. Each isolate has its own memory heap, ensuring that no isolate’s state is accessible from any other isolate.
The isolates and threads are different than each other as in threads memory are shared whereas in isolates it is not. Moreover isolates talk to each other via passing messages.
To use isolates you have to add import 'dart:isolate'; statement in your program code.

To create an isolate we make use of .spawn() method in Dart.
Syntax: Isolate isolate_name = await Isolate.spawn( parameter );

This parameter represents the port that will receive the message back.
To destroy the isolate we make use of .kill() method in Dart.
Syntax: isolate_name.kill( parameters );

We generally use spawn() and kill() together in a single program.
Example:  Creating an isolate in Dart.
Dart
// importing dart libraries  import 'dart:io';import 'dart:async';import 'dart:isolate';  // Creating geek isolateIsolate geek;  void start_geek_process() async {      // port for isolate to receive messages.  ReceivePort geekReceive= ReceivePort();    // Starting an isolate  geek = await Isolate.spawn(gfg, geekReceive.sendPort);}  void gfg(SendPort sendPort) {  int counter = 0;    // Printing Output message after every 2 sec.  Timer.periodic(new Duration(seconds: 2), (Timer t) {    // Increasing the counter    counter++;           //Printing the output message    stdout.writeln('Welcome to GeeksForGeeks $counter');    });}  void stop_geek_process() {      // Checking the isolate with null  if (geek != null) {      stdout.writeln('--------------Stopping Geek Isolate--------------');        // Killing the isolate      geek.kill(priority: Isolate.immediate);        // Setting the isolate to null      geek = null;          }  }  // Main Functionvoid main() async {  stdout.writeln('--------------Starting Geek Isolate--------------');    // Starting the isolate with start_geek_process  await start_geek_process();  stdout.writeln('Press enter key to quit');    // Whenever enter is hit the program is stopped  await stdin.first;    // Calling the stop_geek_process  stop_geek_process();    // Printing the goodbye message  stdout.writeln('GoodBye Geek!');    // Exiting the program.  exit(0);}
Output:
--------------Starting Geek Isolate--------------
Press enter key to quit
Welcome to GeeksForGeeks 1
Welcome to GeeksForGeeks 2
Welcome to GeeksForGeeks 3
Welcome to GeeksForGeeks 4
Welcome to GeeksForGeeks 5
Welcome to GeeksForGeeks 6
Welcome to GeeksForGeeks 7

--------------Stopping Geek Isolate--------------
GoodBye Geek!

Hitting enter after seventh output.
Dart-Exception-Handling
Dart
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What are Wild Pointers? How can we avoid?

01 Oct, 2018
Uninitialized pointers are known as wild pointers because they point to some arbitrary memory location and may cause a program to crash or behave badly.
int main(){  int *p;  /* wild pointer */   /* Some unknown memory location is being corrupted.    This should never be done. */   *p = 12; }
Please note that if a pointer p points to a known variable then it’s not a wild pointer. In the below program, p is a wild pointer till this points to a.
int main(){  int  *p; /* wild pointer */  int a = 10;  p = &a;  /* p is not a wild pointer now*/  *p = 12; /* This is fine. Value of a is changed */ }
If we want pointer to a value (or set of values) without having a variable for the value, we should explicitly allocate memory and put the value in allocated memory.
int main(){   int *p = (int *)malloc(sizeof(int));  *p = 12; /* This is fine (assuming malloc doesn't return NULL) */ }
guruvishnu_desireddy
pointer
Articles
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Add a key value pair to dictionary in Python

Python dictionaries are an unordered collection of key value pairs. In this tutorial we will see how we can add new key value pairs to an already defined dictionary. Below are the two approaches which we can use.
We add a new element to the dictionary by using a new key as a subscript and assigning it a value.
CountryCodeDict = {"India": 91, "UK" : 44 , "USA" : 1}
print(CountryCodeDict)
CountryCodeDict["Spain"]= 34
print "After adding"
print(CountryCodeDict)
Running the above code gives us the following result −
{'India': 91, 'USA': 1, 'UK': 44}
After adding
{'Spain': 34, 'India': 91, 'USA': 1, 'UK': 44}
The update method directly takes a key-value pair and puts it into the existing dictionary. The key value pair is the argument to the update function. We can also supply multiple key values as shown below.
CountryCodeDict = {"India": 91, "UK" : 44 , "USA" : 1, "Spain" : 34}
print(CountryCodeDict)

CountryCodeDict.update( {'Germany' : 49} )

print(CountryCodeDict)

# Adding multiple key value pairs
CountryCodeDict.update( [('Austria', 43),('Russia',7)] )

print(CountryCodeDict)
Running the above code gives us the following result −
{'Spain': 34, 'India': 91, 'USA': 1, 'UK': 44}
{'Germany': 49, 'Spain': 34, 'India': 91, 'USA': 1, 'UK': 44}
{'USA': 1, 'India': 91, 'Austria': 43, 'Germany': 49, 'UK': 44, 'Russia': 7, 'Spain': 34}
We can also append elements to a dictionary by merging two dictionaries. Here again, we use the update() method but the argument to the method is a dictionary itself.
CountryCodeDict1 = {"India": 91, "UK" : 44 , "USA" : 1, "Spain" : 34}
CountryCodeDict2 = {"Germany": 49, "Russia" : 7 , "Austria" : 43}
CountryCodeDict1.update(CountryCodeDict2)
print(CountryCodeDict1)
Running the above code gives us the following result −
{'Austria': 43, 'Germany': 49, 'UK': 44, 'USA': 1, 'India': 91, 'Russia': 7, 'Spain': 34}
MongoDB - Sort Records

In this chapter, we will learn how to sort records in MongoDB.
To sort documents in MongoDB, you need to use sort() method. The method accepts a document containing a list of fields along with their sorting order. To specify sorting order 1 and -1 are used. 1 is used for ascending order while -1 is used for descending order.
The basic syntax of sort() method is as follows −
>db.COLLECTION_NAME.find().sort({KEY:1})
Consider the collection myycol has the following data.
{_id : ObjectId("507f191e810c19729de860e1"), title: "MongoDB Overview"}
{_id : ObjectId("507f191e810c19729de860e2"), title: "NoSQL Overview"}
{_id : ObjectId("507f191e810c19729de860e3"), title: "Tutorials Point Overview"}
Following example will display the documents sorted by title in the descending order.
>db.mycol.find({},{"title":1,_id:0}).sort({"title":-1})
{"title":"Tutorials Point Overview"}
{"title":"NoSQL Overview"}
{"title":"MongoDB Overview"}
>
Please note, if you don't specify the sorting preference, then sort() method will display the documents in ascending order.

    44 Lectures 
     3 hours 

 Arnab Chakraborty

    54 Lectures 
     5.5 hours 

 Eduonix Learning Solutions

    44 Lectures 
     4.5 hours 

 Kaushik Roy Chowdhury

    40 Lectures 
     2.5 hours 

 University Code

    26 Lectures 
     8 hours 

 Bassir Jafarzadeh

    70 Lectures 
     2.5 hours 

 Skillbakerystudios
 Print
 Add Notes
 Bookmark this page
How to sort, select and query subdocument in MongoDB?

To sort, use $sort in MongoDB. Let us create a collection with documents −
> db.demo236.insertOne({"details":{"Name":"Chris","Age":21}});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e419015f4cebbeaebec514c")
}
> db.demo236.insertOne({"details":{"Name":"David","Age":23}});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e41901cf4cebbeaebec514d")
}
> db.demo236.insertOne({"details":{"Name":"Bob","Age":24}});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e419023f4cebbeaebec514e")
}
Display all documents from a collection with the help of find() method −
> db.demo236.find();
This will produce the following output −
{ "_id" : ObjectId("5e419015f4cebbeaebec514c"), "details" : { "Name" : "Chris", "Age" : 21 } }
{ "_id" : ObjectId("5e41901cf4cebbeaebec514d"), "details" : { "Name" : "David", "Age" : 23 } }
{ "_id" : ObjectId("5e419023f4cebbeaebec514e"), "details" : { "Name" : "Bob", "Age" : 24 } }
Following is the query to sort, select and query subdocument in MongoDB −
>  db.demo236.aggregate(
...   [
...      { $unwind: "$details" },
...      { $project: {
...         Name: '$details.Name',
...         Age: '$details.Age'
...
...      }},
...   { $sort: {Name: -1}}
...]
...);
This will produce the following output −
{ "_id" : ObjectId("5e41901cf4cebbeaebec514d"), "Name" : "David", "Age" : 23 }
{ "_id" : ObjectId("5e419015f4cebbeaebec514c"), "Name" : "Chris", "Age" : 21 }
{ "_id" : ObjectId("5e419023f4cebbeaebec514e"), "Name" : "Bob", "Age" : 24 }
DateTimeOffset.ToOffset() Method in C#

The DateTimeOffset.ToOffset() method in C# is used to convert the value of the current DateTimeOffset object to the date and time specified by an offset value.
Following is the syntax −
public DateTimeOffset ToOffset (TimeSpan val);
Above, the value is the offset to convert the DateTimeOffset value to.
Let us now see an example to implement the DateTimeOffset.ToOffset() method −
using System;
public class Demo {
   public static void Main() {
      DateTimeOffset dateTimeOffset = new DateTimeOffset(2019, 9, 10, 4, 20, 30, new TimeSpan(-5, 0, 0));
      Console.WriteLine("DateTimeOffset = {0}", dateTimeOffset);
      DateTimeOffset res = dateTimeOffset.ToOffset(new TimeSpan(-10, 1, 0));
      Console.WriteLine("DateTimeOffset (updated) = {0}", res);
   }
}
This will produce the following output −
DateTimeOffset = 9/10/2019 4:20:30 AM -05:00
DateTimeOffset (updated) = 9/9/2019 11:21:30 PM -09:59
Let us now see another example to implement the DateTimeOffset.ToOffset() method −
using System;
public class Demo {
   public static void Main() {
      DateTimeOffset dateTimeOffset = new DateTimeOffset(2019, 9, 10, 4, 20, 30, new TimeSpan(5, 0, 0));
      Console.WriteLine("DateTimeOffset = {0}", dateTimeOffset);
      DateTimeOffset res = dateTimeOffset.ToOffset(new TimeSpan(3, 1, 0));
      Console.WriteLine("DateTimeOffset (updated) = {0}", res);
   }
}
This will produce the following output −
DateTimeOffset = 9/10/2019 4:20:30 AM +05:00
DateTimeOffset (updated) = 9/10/2019 2:21:30 AM +03:01
How to set encoding in PHP FPDI library?

Below is the same code to set encoding for FPDI library−
Add new fonts that have the correct alphabets.
$pdf->AddFont('DejaVu','','DejaVuSansCondensed.php');
$pdf->SetFont('DejaVu', '', 10, '', false);
The following are three possible encodings that are possible.
cp1250 (Central Europe)
cp1251 (Cyrillic)
cp1252 (Western Europe)
cp1253 (Greek)
cp1254 (Turkish)
cp1255 (Hebrew)
cp1257 (Baltic)
cp1258 (Vietnamese)
cp874 (Thai)
or
ISO-8859-1 (Western Europe)
ISO-8859-2 (Central Europe)
ISO-8859-4 (Baltic)
ISO-8859-5 (Cyrillic)
ISO-8859-7 (Greek)
ISO-8859-9 (Turkish)
ISO-8859-11 (Thai)
ISO-8859-15 (Western Europe)
ISO-8859-16 (Central Europe)
Or
KOI8-R (Russian)
KOI8-U (Ukrainian)
Let us see an example to convert the UTF-8 to cp1250.
$str = iconv('UTF-8', 'cp1250', 'zazółcić gęślą jaźń');
Note− If the string sent by the user to the PDF is in UTF-8 encoding, it needs to be converted to cp1250.
C# | Math.Tan() Method - GeeksforGeeks

31 Jan, 2019
Math.Tan() is an inbuilt Math class method which returns the tangent of a given double value argument(specified angle).
Syntax:
public static double Tan(double num)
Parameter:
num: It is the angle(measured in radian) whose tangent is to be returned and the type of this parameter is System.Double.
Return Value: Returns the tangent of num of type System.Double. If num is equal to NegativeInfinity, PositiveInfinity, or NaN, then this method returns NaN.
Below are the programs to illustrate the Math.Tan() method.
Program 1: To show the working of Math.Tan() method.
// C# program to demonstrate working// Math.Tan() methodusing System;   class Geeks {       // Main Method    public static void Main(String []args)    {        double a = 12;                   // converting value to radians        double b = (a * (Math.PI)) / 180;           // using method and displaying result        Console.WriteLine(Math.Tan(b));        a = 63;                   // converting value to radians        b = (a * (Math.PI)) / 180;           // using method and displaying result        Console.WriteLine(Math.Tan(b));        a = 187;                   // converting value to radians        b = (a * (Math.PI)) / 180;          // using method and displaying result        Console.WriteLine(Math.Tan(b));        a = 45;                   // converting value to radians        b = (a * (Math.PI)) / 180;           // using method and displaying result        Console.WriteLine(Math.Tan(b));    }}
0.212556561670022
1.96261050550515
0.122784560902905
1

 Program 2: To show the working of Math.Tan() method when the argument is NaN or infinity.
// C# program to demonstrate working// Math.Tan() method in infinity caseusing System;  class Geeks {          // Main Method    public static void Main(String []args)    {          double positiveInfinity = Double.PositiveInfinity;                         double negativeInfinity = Double.NegativeInfinity;                                          double nan = Double.NaN;        double result;          // Here argument is negative infinity,        // output will be NaN         result = Math.Tan(negativeInfinity);         Console.WriteLine(result);          // Here argument is positive infinity,        // output will also be NaN        result = Math.Tan(positiveInfinity);        Console.WriteLine(result);          // Here argument is NaN, output will be NaN        result = Math.Tan(nan);        Console.WriteLine(result);    }}
NaN
NaN
NaN

CSharp-Math
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Extension Method in C#
Top 50 C# Interview Questions & Answers
Partial Classes in C#
HashSet in C# with Examples
C# | Inheritance
C# | How to insert an element in an Array?
C# | List Class
Lambda Expressions in C#
C# | Generics - Introduction
What is Regular Expression in C#?
Python Number min() Method

Python number  method min() returns the smallest of its arguments: the value closest to negative infinity.
Following is the syntax for min() method −
min( x, y, z, .... )

x − This is a numeric expression.
x − This is a numeric expression.
y − This is also a numeric expression.
y − This is also a numeric expression.
z − This is also a numeric expression.
z − This is also a numeric expression.
This method returns smallest of its arguments.
The following example shows the usage of min() method.
#!/usr/bin/python

print "min(80, 100, 1000) : ", min(80, 100, 1000)
print "min(-20, 100, 400) : ", min(-20, 100, 400)
print "min(-80, -20, -10) : ", min(-80, -20, -10)
print "min(0, 100, -400) : ", min(0, 100, -400)
When we run above program, it produces following result −
min(80, 100, 1000) :  80
min(-20, 100, 400) :  -20
min(-80, -20, -10) :  -80
min(0, 100, -400) :  -400


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
How we can update a Python tuple element value?

Python tuple is an immutable object. Hence any operation that tries to update it is not allowed. However, following workaround can be used.
First, convert tuple to list by built-in function list(). You can always update an item to list object assigning new value to element at certain index. Then use another built-in function tuple() to convert this list object back to tuple.
>>> T1=(10,50,20,9,40,25,60,30,1,56)
>>> L1=list(T1)
>>> L1[5]=100
>>> T1=tuple(L1)
>>> T1
(10, 50, 20, 9, 40, 100, 60, 30, 1, 56)
Element at index 4 in original tuple has been changed from 25 to 100.
Java Program to Swap two Variables

08 Jun, 2021
Given two numbers x and y, we need to swap their valuesExamples:  
Input : x = 10, y = 20;
Output : x = 20, y = 10

Input : x = 200, y = 100
Output : x = 100, y = 200
 
 
Below are the simple steps we follow: 1) Assign x to a temp variable : temp = x 2) Assign y to x : x = y 3) Assign temp to y : y = tempLet us understand with an example. 
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
x = 100, y = 200After line 1: temp = x temp = 100After line 2: x = y x = 200After line 3 : y = temp y = 100
 
Java
// Java program to swap two variablespublic class GfG {     public static void main(String[] args)    {         int x = 100, y = 200;         System.out.println("Before Swap");        System.out.println("x = " + x);        System.out.println("y = " + y);         int temp = x;        x = y;        y = temp;         System.out.println("After swap");        System.out.println("x = " + x);        System.out.println("y = " + y);    }}
Before Swap
x = 100
y = 200
After swap
x = 200
y = 100
 
How to swap two numbers without using a temporary variable?
How to swap or exchange objects in Java?
Swap two variables in one line in C/C++, Python, PHP and Java
simranarora5sos
Swap-Program
Java Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between semantic and non-semantic elements

11 Sep, 2020
Semantic HTML elements:These elements simply mean, elements with meaning. The reason being, there definition in the code tells the browser and the developer what they are supposed to do. Framing in simpler words, these elements describe the type of content they are supposed to contain.
Following is the list of some semantic elements :
article
aside
details
figcaption
figure
footer
form
header
main
mark
nav
table
section
Example: The following program contains some semantic elements to explain the context better:
<!DOCTYPE html><html><head>    <title>my web page</title>    <style type="text/css">        h1{            color: green;            font-weight: bold;        }        table, tr, td{            border: 1px solid black;        }        th{            font-weight: bold;            color: red;        }    </style></head><body>     <article>          <h1>GeeksforGeeks</h1>          <p>A Computer Science Portal for Geeks</p>       </article>       <table>          <tr>              <th>head1</th>              <th>head2</th>          </tr>          <tr>              <td>A</td>              <td>0</td>          </tr>          <tr>              <td>B</td>              <td>1</td>          </tr>      </table></body></html>
Output:
Non-Semantic elements: Unlike, semantic elements they don’t have any meaning. They don’t tell anything about the content they contain. They can be used with different attributes to mark up semantics common to a group.
Following is the list of some non-semantic elements:
div
span
Example:The following code depicts how non-semantic elements work:
<!DOCTYPE html><html><head>    <title>my web page</title>    <style type="text/css">     span{         color: green;         font-size: 40px ;         font-weight: bold;              }    </style></head><body>    <div>        <span>GeeksForGeeks</span> <br>        A computer science portal for geeks    </div></body></html>
Output:
Difference between semantic and non-semantic elements:
HTML-Basics
HTML-Misc
Picked
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
REST API (Introduction)
Hide or show elements in HTML using display property
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Make HTML5 Canvas fill the whole page

To make canvas fill the whole page, you need to be 100% in width and height of the page.
* {
   margin: 0;
   padding: 0;
}
body, html {
   height:100%;
}
#canvas {
   position:absolute;
   height:100%; width:100%;
}
Updating Data into MySQL Database

Data can be updated into MySQL tables by executing SQL UPDATE statement through PHP function mysql_query.
Below is a simple example to update records into employee table. To update a record in any table it is required to locate that record by using a conditional clause. Below example uses primary key to match a record in employee table.
Try out following example to understand update operation. You need to provide an employee ID to update an employee salary.
<html>
   
   <head>
      <title>Update a Record in MySQL Database</title>
   </head>
   
   <body>
      <?php
         if(isset($_POST['update'])) {
            $dbhost = 'localhost:3036';
            $dbuser = 'root';
            $dbpass = 'rootpassword';
            
            $conn = mysql_connect($dbhost, $dbuser, $dbpass);
            
            if(! $conn ) {
               die('Could not connect: ' . mysql_error());
            }
            
            $emp_id = $_POST['emp_id'];
            $emp_salary = $_POST['emp_salary'];
            
            $sql = "UPDATE employee ". "SET emp_salary = $emp_salary ". 
               "WHERE emp_id = $emp_id" ;
            mysql_select_db('test_db');
            $retval = mysql_query( $sql, $conn );
            
            if(! $retval ) {
               die('Could not update data: ' . mysql_error());
            }
            echo "Updated data successfully\n";
            
            mysql_close($conn);
         }else {
            ?>
               <form method = "post" action = "<?php $_PHP_SELF ?>">
                  <table width = "400" border =" 0" cellspacing = "1" 
                     cellpadding = "2">
                  
                     <tr>
                        <td width = "100">Employee ID</td>
                        <td><input name = "emp_id" type = "text" 
                           id = "emp_id"></td>
                     </tr>
                  
                     <tr>
                        <td width = "100">Employee Salary</td>
                        <td><input name = "emp_salary" type = "text" 
                           id = "emp_salary"></td>
                     </tr>
                  
                     <tr>
                        <td width = "100"> </td>
                        <td> </td>
                     </tr>
                  
                     <tr>
                        <td width = "100"> </td>
                        <td>
                           <input name = "update" type = "submit" 
                              id = "update" value = "Update">
                        </td>
                     </tr>
                  
                  </table>
               </form>
            <?php
         }
      ?>
      
   </body>
</html>

    45 Lectures 
     9 hours 

 Malhar Lathkar

    34 Lectures 
     4 hours 

 Syed Raza

    84 Lectures 
     5.5 hours 

 Frahaan Hussain

    17 Lectures 
     1 hours 

 Nivedita Jain

    100 Lectures 
     34 hours 

 Azaz Patel

    43 Lectures 
     5.5 hours 

 Vijay Kumar Parvatha Reddy
 Print
 Add Notes
 Bookmark this page
MongoDB - $pop Operator - GeeksforGeeks

10 May, 2020
MongoDB provides different types of array update operators to update the values of the array fields in the documents and $pop operator is one of them. This operator is used to remove the first or the last item from the array.
Syntax:
{ $pop: { <field>: <-1 | 1>, ... } }
Here, <field> can specify with dot notation in embedded/nested documents or an array.
If you pass -1 value in $pop operator, then it will remove the first item from the array.
If you pass 1 value in $pop operator, then it will remove the last item from the array.
If the <field> is not an array, then this operator will fail.
If $pop operator will remove the last item from the specified field, then the field holds an empty array.
You can use this operator with methods like update(), findAndModify(), etc., according to your requirement.
In the following examples, we are working with:
Database: GeeksforGeeksCollection: contributorDocument: two documents that contain the details of the contributor in the form of field-value pairs.
In this example, we are removing the first element of the language field in the document that matches the specified condition, i.e., name: “Rohit”, by setting the value of $pop operator to -1.
db.contributor.update({name: "Rohit"}, {$pop: { language: -1}})
In this example, we are removing the last element of the language field in the document that matches the specified condition, i.e., name: “Sumit”, by setting the value of $pop operator to 1.
db.contributor.update({name: "Sumit"}, {$pop: {language: 1}})
In this example, we are removing the last element of the personal.semesterMarks field in the nested document by setting the value of $pop operator to -1.
db.contributor.update({name: "Sumit"},                       {$pop: {"personal.semesterMarks": -1}})
MongoDB
MongoDB-operators
MongoDB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
MongoDB - Distinct() Method
How to connect MongoDB with ReactJS ?
MongoDB - limit() Method
MongoDB - FindOne() Method
MongoDB insertMany() Method - db.Collection.insertMany()
MongoDB updateOne() Method - db.Collection.updateOne()
MongoDB - Update() Method
Create user and add role in MongoDB
MongoDB - sort() Method