code-rag-bench/online-tutorials huggingface dataset:
Python | Set 6 (Command Line and Variable Arguments) - GeeksforGeeks

25 Jan, 2022
Previous Python Articles (Set 1 | Set 2 | Set 3 | Set 4 | Set 5) This article is focused on command line arguments as well as variable arguments (args and kwargs) for the functions in python. 
Till now, we have taken input in python using raw_input() or input() [for integers]. There is another method that uses command line arguments. The command line arguments must be given whenever we want to give the input before the start of the script, while on the other hand, raw_input() is used to get the input while the python program / script is running.For example, in the UNIX environment, the arguments ‘-a’ and ‘-l’ for the ‘ls’ command give different results.The command line arguments in python can be processed by using either ‘sys’ module or ‘argparse’ module.  
Python3
# Python code to demonstrate the use of 'sys' module# for command line arguments import sys # command line arguments are stored in the form# of list in sys.argvargumentList = sys.argvprint (argumentList) # Print the name of fileprint (sys.argv[0])
OUTPUT :  
['program1.py']
program1.py
NOTE : The above code runs only on command line. We need to fire the below command given that the program is saved as program1.py python program1.py test 123 
Please note the following points about the above program :  
The sys.argv takes the command line arguments in the form of a list.
The first element in the list is the name of the file.
The arguments always come in the form of a string even if we type an integer in the argument list. We need to use int() function to convert the string to integer.
amartyaniel20
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Enumerate() in Python
Python Dictionary
Defaultdict in Python
sum() function in Python
Python String | replace()
Read a file line by line in Python
How to Install PIP on Windows ?
Deque in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
How to find inverse log transformation in R ? - GeeksforGeeks

21 Apr, 2021
A logarithm of a given number n is the exponent to which another number which is been fixed, the base b, must be raised, to produce that number n. In layman terms the logarithm counts the number of occurrences of the same factor in repeated multiplication.  A logarithmic function is represented as:
f(x) = log b (x)
When the base b of the logarithm equals 10, we generally don’t mention it, i.e. f(x) = log (x). The inverse of a log or exponential function is given by :
In general case,  
y = log b (x)  ⇐⇒  b y = x
For natural log: 
y = ln (x)    ⇐⇒   e y = x
let us look at some examples for better understanding:
Example 1: if y = ln (544) = 6.298949
                       antilog ( y ) = e y = 544
Example 2: if y = log (544) = 2.735598
                       antilog ( y ) = 10 y = 544
An inverse log transformation in the R programming language can be exp(x) and expm1(x) functions. exp( ) function simply computes the exponential function, whereas the expm1( ) function computes exp(x) – 1 accurately also for |x| << 1. Here x must be a numeric or complex vector and base must be positive.
Syntax:
 exp ( x )
Where, x is a numeric value.
Example:
R
exp (100) exp (9867528) exp (0)exp (1.7865)
Output:
[1] 2.688117e+43      # exp (100)
[1] Inf               # exp (9867528)
[1] 1                 # exp (0)
[1] 5.968526          # exp (1.7865)
For bigger numbers, it generally returns “Inf” which means infinity.
Syntax:
 expm1 ( x ) = exp (x) – 1
Where, x is a numeric value.
Example:
R
expm1 (100)expm1 (9867528)expm1 (0)expm1 (1.7865)
Output:
[1] 2.688117e+43      # expm1 (100)
[1] Inf               # expm1 (9867528)
[1] 0                 # expm1 (0)
[1] 4.968526          # expm1 (1.7865)
For large numeric values exp( ) and expm1( ) functions return the same values.
Example :
R
# calculate logarithmic of a numbery = log(544, base = exp(1))print(y)  # calculate its inverse log# using exp( ) function. antilog_y1 = exp (y)print(antilog_y1)  # calculate its inverse log# using expm1( ) function. antilog_y2 = expm1 (y)print(antilog_y2)
Output:
[1] 6.298949               # print(y)
[1] 544                    # print(antilog_y1)
[1] 543                    # print(antilog_y2)
Picked
R Math-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to import an Excel File into R ?
How to filter R DataFrame by values in a column?
Time Series Analysis in R
R - if statement
Logistic Regression in R Programming
Python - Key with all Characters in String - GeeksforGeeks

08 May, 2020
Sometimes, while working with Python Strings, we can have problem in which we need to extract all the keys that have all the characters in the character value list. This kind of problem has application has many domains such as day-day programming. Let’s discuss a way in which this problem can be solved.
Method : Using all() + dictionary comprehensionThe combination of above functionalities can be used to solve this problem. In this, we use all() to perform check in whole of dictionary and extraction of items using items().
# Python3 code to demonstrate working of # Key with all Characters in String# Using all() + dictionary comprehension  # initializing dictionarytest_dict = { 'gfg' : ['a', 'b', 'c', 'd', 'g'],              'is' : ['b', 'f', 'e'],              'best' : ['c', 'd', 'g'],              'for' : ['n', 'z'],              'CS' : ['g', 'd'] }  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # initializing keys test_str = 'gd'  # Key with all Characters in String# Using all() + dictionary comprehensionres = list({key for key, val in test_dict.items()             if all(chr in val for chr in test_str)})  # printing result print("The keys list : " + str(res)) 
The original dictionary is : {‘is’: [‘b’, ‘f’, ‘e’], ‘best’: [‘c’, ‘d’, ‘g’], ‘for’: [‘n’, ‘z’], ‘CS’: [‘g’, ‘d’], ‘gfg’: [‘a’, ‘b’, ‘c’, ‘d’, ‘g’]}The keys list : [‘best’, ‘CS’, ‘gfg’]
Python dictionary-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 ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
Cauchy's Mean Value Theorem - GeeksforGeeks

15 Apr, 2018
Suppose f(x) and g(x) are 2 functions satisfying three conditions:
1) f(x), g(x) are continuous in the closed interval a <= x <= b
2) f(x), g(x) are differentiable in the open interval a < x < b and
3) g'(x) != 0 for all x belongs to the open interval a < x < b
Then according to Cauchy’s Mean Value Theorem there exists a point c in the open interval a < c < b such that:
The conditions (1) and (2) are exactly same as the first two conditions of Lagranges Mean Value Theorem for the functions individually. Lagranges mean value theorem is defined for one function but this is defined for two functions.
Engineering Mathematics
GATE CS
GFacts
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Inequalities in LaTeX
Activation Functions
Arrow Symbols in LaTeX
Newton's Divided Difference Interpolation Formula
Set Notations in LaTeX
Layers of OSI Model
ACID Properties in DBMS
TCP/IP Model
Types of Operating Systems
Normal Forms in DBMS
filepath.Ext() Function in Golang With Examples - GeeksforGeeks

10 May, 2020
In Go language, path package used for paths separated by forwarding slashes, such as the paths in URLs. The filepath.Ext() function in Go language used to return the file name extension used by the specified path. The extension is the suffix beginning at the final dot in the final element of path; it is empty if there is no dot. Moreover, this function is defined under the path package. Here, you need to import the “path/filepath” package in order to use these functions.
Syntax:
func Ext(path string) string

Here, ‘path’ is the specified path.
Return Value: It returns the file name extension used by the specified path.
Example 1:
// Golang program to illustrate the usage of// filepath.Ext() function  // Including the main packagepackage main  // Importing fmt and path/filepathimport (    "fmt"    "path/filepath")  // Calling mainfunc main() {      // Calling the Ext() function    fmt.Println(filepath.Ext("gfg.org"))    fmt.Println(filepath.Ext("GeeksforGeeks."))    fmt.Println(filepath.Ext(".org"))      }
Output:
.org
.
.org

Example 2:
// Golang program to illustrate the usage of// filepath.Ext() function  // Including the main packagepackage main  // Importing fmt and path/filepathimport (    "fmt"    "path/filepath")  // Calling mainfunc main() {      // Calling the Ext() function    fmt.Println(filepath.Ext("a.b"))    fmt.Println(filepath.Ext("gfg"))    fmt.Println(filepath.Ext("ide.gfg.org"))    fmt.Println(filepath.Ext(".ab.cd"))      }
Output:
.b

.org
.cd

Golang-filepath
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
6 Best Books to Learn Go Programming Language
How to Parse JSON in Golang?
Strings in Golang
Time Durations in Golang
Structures in Golang
How to iterate over an Array using for loop in Golang?
Rune in Golang
Loops in Go Language
Defer Keyword in Golang
Class and Object in Golang
GATE | GATE CS 2020 | Question 56 - GeeksforGeeks

11 Aug, 2021
Consider the following C functions.
int fun1(int n) {    static int i= 0;    if (n > 0) {       ++i;      fun1(n-1);   }  return (i);}int fun2(int n) {   static int i= 0;   if (n>0) {      i = i+ fun1 (n) ;      fun2(n-1) ;  }return (i);}
The return value of fun2(5) is ________ .
Note – This question was Numerical Type.(A) 55(B) 45(C) 50(D) 52Answer: (A)Explanation: fun1() adds its previous value because of ‘static variable‘.Therefore, it prints 55.
#include <stdio.h>   int fun1(int n);int fun2(int n);  int fun1(int n) {    static int i= 0;    if (n > 0) {       ++i;      fun1(n-1);   }  return (i);}int fun2(int n) {   static int i= 0;   if (n>0) {      i = i+ fun1 (n) ;      fun2(n-1) ;  }return (i);}  int main()  {        printf("%d", fun2(5));   return 0;  } 
Code – https://ide.geeksforgeeks.org/RAcxRv1gaA
Option (A) is correct.
YouTubeGeeksforGeeks GATE Computer Science16.1K subscribersGATE PYQs 2019 and 2020 | Programming and Data Structures | Shubham Agrawal | GeeksforGeeks GATE CSEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:001:07:53 / 1:16:33•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=fP8QED8d6ws" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-IT-2004 | Question 66
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 2010 | Question 24
GATE | GATE CS 2011 | Question 7
GATE | GATE-IT-2004 | Question 71
GATE | GATE-CS-2004 | Question 3
GATE | GATE CS 2019 | Question 27
GATE | GATE CS 2012 | Question 54
GATE | GATE-CS-2016 (Set 1) | Question 65
Fibonacci Series in C#

To find Fibonaccli series, firsty set the first two number in the series as 0 and 1.
int val1 = 0, val2 = 1, v
Now loop through 2 to n and find the fibonai series. Every number in the series is the sum of the last 2 elements −
for(i=2;i<n;++i) {
   val3 = val1 + val2;
   Console.Write(val3+" ");
   val1 = val2;
   val2 = val3;
}
The following is the complete code to display Fibonacci series in C# −
 Live Demo
using System;
public class Demo {
   public static void Main(string[] args) {
      int val1 = 0, val2 = 1, val3, i, n;
      n = 7;
      Console.WriteLine("Fibonacci series:");
      Console.Write(val1+" "+val2+" ");
      for(i=2;i<n;++i) {
         val3 = val1 + val2;
         Console.Write(val3+" ");
         val1 = val2;
         val2 = val3;
      }
   }
}
Fibonacci series:
0 1 1 2 3 5 8
How to create spinner Programmatically from array in Android?

This example demonstrates how do I create spinner programmatically from array in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity">
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerHorizontal="true"
      android:layout_marginBottom="30dp"
      android:layout_above="@id/spinner"
      android:text="Spinner from Array in Android"
      android:textSize="16sp"
      android:textStyle="bold"/>
   <Spinner
      android:id="@+id/spinner"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerInParent="true">
   </Spinner>
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
public class MainActivity extends AppCompatActivity {
   Spinner spinner;
   String colors[] = {"Red","Blue","White","Yellow","Black", "Green","Purple","Orange","Grey"};
   ArrayAdapter<String> spinnerArrayAdapter;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      spinner = findViewById(R.id.spinner);
      spinnerArrayAdapter = new ArrayAdapter<>(this,
      android.R.layout.simple_spinner_dropdown_item, colors);
      spinner.setAdapter(spinnerArrayAdapter);
   }
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
Click here to download the project code.
JavaScript - Page Printing

Many times you would like to place a button on your webpage to print the content of that web page via an actual printer. JavaScript helps you to implement this functionality using the print function of window object.
The JavaScript print function window.print() prints the current web page when executed. You can call this function directly using the onclick event as shown in the following example.
Try the following example.
<html>
   <head>      
      <script type = "text/javascript">
         <!--
         //-->
      </script>
   </head>
   
   <body>      
      <form>
         <input type = "button" value = "Print" onclick = "window.print()" />
      </form>   
   </body>
<html>
Although it serves the purpose of getting a printout, it is not a recommended way. A printer friendly page is really just a page with text, no images, graphics, or advertising.
You can make a page printer friendly in the following ways −
Make a copy of the page and leave out unwanted text and graphics, then link to that printer friendly page from the original. Check Example.
Make a copy of the page and leave out unwanted text and graphics, then link to that printer friendly page from the original. Check Example.
If you do not want to keep an extra copy of a page, then you can mark your printable text using proper comments like <!-- PRINT STARTS HERE -->..... <!-- PRINT ENDS HERE --> and then you can use PERL or any other script in the background to purge printable text and display for final printing. We at Tutorialspoint use this method to provide print facility to our site visitors. 

If you do not want to keep an extra copy of a page, then you can mark your printable text using proper comments like <!-- PRINT STARTS HERE -->..... <!-- PRINT ENDS HERE --> and then you can use PERL or any other script in the background to purge printable text and display for final printing. We at Tutorialspoint use this method to provide print facility to our site visitors. 
If you don’t find the above facilities on a web page, then you can use the browser's standard toolbar to get print the web page. Follow the link as follows.
File →  Print → Click OK  button.


    25 Lectures 
     2.5 hours 

 Anadi Sharma

    74 Lectures 
     10 hours 

 Lets Kode It

    72 Lectures 
     4.5 hours 

 Frahaan Hussain

    70 Lectures 
     4.5 hours 

 Frahaan Hussain

    46 Lectures 
     6 hours 

 Eduonix Learning Solutions

    88 Lectures 
     14 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page
How to define variables in C#?

Each variable in C# has a specific type, which determines the size and layout of the variable's memory the range of values that can be stored within that memory and the set of operations that can be applied to the variable.
For variables −
<data_type> <variable_list>;

Let us see an example −
int x, y;

Above the variable is of int type. Let us declare a variable for other types.
Variable of float type −
float z;

Variable of short type −
short p;
Check for an element in a HashSet in Java

To check whether an element is in a HashSet or not in Java, use the contains() method.
Create a HashSet −
HashSet hs = new HashSet();
Add elements to it −
hs.add("R");
hs.add("S");
hs.add("T");
hs.add("V");
hs.add("W");
hs.add("Y");
hs.add("Z");
To check for an element, for example, S here, use the contains() −
hs.contains("S")
The following is an example to check for an element in a HashSet −
 Live Demo
import java.util.*;
public class Demo {
   public static void main(String args[]) {
      HashSet hs = new HashSet();
      // add elements to the HashSet
      hs.add("R");
      hs.add("S");
      hs.add("T");
      hs.add("V");
      hs.add("W");
      hs.add("Y");
      hs.add("Z");
      System.out.println("Set = "+hs);
      System.out.println("Is character S part of the set? "+hs.contains("S"));
      System.out.println("Is character B part of the set? "+hs.contains("B"));
   }
}
Set = [R, S, T, V, W, Y, Z]
Is character S part of the set? true
Is character B part of the set? false
Encoding string to reduce its size in JavaScript

We are required to write a JavaScript function that takes in a string of characters, str, as the only argument. Our function should encode the input string and compare its size with the original string and return the string which is smaller in size.
The rule to encode a particular string is −
n[s], where the s inside the square brackets is being repeated exactly k times.
n[s], where the s inside the square brackets is being repeated exactly k times.
For instance, ddd can be encoded to 3[d] but 3[d] has a length of 4 whereas ddd is only 3 characters long so our function should eventually return ddd.
For example, if the input to the function is −
const str = 'aabcaabcd';
Then the output should be −
const output = '2[aabc]d';
The code for this will be −
 Live Demo
const str = 'aabcaabcd';
function encode(s) {
   const { length } = s;
   const dp = Array(length).fill([]);
   dp.forEach((el, ind) => {
      dp[ind] = Array(length).fill(null);
   });
   for(let l = 1; l <= length; l++){
      for(let i = 0; i + l <= length; i++){
         let j = i + l - 1;
         dp[i][j] = s.substring(i, j + 1);
         for (let k = i; k < j ; k ++) {
            let acc = dp[i][k] + dp[k + 1][j];
            if (acc.length < dp[i][j].length) {
               dp[i][j] = acc;
            }
         }
         let sub = s.substring(i, j + 1);
         let double = sub + sub;
         let cut = double.indexOf(sub, 1);
         if (cut != -1 && cut < sub.length) {
            let acc = sub.length / cut + "[" + dp[i][i + cut - 1] +"]";
            if (acc.length < dp[i][j].length) {
               dp[i][j] = acc;
            }
         }
      }
   }
   let res = dp[0][dp.length - 1];
   return res;
}
console.log(encode(str));
And the output in the console will be −
2[aabc]d
C Program Coin Change - GeeksforGeeks

14 May, 2021
Given a value N, if we want to make change for N cents, and we have infinite supply of each of S = { S1, S2, .. , Sm} valued coins, how many ways can we make the change? The order of coins doesn\’t matter.For example, for N = 4 and S = {1,2,3}, there are four solutions: {1,1,1,1},{1,1,2},{2,2},{1,3}. So output should be 4. For N = 10 and S = {2, 5, 3, 6}, there are five solutions: {2,2,2,2,2}, {2,2,3,3}, {2,2,6}, {2,3,5} and {5,5}. So the output should be 5.  
C
// C program for coin change problem.#include<stdio.h> int count( int S[], int m, int n ){    int i, j, x, y;     // We need n+1 rows as the table is constructed    // in bottom up manner using the base case 0    // value case (n = 0)    int table[n+1][m];        // Fill the entries for 0 value case (n = 0)    for (i=0; i<m; i++)        table[0][i] = 1;     // Fill rest of the table entries in bottom    // up manner     for (i = 1; i < n+1; i++)    {        for (j = 0; j < m; j++)        {            // Count of solutions including S[j]            x = (i-S[j] >= 0)? table[i - S[j]][j]: 0;             // Count of solutions excluding S[j]            y = (j >= 1)? table[i][j-1]: 0;             // total count            table[i][j] = x + y;        }    }    return table[n][m-1];} // Driver program to test above functionint main(){    int arr[] = {1, 2, 3};    int m = sizeof(arr)/sizeof(arr[0]);    int n = 4;    printf(" %d ", count(arr, m, n));    return 0;}
Output:
4
Time Complexity: O(mn) Following is a simplified version of method 2. The auxiliary space required here is O(n) only. 
C
C
int count( int S[], int m, int n ){    // table[i] will be storing the number of solutions for    // value i. We need n+1 rows as the table is constructed    // in bottom up manner using the base case (n = 0)    int table[n+1];     // Initialize all table values as 0    memset(table, 0, sizeof(table));     // Base case (If given value is 0)    table[0] = 1;     // Pick all coins one by one and update the table[] values    // after the index greater than or equal to the value of the    // picked coin    for(int i=0; i<m; i++)        for(int j=S[i]; j<=n; j++)            table[j] += table[j-S[i]];     return table[n];}
Please refer complete article on Dynamic Programming | Set 7 (Coin Change) for more details!
anikakapoor
dp-coin-change
C Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C Program to read contents of Whole File
Header files in C/C++ and its uses
How to Append a Character to a String in C
Producer Consumer Problem in C
C program to sort an array in ascending order
Program to find Prime Numbers Between given Interval
time() function in C
Program to calculate First and Follow sets of given grammar
C Program to Swap two Numbers
C program to find the length of a string
React Native - HTTP

In this chapter, we will show you how to use fetch for handling network requests.
import React from 'react';
import HttpExample from './http_example.js'

const App = () => {
   return (
      <HttpExample />
   )
}
export default App
We will use the componentDidMount lifecycle method to load the data from server as soon as the component is mounted. This function will send GET request to the server, return JSON data, log output to console and update our state.
import React, { Component } from 'react'
import { View, Text } from 'react-native'

class HttpExample extends Component {
   state = {
      data: ''
   }
   componentDidMount = () => {
      fetch('https://jsonplaceholder.typicode.com/posts/1', {
         method: 'GET'
      })
      .then((response) => response.json())
      .then((responseJson) => {
         console.log(responseJson);
         this.setState({
            data: responseJson
         })
      })
      .catch((error) => {
         console.error(error);
      });
   }
   render() {
      return (
         <View>
            <Text>
               {this.state.data.body}
            </Text>
         </View>
      )
   }
}
export default HttpExample

    20 Lectures 
     1.5 hours 

 Anadi Sharma

    61 Lectures 
     6.5 hours 

 A To Z Mentor

    40 Lectures 
     4.5 hours 

 Eduonix Learning Solutions

    56 Lectures 
     12.5 hours 

 Eduonix Learning Solutions

    62 Lectures 
     4.5 hours 

 Senol Atac

    67 Lectures 
     4.5 hours 

 Senol Atac
 Print
 Add Notes
 Bookmark this page
Difference between type() and isinstance() in Python | by Eden Au | Towards Data Science

Last time we talked about 4 introspection tools in Python that every beginner should use. Check out the article below if you have not read it. The first two functions introduced were type() and isinstance().
towardsdatascience.com
A bit of recap here.
Every object in Python has a data type, a built-in one or a customised one. It can be an integer int, a string str, a NumPy array numpy.array etc.. It can also be an object of a self-defined class.
Given some object obj, type(obj) returns the data type of the object. isintance(obj, dtype) returns True if the object is an instance of dtype, or False otherwise.
So what exactly is an instance of some class?
First things first. We need to understand subclasses and inheritance. Take the following code as an example:
We define class Rectangle(Shape) as a subclass of Shape, and Square(Rectangle) as a subclass of Rectangle. Subclasses inherit methods, properties, and other functionalities of their superclasses.
We define the hierarchy in a way such that an object of class Square inherits all properties and methods of Rectangle. After all, a square is a special case of a rectangle with the same length for all sides.
If we create a Square object a with length=5, we can call get_area() method to calculate its area. Note that this method is not explicitly defined within the Square class, but is specified in its superclass, i.e. Rectangle.
a = Square(5)a.get_area() # 25
We therefore say Square(Rectangle) inherits the method get_area() from its superclass Rectangle.
you should have a basic understanding of subclasses and inheritance by now. But how is it related to type() and isinstance()? Consider the following statements regarding the Square object a. What will these two statements return? Both True? Both False?
type(a) == Rectangleisinstance(a, Rectangle)
First, we know for sure that type(a) returns Square. And class Square does not equal to class Rectangle. So the first statement returns False.
Square == Rectangle # returns False
However, the second statement will return True! Because Square is a subclass of Rectangle, and therefore the object a is an instance of Rectangle.
An instance of a subclass is also an instance of a base class.
To conclude, isinstance() considers inheritance, but checking the type() of an object using equality (==) statement does not.
A subclass does not equal to its base class.
Thanks for reading! You can sign up for my newsletter to receive updates on my new articles. If you are interested in improving your Python skills, the following articles might be useful:
Group values in array by two properties JavaScript

We have an array of objects like this −
const arr = [
   { value: 12, gap: 1 },
   { value: 13, gap: 1 },
   { value: 14, gap: 1 },
   { value: 15, gap: 1 },
   { value: 19, gap: 2 },
   { value: 21, gap: 1 },
   { value: 22, gap: 1 },
   { value: 23, gap: 1 },
   { value: 27, gap: 1 },
   { value: 31, gap: 4 },
   { value: 35, gap: 4 },
   { value: 39, gap: 4 },
   { value: 43, gap: 1 },
   { value: 50, gap: 1 },
   { value: 51, gap: 1 },
   { value: 52, gap: 1 },
   { value: 55, gap: 1 },
   { value: 57, gap: 1 },
];
We are required to write a function that takes in this array and returns a new array where all
those consecutive objects whose value is equal to the sum of previous object’s value and gap
must be grouped together in a subarray.
For example − The object with value 12 has gap 1 and its next object has value 13, so they must
be grouped and with them the object with value 14 and 15, and like this.
Now, with the problem understood, let’s move on to writing the code for this problem. We will
use Array.prototype.reduce() method to construct the desired array −
const arr = [
   { value: 12, gap: 1 },
   { value: 13, gap: 1 },
   { value: 14, gap: 1 },
   { value: 15, gap: 1 },
   { value: 19, gap: 2 },
   { value: 21, gap: 1 },
   { value: 22, gap: 1 },
   { value: 23, gap: 1 },
   { value: 27, gap: 1 },
   { value: 31, gap: 4 },
   { value: 35, gap: 4 },
   { value: 39, gap: 4 },
   { value: 43, gap: 1 },
   { value: 50, gap: 1 },
   { value: 51, gap: 1 },
   { value: 52, gap: 1 },
   { value: 55, gap: 1 },
   { value: 57, gap: 1 },
];
const groupArray = arr => {
   return arr.reduce((acc, val, ind, array) => {
      // the accumulated data and lastIndex of accumulated data
      const { data, currentIndex } = acc;
      // the current object properties
      const { value, gap } = val;
      // the previous object properties
      const v = arr[ind-1]?.value;
      const g = arr[ind-1]?.gap;
      if(ind === 0 || value !== v + g){
         // recording the index of last object and pushing new subarray
         const index = data.push([val]) - 1;
         return { data, currentIndex: index };
      };
      data[currentIndex].push(val);
      return { data, currentIndex };
   }, {
      data: [],
      currentIndex: 0
   }).data;
}
console.log(groupArray(arr));
The output in the console will be −
[
   [
      { value: 12, gap: 1 },
      { value: 13, gap: 1 },
      { value: 14, gap: 1 },
      { value: 15, gap: 1 }
   ],
   [
      { value: 19, gap: 2 },
      { value: 21, gap: 1 },
      { value: 22, gap: 1 },
      { value: 23, gap: 1 }
   ],
   [ { value: 27, gap: 1 } ],
   [
      { value: 31, gap: 4 },
      { value: 35, gap: 4 },
      { value: 39, gap: 4 },
      { value: 43, gap: 1 }
   ],
   [
      { value: 50, gap: 1 },
      { value: 51, gap: 1 },
      { value: 52, gap: 1 }
   ],
      [ { value: 55, gap: 1 } ],
      [ { value: 57, gap: 1 } ]
]
How to disable/enable an input box with jQuery?

We can easily disable input box(textbox,textarea) using disable attribute to “disabled”.
$(‘elementname’).attr(‘disabled’,’disabled’);
To enable disabled element we need to remove “disabled” attribute from this element.
$(‘elementname’).removeAttr(‘disabled’);
<html >
<head>
   <title>ed</title>
      <script src="../../Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
      <script type="text/javascript">
         $(document).ready(function () {
            $('#btn1').click(function () {
               $('input').attr('disabled', 'disabled');
            });
            $('#btn2').click(function () {
               $('input').removeAttr('disabled');
            });
         });
      </script>
   </head>
<body>
<div>
<input type="text" id="tt1" /><br />
   <button type="button" id="btn1">Disable</button>
   <button type="button" id="btn2">Enable</button>
</div>
</body>
</html>
How to schedule tasks in Java to run for repeated fixed-rate execution, beginning at the specified time

One of the methods the Timer class is void scheduleAtFixedRate(TimerTask task, Date firstTime, long period). This method schedules the specified task for repeated fixed-rate execution, beginning at the specified time.
In fixed-rate execution, each execution is scheduled with respect to the scheduled run time of the initial execution. Fixed-rate execution is apt for repetitive activities that are respond to absolute time. Likewise,fixed-rate execution is appropriate for scheduling multiple repeating timer tasks that must remain in sync.
Declaration − The java.util.Time.scheduleAtFixedRate(TimerTask task, Date firstTime, long period) method is declared as follows −
public void scheduleAtFixedRate(TimerTask task, Date firstTime, long period)
Here, task is the task to be scheduled, firstTime is the first time at which the task is executed and period is the time in milliseconds between successive task executions.
There are few exceptions thrown by the scheduleAtFixedRate(Timertask task, Date firstTime, long period) method. They are as follows −
Let us see an example showing how to schedule tasks in Java to run for repeated fixed-rate execution, beginning at the specified time −
 Live Demo
import java.util.*;
class MyTask extends TimerTask {
   public void run() {
      System.out.println("Task is running");
   }
}
public class Example {
   public static void main(String[] args) {
      Timer timer = new Timer(); // creating timer
      TimerTask task = new MyTask(); // creating timer task
      timer.scheduleAtFixedRate(task,new Date(),2000);
      // scheduling the task at the specified time at fixed-rate
   }
}
Task is running
Task is running
Task is running
Task is running
Task is running
How to display an element on hover with CSS?

To display an element on hover with CSS, the code is as follows −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
   body{
      margin:20px;
      padding:20px;
      font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
   }
   .hiddenText {
      display: none;
   }
   .hoverDiv:hover + .hiddenText {
      display: block;
      color: rgb(71, 0, 65);
      font-size: 22px;
      font-weight: bold;
   }
</style>
</head>
<body>
<h1>Display an Element on Hover Example</h1>
<div class="hoverDiv" style="font-size: 18px;">Hover over me.</div>
<div class="hiddenText">This text is shown by hovering on the above div</div>
</body>
</html>
The above code produces the following output −
On hovering over the “Hover over me” text −
Calculating average of an array in JavaScript

Following is the code for calculating average of an array in JavaScript −
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result,
   .sample {
      font-size: 18px;
      font-weight: 500;
      color: blueviolet;
   }
   .sample {
      color: red;
   }
</style>
</head>
<body>
<h1>Calculating average of an array</h1>
<div><pre class="sample"></pre></div>
<div class="result"></div>
<button class="Btn">Check</button>
<h3>Click on the above button to see document state</h3>
<script>
   let resEle = document.querySelector(".result");
   let BtnEle = document.querySelector(".Btn");
   let sampleEle = document.querySelector(".sample");
   let arr = [1, 2, 3, 4, 5, 11, 22];
   sampleEle.innerHTML = arr;
   BtnEle.addEventListener("click", () => {
      let sum = 0;
      arr.forEach((item) => (sum += item));
      resEle.innerHTML = "The average of the array = " + sum / arr.length;
   });
</script>
</body>
</html>
On clicking the ‘Calculate’ button −
MomentJS - Using Duration with Diff

This method is used to get the duration difference between two moments.
var duration = moment.duration(x.diff(y))

var d = moment.duration(moment(["2017,07,04"]).diff(moment(["2015,08,20"])));
 Print
 Add Notes
 Bookmark this page
Bokeh - Rectangle, Oval and Polygon

It is possible to render rectangle, ellipse and polygons in a Bokeh figure. The rect() method of Figure class adds a rectangle glyph based on x and y coordinates of center, width and height. The square() method on the other hand has size parameter to decide dimensions.
The ellipse() and oval() methods adds an ellipse and oval glyph. They use similar signature to that of rect() having x, y,w and h parameters. Additionally, angle parameter determines rotation from horizontal.
Following code shows use of different shape glyph methods −
from bokeh.plotting import figure, output_file, show
fig = figure(plot_width = 300, plot_height = 300)
fig.rect(x = 10,y = 10,width = 100, height = 50, width_units = 'screen', height_units = 'screen')
fig.square(x = 2,y = 3,size = 80, color = 'red')
fig.ellipse(x = 7,y = 6, width = 30, height = 10, fill_color = None, line_width = 2)
fig.oval(x = 6,y = 6,width = 2, height = 1, angle = -0.4)
show(fig)
 Print
 Add Notes
 Bookmark this page
JavaScript - length of array objects

The length property in JavaScript returns the size of the object. Following is the code for the length of string and array objects −
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .sample,
   .result {
      font-size: 18px;
      font-weight: 500;
      color: red;
   }
</style>
</head>
<body>
<h1>JavaScript length property</h1>
<div class="sample"></div>
<div style="font-weight: bold; color: black;" class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>
Click on the above button to find the length of the array
</h3>
<script>
   let sampleEle = document.querySelector(".sample");
   let resultEle = document.querySelector(".result");
   let arr = [1, 2, "A", "B", "D"];
   sampleEle.innerHTML = arr;
   document.querySelector(".Btn").addEventListener("click", () => {
      resultEle.innerHTML += "The array length is = " + arr.length;
   });
</script>
</body>
</html>
On clicking the ‘CLICK HERE’ button −
How to use indexOf () in Android textview?

This example demonstrate about How to use indexOf () in Android textview.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical"
   android:gravity="center"
   tools:context=".MainActivity">
   <EditText
      android:id="@+id/name"
      android:layout_width="match_parent"
      android:hint="Enter name"
      android:layout_height="wrap_content" />
   <Button
      android:id="@+id/click"
      android:text="Click"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content" />
   <TextView
      android:id="@+id/textview"
      android:layout_width="wrap_content"
      android:textSize="25sp"
      android:layout_height="wrap_content" />
</LinearLayout>
In the above code, we have taken name as Edit text, when user click on button it will take data and returns index of “sai”.
Step 3 − Add the following code to src/MainActivity.java
package com.example.myapplication;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
   EditText name;
   Button button;
   TextView text;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      name = findViewById(R.id.name);
      button = findViewById(R.id.click);
      text = findViewById(R.id.textview);
      button.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            if (!name.getText().toString().isEmpty()) {
               if (name.getText().toString().length() >= 0) {
                  int index = name.getText().toString().indexOf("sai");
                  text.setText(String.valueOf(index));
               }
            } else {
               name.setError("Plz enter name");
            }
         }
      });
   }
}

Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
In the above result, enter the string as “Krishna sai” and it returned index of sai as 8.
Click here to download the project code
NumPy Tutorial

NumPy is a Python library.
NumPy is used for working with arrays.
NumPy is short for "Numerical Python".
We have created 43 tutorial pages for you to learn more about NumPy.
Starting with a basic introduction and ends up with creating and plotting random data sets, and working with NumPy functions:
Test your NumPy skills with a quiz test.
Start NumPy Quiz
Insert the correct method for creating a NumPy array.
arr = np.([1, 2, 3, 4, 5])

Start the Exercise
In our "Try it Yourself" editor, you can use the NumPy module, and modify the code to see the result.
Create a NumPy array:
Click on the "Try it Yourself" button to see how it works.
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
Scala Map foreach() method with example - GeeksforGeeks

13 Aug, 2019
The foreach() method is utilized to apply the given function to all the elements of the map.
Method Definition: def foreach(f: ((A, B)) => Unit): Unit
Return Type: It returns all the elements of the map after applying the given function to each of them.
Example #1:
// Scala program of foreach()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Creating map        val m1 = Map(3 -> "geeks", 1 -> "for", 2 -> "cs", 6 -> "geeks")                  // Applying foreach method and         // displaying output         val result = m1.foreach(x => println("key=" + x._1 + ", value=" + x._2))              }}
key=3, value=geeks
key=1, value=for
key=2, value=cs
key=6, value=geeks

Example #2:
// Scala program of foreach()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Creating map        val m1 = Map(3 -> "geeks", 1 -> "for", 2 -> "cs", 3 -> "geeks")                  // Applying foreach method and         // displaying output         val result = m1.foreach(x => println("key=" + x._1 + ", value=" + x._2))              }}
key=3, value=geeks
key=1, value=for
key=2, value=cs

So, the identical elements are taken only once.
Scala
Scala-Map
Scala-Method
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Class and Object in Scala
Scala Lists
Scala Tutorial – Learn Scala with Step By Step Guide
Operators in Scala
Inheritance in Scala
Scala Constructors
Scala | Arrays
How to get the first element of List in Scala
Lambda Expression in Scala
Break statement in Scala
Node.js MySQL Delete Query - GeeksforGeeks

07 Oct, 2021
We use SQL DELETE Query to delete data with some condition from MySQL Table.
Syntax:
This will delete all rows of customers’ tables but everything else will remain as it is (indexing, etc).DELETE FROM users
DELETE FROM users
This will delete all rows of users table where userId is 2.DELETE FROM users WHERE userId = 2
DELETE FROM users WHERE userId = 2
Modules:
mysql: To handle sql connection and queriesnpm install mysql
npm install mysql
SQL users table preview:
Example 1: Delete all rows from users table
Javascript
const mysql = require("mysql");  let db_con  = mysql.createConnection({    host: "localhost",    user: "root",    password: '',    database: 'gfg_db'});  db_con.connect((err) => {    if (err) {      console.log("Database Connection Failed !!!", err);      return;    }      console.log("We are connected to gfg_db database");      // here is our query    let query = 'DELETE FROM users';      db_con.query(query, (err, rows) => {        if(err) throw err;          console.log('Cleared users Table');    });});
Output:
Example 2: Delete all users whose name = ‘pratik’.
Approach 1: Hard code the value
Javascript
const mysql = require("mysql");  let db_con  = mysql.createConnection({    host: "localhost",    user: "root",    password: '',    database: 'gfg_db'});  db_con.connect((err) => {    if (err) {      console.log("Database Connection Failed !!!", err);      return;    }      console.log("We are connected to gfg_db database");      // This is our Hard Coded Query    let query = "DELETE FROM users WHERE name = 'pratik'";      db_con.query(query, (err, rows) => {        if(err) throw err;          console.log('Number of rows deleted = ' + rows.affectedRows);    });});
Approach 2: Dynamic Query
Javascript
const mysql = require("mysql");  let db_con  = mysql.createConnection({    host: "localhost",    user: "root",    password: '',    database: 'gfg_db'});  db_con.connect((err) => {    if (err) {      console.log("Database Connection Failed !!!", err);      return;    }      console.log("We are connected to gfg_db database");      // notice the ? in below query    let query = "DELETE FROM users WHERE name = ?";          // Dynamic Value    let name = 'pratik';      // Notice the name variable below    // It will replace the ? in query    db_con.query(query, name, (err, rows) => {        if(err) throw err;          console.log('Number of rows deleted = ' + rows.affectedRows);    });});
Output:
NodeJS-MySQL
Technical Scripter 2020
Node.js
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between dependencies, devDependencies and peerDependencies
How to connect Node.js with React.js ?
Node.js Export Module
Mongoose find() Function
Mongoose Populate() Method
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript