code-rag-bench/online-tutorials huggingface dataset:
Changing the appearance of a Scrollbar in Tkinter (using ttk styles)

Scrollbars are used to wrap an amount of text or characters in a frame or window. It provides a text widget to contain as many characters as the user wants.
The Scrollbar can be of two types: Horizontal Scrollbar and Vertical Scrollbar.
The length of a scrollbar changes whenever the number of characters in the Text widget increases. We can configure the style of Scrollbar by using ttk.Scrollbar. Ttk provides many inbuilt features and attributes that can be used to configure the Scrollbar.
In this example, we will add a vertical scrollbar in a Text widget. We will use a ttk style theme to customize the look of the scrollbar. We have used here the 'classic' theme. Refer this link for a complete list ttk themes.
# Import the required libraries
from tkinter import *
from tkinter import ttk

# Create an instance of Tkinter Frame
win = Tk()

# Set the geometry of Tkinter Frame
win.geometry("700x250")

style=ttk.Style()
style.theme_use('classic')
style.configure("Vertical.TScrollbar", background="green", bordercolor="red", arrowcolor="white")

# Create a vertical scrollbar
scrollbar = ttk.Scrollbar(win, orient='vertical')
scrollbar.pack(side=RIGHT, fill=BOTH)

# Add a Text Widget
text = Text(win, width=15, height=15, wrap=CHAR,
yscrollcommand=scrollbar.set)

for i in range(1000):
   text.insert(END, i)

text.pack(side=TOP, fill=X)

# Configure the scrollbar
scrollbar.config(command=text.yview)

win.mainloop()
Running the above code will display a window with a text widget and a customized vertical Scrollbar.
Python - scipy.fft.dct() method - GeeksforGeeks

01 Oct, 2020
With the help of scipy.fft.dct() method, we can compute the discrete cosine transform by selecting different types of sequences and return the transformed array by using this method.
Syntax : 
scipy.fft.dct(x, type=2)

Return value: It will return the transformed array.
Example #1: In this example, we can see that by using scipy.fft.dct() method, we are able to get the discrete cosine transform by selecting different types of sequences by default it’s 2.
Python3
# import scipyfrom scipy import fft  # Using scipy.fft.dct() methodgfg = fft.dct([1, 2, 3, 4])  print(gfg)
Output :
[20.00000000  -6.30864406  0.00000000  -0.44834153]

Example #2 :
Python3
# import scipyfrom scipy import fft  # Using scipy.fft.dct() methodgfg = fft.dct([-6, 5, -4, 3, -2, 1], 3)  print(gfg)
Output :
[ -0.50866619  -0.58578644  -0.79439535  -1.34919819  -3.41421356
 -29.34774027]

Python-scipy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
AngularJS | ng-src Directive - GeeksforGeeks

28 Mar, 2019
The ng-src Directive in AngularJS is used to specify the src attribute of an <img> element. It ensures that the wrong image is not produced until AngularJS has been evaluated. It is supported by <img> element.
Syntax:
<img ng-src="url"> </img> 

Example:
<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml">    <head>        <title>ng-src Directive</title>        <script src=        "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js">        </script>      </head>    <body ng-app="app" style="text-align:center">      <h1 style="color:green">GeeksforGeeks</h1>      <h2>ng-src Directive</h2>        <div ng-controller="geek">            <img ng-src="{{pic}}" /><br><br><br>        <script>            var app = angular.module("app", []);            app.controller('geek', ['$scope', function ($scope) {                $scope.pic =   "https://media.geeksforgeeks.org/wp-content/uploads/20190328034223/ngimg1.png";            }]);        </script>    </body></html>
Output:
AngularJS-Directives
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Angular PrimeNG Dropdown Component
Angular PrimeNG Calendar Component
Angular 10 (blur) Event
Angular PrimeNG Messages Component
How to make a Bootstrap Modal Popup in Angular 9/8 ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
PREVIOUSDAY function

Returns a table that contains a column of all dates representing the day that is previous to the first date in the dates column, in the current context.
PREVIOUSDAY (<dates>) 

dates
A column that contains dates.
A table containing a single column of date values.
The dates parameter can be any of the following −
A reference to a date/time column.
A reference to a date/time column.
A table expression that returns a single column of date/time values.
A table expression that returns a single column of date/time values.
A Boolean expression that defines a single-column table of date/time values.
A Boolean expression that defines a single-column table of date/time values.
Constraints on Boolean expressions −
The expression cannot reference a calculated field.
The expression cannot reference a calculated field.
The expression cannot use CALCULATE function.
The expression cannot use CALCULATE function.
The expression cannot use any function that scans a table or returns a table, including aggregation functions.
The expression cannot use any function that scans a table or returns a table, including aggregation functions.
However, a Boolean expression can use any function that looks up a single value, or that calculates a scalar value.
Previous Day Sales: = CALCULATE ( 
   SUM (Sales[Sales Amount]),PREVIOUSDAY (Sales[Date])
) 

    53 Lectures 
     5.5 hours 

 Abhay Gadiya

    24 Lectures 
     2 hours 

 Randy Minder

    26 Lectures 
     4.5 hours 

 Randy Minder
 Print
 Add Notes
 Bookmark this page
Python | Remove List elements containing given String character - GeeksforGeeks

22 Apr, 2020
Sometimes, while working with Python lists, we can have problem in which we need to perform the task of removing all the elements of list which contain at least one character of String. This can have application in day-day programming. Lets discuss certain ways in which this task can be performed.
Method #1 : Using loopThis is brute force way in which this task can be performed. In this, we iterate for all list elements and check for occurrence of any character using loop.
# Python3 code to demonstrate working of # Remove List elements containing String character# Using loop  # initializing listtest_list = ['567', '840', '649', '7342']  # initializing string test_str = '1237'  # printing original listprint("The original list is : " + str(test_list))  # Remove List elements containing String character# Using loopres = []for sub in test_list:    flag = 0    for ele in sub:        if ele in test_str:            flag = 1    if not flag:        res.append(sub)  # printing result print("The list after removal : " + str(res)) 
The original list is : ['567', '840', '649', '7342']
The list after removal : ['840', '649']

 
Method #2 : Using list comprehensionThis is another way to perform this task. This is similar to above method. In this we perform the task in similar way as above just as one liner.
# Python3 code to demonstrate working of # Remove List elements containing String character# Using list comprehension  def check_pres(sub, test_str):    for ele in sub:        if ele in test_str:            return 0    return 1      # initializing listtest_list = ['567', '840', '649', '7342']  # initializing string test_str = '1237'  # printing original listprint("The original list is : " + str(test_list))  # Remove List elements containing String character# Using list comprehensionres = [ele for ele in test_list if check_pres(ele, test_str)]  # printing result print("The list after removal : " + str(res)) 
The original list is : ['567', '840', '649', '7342']
The list after removal : ['840', '649']

Python list-programs
Python
Python Programs
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
Python program to convert a list to string
Defaultdict in Python
Python | Split string into list of characters
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Convert nested array to string - JavaScript

We are required to write a JavaScript function that takes in a nested array of literals and converts it to a string by concatenating all the values present in it to the string
const arr = [
   'hello', [
      'world', 'how', [
         'are', 'you', [
            'without', 'me'
         ]
      ]
   ]
];
Let’s say the following is our nested array −
const arr = [
   'hello', [
      'world', 'how', [
         'are', 'you', [
            'without', 'me'
         ]
      ]
   ]
];
const arrayToString = (arr) => {
   let str = '';
   for(let i = 0; i < arr.length; i++){
      if(Array.isArray(arr[i])){
         str += arrayToString(arr[i]);
      }else{
         str += arr[i];
      };
   };
   return str;
};
console.log(arrayToString(arr));
Following is the output in the console −
helloworldhowareyouwithoutme
ssh-keyscan - Unix, Linux Command

ssh-keyscan
uses non-blocking socket I/O to contact as many hosts as possible in
parallel, so it is very efficient.
The keys from a domain of 1,000
hosts can be collected in tens of seconds, even when some of those
hosts are down or do not run ssh.
For scanning, one does not need
login access to the machines that are being scanned, nor does the
scanning process involve any encryption.


The options are as follows:

1.2.3.4,1.2.4.4 name.my.domain,name,n.my.domain,n,1.2.3.4,1.2.4.4


 Output format for rsa1 keys:

host-or-namelist bits exponent modulus


 Output format for rsa and dsa keys:

host-or-namelist keytype base64-encoded-key


Where
 keytype
is either
"ssh-rsa"
or
"ssh-dss".


 /etc/ssh/ssh_known_hosts

$ ssh-keyscan hostname


Find all hosts from the file
 ssh_hosts
which have new or different keys from those in the sorted file
 ssh_known_hosts:

$ ssh-keyscan -t rsa,dsa -f ssh_hosts | \
        sort -u - ssh_known_hosts | diff ssh_known_hosts -


Advertisements


    129 Lectures 
     23 hours 

 Eduonix Learning Solutions

    5 Lectures 
     4.5 hours 

 Frahaan Hussain

    35 Lectures 
     2 hours 

 Pradeep D

    41 Lectures 
     2.5 hours 

 Musab Zayadneh

    46 Lectures 
     4 hours 

 GUHARAJANM

    6 Lectures 
     4 hours 

 Uplatz
 Print
 Add Notes
 Bookmark this page
C library function - strspn()

The C library function size_t strspn(const char *str1, const char *str2) calculates the length of the initial segment of str1 which consists entirely of characters in str2.
Following is the declaration for strspn() function.
size_t strspn(const char *str1, const char *str2)
str1 − This is the main C string to be scanned.
str1 − This is the main C string to be scanned.
str2 − This is the string containing the list of characters to match in str1.
str2 − This is the string containing the list of characters to match in str1.
This function returns the number of characters in the initial segment of str1 which consist only of characters from str2.
The following example shows the usage of strspn() function.
#include <stdio.h>
#include <string.h>

int main () {
   int len;
   const char str1[] = "ABCDEFG019874";
   const char str2[] = "ABCD";

   len = strspn(str1, str2);

   printf("Length of initial segment matching %d\n", len );
   
   return(0);
}
Let us compile and run the above program that will produce the following result −
Length of initial segment matching 4


    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
Are static methods inherited in Java?

The static keyword is used to create methods that will exist independently of any instances created for the class.
Static methods do not use any instance variables of any object of the class they are defined in. Static methods take all the data from parameters and compute something from those parameters, with no reference to variables.
We can inherit static methods in Java.
In the example we are creating a class named Demo and, declared a static method named display().
We created another class Sample, extended the Demo class and tried to access the display() method using the sub class object.
 Live Demo
class Dem{
   public static void display(){}
}
public class Sample extends Dem {
   public static void display(){
      System.out.println("Hello this is a static method");
   }
   public static void main(String args[]) throws Exception{
      new Sample().display();
   }
}
Hello this is a static method
IPGeoLocation - Find IP address information in Kali Linux - GeeksforGeeks

17 Jun, 2021
IPGeoLocation is a free and open-source tool written in Python available on GitHub which is used to find information about the IP address on your Kali Linux operating system. It is used to retrieve IP Geolocation information. The tool is powered by the IP-API, which is an API used to retrieve information about IP Geolocation. This tool is written in python, so you must have python3, termcolor, colorama modules installed in your system in order to use the tool.  This tool selects a random proxy on the new line and the IP geolocation maps that IP using Google Map. You can export CSV, XML, and txt formats.
Step 1: Open your Kali Linux operating system. Use the following command to install the tool.
git clone https://github.com/maldevel/IPGeoLocation.git
Step 2: Use the following command to move in the directory of the tool.
cd IPGeoLocation
ls
Step 3: Now the tool has been downloaded. Now you have to install the requirements using the following commands.
pip3 install -r requirements.txt --user
Step 4: Now you have to give permission to the tool using the following command.
chmod +x ipgeolocation.py
Step 3: All the requirements have been installed. To run the tool use the following commands.
./ipgeolocation.py
The tool is running successfully. Now we will see examples.
Example 1: Use the IPGeoLocation tool to know your own IP information.
./ipgeolocation.py -m 
Example 2: Use the IPGeoLocation tool to find out the geolocation information of a domain.
./ipgeolocation.py -t google.com
You can see that the tool gives all the geolocation information about the target. You can also use the geolocation tool to find your own target geolocation information.
Kali-Linux
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Thread functions in C/C++
mv command in Linux with examples
nohup Command in Linux with Examples
scp command in Linux with Examples
Docker - COPY Instruction
chown command in Linux with Examples
nslookup command in Linux with Examples
SED command in Linux | Set 2
Named Pipe or FIFO with example C program
uniq Command in LINUX with examples
DAX Text - CONCATENATE function

Joins two text strings into one text string.
CONCATENATE (<text1>, <text2>) 

The text strings to be joined into a single text string.
Text strings can be
Text, or
Numbers, or
Column references.
The concatenated string.
DAX CONCATENATE function accepts only two arguments.
If you need to concatenate multiple columns, you can either nest the CONCATENATE functions or use the text concatenation operator (&) to join all of them.
If you want to use text strings directly, rather than using column references, you must enclose each text string in double quotation marks.
= CONCATENATE ("John ","Lever") returns John Lever.
= CONCATENATE (LEFT ([Product], 5), [No. of Units])
returns a calculated column with values – left 5 characters of Product concatenated with No. of Units in the corresponding row.

    53 Lectures 
     5.5 hours 

 Abhay Gadiya

    24 Lectures 
     2 hours 

 Randy Minder

    26 Lectures 
     4.5 hours 

 Randy Minder
 Print
 Add Notes
 Bookmark this page
Binary search in C#

Binary search works on a sorted array. The value is compared with the middle element of the array. If equality is not found, then the half part is eliminated in which the value is not there. In the same way, the other half part is searched.
Here is the mid element in our array. Let’s say we need to find 62, then the left part would be eliminated and the right part is then searched −
These are the complexities of a binary search −
Let us see the method to implement the binary search −
public static object BinarySearchDisplay(int[] arr, int key) {
   int minNum = 0;
   int maxNum = arr.Length - 1;

   while (minNum <=maxNum) {
      int mid = (minNum + maxNum) / 2;
      if (key == arr[mid]) {
         return ++mid;
      } else if (key < arr[mid]) {
         max = mid - 1;
      }else {
         min = mid + 1;
      }
   }
   return "None";
}
SVG visibility Attribute - GeeksforGeeks

31 Mar, 2022
The visibility attribute allows you to control the visibility of graphical elements. It has effect only on the following elements <a>, <altGlyph>, <audio>, <canvas>, <circle>, <ellipse>, <foreignObject>, <iframe>, <image>, <line>, <path>, <polygon>, <polyline>, <rect>, <text>, <textPath>, <tref>, <tspan>, <video>
Syntax:
visibility = visible | hidden | collapse

Attribute Values: The visibility attribute accepts the values mentioned above and described below
visible: This value indicates that the element will be visible.
hidden: This value indicates that the element will not be visible.
collapse: This value is equivalent to hidden.
Example 1: Below is the example that illustrates the use of the visibility attribute.
HTML
 
Output:
Example 2: Below is the example that illustrates the use of the visibility attribute.
HTML
<!DOCTYPE html><html>  <body>    <h1 style="color:green; font-size:60px;">        GeeksforGeeks    </h1>      <svg viewBox="0 0 620 520"         xmlns="http://www.w3.org/2000/svg">                  <rect x="10" y="10" width="200"             height="100" stroke="green"             stroke-width="5" fill="transparent" />          <g stroke="seagreen" stroke-width="5"             fill="lightgreen">                          <rect x="20" y="20" width="80"                 height="80" visibility="hidden" />                          <rect x="120" y="20" width="80"                 height="80" visibility="visible" />        </g>    </svg>  </body>  </html>
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
HTML-SVG
SVG-Attribute
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to set the default value for an HTML <select> element ?
How to update Node.js and NPM to next version ?
How to set input type date in dd-mm-yyyy format using HTML ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
Convert a string to an integer in JavaScript
Check if a Matrix is Symmetric or not in R Programming - isSymmetric() Function - GeeksforGeeks

16 Jun, 2020
isSymmetric() function in R Language is used to check if a matrix is a symmetric matrix. A Symmetric matrix is one whose transpose is equal to the matrix itself.
Syntax: isSymmetric(x)
Parameters:x: Matrix to be checked
Example 1:
# R program to check if # a matrix is symmetric  # Creating a diagonal matrixx1 <- diag(3)  # Creating a matrixx2 <- matrix(c(1, 2, 2, 3), 2)  # Calling isSymmetric() functionisSymmetric(x1)isSymmetric(x2)
Output:
[1] TRUE
[1] TRUE

Example 2:
# R program to check if # a matrix is symmetric  # Creating a matrixx1 <- matrix(c(1:9), 3, 3)  # Calling isSymmetric() functionisSymmetric(x1)
Output:
[1] FALSE

R Matrix-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
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
How to import an Excel File into R ?
How to filter R dataframe by multiple conditions?
Replace Specific Characters in String in R
R - if statement
Time Series Analysis in R
Set PIN validation with JavaScript?

You can validate pin on the basis of length and type of pin must be string etc.
Following is the code −
function simpleValidationForPin(pinValues) {
   if (!(typeof pinValues === "string" && !~pinValues.indexOf('.') && !isNaN(Number(pinValues)) && (pinValues.length === 2 || pinValues.length === 4))) {
      return false;
   } else {
      return true;
   }
}
if (simpleValidationForPin("0000.00") == true)
   console.log("This is a valid pin")
else
   console.log("This is not a valid pin")
if (simpleValidationForPin(66) == true)
   console.log("This is a valid pin")
else
   console.log("This is not valid pin")
if (simpleValidationForPin("4444") == true)
   console.log("This is a valid pin")
else
   console.log("This is not a valid pin")
if (simpleValidationForPin("66") == true)
   console.log("This is a valid pin")
else
   console.log("This is not valid pin")
if (simpleValidationForPin("666") == true)
   console.log("This is a valid pin")
else
   console.log("This is not a valid pin")
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo254.js.
This will produce the following output on console −
PS C:\Users\Amit\javascript-code> node demo254.js
This is not a valid pin
This is not a valid pin
This is a valid pin
This is a valid pin
This is not a valid pin
Calling Stored Procedure inside foreach PHP Codeigniter

The code inside the 'Model' and the 'Controller' needs to be changed to include code that is shown below −
$header = $this->model_name->call_head();
foreach($header as $item) {
   $name = $item['name'];
   $array['name'] = $name;
   $array['data'] = $item['data'];
   $child_val = $this->model_name->call_child($name);
   foreach($child_val as $value) {
      $array['child'] = array(
         'child_name' => $value['child_name'],
         'child_data' => $value['child_data']
      );
   }
}
public function call_head() {
   $query = "CALL PROCEDURE_HEAD()";
   $result = $this->db->query($query)->result_array();
   $query->next_result();
   $query->free_result();
   return $result;
}
public function call_child($name) {
   $query = "CALL PROCEDURE_CHILD($name)";
   $result = $this->db->query($query)->result_array();
   $query->next_result();
   $query->free_result();
   return $result;
}
Passing arrays to methods in C#?

To pass arrays to methods, you need to pass an array as a method argument.
int displaySum(int[] arr, int size) {
}
Now call it −
sum = d.displaySum(myArr, 5 ) ;
 Live Demo
using System;

namespace Test {
   class Demo {
      int displaySum(int[] arr, int size) {
         int i;
         int sum = 0;

         for (i = 0; i < size; ++i) {
            sum += arr[i];
         }

         return sum;
      }
   
      static void Main(string[] args) {
         Demo d = new Demo();

         int [] myArr = new int[] {59, 34, 76, 65, 12, 99};
         int sum;

         sum = d.displaySum(myArr, 5 ) ;

         /* output the returned value */
         Console.WriteLine( "Sum: {0} ", sum );
         Console.ReadKey();
      }
   }
}
Sum: 246
Apache Flink - Setup/Installation

Before the start with the setup/ installation of Apache Flink, let us check whether we have Java 8 installed in our system.
We will now proceed by downloading Apache Flink.
wget http://mirrors.estointernet.in/apache/flink/flink-1.7.1/flink-1.7.1-bin-scala_2.11.tgz

Now, uncompress the tar file.
tar -xzf flink-1.7.1-bin-scala_2.11.tgz

Go to Flink's home directory.
cd flink-1.7.1/

Start the Flink Cluster.
./bin/start-cluster.sh

Open the Mozilla browser and go to the below URL, it will open the Flink Web Dashboard.
http://localhost:8081
This is how the User Interface of Apache Flink Dashboard looks like.
Now the Flink cluster is up and running.

    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
Difference between Call by Value and Call by Reference

In programming on the basis of passing parameters to a function we classified function invocation into two : Call by value and Call by reference.As name suggest in both invocations we are calling function by type of parameters in one we are passing actual value of parameter and in other we are passing the location/reference of parameter.
Following are the important differences between Call by Value and Call by Reference.
ByValue.c
#include <stdio.h>
class ByValue{
   void swapByValue(int, int); /* Prototype */
   int main(){
      int n1 = 10, n2 = 20;
      swapByValue(n1, n2);
      printf("n1: %d, n2: %d\n", n1, n2);
   }
   void swapByValue(int a, int b){
      int t;
      t = a; a = b; b = t;
   }
}
n1: 10, n2: 20
ByReference.c
#include <stdio.h>
class ByReference{
   void swapByReference(int*, int*);
   int main(){
      int n1 = 10, n2 = 20;
      swapByReference(&n1, &n2);
      printf("n1: %d, n2: %d\n", n1, n2);
   }
   void swapByReference(int *a, int *b){
      int t;
      t = *a; *a = *b; *b = t;
   }
}
n1: 20, n2: 10
GATE | GATE-CS-2017 (Set 1) | Question 49 - GeeksforGeeks

13 Aug, 2021
Consider the following two functions
void fun1(int n){ 

     if(n == 0) return; 
     printf(“%d”, n); 
     fun2(n-2);
     printf(“%d”, n);  
}

void fun2(int n){ 

     if(n == 0) return; 
     printf(“%d”, n); 
     fun1(++n);
     printf(“%d”, n);  
}

The output printed when fun1 (5) is called is(A) 53423122233445(B) 53423120112233(C) 53423122132435(D) 53423120213243Answer: (A)Explanation: 
This solution is contributed by parul sharma.
Alternate Solution
This solution is contributed by Sumouli Chaudhary.
YouTubeGeeksforGeeks GATE Computer Science16.2K subscribersGATE PYQs 2017 and 2018 with 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:0014:56 / 1:11:13•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=j9Vmf5yRw-I" 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-CS-2017 (Set 1)
GATE-GATE-CS-2017 (Set 1)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE CS 2019 | Question 27
GATE | GATE-IT-2004 | Question 66
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2006 | Question 49
GATE | GATE-CS-2004 | Question 3
GATE | GATE-CS-2017 (Set 2) | Question 42
GATE | GATE CS 2010 | Question 24
GATE | GATE-CS-2000 | Question 43
GATE | GATE CS 2021 | Set 1 | Question 47
How to remove the hash from window.location (URL) with JavaScript without page refresh?

You can use the replaceState method on the history API to remove the hash.
The replaceState() method modifies the current history entry, replacing it with the state objects, title, and URL passed in the method parameters. This method is particularly useful when you want to update the state object or URL of the current history entry in response to some user action.
To remove the hash you can use −
history.replaceState(null, null, ' ');
How to convert a spreadsheet to Python dictionary?

The easiest way to convert a spreadsheet to Python dictionary is to use an external library like pandas. This provides very helpful features like to_dict on excel objects. You can use these like −
from pandas import *
xls = ExcelFile('my_file.xls')
data = xls.parse(xls.sheet_names[0])
print(data.to_dict())
This will give the output −
{'id': 10, 'name': "John"}
Deep Reinforcement Learning With Python | Part 3| Using Tensorboard to Analyse Trained Models | by Mohammed AL-Ma'amari | Towards Data Science

First part explained and created the game environment.
towardsdatascience.com
Second part discussed the process of training the DQN, explained DQNs and gave reasons to choose DQN over Q-Learning.
towardsdatascience.com
We are going to:
Use Tensorboard to visualize the goodness of trained models.
Explain the way of loading and trying a trained model.
Use the best model and let it play the game.
1- Use a modified Tensorboard to make Tensorboard logs the data from all episodes in the training process in one log file instead of making a new log file every time we fit the model.
The next code of the ModifiedTensorBoard is from this blog by sentdex, I just changed it a little bit to make it run on TensorFlow2.0:
2- Define an object of the modified tensorboard in the __init__ of the agent class:
PATH and name are used to define the full path where the log file will be saved in.
3- Pass the modified tensorboard as a callback when fitting the model:
4- At the start of each episode :
5- To update the logs, use the next line:
Open the terminal on the directory where the “logs” folder is and run:
tensorboard --logdir="logs/"
A browser window will appear:
You can try the other options by yourself.
By using these visualisations we can see the relations between logged variables, such as epsilon and max_reward.
Deep Q Learning w/ DQN — Reinforcement Learning p.5
Other parts of this series:
towardsdatascience.com
towardsdatascience.com
You can follow me on:
Twitter
LinkedIn
FaceBook
Deep Neural Networks for Regression Problems
AI Generates Taylor Swift’s Song Lyrics
Introduction to Random Forest Algorithm with Python
Machine Learning Crash Course with TensorFlow APIs Summary
How To Make A CNN Using Tensorflow and Keras ?
How to Choose the Best Machine Learning Model ?
Difference Between throw and throws in Java - GeeksforGeeks

07 Dec, 2021
Prerequisite: Throw and Throws in Java
The throw and throws are the concepts of exception handling in Java where the throw keyword throws the exception explicitly from a method or a block of code, whereas the throws keyword is used in the signature of the method.
The differences between throw and throws in Java are:
S. No.
Key Difference
throw
throws
1. Java throw
Java
// Java program to demonstrate the working // of throw keyword in exception handling  public class GFG {    public static void main(String[] args)    {        // Use of unchecked Exception        try {            // double x=3/0;            throw new ArithmeticException();        }        catch (ArithmeticException e) {            e.printStackTrace();        }    }}
Output: 
java.lang.ArithmeticException
    at GFG.main(GFG.java:10)
2. Java throws
Java
// Java program to demonstrate the working// of throws keyword in exception handlingimport java.io.*;import java.util.*;  public class GFG {      public static void writeToFile() throws Exception    {        BufferedWriter bw = new BufferedWriter(            new FileWriter("myFile.txt"));        bw.write("Test");        bw.close();    }      public static void main(String[] args) throws Exception    {        try {            writeToFile();        }        catch (Exception e) {            e.printStackTrace();        }    }}
Output:
java.security.AccessControlException: access denied ("java.io.FilePermission" "myFile.txt" "write")
  at GFG.writeToFile(GFG.java:10)
nishkarshgandhi
Exception Handling
java-basics
Java-Exceptions
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
ArrayList in Java
Multidimensional Arrays in Java
Stack Class in Java
Stream In Java
Singleton Class in Java
Set in Java
Overriding in Java
LinkedList in Java
Collections in Java
Is it possible to style HTML5 audio tag?

HTML 5 audio tags can be styled. By using the audio tag with “controls” attribute, the default browsers player is used. You can customize by not using the browsers controls. 
By removing the controls attribute, you can hide the built in browser user’s interface −
<audioid = "player" src = "kalimba.mp3"></audio>
<div>
   <buttononclick = "document.getElementById('player').play()">Play</button>
   <buttononclick = "document.getElementById('player').pause()">Pause</button>
   <buttononclick = "document.getElementById('player').volume += 0.2">Vol+</button>
   <buttononclick = "document.getElementById('player').volume -= 0.2">Vol-</button>
</div>
You can also add CSS classes to each one of the elements and style them accordingly.
Count by multiple fields with MongoDB aggregation

To count by multiple fields, use $facet in MongoDB. The $facet processes multiple aggregation pipelines within a single stage on the same set of input documents. Let us create a collection with documents −
> db.demo721.insertOne(
...    {
...
...       "details1": {
...          "id":101
...
...       },
...       "details2": {
...          "id":101
...       },
...       "details3": {
...          "id":101
...       }
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5eaaebdd43417811278f5887")
}
>
>
> db.demo721.insertOne(
...    {
...
...       "details1": {
...          "id":101
...
...       },
...       "details2": {
...          "id":102
...       },
...       "details3": {
...          "id":102
...       }
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5eaaebe943417811278f5888")
}
Display all documents from a collection with the help of find() method −
> db.demo721.find();
This will produce the following output −
{ "_id" : ObjectId("5eaaebdd43417811278f5887"), "details1" : { "id" : 101 }, "details2" : { "id" : 101 }, "details3" : { "id" : 101 } }
{ "_id" : ObjectId("5eaaebe943417811278f5888"), "details1" : { "id" : 101 }, "details2" : { "id" : 102 }, "details3" : { "id" : 102 } }
Following is the query to count by multiple fields −
> db.demo721.aggregate([
...    {$facet:{
...       ids:[
...          {$group:{ _id:null,
...             d3:{$addToSet: "$details3.id"},
...             d2:{$addToSet:"$details2.id"},
...             d1:{$addToSet:"$details1.id"}}},
...          {$project:{ _id:0,
...             listofall:{$setUnion:["$d1","$d2","$d3"]}}}],
...       d:[{$project:{ _id:0,
...          a1:"$details1.id",
...          a2:"$details2.id",
...          a3:"$details3.id"}}]}},
... {$unwind:"$d"},
... {$unwind:"$ids"},
... {$unwind:"$ids.listofall"},
... {$group:{ _id:"$ids.listofall",
...    details1id:{$sum:{$cond:[{$eq:["$d.a1","$ids.listofall"]},1,0]}},
...    details2id:{$sum:{$cond:[{$eq:["$d.a2","$ids.listofall"]},1,0]}},
...    details3id:{$sum:{$cond:[{$eq:["$d.a3","$ids.listofall"]},1,0]}}}}])
This will produce the following output −
{ "_id" : 102, "details1id" : 0, "details2id" : 1, "details3id" : 1 }
{ "_id" : 101, "details1id" : 2, "details2id" : 1, "details3id" : 1 }
File Path with double slash in Java

The double slash in the file path is required as to create the ’\’ character , another ‘\’ needs to be added to escape it. A program that demonstrates this is given as follows −
 Live Demo
import java.io.File;
public class Demo {
   public static void main(String[] args) {
      File file = new File("C:\\jdk11.0.2\\demo1.txt");
      System.out.println(file);
   }
}
The output of the above program is as follows −
C:\jdk11.0.2\demo1.txt
Now let us understand the above program.
The file path of the file is provided with double slash and then it is printed. A code snippet that demonstrates this is given as follows −
File file = new File("C:\\jdk11.0.2\\demo1.txt");
System.out.println(file);
Program to find number of swaps required to sort the sequence in python

Suppose we have a list of distinct numbers; we have to find the minimum number of swaps required to sort the list in increasing order.
So, if the input is like nums = [3, 1, 7, 5], then the output will be 2, as we can swap 3 and 1, then 5 and 7.
To solve this, we will follow these steps:
sort_seq := sort the list nums
table := a new map
for each index i and value n in nums, dotable[n] := i
table[n] := i
swaps := 0
for i in range 0 to size of nums, don := nums[i]s_n := sort_seq[i]s_i := table[s_n]if s_n is not same as n, thenswaps := swaps + 1nums[s_i] := nnums[i] := s_ntable[n] := s_itable[s_n] := i
n := nums[i]
s_n := sort_seq[i]
s_i := table[s_n]
if s_n is not same as n, thenswaps := swaps + 1nums[s_i] := nnums[i] := s_ntable[n] := s_itable[s_n] := i
swaps := swaps + 1
nums[s_i] := n
nums[i] := s_n
table[n] := s_i
table[s_n] := i
return swaps
Let us see the following implementation to get better understanding:
Live Demo
class Solution:
def solve(self, nums):
   sort_seq = sorted(nums)
   table = {}

   for i, n in enumerate(nums):
      table[n] = i
   swaps = 0
   for i in range(len(nums)):
      n = nums[i]
      s_n = sort_seq[i]
      s_i = table[s_n]

      if s_n != n:
         swaps += 1
         nums[s_i] = n
         nums[i] = s_n
         table[n] = s_i
         table[s_n] = i

      return swaps

ob = Solution()
nums = [3, 1, 7, 5]
print(ob.solve(nums))
[3, 1, 7, 5]
2
C# Program to combine Dictionary of two keys

Firstly, set the Dictionaries to be combined −
Dictionary <string, int> dict1 = new Dictionary <string, int> ();
dict1.Add("one", 1);
dict1.Add("Two", 2);
Dictionary <string, int> dict2 = new Dictionary <string, int> ();
dict2.Add("Three", 3);
dict2.Add("Four", 4);
Now, use HashSet to combine them. The method used for the same purpose is UnionWith() −
HashSet <string> hSet = new HashSet <string> (dict1.Keys);
hSet.UnionWith(dict2.Keys);
The following is the complete code −
 Live Demo
using System;
using System.Collections.Generic;
public class Program {
   public static void Main() {
      Dictionary <string, int> dict1 = new Dictionary <string, int> ();
      dict1.Add("one", 1);
      dict1.Add("Two", 2);
      Dictionary <string, int> dict2 = new Dictionary <string, int> ();
      dict2.Add("Three", 3);
      dict2.Add("Four", 4);
      HashSet <string> hSet = new HashSet <string> (dict1.Keys);
      hSet.UnionWith(dict2.Keys);
      Console.WriteLine("Union of Dictionary...");
      foreach(string val in hSet) {
         Console.WriteLine(val);
      }
   }
}
Union of Dictionary...
one
Two
Three
Four
Parse and balance angle brackets problem in JavaScript

We are given a string of angle brackets, and we are required to write a function that add brackets at the beginning and end of the string to make all brackets match.
The angle brackets match if for every < there is a corresponding > and for every > there is a corresponding <.
For example − If the input string is −
const str = '><<><';
Then the output should be −
const output = '<><<><>>';
Here, we added, '<' at the beginning and '>>' at the end to balance the string.
We will use a number that will keep count of the number of open '<' tags so far. And then, when we encounter a '>' tag, if there are no current open tags, we will add '<' to the beginning of the string (while keeping the open tag count at 0).
Then, at the end, add a number of '>'s matching the number of currently open tags.
The code for this will be −
const str = '><<><';
const buildPair = (str = '') => {
   let count = 0;
   let extras = 0;
   for (const char of str) {
      if (char === '>') {
         if (count === 0) {
            extras++;
         } else {
            count−−;
         };
      } else {
         count++;
      };
   };
   const leadingTags = '<'.repeat(extras);
   const trailingTags = '>'.repeat(count);
   return leadingTags + str + trailingTags;
};
console.log(buildPair(str));
And the output in the console will be −
><<><>>
Plotly - Histogram

Introduced by Karl Pearson, a histogram is an accurate representation of the distribution of numerical data which is an estimate of the probability distribution of a continuous variable (CORAL). It appears similar to bar graph, but, a bar graph relates two variables, whereas a histogram relates only one.
A histogram requires bin (or bucket) which divides the entire range of values into a series of intervals—and then count how many values fall into each interval. The bins are usually specified as consecutive, non-overlapping intervals of a variable. The bins must be adjacent, and are often of equal size. A rectangle is erected over the bin with height proportional to the frequency—the number of cases in each bin.
Histogram trace object is returned by go.Histogram() function. Its customization is done by various arguments or attributes. One essential argument is x or y set to a list, numpy array or Pandas dataframe object which is to be distributed in bins.
By default, Plotly distributes the data points in automatically sized bins. However, you can define custom bin size. For that you need to set autobins to false, specify nbins (number of bins), its start and end values and size.
Following code generates a simple histogram showing distribution of marks of students in a class inbins (sized automatically) −
import numpy as np
x1 = np.array([22,87,5,43,56,73,55,54,11,20,51,5,79,31,27])
data = [go.Histogram(x = x1)]
fig = go.Figure(data)
iplot(fig)
The output is as shown below −
The go.Histogram() function accepts histnorm, which specifies the type of normalization used for this histogram trace. Default is "", the span of each bar corresponds to the number of occurrences (i.e. the number of data points lying inside the bins). If assigned "percent" / "probability", the span of each bar corresponds to the percentage / fraction of occurrences with respect to the total number of sample points. If it is equal to "density", the span of each bar corresponds to the number of occurrences in a bin divided by the size of the bin interval.
There is also histfunc parameter whose default value is count. As a result, height of rectangle over a bin corresponds to count of data points. It can be set to sum, avg, min or max.
The histogram() function can be set to display cumulative distribution of values in successive bins. For that, you need to set cumulative property to enabled. Result can be seen as below −
data=[go.Histogram(x = x1, cumulative_enabled = True)]
fig = go.Figure(data)
iplot(fig)
The output is as mentioned below −

    12 Lectures 
     53 mins

 Pranjal Srivastava
 Print
 Add Notes
 Bookmark this page
Check if a Stack contains an element in C#

To check if a Stack has elements, use the C# Contains() method. Following is the code −
 Live Demo
using System;
using System.Collections.Generic;
public class Demo {
   public static void Main(){
      Stack<int> stack = new Stack<int>();
      stack.Push(100);
      stack.Push(150);
      stack.Push(175);
      stack.Push(200);
      stack.Push(225);
      stack.Push(250);
      stack.Push(300);
      stack.Push(400);
      stack.Push(450);
      stack.Push(500);
      Console.WriteLine("Elements in the Stack:");
      foreach(var val in stack){
         Console.WriteLine(val);
      }
      Console.WriteLine("Count of elements in the Stack = "+stack.Count);
      Console.WriteLine("Does Stack has the element 400?= "+stack.Contains(400));
   }
}
This will produce the following output −
Elements in the Stack:
500
450
400
300
250
225
200
175
150
100
Count of elements in the Stack = 10 Does Stack has the element40400?= True
Let us see another example −
 Live Demo
using System;
using System.Collections.Generic;
public class Demo {
   public static void Main(){
      Stack<string> stack = new Stack<string>();
      stack.Push("Steve");
      stack.Push("Gary");
      stack.Push("Stephen");
      stack.Push("Nathan");
      stack.Push("Katie");
      stack.Push("Andy");
      stack.Push("David");
      stack.Push("Amy");
      Console.WriteLine("Elements in the Stack:");
      foreach(var val in stack){
         Console.WriteLine(val);
      }
      Console.WriteLine("Count of elements in the Stack = "+stack.Count);
      Console.WriteLine("Does Stack has the element 400?= "+stack.Contains("Michael"));
   }
}
This will produce the following output −
Elements in the Stack:
Amy
David
Andy
Katie
Nathan
Stephen
Gary
Steve
Count of elements in the Stack = 8 Does Stack has the element 400?= False
scipy stats.genpareto() | Python - GeeksforGeeks

27 Mar, 2019
scipy.stats.genpareto() is an generalized Pareto continuous random variable that is defined with a standard format and some shape parameters to complete its specification.
Parameters :-> q : lower and upper tail probability-> a, b : shape parameters-> x : quantiles-> loc : [optional]location parameter. Default = 0-> scale : [optional]scale parameter. Default = 1-> size : [tuple of ints, optional] shape or random variates.-> moments : [optional] composed of letters [‘mvsk’]; ‘m’ = mean, ‘v’ = variance, ‘s’ = Fisher’s skew and ‘k’ = Fisher’s kurtosis. (default = ‘mv’).
Results : generalized Pareto continuous random variable
Code #1 : Creating generalized Pareto continuous random variable
from scipy.stats import genpareto   numargs = genpareto .numargs[a] = [0.7, ] * numargsrv = genpareto (a)  print ("RV : \n", rv) 
Output :
RV : 
 <scipy.stats._distn_infrastructure.rv_frozen object at 0x0000018D579B85C0>

Code #2 : generalized Pareto random variates.
import numpy as npquantile = np.arange (0.01, 1, 0.1)   # Random VariatesR = genpareto.rvs(a, scale = 2,  size = 10)print ("Random Variates : \n", R)
Output :
Random Variates : 
 [ 1.55978773  0.03897083  7.68148511  0.78339525  1.1217962   0.20434352
  1.16663003  2.06115353 12.82886098  0.27780119]
Code #3 : Graphical Representation.
import numpy as npimport matplotlib.pyplot as plt  distribution = np.linspace(0, np.minimum(rv.dist.b, 3))print("Distribution : \n", distribution)  plot = plt.plot(distribution, rv.pdf(distribution))
Output :
Distribution : 
 [0.         0.06122449 0.12244898 0.18367347 0.24489796 0.30612245
 0.36734694 0.42857143 0.48979592 0.55102041 0.6122449  0.67346939
 0.73469388 0.79591837 0.85714286 0.91836735 0.97959184 1.04081633
 1.10204082 1.16326531 1.2244898  1.28571429 1.34693878 1.40816327
 1.46938776 1.53061224 1.59183673 1.65306122 1.71428571 1.7755102
 1.83673469 1.89795918 1.95918367 2.02040816 2.08163265 2.14285714
 2.20408163 2.26530612 2.32653061 2.3877551  2.44897959 2.51020408
 2.57142857 2.63265306 2.69387755 2.75510204 2.81632653 2.87755102
 2.93877551 3.        ]
Code #4 : Varying Positional Arguments
import matplotlib.pyplot as pltimport numpy as np  x = np.linspace(0, 5, 100)  # Varying positional argumentsy1 = genpareto.pdf(x, 1, 3)y2 = genpareto.pdf(x, 1, 4)plt.plot(x, y1, "*", x, y2, "r--")
Output :
Python scipy-stats-functions
Python-scipy
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
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python