code-rag-bench/online-tutorials huggingface dataset:
C# - Nested if Statements

It is always legal in C# to nest if-else statements, which means you can use one if or else if statement inside another if or else if statement(s).
The syntax for a nested if statement is as follows −
if( boolean_expression 1) {
   /* Executes when the boolean expression 1 is true */
   if(boolean_expression 2) {
      /* Executes when the boolean expression 2 is true */
   }
}

You can nest else if...else in the similar way as you have nested if statement.
using System;

namespace DecisionMaking {
   class Program {
      static void Main(string[] args) {
         //* local variable definition */
         int a = 100;
         int b = 200;
         
         /* check the boolean condition */
         if (a == 100) {
            
            /* if condition is true then check the following */
            if (b == 200) {
               /* if condition is true then print the following */
               Console.WriteLine("Value of a is 100 and b is 200");
            }
         }
         Console.WriteLine("Exact value of a is : {0}", a);
         Console.WriteLine("Exact value of b is : {0}", b);
         Console.ReadLine();
      }
   }
}
When the above code is compiled and executed, it produces the following result −
Value of a is 100 and b is 200
Exact value of a is : 100
Exact value of b is : 200


    119 Lectures 
     23.5 hours 

 Raja Biswas

    37 Lectures 
     13 hours 

 Trevoir Williams

    16 Lectures 
     1 hours 

 Peter Jepson

    159 Lectures 
     21.5 hours 

 Ebenezer Ogbu

    193 Lectures 
     17 hours 

 Arnold Higuit

    24 Lectures 
     2.5 hours 

 Eric Frick
 Print
 Add Notes
 Bookmark this page
How to create hidden comments in HTML?

To create hidden comments in HTML, add <!--- tag and end it with -- >. Whatever comes inside it is hidden. These comments are beneficial for those who need to refer the code again, which allow them to easily understand the code.
Comments can be considered as a note to yourself, which also hides HTML code, so the browser doesn't display it.
You can try to run the following code to learn about hidden comments in HTML
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>HTML Comments</title>
</head>
<body>
   <!-- This is a comment. -->
   <p>
      <!-- This is a comment. -->
      This is demo text.
   </p>
</body>
</html>
C program to delete a file

In programming, working with files is very important and every programming language has its own set of functions or library that help in manipulation of files.
In C Programming Language also there is a function remove which can be used by the programmer to delete a file.
The remove function is used to delete the file whose name is specified. This function is in the stdio header file.
remove (“file_name”);
The function accepts one parameter which is the name of the file that is to be deleted.
File name can also be the path to the file but only if the system supports it.
It returns zero, if the deletion operation is successfully completed. otherwise a non zero return on failure.
#include<stdio.h>
int main() {
   int del = remove("textFile.txt");
   if (!del)
      printf("The file is Deleted successfully");
   else
      printf("the file is not Deleted");
   return 0;
}
The file is Deleted successfully
Tryit Editor v3.7

Tryit: Different HSL colors
How to exit from Python using a Tkinter Button?

To exit from Python using a Tkinter button, you can follow the steps given below −
Import the tkinter library and create an instance of tkinter frame.
Import the tkinter library and create an instance of tkinter frame.
Set the size of the frame using geometry method.
Set the size of the frame using geometry method.
Define a function close() to close the window. Call the method win.destroy() inside close().
Define a function close() to close the window. Call the method win.destroy() inside close().
Next, create a button and call the close() function.
Next, create a button and call the close() function.
Finally, run the mainloop of the application window.
Finally, run the mainloop of the application window.
# Import the library
from tkinter import *

# Create an instance of window
win = Tk()

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

# Title of the window
win.title("Click the Button to Close the Window")

# Define a function to close the window
def close():
   #win.destroy()
   win.quit()

# Create a Button to call close()
Button(win, text= "Close the Window", font=("Calibri",14,"bold"), command=close).pack(pady=20)

win.mainloop()
On execution, it will produce the following output −
On clicking the button, it will close the window.
Instead of win.destroy(), you can also use win.quit() to close the application. However, there is a subtle difference between the two. win.quit() abruptly quits the application which means the mainloop will still be running in the background. win.destroy() on the other hand terminates the mainloop and destroys all the widgets inside the window.
NumPy - Determinant

Determinant is a very useful value in linear algebra. It calculated from the diagonal elements of a square matrix. For a 2x2 matrix, it is simply the subtraction of the product of the top left and bottom right element from the product of other two.
In other words, for a matrix [[a,b], [c,d]], the determinant is computed as ‘ad-bc’. The larger square matrices are considered to be a combination of 2x2 matrices.
The numpy.linalg.det() function calculates the determinant of the input matrix.
import numpy as np
a = np.array([[1,2], [3,4]]) 
print np.linalg.det(a)
It will produce the following output −
-2.0

import numpy as np 

b = np.array([[6,1,1], [4, -2, 5], [2,8,7]]) 
print b 
print np.linalg.det(b) 
print 6*(-2*7 - 5*8) - 1*(4*7 - 5*2) + 1*(4*8 - -2*2)
It will produce the following output −
[[ 6 1 1]
 [ 4 -2 5]
 [ 2 8 7]]

-306.0

-306


    63 Lectures 
     6 hours 

 Abhilash Nelson

    19 Lectures 
     8 hours 

 DATAhill Solutions Srinivas Reddy

    12 Lectures 
     3 hours 

 DATAhill Solutions Srinivas Reddy

    10 Lectures 
     2.5 hours 

 Akbar Khan

    20 Lectures 
     2 hours 

 Pruthviraja L

    63 Lectures 
     6 hours 

 Anmol
 Print
 Add Notes
 Bookmark this page
jQuery | :button Selector - GeeksforGeeks

26 Feb, 2019
The jQuery :button selector selects button elements and input elements with type=”button”. The button element is not selected if we use input=” button” as a selector.
Syntax:
$(":button")
Example-1:
<!DOCTYPE html><html>  <head>    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">  </script>     <script>        $(document).ready(function() {            $(":button").css(              "background-color", "lightgreen");        });    </script></head>  <body>      <center>        <form action="">            Name:            <input type="text"                    name="user">            <br> Password:            <input type="password"                    name="password">            <br>            <button type="button">              Button          </button>            <br>            <input type="reset"                    value="Reset">            <input type="submit"                   value="Submit">            <br>        </form>    </center>  </body>  </html>
Output:
Example-2:
<!DOCTYPE html><html>  <head>    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js">  </script>  </head>  <body>    <input type="button"            value="Test" />    <br>    <input id="txtName"            type="text" />    <input type="submit"            value="Test" />    <br>      <button id="button1">      This is a button  </button>    <br>      <script>        $(function() {            $(":button").css(            "border", "10px dashed green");        });    </script></body>  </html>
Output:
jQuery-Selectors
Picked
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Scroll to the top of the page using JavaScript/jQuery
jQuery | children() with Examples
How to check whether a checkbox is checked in jQuery?
How to reset a form using jQuery with .reset() method?
How to prevent Body from scrolling when a modal is opened using jQuery ?
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?
Tryit Editor v3.6 - Show C++

using namespace std;
​
int main() {
  string fullName;
  cout << "Type your full name: ";
  getline (cin, fullName);
  cout << "Your name is: " << fullName;
AWK - Arithmetic Functions

AWK has the following built-in arithmetic functions −
It returns the arctangent of (y/x) in radians. The following example demonstrates this −
[jerry]$ awk 'BEGIN {
   PI = 3.14159265
   x = -10
   y = 10
   result = atan2 (y,x) * 180 / PI;
   
   printf "The arc tangent for (x=%f, y=%f) is %f degrees\n", x, y, result
}'
On executing this code, you get the following result −
The arc tangent for (x=-10.000000, y=10.000000) is 135.000000 degrees

This function returns the cosine of expr, which is expressed in radians. The following example demonstrates this −
[jerry]$ awk 'BEGIN {
   PI = 3.14159265
   param = 60
   result = cos(param * PI / 180.0);

   printf "The cosine of %f degrees is %f.\n", param, result
}'
On executing this code, you get the following result −
The cosine of 60.000000 degrees is 0.500000.

This function is used to find the exponential value of a variable.
[jerry]$ awk 'BEGIN {
   param = 5
   result = exp(param);
   
   printf "The exponential value of %f is %f.\n", param, result
}'
On executing this code, you get the following result −
The exponential value of 5.000000 is 148.413159.

This function truncates the expr to an integer value. The following example demonstrates this −
[jerry]$ awk 'BEGIN {
   param = 5.12345
   result = int(param)
   
   print "Truncated value =", result
}'
On executing this code, you get the following result −
Truncated value = 5

This function calculates the natural logarithm of a variable.
[jerry]$ awk 'BEGIN {
   param = 5.5
   result = log (param)
   
   printf "log(%f) = %f\n", param, result
}'
On executing this code, you get the following result −
log(5.500000) = 1.704748

This function returns a random number N, between 0 and 1, such that 0 <= N < 1. For instance, the following example generates three random numbers
[jerry]$ awk 'BEGIN {
   print "Random num1 =" , rand()
   print "Random num2 =" , rand()
   print "Random num3 =" , rand()
}'
On executing this code, you get the following result −
Random num1 = 0.237788
Random num2 = 0.291066
Random num3 = 0.845814

This function returns the sine of expr, which is expressed in radians. The following example demonstrates this −
[jerry]$ awk 'BEGIN {
   PI = 3.14159265
   param = 30.0
   result = sin(param * PI /180)

   printf "The sine of %f degrees is %f.\n", param, result
}'
On executing this code, you get the following result −
The sine of 30.000000 degrees is 0.500000.

This function returns the square root of expr.
[jerry]$ awk 'BEGIN {
   param = 1024.0
   result = sqrt(param)
   
   printf "sqrt(%f) = %f\n", param, result
}'
On executing this code, you get the following result −
sqrt(1024.000000) = 32.000000

This function generates a random number using seed value. It uses expr as the new seed for the random number generator. In the absence of expr, it uses the time of day as the seed value.
[jerry]$ awk 'BEGIN {
   param = 10
   
   printf "srand() = %d\n", srand()
   printf "srand(%d) = %d\n", param, srand(param)
}'
On executing this code, you get the following result−
srand() = 1
srand(10) = 1417959587

 Print
 Add Notes
 Bookmark this page
mktemp - Unix, Linux Command

The trailing ‘Xs’ are replaced with a combination
of the current process number and random letters.
The name chosen depends both on the number of ‘Xs’ in the
template and the number of collisions with pre-existing files.
The number of unique filenames
mktemp can return depends on the number of
‘Xs’ provided; ten ‘Xs’ will result in
mktemp testing roughly 26 ** 10 combinations.


If
mktemp can successfully generate a unique filename, the file (or directory)
is created with file permissions such that it is only readable and writable
by its owner (unless the
-u flag is given) and the filename is printed to standard output.


mktemp is provided to allow shell scripts to safely use temporary
files.  Traditionally, many shell scripts take the name of the program with
the PID as a suffix and use that as a temporary filename.
This kind of naming scheme is predictable and the race condition it creates
is easy for an attacker to win.
A safer, though still inferior approach
is to make a temporary directory using the same naming scheme.
While this does allow one to guarantee that a temporary file will not be
subverted, it still allows a simple denial of service attack.
For these reasons it is suggested that
mktemp be used instead.


The options are as follows:


TMPFILE=‘mktemp /tmp/example.XXXXXXXXXX‘ || exit 1
echo "program output" >> $TMPFILE



TMPFILE=‘mktemp /tmp/example.XXXXXXXXXX‘ || exit 1
echo "program output" >> $TMPFILE




TMPFILE=‘mktemp -t example.XXXXXXXXXX‘ || exit 1
echo "program output" >> $TMPFILE



TMPFILE=‘mktemp -t example.XXXXXXXXXX‘ || exit 1
echo "program output" >> $TMPFILE




TMPFILE=‘mktemp‘ || exit 1
echo "program output" >> $TMPFILE



TMPFILE=‘mktemp‘ || exit 1
echo "program output" >> $TMPFILE




TMPFILE=‘mktemp -p /extra/tmp example.XXXXXXXXXX‘ || exit 1
echo "program output" >> $TMPFILE



TMPFILE=‘mktemp -p /extra/tmp example.XXXXXXXXXX‘ || exit 1
echo "program output" >> $TMPFILE




TMP1=‘mktemp -t example.1.XXXXXXXXXX‘ || exit 1
TMP2=‘mktemp -t example.2.XXXXXXXXXX‘
if [ $? -ne 0 ]; then
        rm -f $TMP1
        exit 1
fi



TMP1=‘mktemp -t example.1.XXXXXXXXXX‘ || exit 1
TMP2=‘mktemp -t example.2.XXXXXXXXXX‘
if [ $? -ne 0 ]; then
        rm -f $TMP1
        exit 1
fi




TMPFILE=‘mktemp -t example.XXXXXXXXXX‘ && {
        # Safe to use $TMPFILE in this block
        echo data > $TMPFILE
        ...
        rm -f $TMPFILE
}



TMPFILE=‘mktemp -t example.XXXXXXXXXX‘ && {
        # Safe to use $TMPFILE in this block
        echo data > $TMPFILE
        ...
        rm -f $TMPFILE
}




Advertisements


    129 Lectures 
     23 hours 

 Eduonix Learning Solutions

    5 Lectures 
     4.5 hours 

 Frahaan Hussain

    35 Lectures 
     2 hours 

 Pradeep D

    41 Lectures 
     2.5 hours 

 Musab Zayadneh

    46 Lectures 
     4 hours 

 GUHARAJANM

    6 Lectures 
     4 hours 

 Uplatz
 Print
 Add Notes
 Bookmark this page
Ruby | Encapsulation - GeeksforGeeks

01 Jan, 2019
Encapsulation is defined as the wrapping up of data under a single unit. It is the mechanism that binds together code and the data it manipulates. In a different way, encapsulation is a protective shield that prevents the data from being accessed by the code outside this shield.
Technically in encapsulation, the variables or data of a class are hidden from any other class and can be accessed only through any member function of own class in which they are declared.
Encapsulation can be achieved by declaring all the variables in the class as private and writing public methods in the class to set and get the values of variables.
Example:
# Ruby program to illustrate encapsulation#!/usr/bin/ruby     class Demoencapsulation         def initialize(id, name, addr)           # Instance Variables       @cust_id = id  @cust_name = name  @cust_addr = addr  end      # displaying result  def display_details()  puts "Customer id: #@cust_id" puts "Customer name: #@cust_name" puts "Customer address: #@cust_addr" endend    # Create Objects cust1 = Demoencapsulation .new("1", "Mike",               "Wisdom Apartments, Ludhiya")   cust2 = Demoencapsulation .new("2", "Jackey",                 "New Empire road, Khandala")     # Call Methods cust1.display_details() cust2.display_details() 
Output:
Customer id: 1
Customer name: Mike
Customer address: Wisdom Apartments, Ludhiya
Customer id: 2
Customer name: Jackey
Customer address: New Empire road, Khandala

Explanation: In the above program, the class Demoencapsulation encapsulate the methods of the class. You can only access these methods with the help of objects of the Demoencapsulation class i.e. cust1 and cust2.
Advantages of Encapsulation:
Data Hiding:The user will have no idea about the inner implementation of the class. It will not be visible to the user that how the class is storing values in the variables. He only knows that we are passing the values to a setter method and variables are getting initialized with that value.
Reusability: Encapsulation also improves the re-usability and easy to change with new requirements.
Testing code is easy:Encapsulated code is easy to test for unit testing.
Ruby-OOP
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Ruby | Array count() operation
Ruby | Array slice() function
Ruby | Enumerator each_with_index function
Global Variable in Ruby
Ruby | Array select() function
Ruby | Hash delete() function
Ruby | String gsub! Method
Ruby | String capitalize() Method
How to Make a Custom Array of Hashes in Ruby?
Ruby | Case Statement
Python List index() Method

Python list method index() returns the lowest index in list that obj appears.
Following is the syntax for index() method −
list.index(obj)

obj − This is the object to be find out.
obj − This is the object to be find out.
This method returns index of the found object otherwise raise an exception indicating that value does not find.
The following example shows the usage of index() method.
#!/usr/bin/python

aList = [123, 'xyz', 'zara', 'abc'];
print "Index for xyz : ", aList.index( 'xyz' ) 
print "Index for zara : ", aList.index( 'zara' ) 
When we run above program, it produces following result −
Index for xyz :  1
Index for zara :  2


    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
RxJava - Creating Operators

Following are the operators which are used to create an Observable.
Create
Creates an Observable from scratch and allows observer method to call programmatically.
Defer
Do not create an Observable until an observer subscribes. Creates a fresh observable for each observer.
Empty/Never/Throw
Creates an Observable with limited behavior.
From
Converts an object/data structure into an Observable.
Interval
Creates an Observable emitting integers in sequence with a gap of specified time interval.
Just
Converts an object/data structure into an Observable to emit the same or same type of objects.
Range
Creates an Observable emitting integers in sequence of given range.
Repeat
Creates an Observable emitting integers in sequence repeatedly.
Start
Creates an Observable to emit the return value of a function.
Timer
Creates an Observable to emit a single item after given delay.
Create the following Java program using any editor of your choice in, say, C:\> RxJava.
import io.reactivex.Observable;
//Using fromArray operator to create an Observable
public class ObservableTester  {
   public static void main(String[] args) { 
      String[] letters = {"a", "b", "c", "d", "e", "f", "g"};
      final StringBuilder result = new StringBuilder();
      Observable<String> observable = Observable.fromArray(letters);
      observable
         .map(String::toUpperCase)
         .subscribe( letter -> result.append(letter));
      System.out.println(result);
   }
}
Compile the class using javac compiler as follows −
C:\RxJava>javac ObservableTester.java

Now run the ObservableTester as follows −
C:\RxJava>java ObservableTester

It should produce the following output −
ABCDEFG

 Print
 Add Notes
 Bookmark this page
Tryit Editor v3.7

Tryit: HTML table caption
Checked vs Unchecked Exceptions in C#

You can execute statements in C# in checked or unchecked context.
In checked, the exception is raised by arithmetic overflow, whereas in unchecked context, arithmetic overflow is ignored.
Use the checked keyword to explicitly enable overflow checking for integral-type arithmetic operations and conversions. For this, just set the checked keyword.
Overflow checking can be enabled by compiler options, environment configuration, or use of the checked keyword.
res = checked(val + 10);
Let’s say the value of val is 2147483647 i.e. the max value of int type. The above will raise an error since it is checked. This enables overflow checking at runtime.
Use the unchecked keyword to prevent overflow checking for integral-type arithmetic operations and conversions. For this, just set the unchecked keyword.
Here, the arithmetic overflow is ignored. Use it to prevent overflow checking.
res =unchecked(val + 10);

Let’s say the value of val is 2147483647. The above will not throw an error since the overflow checking is prevented using the unchecked keyword.
Default constructor in C#

A Constructor in C# is invoked automatically when an object gets created. The constructor has the same name as that of the class, for example −
public class Department {
   public Department () {
      Console.WriteLine("Default Constructor! ");
   }
}
The following is the code that shows the usage of default constructor in C#. The constructor invokes immediately when the object gets created.
Department dept1 = new Department ();
A default constructor is a constructor that has no argument, for example −
Department () {
}
Let us see the complete example to learn how to work with default contructors.
 Live Demo
using System;
public class Department {
   public Department () {
      Console.WriteLine("Constructor Invoked");
   }
   public static void Main(string[] args) {
      // object
      Department dept1 = new Department ();
   }
}
Constructor Invoked
Lowest Common Ancestor of a Binary Search Tree in Python

Suppose we have a binary search tree. we have to find the Lowest common ancestor nodes of two given nodes. The LCA of two nodes p and q is actually as the lowest node in tree that has both p and q as decedent. So if the binary tree is like [6, 2, 8, 0, 4, 7, 9, null, null, 3, 5]. The tree will be like −
Here LCA of 2 and 8 is 6
To solve this, we will follow these steps −
If the tree is empty, then return null
if p and q both are same as root, then return root
left := LCA of left subtree of the root using p and q
right := LCA of right subtree of the root using p and q
if left and right both are non-zero, then return root
return left OR right
Let us see the following implementation to get better understanding −
 Live Demo
class TreeNode:
   def __init__(self, data, left = None, right = None):
      self.data = data
      self.left = left
      self.right = right
class Solution():
   def lowestCommonAncestor(self, root, p, q):
      if not root:
         return None
      if p == root or q==root:
         return root
      left = self.lowestCommonAncestor(root.left, p, q)
      right = self.lowestCommonAncestor(root.right, p, q)
      if left and right:
         return root
      return left or right
def insert(temp,data):
   que = []
   que.append(temp)
   while (len(que)):
      temp = que[0]
      que.pop(0)
      if (not temp.left):
         temp.left = TreeNode(data)
         break
      else:
         que.append(temp.left)
      if (not temp.right):
         temp.right = TreeNode(data)
         break
      else:
         que.append(temp.right)
def make_tree(elements):
   Tree = TreeNode(elements[0])
   for element in elements[1:]:
      insert(Tree, element)
   return Tree
def search_node(root, element):
   if (root == None):
      return None
   if (root.data == element):
      return root
   res1 = search_node(root.left, element)
   if res1:
      return res1
   res2 = search_node(root.right, element)
   return res2

root = make_tree([6,2,8,0,4,7,9,None,None,3,5])
ob1 = Solution()
op = ob1.lowestCommonAncestor(root, search_node(root, 2), search_node(root, 8))
print(op.data)
[6,2,8,0,4,7,9,null,null,3,5]
2
8
6
Can we use MySQL GROUP BY clause with multiple columns like MySQL DISTINCT clause is used?

Yes, it is possible to use MySQL GROUP BY clause with multiple columns just as we can use MySQL DISTINCT clause. Consider the following example in which we have used DISTINCT clause in first query and GROUP BY clause in the second query, on ‘fname’ and ‘Lname’ columns of the table named ‘testing’.
mysql> Select * from testing;
+------+---------+---------+
| id   | fname   | Lname   |
+------+---------+---------+
|  200 | Raman   | Kumar   |
|  201 | Sahil   | Bhalla  |
|  202 | Gaurav  | NULL    |
|  203 | Aarav   | NULL    |
|  204 | Harshit | Khurana |
|  205 | Rahul   | NULL    |
|  206 | Piyush  | Kohli   |
|  207 | Lovkesh | NULL    |
|  208 | Gaurav  | Kumar   |
|  209 | Raman   | Kumar   |
+------+---------+---------+
10 rows in set (0.00 sec)

mysql> Select DISTINCT FNAME,LNAME from testing;
+---------+---------+
| FNAME   | LNAME   |
+---------+---------+
| Raman   | Kumar   |
| Sahil   | Bhalla  |
| Gaurav  | NULL    |
| Aarav   | NULL    |
| Harshit | Khurana |
| Rahul   | NULL    |
| Piyush  | Kohli   |
| Lovkesh | NULL    |
| Gaurav  | Kumar   |
+---------+---------+
9 rows in set (0.00 sec)

mysql> Select Fname, LNAME from testing GROUP BY Fname,Lname;
+---------+---------+
| Fname   | LNAME   |
+---------+---------+
| Aarav   | NULL    |
| Gaurav  | NULL    |
| Gaurav  | Kumar   |
| Harshit | Khurana |
| Lovkesh | NULL    |
| Piyush  | Kohli   |
| Rahul   | NULL    |
| Raman   | Kumar   |
| Sahil   | Bhalla |
+---------+---------+
9 rows in set (0.00 sec)
The only difference is that the result set returns by MySQL query using GROUP BY clause is sorted and in contrast, the result set return by MySQL query using DISTICT clause is not sorted.
Tryit Editor v3.7

Tryit: HTML meta element
Convert JSON to dictionary in Python - GeeksforGeeks

07 Dec, 2021
JSON stands for JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called json. To use this feature, we import the json package in Python script. The text in JSON is done through quoted-string which contains value in key-value mapping within { }. It is similar to the dictionary in Python.Function Used: 
json.load(): json.loads() function is present in python built-in ‘json’ module. This function is used to parse the JSON string. 
Syntax: json.load(file_name)Parameter: It takes JSON file as the parameter.Return type: It returns the python dictionary object.  
Example 1: Let’s suppose the JSON file looks like this: 
We want to convert the content of this file to Python dictionary. Below is the implementation. 
Python3
# Python program to demonstrate# Conversion of JSON data to# dictionary  # importing the moduleimport json # Opening JSON filewith open('data.json') as json_file:    data = json.load(json_file)     # Print the type of data variable    print("Type:", type(data))     # Print the data of dictionary    print("\nPeople1:", data['people1'])    print("\nPeople2:", data['people2'])
Output : 
Example 2: Reading nested data In the above JSON file, there is a nested dictionary in the first key people1. Below is the implementation of reading nested data. 
Python3
# Python program to demonstrate# Conversion of JSON data to# dictionary  # importing the moduleimport json # Opening JSON filewith open('data.json') as json_file:    data = json.load(json_file)     # for reading nested data [0] represents    # the index value of the list    print(data['people1'][0])         # for printing the key-value pair of    # nested dictionary for loop can be used    print("\nPrinting nested dictionary as a key-value pair\n")    for i in data['people1']:        print("Name:", i['name'])        print("Website:", i['website'])        print("From:", i['from'])        print()
Output : 
 
sumitgumber28
simranarora5sos
Python json-programs
Python-json
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Reading and Writing to text files in Python
*args and **kwargs in Python
Python – All pair combinations of 2 tuples

03 Jul, 2020
Sometimes, while working with Python tuples data, we can have a problem in which we need to extract all possible combination of 2 argument tuples. This kind of application can come in Data Science or gaming domains. Let’s discuss certain ways in which this task can be performed.
Input : test_tuple1 = (7, 2), test_tuple2 = (7, 8)Output : [(7, 7), (7, 8), (2, 7), (2, 8), (7, 7), (7, 2), (8, 7), (8, 2)]
Input : test_tuple1 = (9, 2), test_tuple2 = (7, 8)Output : [(9, 7), (9, 8), (2, 7), (2, 8), (7, 9), (7, 2), (8, 9), (8, 2)]
Method #1 : Using list comprehensionThis is one of the ways in which this task can be performed. In this, we perform task of forming one index combination in one pass, in other pass change the index, and add to the initial result list.
# Python3 code to demonstrate working of # All pair combinations of 2 tuples# Using list comprehension  # initializing tuplestest_tuple1 = (4, 5)test_tuple2 = (7, 8)  # printing original tuplesprint("The original tuple 1 : " + str(test_tuple1))print("The original tuple 2 : " + str(test_tuple2))  # All pair combinations of 2 tuples# Using list comprehensionres =  [(a, b) for a in test_tuple1 for b in test_tuple2]res = res +  [(a, b) for a in test_tuple2 for b in test_tuple1]  # printing result print("The filtered tuple : " + str(res))
The original tuple 1 : (4, 5)
The original tuple 2 : (7, 8)
The filtered tuple : [(4, 7), (4, 8), (5, 7), (5, 8), (7, 4), (7, 5), (8, 4), (8, 5)]

 
Method #2 : Using chain() + product()The combination of above functions provide yet another way to solve this problem. In this, we perform task of pair creation using product() and chain() is used to add both the results from product() used twice.
# Python3 code to demonstrate working of # All pair combinations of 2 tuples# Using chain() + product()from itertools import chain, product  # initializing tuplestest_tuple1 = (4, 5)test_tuple2 = (7, 8)  # printing original tuplesprint("The original tuple 1 : " + str(test_tuple1))print("The original tuple 2 : " + str(test_tuple2))  # All pair combinations of 2 tuples# Using chain() + product()res = list(chain(product(test_tuple1, test_tuple2), product(test_tuple2, test_tuple1)))  # printing result print("The filtered tuple : " + str(res))
The original tuple 1 : (4, 5)
The original tuple 2 : (7, 8)
The filtered tuple : [(4, 7), (4, 8), (5, 7), (5, 8), (7, 4), (7, 5), (8, 4), (8, 5)]

Python List-of-Tuples
Python tuple-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
C# program to count the number of words in a string

Let us first declare the string −
string str = "Hello World!";
Now loop through the complete string and find the whitespace or tab or newline character −
while (a <= str.Length - 1) {
   if(str[a]==' ' || str[a]=='\n' || str[a]=='\t') {
      myWord++;
   }
   a++;
}
Let us see the complete code to count a number of words in a string in C#.
Live Demo
using System;
public class Demo {
   public static void Main() {
      int a = 0 , myWord = 1;
      string str = "Hello World!";
      while (a <= str.Length - 1) {
         if(str[a]==' ' || str[a]=='\n' || str[a]=='\t') {
            myWord++;
         }
         a++;
      }
      Console.Write("Number of words in the string = {0}\n", myWord);
   }
}
Number of words in the string = 2
How can we update an existing JSON data using javax.json API in Java?

The JsonBuilderFactory interface is a factory to create JsonObjectBuilder instance and JsonObjectBuilder is a builder for creating JsonObject models from scratch. This interface initializes an empty JSON object model and provides methods to add name/value pairs to the object model and to return the resulting object. We can create a JsonObjectBuilder instance that can be used to build JsonObject using the createObjectBuilder() method.
JsonObjectBuilder createObjectBuilder()
In the below example, We can update an existing JSON data with newly added data.
import java.io.*;
import javax.json.*;
public class UpdateExistingJsonTest {
   public static void main(String[] args) throws Exception {
      String jsonString = "{\"id\":\"115\", \"name\":\"Raja\", \"address\":[{\"area\":\"Madhapur\", \"city\":\"Hyderabad\"}]}";
      StringReader reader = new StringReader(jsonString);
      JsonReader jsonReader = Json.createReader(reader);
      System.out.println("Existing JSON: \n" + jsonString);
      StringWriter writer = new StringWriter();
      JsonWriter jsonWriter = Json.createWriter(writer);
      JsonObject jsonObject = jsonReader.readObject();
      JsonBuilderFactory jsonBuilderFactory = Json.createBuilderFactory(null);
      JsonObjectBuilder jsonObjectBuilder = jsonBuilderFactory.createObjectBuilder();
      for(String key : jsonObject.keySet()) {
         jsonObjectBuilder.add(key, jsonObject.get(key));
      }
      jsonObjectBuilder.add("Contact Number", "9959984000");
      jsonObjectBuilder.add("Country", "India");
      jsonObject = jsonObjectBuilder.build();
      jsonWriter.writeObject(jsonObject);
      System.out.println("new JSON: \n" + jsonObject);
   }
}
Existing JSON:
{"id":"115", "name":"Raja", "address":[{"area":"Madhapur", "city":"Hyderabad"}]}

new JSON:
{"id":"115","name":"Raja","address":[{"area":"Madhapur","city":"Hyderabad"}],"Contact Number":"9959984000","Country":"India"}
Thread-based parallelism in C#

In C#, Task parallelism divide tasks. The tasks are then allocated to separate threads for processing. In .NET, you have the following mechanisms to run code in parallel: Thread, ThreadPool, and Task. For parallelism, use tasks in C# instead of Threads.
A task will not create its own OS thread, whereas they are executed by a TaskScheduler.
Let us see how to create tasks. Use a delegate to start a task −
Task tsk = new Task(delegate { PrintMessage(); });
tsk.Start();
Use Task Factory to start a task −
Task.Factory.StartNew(() => {Console.WriteLine("Welcome!"); });
You can also use Lambda −
Task tsk = new Task( () => PrintMessage() );
tsk.Start();
The most basic way to start a task is using the run() −
 Live Demo
using System;
using System.Threading.Tasks;

public class Example {
   public static void Main() {
      Task tsk = Task.Run(() => {
         int a = 0;
         for (a = 0; a <= 1000; a++) {}
         Console.WriteLine("{0} loop iterations ends", a);
      });
      tsk.Wait();
   }
}
1001 loop iterations ends
Breadth First Search or BFS for a Graph

The Breadth First Search (BFS) traversal is an algorithm, which is used to visit all of the nodes of a given graph. In this traversal algorithm one node is selected and then all of the adjacent nodes are visited one by one. After completing all of the adjacent vertices, it moves further to check another vertices and checks its adjacent vertices again.
To implement this algorithm, we need to use the Queue data structure. All the adjacent vertices are added into the queue, when all adjacent vertices are completed, one item is removed from the queue and start traversing through that vertex again.
In Graph sometimes, we may get some cycles, so we will use an array to mark when a node is visited already or not.
Input - The Adjacency matrix of the graph.
A B C D E F
A 0 1 1 1 0 0
B 1 0 0 1 1 0
C 1 0 0 1 0 1
D 1 1 1 0 1 1
E 0 1 0 1 0 1
F 0 0 1 1 1 0
Output - BFS Traversal: B A D E C F
Input − The list of vertices, and the start vertex.
Output − Traverse all of the nodes, if the graph is connected.
Begin
   define an empty queue que
   at first mark all nodes status as unvisited
   add the start vertex into the que
   while que is not empty, do
      delete item from que and set to u
      display the vertex u
      for all vertices 1 adjacent with u, do
         if vertices[i] is unvisited, then
            mark vertices[i] as temporarily visited
            add v into the queue
         mark
      done
      mark u as completely visited
   done
End
#include<iostream>
#include<queue>
#define NODE 6
using namespace std;
typedef struct node{
   int val;
   int state; //status
}node;
int graph[NODE][NODE] = {
   {0, 1, 1, 1, 0, 0},
   {1, 0, 0, 1, 1, 0},
   {1, 0, 0, 1, 0, 1},
   {1, 1, 1, 0, 1, 1},
   {0, 1, 0, 1, 0, 1},
   {0, 0, 1, 1, 1, 0}
};
void bfs(node *vert, node s){
   node u;
   int i, j;
   queue<node> que;
   for(i = 0; i<NODE; i++){
      vert[i].state = 0; //not visited
   }
   vert[s.val].state = 1;//visited
   que.push(s); //insert starting node
   while(!que.empty()){
      u = que.front(); //delete from queue and print
      que.pop();
      cout << char(u.val+'A') << " ";
      for(i = 0; i<NODE; i++){
         if(graph[i][u.val]){
            //when the node is non-visited
            if(vert[i].state == 0){
               vert[i].state = 1;
               que.push(vert[i]);
            }
         }
      }
      u.state = 2;//completed for node u
   }
}
int main(){
   node vertices[NODE];
   node start;
   char s;
   for(int i = 0; i<NODE; i++){
      vertices[i].val = i;
   }
   s = 'B';//starting vertex B
   start.val = s-'A';
   cout << "BFS Traversal: ";
   bfs(vertices, start);
   cout << endl;
}
BFS Traversal: B A D E C F
Go - Logical Operators

The following table lists all the logical operators supported by Go language. Assume variable A holds 1 and variable B holds 0, then −
The following table shows all the logical operators supported by Go language. Assume variable A holds true and variable B holds false, then −
Try the following example to understand all the logical operators available in Go programming language −
package main

import "fmt"

func main() {
   var a bool = true
   var b bool = false
   if ( a && b ) {
      fmt.Printf("Line 1 - Condition is true\n" )
   }
   if ( a || b ) {
      fmt.Printf("Line 2 - Condition is true\n" )
   }
   
   /* lets change the value of  a and b */
   a = false
   b = true
   if ( a && b ) {
      fmt.Printf("Line 3 - Condition is true\n" )
   } else {
      fmt.Printf("Line 3 - Condition is not true\n" )
   }
   if ( !(a && b) ) {
      fmt.Printf("Line 4 - Condition is true\n" )
   }
}
When you compile and execute the above program it produces the following result −
Line 2 - Condition is true
Line 3 - Condition is not true
Line 4 - Condition is true


    64 Lectures 
     6.5 hours 

 Ridhi Arora

    20 Lectures 
     2.5 hours 

 Asif Hussain

    22 Lectures 
     4 hours 

 Dilip Padmanabhan

    48 Lectures 
     6 hours 

 Arnab Chakraborty

    7 Lectures 
     1 hours 

 Aditya Kulkarni

    44 Lectures 
     3 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
Python - How to drop the null rows from a Pandas DataFrame

To drop the null rows in a Pandas DataFrame, use the dropna() method. Let’s say the following is our CSV file with some NaN i.e. null values −
Let us read the CSV file using read_csv(). Our CSV is on the Desktop −
dataFrame = pd.read_csv("C:\\Users\\amit_\\Desktop\\CarRecords.csv")
Remove the null values using dropna() −
dataFrame = dataFrame.dropna()

Following is the complete code −
import pandas as pd

# reading csv file
dataFrame = pd.read_csv("C:\\Users\\amit_\\Desktop\\CarRecords.csv")
print("DataFrame...\n",dataFrame)

# count the rows and columns in a DataFrame
print("\nNumber of rows and column in our DataFrame = ",dataFrame.shape)

dataFrame = dataFrame.dropna()
print("\nDataFrame after removing null values...\n",dataFrame)
print("\n(Updated) Number of rows and column in our DataFrame = ",dataFrame.shape)


This will produce the following output −
DataFrame...
           Car       Place   UnitsSold
0         Audi   Bangalore        80.0
1      Porsche      Mumbai       110.0
2   RollsRoyce        Pune         NaN
3          BMW       Delhi       200.0
4     Mercedes   Hyderabad        80.0
5  Lamborghini  Chandigarh         NaN
6         Audi      Mumbai         NaN
7     Mercedes        Pune       120.0
8  Lamborghini       Delhi       100.0

Number of rows and column in our DataFrame = (9, 3)

DataFrame after removing null values...
           Car      Place   UnitsSold
0         Audi  Bangalore        80.0
1      Porsche     Mumbai       110.0
3          BMW      Delhi       200.0
4     Mercedes  Hyderabad        80.0
7     Mercedes       Pune       120.0
8  Lamborghini      Delhi       100.0

(Updated) Number of rows and column in our DataFrame = (6, 3)
Pafy – Getting Best Audio Stream of the Video

20 Jul, 2020
In this article we will see how we can get best audio stream of the given youtube video in pafy. Pafy is a python library to download YouTube content and retrieve metadata. Pafy object is the object which contains all the information about the given video. Best audio stream is basically a audio stream which is available and in highest resolution. This is best stream available for the audio.
We can get the pafy object with the help of new method, below is the command to get the pafy object for given video
video = pafy.new(url)
The video url should exist on youtube as it get the information of those videos which are present on the youtube. YouTube is an American online video-sharing platform.
In order to do this we use getbestaudio method with the pafy object of video
Syntax : video.getbestaudio()
Argument : It takes no argument
Return : It returns YtdlStream object
Below is the implementation
# importing pafyimport pafy     # url of video url = "https://www.youtube.com / watch?v = vG2PNdI8axo"    # getting videovideo = pafy.new(url)   # getting best audio stream of videovalue = video.getbestaudio()  # printing the valueprint("Best Audio Stream : " + str(value))
Output :
Best Audio Stream : audio:webm@160k

Another example
# importing pafyimport pafy     # url of video url = "https://www.youtube.com / watch?v = i6rhnSoK_gc"    # getting videovideo = pafy.new(url) # getting best audio stream of videovalue = video.getbestaudio()  # printing the valueprint("Best Audio Stream : " + str(value))
Output :
Best Audio Stream : audio:webm@160k

Python-Pafy
Python
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
Python Classes and Objects
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
MATLAB – Image Edge Detection using Robert Operator from Scratch

17 May, 2020
Robert Operator: This gradient-based operator computes the sum of squares of the differences between diagonally adjacent pixels in an image through discrete differentiation. Then the gradient approximation is made. It uses the following 2 x 2 kernels or masks –
    
Approach:
Step 1: Input – Read an imageStep 2: Convert the true-color RGB image to the grayscale imageStep 3: Convert the image to doubleStep 4: Pre-allocate the filtered_image matrix with zerosStep 5: Define Robert Operator MaskStep 6: Edge Detection Process (Compute Gradient approximation and magnitude of vector)Step 7: Display the filtered imageStep 8: Thresholding on the filtered imageStep 9: Display the edge-detected image
Implementation in MATLAB:
% MATLAB Code | Robert Operator from Scratch  % Read Input Imageinput_image = imread('[name of input image file].[file format]');  % Displaying Input Imageinput_image = uint8(input_image);figure, imshow(input_image); title('Input Image');  % Convert the truecolor RGB image to the grayscale imageinput_image = rgb2gray(input_image);  % Convert the image to doubleinput_image = double(input_image);  % Pre-allocate the filtered_image matrix with zerosfiltered_image = zeros(size(input_image));  % Robert Operator MaskMx = [1 0; 0 -1];My = [0 1; -1 0];  % Edge Detection Process% When i = 1 and j = 1, then filtered_image pixel  % position will be filtered_image(1, 1)% The mask is of 2x2, so we need to traverse % to filtered_image(size(input_image, 1) - 1%, size(input_image, 2) - 1)for i = 1:size(input_image, 1) - 1    for j = 1:size(input_image, 2) - 1          % Gradient approximations        Gx = sum(sum(Mx.*input_image(i:i+1, j:j+1)));        Gy = sum(sum(My.*input_image(i:i+1, j:j+1)));                         % Calculate magnitude of vector        filtered_image(i, j) = sqrt(Gx.^2 + Gy.^2);             endend  % Displaying Filtered Imagefiltered_image = uint8(filtered_image);figure, imshow(filtered_image); title('Filtered Image');  % Define a threshold valuethresholdValue = 100; % varies between [0 255]output_image = max(filtered_image, thresholdValue);output_image(output_image == round(thresholdValue)) = 0;  % Displaying Output Imageoutput_image = im2bw(output_image);figure, imshow(output_image); title('Edge Detected Image');
Input Image –
Filtered Image:
Edge Detected Image:
Advantages:
Detection of edges and orientation are very easyDiagonal direction points are preserved
Detection of edges and orientation are very easy
Diagonal direction points are preserved
Limitations:
Very sensitive to noiseNot very accurate in edge detection
Very sensitive to noise
Not very accurate in edge detection
Image-Processing
MATLAB
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to use .svg files in a webpage?

The svg files are Scalable Vector Graphics. You can add it to a web page using the <img>, <iframe>, <object> or <embed> tag.
The .svg file is to be referenced in the src attribute of the <img> tag. Let’s see how to add it using the <img> tag.
You can try to run the following code to learn how to use .svg files in a web page. We have a smiley.svg file −
<!DOCTYPE html>
<html>
   <head>
      <title>HTML SVG</title>
   </head>

   <body>
      <h1>Design</h1>
      <img src=
         "https://www.tutorialspoint.com/html5/src/svg/extensions/imagelib/smiley.svg"
         id="demo" alt="smiley">
   </body>
</html>