code-rag-bench/online-tutorials huggingface dataset:
Python – Mapping Matrix with Dictionary

14 Oct, 2020
Given a Matrix, map its values with dictionary values.
Input : test_list = [[4, 2, 1], [1, 2, 3]], sub_dict = {1 : “gfg”, 2: “best”, 3 : “CS”, 4 : “Geeks”}Output : [[‘Geeks’, ‘best’, ‘gfg’], [‘gfg’, ‘best’, ‘CS’]]Explanation : Matrix elements are substituted using dictionary.
Input : test_list = [[4, 2, 1]], sub_dict = {1 : “gfg”, 2: “best”, 4 : “Geeks”}Output : [[‘Geeks’, ‘best’, ‘gfg’]]Explanation : Matrix elements are substituted using dictionary.
Method #1 : Using loop
This is brute way in which this task can be performed. In this, we iterate for all the elements of Matrix and map from dictionary.
Python3
# Python3 code to demonstrate working of # Mapping Matrix with Dictionary# Using loop  # initializing listtest_list = [[4, 2, 1], [1, 2, 3], [4, 3, 1]]  # printing original listprint("The original list : " + str(test_list))  # initializing dictionarysub_dict = {1 : "gfg", 2: "best", 3 : "CS", 4 : "Geeks"}  # Using loop to perform required mappingres = []for sub in test_list:    temp = []    for ele in sub:                  # mapping values from dictionary        temp.append(sub_dict[ele])    res.append(temp)  # printing result print("Converted Mapped Matrix : " + str(res))
The original list : [[4, 2, 1], [1, 2, 3], [4, 3, 1]]
Converted Mapped Matrix : [['Geeks', 'best', 'gfg'], ['gfg', 'best', 'CS'], ['Geeks', 'CS', 'gfg']]

Method #2 : Using list comprehension
This is yet another way in which this task can be performed. This is just shorthand to above method. 
Python3
# Python3 code to demonstrate working of # Mapping Matrix with Dictionary# Using list comprehension  # initializing listtest_list = [[4, 2, 1], [1, 2, 3], [4, 3, 1]]  # printing original listprint("The original list : " + str(test_list))  # initializing dictionarysub_dict = {1 : "gfg", 2: "best", 3 : "CS", 4 : "Geeks"}  # Using list comprehension to perform required mapping# in one line res = [[sub_dict[val] for val in sub] for sub in test_list]  # printing result print("Converted Mapped Matrix : " + str(res))
The original list : [[4, 2, 1], [1, 2, 3], [4, 3, 1]]
Converted Mapped Matrix : [['Geeks', 'best', 'gfg'], ['gfg', 'best', 'CS'], ['Geeks', 'CS', 'gfg']]

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to toggle play/pause in ReactJS with audio ?

10 Jul, 2021
In this article, we will learn to create a play/pause button for an audio file using ReactJS
Approach: We are going to use the following steps:
Take the reference of the audio file in ReactJS Using Audio Class 
Set the default state of the song as not playing.
Make a function to handle the Play/Pause of the song.
Use the play() and pause() functions of audio class to do these operations.
let song = new Audio(my_song);
song.play();
song.pause();
Setting up environment and Execution:
Step 1: Create React App command
npx create-react-app foldername
Step 2: After creating your project folder, i.e., folder name, move to it using the following command:
cd foldername
Step 3: Create a Static folder and add an audio file to it.
Project Structure: It will look like the following.
Example:
import React, { Component } from "react";

// Import your audio file
import song from "./static/a.mp3";

class App extends Component {
  // Create state
  state = {

    // Get audio file in a variable
    audio: new Audio(song),

    // Set initial state of song
    isPlaying: false,
  };

  // Main function to handle both play and pause operations
  playPause = () => {

    // Get state of song
    let isPlaying = this.state.isPlaying;

    if (isPlaying) {
      // Pause the song if it is playing
      this.state.audio.pause();
    } else {

      // Play the song if it is paused
      this.state.audio.play();
    }

    // Change the state of song
    this.setState({ isPlaying: !isPlaying });
  };

  render() {
    return (
      <div>
        {/* Show state of song on website */}
        <p>
          {this.state.isPlaying ? 
            "Song is Playing" : 
            "Song is Paused"}
        </p>

        {/* Button to call our main function */}
        <button onClick={this.playPause}>
          Play | Pause
        </button>
      </div>
    );
  }
}

export default App;


Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, Turn on speakers to listen to audio.
rajeev0719singh
Picked
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Axios in React: A Guide for Beginners
ReactJS useNavigate() Hook
How to do crud operations in ReactJS ?
How to install bootstrap in React.js ?
How to navigate on path by button click in react router ?
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?
Remove elements from a JavaScript Array
Python – Remove Non-English characters Strings from List

02 Sep, 2020
Given a List of Strings, perform removal of all Strings with non-english characters.
Input : test_list = [‘Good| ????’, ‘??Geeks???’]Output : []Explanation : Both contain non-English characters
Input : test_list = [“Gfg”, “Best”]Output : [“Gfg”, “Best”]Explanation : Both are valid English words.
Method #1 : Using regex + findall() + list comprehension
In this, we create a regex of unicodes and check for occurrence in String List, extract each String without unicode using findall().
Python3
# Python3 code to demonstrate working of # Remove Non-English characters Strings from List# Using regex + findall() + list comprehensionimport re  # initializing listtest_list = ['Gfg', 'Good| ????', "for",  '??Geeks???']  # printing original listprint("The original list is : " + str(test_list))  # using findall() to neglect unicode of Non-English alphabetsres = [idx for idx in test_list if not re.findall("[^\u0000-\u05C0\u2100-\u214F]+", idx)]  # printing result print("The extracted list : " + str(res))
Method #2 : Using regex + search() + filter() + lambda
In this, we search for only English alphabets in String, and extract only those that have those. We use filter() + lambda to perform the task of passing filter functionality and iteration.
Python3
# Python3 code to demonstrate working of # Remove Non-English characters Strings from List# Using regex + search() + filter() + lambdaimport re  # initializing listtest_list = ['Gfg', 'Good| ????', "for",  '??Geeks???']  # printing original listprint("The original list is : " + str(test_list))  # using search() to get only those strings with alphabetsres = list(filter(lambda ele: re.search("[a-zA-Z\s]+", ele) is not None, test_list))  # printing result print("The extracted list : " + str(res))
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – Extract Key’s value from Mixed Dictionaries List

30 Sep, 2021
Given a list of dictionaries, with each dictionary having different keys, extract value of key K.
Input : test_list = [{“Gfg” : 3, “b” : 7}, {“is” : 5, ‘a’ : 10}, {“Best” : 9, ‘c’ : 11}], K = ‘b’ Output : 7 Explanation : Value of b is 7.
Input : test_list = [{“Gfg” : 3, “b” : 7}, {“is” : 5, ‘a’ : 10}, {“Best” : 9, ‘c’ : 11}], K = ‘c’ Output : 11 Explanation : Value of c is 11.  
Method #1 : Using list comprehension
This is one of the ways in which this task can be performed. In this, we iterate for each dictionary inside list, and check for key in it, if present the required value is returned.
Python3
# Python3 code to demonstrate working of# Extract Key's value from Mixed Dictionaries List# Using list comprehension # initializing listtest_list = [{"Gfg" : 3, "b" : 7},             {"is" : 5, 'a' : 10},             {"Best" : 9, 'c' : 11}] # printing original listprint("The original list : " + str(test_list)) # initializing KK = 'Best' # list comprehension to get key's value# using in operator to check if key is present in dictionaryres = [sub[K] for sub in test_list if K in sub][0] # printing resultprint("The extracted value : " + str(res))
The original list : [{'Gfg': 3, 'b': 7}, {'is': 5, 'a': 10}, {'Best': 9, 'c': 11}]
The extracted value : 9
Method #2 : Using update() + loop
This is yet another way in which this task can be performed. In this, we update each dictionary into each other. Forming one large dictionary, and then the value is extracted from this dictionary.
Python3
# Python3 code to demonstrate working of# Extract Key's value from Mixed Dictionaries List# Using update() + loop # initializing listtest_list = [{"Gfg" : 3, "b" : 7},             {"is" : 5, 'a' : 10},             {"Best" : 9, 'c' : 11}] # printing original listprint("The original list : " + str(test_list)) # initializing KK = 'Best' res = dict()for sub in test_list:         # merging all Dictionaries into 1    res.update(sub) # printing resultprint("The extracted value : " + str(res[K]))
The original list : [{'Gfg': 3, 'b': 7}, {'is': 5, 'a': 10}, {'Best': 9, 'c': 11}]
The extracted value : 9
sweetyty
Python dictionary-programs
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Get first and last elements of a list

02 Jan, 2019
Sometimes, there might be a need to get the range between which a number lies in the list, for such applications we require to get the first and last element of the list. Let’s discuss certain ways to get the first and last element of the list.
Method #1 : Using list indexUsing the list indices inside the master list can perform this particular task. This is most naive method to achieve this particular task one can think of.
# Python3 code to demonstrate # to get first and last element of list# using list indexing  # initializing list test_list = [1, 5, 6, 7, 4]  # printing original list print ("The original list is : " +  str(test_list))  # using list indexing# to get first and last element of listres = [ test_list[0], test_list[-1] ]   # printing resultprint ("The first and last element of list are : " +  str(res))
The original list is : [1, 5, 6, 7, 4]
The first and last element of list are : [1, 4]

 Method #2 : Using List slicingOne can also make use of list slicing technique to perform the particular task of getting first and last element. We can use step of whole list to skip to the last element after the first element.
# Python3 code to demonstrate # to get first and last element of list# using List slicing  # initializing list test_list = [1, 5, 6, 7, 4]  # printing original list print ("The original list is : " +  str(test_list))  # using List slicing# to get first and last element of listres = test_list[::len(test_list)-1]   # printing resultprint ("The first and last element of list are : " +  str(res))
The original list is : [1, 5, 6, 7, 4]
The first and last element of list are : [1, 4]

 Method #3 : Using list comprehensionList comprehension can be employed to provide a shorthand to the loop technique to find first and last element of the list. Naive method of finding is converted to a single line using this method.
# Python3 code to demonstrate # to get first and last element of list# using list comprehension  # initializing list test_list = [1, 5, 6, 7, 4]  # printing original list print ("The original list is : " +  str(test_list))  # using list comprehension# to get first and last element of listres =  [ test_list[i] for i in (0, -1) ]  # printing resultprint ("The first and last element of list are : " +  str(res))
The original list is : [1, 5, 6, 7, 4]
The first and last element of list are : [1, 4]

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Zip a directory in PHP?

10 Aug, 2021
ZIP is an archive file format that supports lossless data compression. A ZIP file may contain one or more files or directories that may have been compressed. The PHP ZipArchive class can be used to zipping and unzipping. It might be need to install the class if it is not present.
Installation for Linux users:In order to use these functions you must compile PHP with zip support by using the –enable-zip configure option.Installation for Windows users:As of PHP 5.3 this extension is inbuilt. Before, Windows users need to enable php_zip.dll inside of php.ini in order to use its functions.
Example: This example uses ZipArchive class and create a zipped file.
<?php  // Enter the name of directory$pathdir = "Directory Name/";   // Enter the name to creating zipped directory$zipcreated = "Name of Zip.zip";  // Create new zip class$zip = new ZipArchive;   if($zip -> open($zipcreated, ZipArchive::CREATE ) === TRUE) {          // Store the path into the variable    $dir = opendir($pathdir);           while($file = readdir($dir)) {        if(is_file($pathdir.$file)) {            $zip -> addFile($pathdir.$file, $file);        }    }    $zip ->close();}  ?>
Example: This example uses ZipArchive class to unzip the file or directory.
<?php  // Create new zip class$zip = new ZipArchive;  // Add zip filename which need// to unzip$zip->open('filename.zip');  // Extracts to current directory$zip->extractTo('./');  $zip->close();   ?>
Steps to run the program: Zip a directory ‘zipfile’ containing a file ‘a.txt’.
Save the above code into two files with extension .php .One for zip and another for unzip the directory. Also give the appropriate path for the directory.
Here we use XAMPP to run a local web server. Place the php files along with the directory to be zipped in C:\xampp\htdocs(XAMPP is installed in C: drive in this case).
In the browser, enter https://localhost/zip.php as the url and the file will be zipped.
After this a new zip file is created named ‘file’.
Similarly, do the same to unzip. Make sure the filename and path are matching. The text file a.txt is extracted from the zip file.
Picked
PHP
PHP Programs
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to compile & run a Java program using Command Prompt?


While many programming environments allow us to compile and run a program within the environment, we can also compile and run java programs using Command Prompt.
After successful installation of JDK in our system and set the path, we can able to compile and execute Java programs using the command prompt.
Step 1  -   Need to create a java program either in Notepad or other IDE.
Step 2  -   Need to save this java file in a folder with "Demo.java" and it can be saved in a folder.
Step 3  -   Need to compile this java file from the command prompt using JAVAC command.
Step 4  -  "Demo.java" file is successfully compiled with a generation of ".class" file.
Step 5  -   Need to execute this java file using JAVA command without ".java" extension.
Step 6  -   Able to see "Welcome to TutorialsPoint" output in the console.
class Demo{
   public static void main(String args[]){
      System.out.println("Welcome to Tutorials Point");
   }
}
Welcome to TutorialsPoint
protected access modifier in Java

Variables, methods, and constructors, which are declared protected in a superclass can be accessed only by the subclasses in other package or any class within the package of the protected members' class.
The protected access modifier cannot be applied to class and interfaces. Methods, fields can be declared protected, however methods and fields in a interface cannot be declared protected.
Protected access gives the subclass a chance to use the helper method or variable, while preventing a non-related class from trying to use it.
The following parent class uses protected access control, to allow its child class override openSpeaker() method -
class AudioPlayer {
   protected boolean openSpeaker(Speaker sp) {
      // implementation details
   }
}
class StreamingAudioPlayer {
   boolean openSpeaker(Speaker sp) {
   // implementation details
   }
}
Here, if we define openSpeaker() method as private, then it would not be accessible from any other class other than AudioPlayer. If we define it as public, then it would become accessible to all the outside world. But our intention is to expose this method to its subclass only, that’s why we have used protected modifier.
Bootstrap Collapsible panel

To create a collapsible panel in Bootstrap, use the panel-collapse class.
You can try to run the following code to create a collapsible panel
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Example</title>
      <link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet">
      <script src = "/scripts/jquery.min.js"></script>
      <script src = "/bootstrap/js/bootstrap.min.js"></script>
   </head>
   <body>
      <div class = "container">
         <h2>Tutorials</h2>
         <p>Click below...</p>
         <div class = "panel-group">
            <div class = "panel panel-default">
               <div class = "panel-heading">
                  <h4 class = "panel-title">
                     <a data-toggle = "collapse" href = "#test">Free learning content</a>
                  </h4>
               </div>
               <div id = "test" class = "panel-collapse collapse">
                  <div class = "panel-body">We provide free learning content and quizzes as well.</div>
                  <div class = "panel-footer">Copyright 2018</div>
               </div>
            </div>
         </div>
      </div>
   </body>
</html>
Get reverse order using Comparator in Java

The objects of a user defined class can be ordered using the Comparator interface in Java. The java.util.Collections.reverseOrder() method reverses the order of an element collection using a Comparator.
A program that demonstrates this is given as follows −
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
public class Demo {
   public static void main(String args[]) throws Exception {
      Comparator comparator = Collections.reverseOrder(); { "John", "Amy", "Susan", "Peter" };
      int n = str.length;
      System.out.println("The array elements are: ");
      for (int i = 0; i < n; i++) {
         System.out.println(str[i]);
      }
      Arrays.sort(str, comparator);
      System.out.println("\nThe array elements sorted in reverse order are: ");
      for (int i = 0; i < n; i++) {
         System.out.println(str[i]);
      }
   }
}
The output of the above program is as follows −
The array elements are:
John
Amy
Susan
Peter
The array elements sorted in reverse order are:
Susan
Peter
John
Amy
Now let us understand the above program.
The Comparator is created along with reverseOrder() method. Then the string array str[] is defined and then the elements are displayed using a for loop. A code snippet which demonstrates this is as follows −
Comparator comparator = Collections.reverseOrder(); { "John", "Amy", "Susan", "Peter" };
int n = str.length;
System.out.println("The array elements are: ");
for (int i = 0; i < n; i++) {
System.out.println(str[i]);
}
The string array is sorted in reverse order using the java.util.Arrays.sort() method. Then the array elements are displayed using a for loop. A code snippet which demonstrates this is as follows −
Arrays.sort(str, comparator);
System.out.println("\nThe array elements sorted in reverse order are: ");
for (int i = 0; i < n; i++) {
   System.out.println(str[i]);
}
Tcl - Nested Switch Statement

It is possible to have a switch as part of the statement sequence of an outer switch. Even if the case constants of the inner and outer switch contain common values, no conflicts will arise.
The syntax for a nested switch statement is as follows −
switch switchingString {
   matchString1 {
      body1
      switch switchingString {
         matchString1 {
            body1
         }
         matchString2 {
            body2
         }
         ...
         matchStringn {
            bodyn
         }
      }
   }
   matchString2 {
      body2
   }
...
   matchStringn {
      bodyn
   }
}

#!/usr/bin/tclsh

set a 100
set b 200

switch $a {
   100 {
      puts "This is part of outer switch"
      switch $b {
         200 {
            puts "This is part of inner switch!"
         }
      }
   }   
}
puts "Exact value of a is : $a"
puts "Exact value of a is : $b"
When the above code is compiled and executed, it produces the following result −
This is part of outer switch
This is part of inner switch!
Exact value of a is : 100
Exact value of a is : 200

 Print
 Add Notes
 Bookmark this page
How can I set the 'backend' in matplotlib in Python?

We can use matplotlib.rcParams['backend'] to override the backend value.
Using get_backend() method, return the name of the current backend, i.e., default name.
Using get_backend() method, return the name of the current backend, i.e., default name.
Now override the backend name.
Now override the backend name.
Using get_backend() method, return the name of the current backend, i.e., updated name.
Using get_backend() method, return the name of the current backend, i.e., updated name.
import matplotlib
print("Before, Backend used by matplotlib is: ", matplotlib.get_backend())
matplotlib.rcParams['backend'] = 'TkAgg'
print("After, Backend used by matplotlib is: ", matplotlib.get_backend())
Before, Backend used by matplotlib is: GTK3Agg
After, Backend used by matplotlib is: TkAgg
Changing the primary key on a MongoDB collection?

To change the primary key, you need to first delete it. Use forEach() along with delete to remove and then get a new primary key. Let us create a collection with documents −
> db.demo41.insertOne({"StudentName":"Carol"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e25ce4acfb11e5c34d898e3")
}
Display all documents from a collection with the help of find() method −
> db.demo41.find();
This will produce the following output −
{ "_id" : ObjectId("5e25ce4acfb11e5c34d898e3"), "StudentName" : "Carol" }
Here is the query to change the primary key on a MongoDB collection −
> var next = db.demo41.find()
>
> next.forEach(function(s) {
...    var prevId=s._id;
...    delete s._id;
...    db.demo41.insert(s);
...    db.demo41.remove(prevId);
... });
Let us check the primary key once again −
> db.demo41.find();
This will produce the following output displaying a new primary key −
{ "_id" : ObjectId("5e25cee5cfb11e5c34d898e4"), "StudentName" : "Carol" }
SQL Tryit Editor v1.6

SELECT * FROM Customers
WHERE City IN ('Paris','London');
​
Edit the SQL Statement, and click "Run SQL" to see the result.
This SQL-Statement is not supported in the WebSQL Database.
The example still works, because it uses a modified version of SQL.
Your browser does not support WebSQL.
Your are now using a light-version of the Try-SQL Editor, with a read-only Database.
If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time.
Our Try-SQL Editor uses WebSQL to demonstrate SQL.
A Database-object is created in your browser, for testing purposes.
You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button.
WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object.
WebSQL is supported in Chrome, Safari, Opera, and Edge(79).
If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
How to get ArrayList<String> to ArrayList<Object> and vice versa in java?

Instead of the typed parameter in generics (T) you can also use “?”, representing an unknown type. These are known as wild cards you can use a wild card as − Type of parameter or, a Field or, a Local field. Using wild cards, you can convert ArrayList<String> to ArrayList<Object> as −
ArrayList<String> stringList = (ArrayList<String>)(ArrayList<?>)(list);
 Live Demo
import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;
public class ArrayListExample {
   public static void main(String args[]) {
      //Instantiating an ArrayList object
      ArrayList<Object> list = new ArrayList<Object>();
      //populating the ArrayList
      list.add("apples");
      list.add("mangoes");
      list.add("oranges");
      //Converting the Array list of object type into String type
      ArrayList<String> stringList = (ArrayList<String>)(ArrayList<?>)(list);
      //listing the contenmts of the obtained list
      Iterator<String> it = stringList.iterator();
      while(it.hasNext()) {
         System.out.println(it.next());
      }
   }
}
apples
mangoes
oranges
To convert the ArrayList<Object> to ArrayList<String> −
Create/Get an ArrayList object of String type.
Create/Get an ArrayList object of String type.
Create a new ArrayList object of Object type by passing the above obtained/created object as a parameter to its constructor.
Create a new ArrayList object of Object type by passing the above obtained/created object as a parameter to its constructor.
 Live Demo
import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;
public class ArrayListExample {
   public static void main(String args[]) {
      //Instantiating an ArrayList object
      ArrayList<String> stringList = new ArrayList<String>();
      //populating the ArrayList
      stringList.add("apples");
      stringList.add("mangoes");
      stringList.add("oranges");
      //Converting the Array list of String type to object type
      ArrayList<Object> objectList = new ArrayList<Object>(stringList);
      //listing the contents of the obtained list
      Iterator<String> it = stringList.iterator();
      while(it.hasNext()) {
         System.out.println(it.next());
      }
   }
}
apples
mangoes
oranges
Java Examples - Summation of Numbers

How to print summation of numbers ?
Following example demonstrates how to add first n natural numbers by using the concept of stack.
import java.io.IOException;

public class AdditionStack {
   static int num;
   static int ans;
   static Stack theStack;
   public static void main(String[] args)
   
   throws IOException {
      num = 50;
      stackAddition();
      System.out.println("Sum = " + ans);
   }
   public static void stackAddition() {
      theStack = new Stack(10000); 
      ans = 0; 
      while (num > 0) {
         theStack.push(num); 
         --num; 
      }
      while (!theStack.isEmpty()) {
         int newN = theStack.pop(); 
         ans += newN; 
      }
   }
}
class Stack {
   private int maxSize; 
   private int[] data;
   private int top; 
   public Stack(int s) {
      maxSize = s;
      data = new int[maxSize];
      top = -1;
   }
   public void push(int p) {
      data[++top] = p;
   }
   public int pop() {
      return data[top--];
   }
   public int peek() {
      return data[top];
   }
   public boolean isEmpty() {
      return (top == -1);
   }
}
The above code sample will produce the following result.
Sum = 1275

The following is an another example of first n natural numbers
public class Demo {
   public static void main(String[] args) {
      int sum = 0;
      int n = 50;
      for (int i = 1; i <= n; i++) {
         sum = sum + i;
      } 
      System.out.println("The Sum Of " + n + "is" + sum);
   }
}
The above code sample will produce the following result.
The Sum Of 50 is 1275

 Print
 Add Notes
 Bookmark this page
Firebase - Facebook Authentication

In this chapter, we will authenticate users with Firebase Facebook authentication.
We need to open Firebase dashboard and click Auth in side menu. Next, we need to choose SIGN-IN-METHOD in tab bar. We will enable Facebook auth and leave this open since we need to add App ID and App Secret when we finish step 2.
To enable Facebook authentication, we need to create the Facebook app. Click on this link to start. Once the app is created, we need to copy App ID and App Secret to the Firebase page, which we left open in step 1. We also need to copy OAuth Redirect URI from this window into the Facebook app. You can find + Add Product inside side menu of the Facebook app dashboard.
Choose Facebook Login and it will appear in the side menu. You will find input field Valid OAuth redirect URIs where you need to copy the OAuth Redirect URI from Firebase.
Copy the following code at the beginning of the body tag in index.html. Be sure to replace the 'APP_ID' to your app id from Facebook dashboard.
Let us consider the following example.
<script>
   window.fbAsyncInit = function() {
      FB.init ({
         appId      : 'APP_ID',
         xfbml      : true,
         version    : 'v2.6'
      });
   };

   (function(d, s, id) {
      var js, fjs = d.getElementsByTagName(s)[0];
      if (d.getElementById(id)) {return;}
      js = d.createElement(s); js.id = id;
      js.src = "//connect.facebook.net/en_US/sdk.js";
      fjs.parentNode.insertBefore(js, fjs);
   } (document, 'script', 'facebook-jssdk'));
	
</script>
We set everything in first three steps, now we can create two buttons for login and logout.
<button onclick = "facebookSignin()">Facebook Signin</button>
<button onclick = "facebookSignout()">Facebook Signout</button>
This is the last step. Open index.js and copy the following code.
var provider = new firebase.auth.FacebookAuthProvider();

function facebookSignin() {
   firebase.auth().signInWithPopup(provider)
   
   .then(function(result) {
      var token = result.credential.accessToken;
      var user = result.user;
		
      console.log(token)
      console.log(user)
   }).catch(function(error) {
      console.log(error.code);
      console.log(error.message);
   });
}

function facebookSignout() {
   firebase.auth().signOut()
   
   .then(function() {
      console.log('Signout successful!')
   }, function(error) {
      console.log('Signout failed')
   });
}

    60 Lectures 
     5 hours 

 University Code

    28 Lectures 
     2.5 hours 

 Appeteria

    85 Lectures 
     14.5 hours 

 Appeteria

    46 Lectures 
     2.5 hours 

 Gautham Vijayan

    13 Lectures 
     1.5 hours 

 Nishant Kumar

    85 Lectures 
     16.5 hours 

 Rahul Agarwal
 Print
 Add Notes
 Bookmark this page
Traversing Diagonally in a matrix in JavaScript

We are required to write a JavaScript function that takes in a square matrix (an array of arrays having the same number of rows and columns). The function should traverse diagonally through that array of array and prepare a new array of elements placed in that order it encountered while traversing.
For example, if the input to the function is −
const arr = [
   [1, 2, 3],
   [4, 5, 6],
   [7, 8, 9]
];
Then the output should be −
const output = [1, 2, 4, 7, 5, 3, 6, 8, 9];
 Live Demo
The code for this will be −
const arr = [
   [1, 2, 3],
   [4, 5, 6],
   [7, 8, 9]
];
const findDiagonalOrder = (arr = []) => {
   if(!arr.length){
      return [];
   };
   let ind = 0;
   let colBegin = 0, rowBegin = 0;
   let rowMax = arr.length, colMax = arr[0].length;
   const res = [], stack = [];
   while(rowBegin< rowMax || colBegin<colMax) {
      for(let row = rowBegin, col = colBegin; row < rowMax && col >=0 ;
      row++,col--){
         if(ind%2 === 0){
            stack.push((arr[row][col]));
         }else{
            res.push(arr[row][col]);
         };
      };
      ind++;
      while(stack.length){
         res.push(stack.pop());
      };
      colBegin++
      if(colBegin> colMax-1 && rowBegin < rowMax){
         colBegin = colMax-1
         rowBegin++
      }
   };
   return res
};
console.log(findDiagonalOrder(arr));
The steps we took are −
Traversed in one direction keeping track of starting point.
Traversed in one direction keeping track of starting point.
If index is even, we'll push to a stack and pop once it reaches end of diagonal, adding popped to our output array.
If index is even, we'll push to a stack and pop once it reaches end of diagonal, adding popped to our output array.
We keep incrementing index as we move to next diagonal.
We keep incrementing index as we move to next diagonal.
We increment column begin index until it reaches end, as it for the next iterations it will be stopped at last index and we'll be incrementing row begin index moving from this point.
We increment column begin index until it reaches end, as it for the next iterations it will be stopped at last index and we'll be incrementing row begin index moving from this point.
And the output in the console will be −
[
   1, 2, 4, 7, 5,
   3, 6, 8, 9
]
Python - tensorflow.executing_eagerly() - GeeksforGeeks

10 Jul, 2020
TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning  neural networks. 
executing_eagerly() is used check if eager execution is enabled or disabled in current thread. By default eager execution is enabled so in most cases it will return true. This will return false in following cases:
If it is executing inside tensorflow.function and tf.init_scope or tf.config.experimental_run_functions_eagerly(True)  is not called previously.
Executing inside a transformation function for tensorflow.dataset.
tensorflow.compat.v1.disable_eager_execution() is called.
Syntax: tensorflow.executing_eagerly()
Parameters: This doesn’t accept any parameters.
Returns: It returns true is eager execution is enabled otherwise it will return false.
Example 1:
Python3
# Importing the libraryimport tensorflow as tf  # Checking eager executionres = tf.executing_eagerly()  # Printing the resultprint('res: ', res)
Output:
res:  True

Example 2: This example checks eager execution for tensorflow.function with and without init_scope.
Python3
# Importing the libraryimport tensorflow as tf  @tf.functiondef gfg():  with tf.init_scope():    # Checking eager execution inside init_scope    res = tf.executing_eagerly()    print("res 1:", res)    # Checking eager execution outside init_scope  res = tf.executing_eagerly()  print("res 2:", res)gfg()
Output:
res 1: True
res 2: False



Python-Tensorflow
Tensorflow
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Reading and Writing to text files in Python
sum() function in Python
C library function - rename()

The C library function int rename(const char *old_filename, const char *new_filename) causes the filename referred to by old_filename to be changed to new_filename.
Following is the declaration for rename() function.
int rename(const char *old_filename, const char *new_filename)
old_filename − This is the C string containing the name of the file to be renamed and/or moved.
old_filename − This is the C string containing the name of the file to be renamed and/or moved.
new_filename − This is the C string containing the new name for the file.
new_filename − This is the C string containing the new name for the file.
On success, zero is returned. On error, -1 is returned, and errno is set appropriately.
The following example shows the usage of rename() function.
#include <stdio.h>

int main () {
   int ret;
   char oldname[] = "file.txt";
   char newname[] = "newfile.txt";
   
   ret = rename(oldname, newname);
	
   if(ret == 0) {
      printf("File renamed successfully");
   } else {
      printf("Error: unable to rename the file");
   }
   
   return(0);
}
Let us assume we have a text file file.txt, having some content. So, we are going to rename this file, using the above program. Let us compile and run the above program to produce the following message and the file will be renamed to newfile.txt file.
File renamed successfully


    12 Lectures 
     2 hours 

 Nishant Malik

    12 Lectures 
     2.5 hours 

 Nishant Malik

    48 Lectures 
     6.5 hours 

 Asif Hussain

    12 Lectures 
     2 hours 

 Richa Maheshwari

    20 Lectures 
     3.5 hours 

 Vandana Annavaram

    44 Lectures 
     1 hours 

 Amit Diwan
 Print
 Add Notes
 Bookmark this page
C++ Algorithm Library - find() Function

The C++ function std::algorithm::find() finds the first occurrence of the element. It uses operator = for comparison.
Following is the declaration for std::algorithm::find() function form std::algorithm header.
template <class InputIterator, class T>
InputIterator find (InputIterator first, InputIterator last, const T& val);

first − Input iterator to the initial position.
first − Input iterator to the initial position.
last − Input iterator to the final position.
last − Input iterator to the final position.
val − Value to compare the elements.
val − Value to compare the elements.
If element found it returns an iterator pointing to the first occurrence of the element otherwise returns last.
Throws exception if either element comparison or an operation on an iterator throws exception.
Please note that invalid parameters cause undefined behavior.
Linear.
The following example shows the usage of std::algorithm::find() function.
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main(void) {
   int val = 5;
   vector<int> v = {1, 2, 3, 4, 5};

   auto result = find(v.begin(), v.end(), val);

   if (result != end(v))
      cout << "Vector contains element " << val << endl;

   val = 15;

   result = find(v.begin(), v.end(), val);

   if (result == end(v))
      cout << "Vector doesn't contain element " << val << endl;

   return 0;
}
Let us compile and run the above program, this will produce the following result −
Vector contains element 5
Vector doesn't contain element 15

 Print
 Add Notes
 Bookmark this page
Laravel - Encryption

Encryption is a process of converting a plain text to a message using some algorithms such that any third user cannot read the information. This is helpful for transmitting sensitive information because there are fewer chances for an intruder to target the information transferred.
Encryption is performed using a process called Cryptography. The text which is to be encrypted is termed as Plain Text and the text or the message obtained after the encryption is called Cipher Text. The process of converting cipher text to plain text is called Decryption.
Laravel uses AES-256 and AES-128 encrypter, which uses Open SSL for encryption. All the values included in Laravel are signed using the protocol Message Authentication Code so that the underlying value cannot be tampered with once it is encrypted.
The command used to generate the key in Laravel is shown below −
php artisan key:generate

Please note that this command uses the PHP secure random bytes’ generator and you can see the output as shown in the screenshot given below −
The command given above helps in generating the key which can be used in web application. Observe the screenshot shown below −
The values for encryption are properly aligned in the config/app.php file, which includes two parameters for encryption namely key and cipher. If the value using this key is not properly aligned, all the values encrypted in Laravel will be insecure.
Encryption of a value can be done by using the encrypt helper in the controllers of Laravel class. These values are encrypted using OpenSSL and AES-256 cipher. All the encrypted values are signed with Message Authentication code (MAC) to check for any modifications of the encrypted string.
The code shown below is mentioned in a controller and is used to store a secret or a sensitive message.
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class DemoController extends Controller{
   **
      * Store a secret message for the user.
      *
      * @param Request $request
      * @param int $id
      * @return Response
   */
   
   public function storeSecret(Request $request, $id) {
      $user = User::findOrFail($id);
      $user->fill([
         'secret' => encrypt($request->secret)
      ])->save();
   }
}
Decryption of the values is done with the decrypt helper. Observe the following lines of code −
use Illuminate\Contracts\Encryption\DecryptException;

// Exception for decryption thrown in facade
try {
   $decrypted = decrypt($encryptedValue);
} catch (DecryptException $e) {
   //
}
Please note that if the process of decryption is not successful because of invalid MAC being used, then an appropriate exception is thrown.

    13 Lectures 
     3 hours 

 Sebastian Sulinski

    35 Lectures 
     3.5 hours 

 Antonio Papa

    7 Lectures 
     1.5 hours 

 Sebastian Sulinski

    42 Lectures 
     1 hours 

 Skillbakerystudios

    165 Lectures 
     13 hours 

 Paul Carlo Tordecilla

    116 Lectures 
     13 hours 

 Hafizullah Masoudi
 Print
 Add Notes
 Bookmark this page
Apache Pig - PigStorage()

The PigStorage() function loads and stores data as structured text files. It takes a delimiter using which each entity of a tuple is separated as a parameter. By default, it takes ‘\t’ as a parameter.
Given below is the syntax of the PigStorage() function.
grunt> PigStorage(field_delimiter)

Let us suppose we have a file named student_data.txt in the HDFS directory named /data/ with the following content.
001,Rajiv,Reddy,9848022337,Hyderabad
002,siddarth,Battacharya,9848022338,Kolkata 
003,Rajesh,Khanna,9848022339,Delhi  
004,Preethi,Agarwal,9848022330,Pune 
005,Trupthi,Mohanthy,9848022336,Bhuwaneshwar
006,Archana,Mishra,9848022335,Chennai.

We can load the data using the PigStorage function as shown below.
grunt> student = LOAD 'hdfs://localhost:9000/pig_data/student_data.txt' USING PigStorage(',')
   as ( id:int, firstname:chararray, lastname:chararray, phone:chararray, city:chararray );
In the above example, we have seen that we have used comma (‘,’) delimiter. Therefore, we have separated the values of a record using (,).
In the same way, we can use the PigStorage() function to store the data in to HDFS directory as shown below.
grunt> STORE student INTO ' hdfs://localhost:9000/pig_Output/ ' USING PigStorage (',');
This will store the data into the given directory. You can verify the data as shown below.
You can verify the stored data as shown below. First of all, list out the files in the directory named pig_output using ls command as shown below.
$ hdfs dfs -ls 'hdfs://localhost:9000/pig_Output/'
 
Found 2 items 
rw-r--r- 1 Hadoop supergroup 0 2015-10-05 13:03 hdfs://localhost:9000/pig_Output/_SUCCESS
 
rw-r--r- 1 Hadoop supergroup 224 2015-10-05 13:03 hdfs://localhost:9000/pig_Output/part-m-00000


You can observe that two files were created after executing the Store statement.
Then, using the cat command, list the contents of the file named part-m-00000 as shown below.
$ hdfs dfs -cat 'hdfs://localhost:9000/pig_Output/part-m-00000'
  
1,Rajiv,Reddy,9848022337,Hyderabad  
2,siddarth,Battacharya,9848022338,Kolkata  
3,Rajesh,Khanna,9848022339,Delhi  
4,Preethi,Agarwal,9848022330,Pune  
5,Trupthi,Mohanthy,9848022336,Bhuwaneshwar 
6,Archana,Mishra,9848022335,Chennai


    46 Lectures 
     3.5 hours 

 Arnab Chakraborty

    23 Lectures 
     1.5 hours 

 Mukund Kumar Mishra

    16 Lectures 
     1 hours 

 Nilay Mehta

    52 Lectures 
     1.5 hours 

 Bigdata Engineer

    14 Lectures 
     1 hours 

 Bigdata Engineer

    23 Lectures 
     1 hours 

 Bigdata Engineer
 Print
 Add Notes
 Bookmark this page
HTML /XHTML  Standard Fonts

Fonts are specific to platform. If you are using different OS then you will have different look and feel of any web page. Here we are giving a list of fonts which are available to various operating systems.
HTML <FONT> tag is deprecated in version 4.0 onwards and now all fonts are set by using CSS. Here is the simple syntax of setting font of a body of web page.
body { font-family: "new century schoolbook"; }

or

<body style = "font-family:new century schoolbook;" >
You can have more information on Microsoft Fonts at http://www.microsoft.com/typography/fonts.
You can check example fonts here − Microsoft Fonts Examples
Following is the list of fonts supported by Macintosh System 7 and higher versions
You can check example fonts here − Mac Fonts Examples
Following is the list of fonts supported by most Unix System variants
You can check example fonts here −Unix Fonts Examples

    19 Lectures 
     2 hours 

 Anadi Sharma

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    18 Lectures 
     1.5 hours 

 Frahaan Hussain

    57 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)

    54 Lectures 
     6 hours 

 DigiFisk (Programming Is Fun)

    45 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)
 Print
 Add Notes
 Bookmark this page
5 Ways to Keep Your Ubuntu System Clean - GeeksforGeeks

19 Feb, 2020
Linux has it’s own data management system that cleans your computer under the belt but still, sometimes we need to know how to manually initiate disk cleaning and control processes to enhance your computer’s performance. Below are 5 ways to keep the ubuntu system clean.
1. Uninstalling and Removing Unnecessary Applications: To uninstall the application you can you simple command.
$ sudo apt remove [application name..]..
Press “Y” and Enter. If you don’t want to use the command line, you can use the Ubuntu Software manager. Just click on the remove button and the application will be removed.
2. Removing Unnecessary Packages and Dependencies: After removing certain apps and packages some data is left which needs to be clean for that just use command.
$ sudo apt autoremove
3. Removing Old Kernels From System: To list all kernels you can use the command
$ sudo dpkg --list 'linux-image*'
And you can remove any of this kernel by command
$ sudo apt-get remove linux-image-VERSION
Choose any version you want to remove and press Enter.
4. Cleaning Apt Cache: APT generates a cache of install apps and keeps them in your /var/cache/apt/archives directory even after those apps have been uninstalled. To check the amount of apt-cache on your system with the command.
$ sudo du -sh /var/cache/apt
To remove this cache use
$ sudo apt-get clean
and this will clean the APT cache.
5. Cleaning Thumbnail Cache from System: To check the size of Cache in the system you can use command.
$ du -sh ~/.cache/thumbnails
To clean this cache you can use the command
$ sudo rm -rf ~/.cache/thumbnails/* 
Technical Scripter 2019
Linux-Unix
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
tar command in Linux with examples
curl command in Linux with Examples
Conditional Statements | Shell Script
'crontab' in Linux with Examples
Tail command in Linux with examples
UDP Server-Client implementation in C
diff command in Linux with examples
Cat command in Linux with examples
touch command in Linux with Examples
Sum of prime numbers between a range - JavaScript

We are required to write a JavaScript function that takes in two numbers, say a and b and returns the sum of all the prime numbers that fall between a and b. We should include a and b if they are prime as well.
Following is the code −
const num1 = 45;
const num2 = 345;
const isPrime = n => {
   if (n===1){
      return false;
   }else if(n === 2){
      return true;
   }else{
      for(let x = 2; x < n; x++){
         if(n % x === 0){
            return false;
         }
      }
      return true;
   };
};
const primeBetween = (a, b) => {
   const res = [];
   while(a <= b){
      if(isPrime(a)){
         res.push(a);
      };
      a++;
   };
   return res;
};
console.log(primeBetween(num1, num2));
Following is the output in the console −
[
    47,  53,  59,  61,  67,  71,  73,  79,  83,
    89,  97, 101, 103, 107, 109, 113, 127, 131,
   137, 139, 149, 151, 157, 163, 167, 173, 179,
   181, 191, 193, 197, 199, 211, 223, 227, 229,
   233, 239, 241, 251, 257, 263, 269, 271, 277,
   281, 283, 293, 307, 311, 313, 317, 331, 337
]