code-rag-bench/online-tutorials huggingface dataset:
C program to print number series without using any loop

In this problem, we are given two numbers N and K. Our task is to create a program that will print number series without using any loop.
The series that is to be printed will start from n and will be subtracted by k till it becomes zero or negative. After that, we will start to add k to it till it becomes n again. If this process we cannot use any type of loop.
Let’s take an example to understand the problem,
n = 12 , k = 3
12 9 6 3 0 3 6 9 12
To solve this problem without using a loop we will use recursion. We will create a recursive function that will call itself again and keep a check on the value of the number to ensure which operation out of addition or subtraction is to be one on the number.
The function will use a flag that will help us to keep track of whether the value is to be subtracted or added.
// C program to print number series without using any loop
 Live Demo
#include <iostream>
using namespace std;
void PrintSeriesRec(int current, int N, int K, bool flag){
   cout<<current<<"\t";
   if (current <= 0)
      flag = !flag;
   if (current == N && !flag)
      return;
   if (flag == true)
      PrintSeriesRec(current - K, N, K, flag);
   else if (!flag)
      PrintSeriesRec(current + K, N, K, flag);
}
int main(){
   int N = 12, K = 4;
   cout<<"The series is : \n";
   PrintSeriesRec(N, N, K, true);
   return 0;
}
The series is −
12 8 4 0 4 8 12
border-info class in Bootstrap 4

Use the border-info class in Bootstrap, to set a border that indicates information. Set the class as if you use any other class in Bootstrap:
<div class="one border border-info">
  Details
</div>
Above, we added border-info class. Another class, “one” is used to give shape to the div element −
.one {
  width: 180px;
  height: 180px;
  margin: 55px;
}
You can try to run the following code to implement the border-info class on a rectangle −
Live Demo
<!DOCTYPE html>
<html>
  <head>
   <title>Bootstrap Example</title>
   <meta charset="utf-8">
   <meta name="viewport" content="width=device-width, initial-scale=1">
   <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
   <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
   <style>
   .one {
     width: 180px;
     height: 180px;
     margin: 55px;
   }
   </style>
  </head>
<body>

<div class="container">
  <p>Rectangle with a border to set information:</p>
  <div class="one border border-info">Details</div>
</div>

</body>
</html>
Matplotlib.pyplot.xticks() in Python - GeeksforGeeks

12 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface.
The annotate() function in pyplot module of matplotlib library is used to get and set the current tick locations and labels of the x-axis.
Syntax:
matplotlib.pyplot.xticks(ticks=None, labels=None, **kwargs)
Parameters: This method accept the following parameters that are described below:
ticks: This parameter is the list of xtick locations. and an optional parameter. If an empty list is passed as an argument then it will removes all xticks
labels: This parameter contains labels to place at the given ticks locations. And it is an optional parameter.
**kwargs: This parameter is Text properties that is used to control the appearance of the labels.
Returns: This returns the following:
locs :This returns the list of ytick locations.
labels :This returns the list of ylabel Text objects.
The resultant is (locs, labels)
Below examples illustrate the matplotlib.pyplot.xticks() function in matplotlib.pyplot:
Example #1:
# Implementation of matplotlib.pyplot.xticks()# function  import numpy as npimport matplotlib.pyplot as plt    x = [1, 2, 3, 4]y = [95, 38, 54, 35]labels = ['Geeks1', 'Geeks2', 'Geeks3', 'Geeks4']  plt.plot(x, y)  # You can specify a rotation for the tick# labels in degrees or with keywords.plt.xticks(x, labels, rotation ='vertical')  # Pad margins so that markers don't get # clipped by the axesplt.margins(0.2)  # Tweak spacing to prevent clipping of tick-labelsplt.subplots_adjust(bottom = 0.15)plt.show()
Output:
Example #2:
# Implementation of matplotlib.pyplot.xticks()# function  import matplotlib.pyplot as plt  from mpl_toolkits.axes_grid1.inset_locator import inset_axes, zoomed_inset_axes  def get_demo_image():    from matplotlib.cbook import get_sample_data    import numpy as np    f = get_sample_data("axes_grid / bivariate_normal.npy",                         asfileobj = False)    z = np.load(f)          # z is a numpy array of 15x15    return z, (3, 19, 4, 13)    fig, ax = plt.subplots(figsize =[5, 4])  Z, extent = get_demo_image()  ax.set(aspect = 1,       xlim =(0, 65),       ylim =(0, 50))    axins = zoomed_inset_axes(ax, zoom = 2,                           loc ='upper right')  im = axins.imshow(Z, extent = extent,                   interpolation ="nearest",                  origin ="upper")  plt.xlabel('X-axis') plt.ylabel('Y-axis')  plt.xticks(visible = False)plt.show() 
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Convert integer to string in Python
Python | Introduction to Matplotlib - GeeksforGeeks

14 May, 2018
Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. It was introduced by John Hunter in the year 2002.
One of the greatest benefits of visualization is that it allows us visual access to huge amounts of data in easily digestible visuals. Matplotlib consists of several plots like line, bar, scatter, histogram etc.
Installation :Windows, Linux and macOS distributions have matplotlib and most of its dependencies as wheel packages. Run the following command to install matplotlib package :
python -mpip install -U matplotlib
 Importing matplotlib :
from matplotlib import pyplot as plt
or
import matplotlib.pyplot as plt 
Matplotlib comes with a wide variety of plots. Plots helps to understand trends, patterns, and to make correlations. They’re typically instruments for reasoning about quantitative information. Some of the sample plots are covered here.
Line plot :
# importing matplotlib module from matplotlib import pyplot as plt  # x-axis valuesx = [5, 2, 9, 4, 7]  # Y-axis valuesy = [10, 5, 8, 4, 2]  # Function to plotplt.plot(x,y)  # function to show the plotplt.show()
Output :
 Bar plot :
# importing matplotlib module from matplotlib import pyplot as plt  # x-axis valuesx = [5, 2, 9, 4, 7]  # Y-axis valuesy = [10, 5, 8, 4, 2]  # Function to plot the barplt.bar(x,y)  # function to show the plotplt.show()
Output : Histogram :
# importing matplotlib module from matplotlib import pyplot as plt  # Y-axis valuesy = [10, 5, 8, 4, 2]  # Function to plot histogramplt.hist(y)  # Function to show the plotplt.show()
Output :
# importing matplotlib module from matplotlib import pyplot as plt  # x-axis valuesx = [5, 2, 9, 4, 7]  # Y-axis valuesy = [10, 5, 8, 4, 2]  # Function to plot scatterplt.scatter(x, y)  # function to show the plotplt.show()
Output :
Reference : Matplotlib Documentation.
Python-Library
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Taking input in Python
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Remove Vertical or Horizontal Gridlines in ggplot2 Plot in R - GeeksforGeeks

14 Sep, 2021
In this article, we are going to learn how to remove Vertical or Horizontal Gridlines in the background of a ggplot2 Plot in R programming language.
To understand how to remove Vertical or Horizontal Gridlines, first import all the required libraries to the working space and create a dataframe. Let us first create a regular plot so that the difference is apparent.
Example: default plot
R
library("ggplot2")   # Store 10 entries of data in data frameA <- data.frame(x = 1:10, y = c(1,4,2,3,7,5,4,8,2,5))  # A ggplot2 plot with gridlinesp <- ggplot(A, aes(x, y)) + geom_point()  # Display the plotp
Output:
Now for removing gridlines, separate functions are added while creating a plot. In ggplot2, scales control how the data is mapped into aesthetics. When we provide some data, it takes the data and converts it into something visual for us like position, size, color, or shape. 
Scales toolbox can have different attributes like the following two main types:
Position scales and axes
Colour scales and legend
In order to remove gridlines, we are going to focus on position scales. There are two position scales in a plot corresponding to x and y aesthetics. Two most common types of continuous position scales are the default scale_x_continuous() and scale_y_continuous() functions. We are going to use these functions to remove the gridlines.
To remove vertical grid lines scale_x_continuous() function is passed with the breaks parameter as NULL.
Syntax:
scale_x_continuous(breaks =NULL )
Example: Removing vertical gridlines
R
library("ggplot2")   # Store 10 entries of data in data frameA <- data.frame(x = 1:10, y = c(1,4,2,3,7,5,4,8,2,5))  # A ggplot2 plot with gridlinesp <- ggplot(A, aes(x, y)) + geom_point()  # Remove Vertical Gridlines p + scale_x_continuous(breaks = NULL)
Output:
Similarly for removing horizontal gridlines break parameter of scale_y_continuous() is set to NULL.
Example: Removing horizontal lines 
R
library("ggplot2")   # Store 10 entries of data in data frameA <- data.frame(x = 1:10, y = c(1,4,2,3,7,5,4,8,2,5))  # A ggplot2 plot with gridlinesp <- ggplot(A, aes(x, y)) + geom_point()  # Remove Horizontal Gridlinesp + scale_y_continuous(breaks = NULL)
Output:
Picked
R-ggplot
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 filter R DataFrame by values in a column?
How to import an Excel File into R ?
R - if statement
Time Series Analysis in R
How to filter R dataframe by multiple conditions?
What is currying in JavaScript?

Currying is a technique of evaluating function with multiple arguments, into sequence of functions with single argument.In other words, when a function, instead of taking all arguments at one time, takes the first one and return a new function that takes the second one and returns a new function which takes the third one, and so forth, until all arguments have been fulfilled.
  a) It helps to avoid passing same variable again and again.
  b) It is extremely useful in event handling. 
syntax:
     function Myfunction(a) {
        return (b) => {
           return (c) => {
             return a * b * c
             }
            }
         }
In the following example,since no currying is used, all the parameters were passed at once(volume(11,2,3))  to the existing function to calculate the volume.
 Live Demo
<html>
<body>
<script>
   function volume(length, width, height) {
      return length * width * height;
   }
   document.write((volume(11,2,3)));
</script>
</body>
</html>
66
In the following example,since currying is used,parameters were passed one by one(volume(11)(2)(3))  until the last function called the last parameter .
 Live Demo
<html>
<body>
<script>
   function volume(length) {
      return function(width) {
         return function(height) {
            return height * width * length;
         }
      }
   }
document.write(volume(11)(2)(3))
</script>
</body>
</html>
66
Pattern compile() method in Java with Examples

The pattern class of the java.regex package is a compiled representation of a regular expression.
The compile() method of this class accepts a string value representing a regular expression and returns a Pattern object.
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CompileExample {
   public static void main( String args[] ) {
      //Reading string value
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter input string");
      String input = sc.nextLine();
      //Regular expression to find digits
      String regex = "(\\d)";
      //Compiling the regular expression
      Pattern pattern = Pattern.compile(regex);
      //Printing the regular expression
      System.out.println("Compiled regular expression: "+pattern.toString());
      //Retrieving the matcher object
      Matcher matcher = pattern.matcher(input);
      //verifying whether match occurred
      if(matcher.find()) {
         System.out.println("Given String contains digits");
      } else {
         System.out.println("Given String does not contain digits");
      }
   }
}
Enter input string
hello my id is 1120KKA
Compiled regular expression: (\d)
Given String contains digits
Another variant of this method accepts an integer value representing flags, where each flag specifies an optional condition, for example, CASE_INSENSITIVE ignores the case while compiling the regular expression.
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CompileExample {
   public static void main( String args[] ) {
      //Compiling the regular expression
      Pattern pattern = Pattern.compile("[t]", Pattern.CASE_INSENSITIVE);
      //Retrieving the matcher object
      Matcher matcher = pattern.matcher("Tutorialspoint");
      int count = 0;
      while(matcher.find()) {
         count++;
      }
      System.out.println("Number of matches: "+count);
   }
}
Enter input string
Tutorialspoint
Number of matches: 3
Matplotlib.figure.Figure.subplots() in Python

03 May, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The figure module provides the top-level Artist, the Figure, which contains all the plot elements. This module is used to control the default spacing of the subplots and top level container for all plot elements.
The subplots() method figure module of matplotlib library is used to display the figure window.
Syntax: subplots(self, nrows=1, ncols=1, sharex=False, sharey=False, squeeze=True, subplot_kw=None, gridspec_kw=None)
Parameters: This method accept the following parameters that are described below:
nrows, ncols : These parameter are the number of rows/columns of the subplot grid.
sharex, sharey : These parameter controls sharing of properties among x (sharex) or y (sharey) axes.
squeeze : This parameter is an optional parameter and it contains boolean value with default as True.
num: This parameter is the pyplot.figure keyword that sets the figure number or label.
subplot_kwd: This parameter is the dict with keywords passed to the add_subplot call used to create each subplot.
gridspec_kw: This parameter is the dict with keywords passed to the GridSpec constructor used to create the grid the subplots are placed on.
Returns: This method return the following values.
ax : This method return the axes.Axes object or array of Axes objects.
Below examples illustrate the matplotlib.figure.Figure.subplots() function in matplotlib.figure:
Example 1:
# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt     x = np.linspace(0, 2 * np.pi, 400)y = np.sin(x**2)   fig = plt.figure()ax = fig.subplots()  ax.plot(x, y)  fig.suptitle("""matplotlib.figure.Figure.subplots()function Example\n\n""", fontweight ="bold")   fig.show() 
Output:
Example 2:
# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt     x = np.linspace(0, 1.5 * np.pi, 100)y = np.sin(x**2)+np.cos(x**2)   fig = plt.figure()axs = fig.subplots(2, 2, subplot_kw = dict(polar = True))  axs[0, 0].plot(x, y)axs[1, 1].scatter(x, y)  fig.suptitle("""matplotlib.figure.Figure.subplots()function Example\n\n""", fontweight ="bold")   fig.show() 
Output:
Matplotlib figure-class
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JavaScript SyntaxError – Unexpected token

31 Jul, 2020
This JavaScript exceptions unexpected token occur if a specific language construct was expected, but anything else is typed mistakenly. This could be a simple typing mistake.
Message:
SyntaxError: expected expression, got "x"
SyntaxError: expected property name, got "x" 
SyntaxError: expected target, got "x"
SyntaxError: expected rest argument name, got "x"
SyntaxError: expected closing parenthesis, got "x"
SyntaxError: expected '=>' after argument list, got "x"


Error Type:
SyntaxError

Cause of Error: There is a simple typing mistake in the code.
Example 1:
HTML
<!DOCTYPE html><html><head>    <title>Unexpected Token Error</title></head><body>    <script>        for (let i = 0; i < 5; ++i) {          document.write(i);         }    </script></body></html>
Output:
01234

Example 2: There is a typing mistake in the code, So the error occurred.
HTML
<!DOCTYPE html><html><head>    <title>Unexpected Token Error</title></head><body>    <script>        for (let i = 0; i < 5,; ++i) {          document.write(i);         }    </script></body></html>
Output(in console):
SyntaxError: Unexpected token ';'

javascript-basics
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Pandas Series.transpose()

05 Feb, 2019
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index.
Pandas Series.transpose() function return the transpose, which is by definition self.
Syntax: Series.transpose(*args, **kwargs)
Parameter : None
Returns : self
Example #1: Use Series.transpose() function to find the transpose of the given Series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio', 'Moscow'])  # Create the Datetime Indexdidx = pd.DatetimeIndex(start ='2014-08-01 10:00', freq ='W',                      periods = 6, tz = 'Europe/Berlin')   # set the indexsr.index = didx  # Print the seriesprint(sr)
Output :
Now we will use Series.transpose() function to find the transpose of the given series object.
# find the transposesr.transpose()
Output :
As we can see in the output, the Series.transpose() function has returned the same object as the transpose of the given series object, which is by definition self. Example #2: Use Dataframe.transpose() function to find the transpose of the given Dataframe.
# importing pandas as pdimport pandas as pd  # Creating the Dataframedf = pd.DataFrame({'Date':['10/2/2011', '11/2/2011', '12/2/2011', '13/2/2011'],                    'Event':['Music', 'Poetry', 'Theatre', 'Comedy'],                    'Cost':[10000, 5000, 15000, 2000]})  # Print the dataframeprint(df)
Output :
Now we will use Dataframe.transpose() function to find the transpose of the given Dataframe.
# find the transposedf.transpose()
Output :
As we can see in the output, the Dataframe.transpose() function has successfully returned the transpose of the given Dataframe object.
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Indexing Multi-dimensional arrays in Python using NumPy

05 Aug, 2021
NumPy is a general-purpose array-processing package. It provides a high-performance multidimensional array object and tools for working with these arrays. It is the fundamental package for scientific computing with Python. It contains various features.Note: For more information, refer to Python NumpyExample:  
Python3
# numpy library importedimport numpy as np # creating single-dimensional arrayarr_s = np.arrange(5)print(arr_s)
Output:  
[0 1 2 3 4]
arrange() method in numpy creates single dimension array of length 5. Single parameter inside the arrange() method acts as the end element for the range. arrange() also takes start and end arguments with steps. Example: 
Python3
import numpy as np # here inside arrange method we# provide start, end, step as# arguments.arr_b = np.arrange(20, 30, 2) # step argument helps in printing# every said step and skipping the# rest.print(arr_b)
Output: 
[20 22 24 26 28]
Indexing these arrays is simple. Every array element has a particular index associated with them. Indexing starts at 0 and goes on till the length of array-1. In the previous example, arr_b has 5 elements within itself. Accessing these elements can be done with:  
array_name[index_number]
Example:  
Python3
import numpy as np # here inside arrange method we# provide start, end, step as# arguments.arr_b = np.arrange(20, 30, 2) # step argument helps in printing# every said step and skipping the# rest.print(arr_b)  print(arr_b[2]) # Slicing operation from index# 1 to 3print(arr_b[1:4])
Output 
[20 22 24 26 28]
24
[22 24 26]
For Multidimensional array you can use reshape() method along with arrange()  
Python3
import numpy as np arr_m = np.arrange(12).reshape(6, 2)print(arr_m)
Output:  
[[ 0  1]
 [ 2  3]
 [ 4  5]
 [ 6  7]
 [ 8  9]
 [10 11]]
Inside reshape() the parameters should be the multiple of the arrange() parameter. In our previous example, we had 6 rows and 2 columns. You can specify another parameter whereby you define the dimension of the array. By default, it is an 2d array. Example: 
Python3
import numpy as np arr_m = np.arrange(12).reshape(2, 2, 3)print(arr_m)
Output  
[[[ 0  1  2]
  [ 3  4  5]]

 [[ 6  7  8]
  [ 9 10 11]]]
To index a multi-dimensional array you can index with slicing operation similar to a single dimension array.Example: 
Python3
import numpy as np arr_m = np.arrange(12).reshape(2, 2, 3) # Indexingprint(arr_m[0:3])print()print(arr_m[1:5:2,::3])
Output: 
[[[ 0  1  2]
  [ 3  4  5]]

 [[ 6  7  8]
  [ 9 10 11]]]

[[[6 7 8]]]
 
saurabh1990aror
Python numpy-Indexing
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Pandas Index.intersection()

17 Dec, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas Index.intersection() function form the intersection of two Index objects. This returns a new Index with elements common to the index and other, preserving the order of the calling index.
Syntax: Index.intersection(other)
Parameters :other : Index or array-like
Returns : intersection : Index
Example #1: Use Index.intersection() function to find the set intersection of two Indexes.
# importing pandas as pdimport pandas as pd  # Creating the first Indexidx1 = pd.Index(['Labrador', 'Beagle', 'Mastiff',                      'Lhasa', 'Husky', 'Beagle'])  # Creating the second Indexidx2 = pd.Index(['Labrador', 'Great_Dane', 'Pug',           'German_sepherd', 'Husky', 'Pitbull'])  # Print the first and second Indexprint(idx1, '\n', idx2)
Output :
Now we find the set intersection of the two Indexes.
# Find the elements common to both the Indexesidx2.intersection(idx1)
Output :
As we can see in the output, the Index.intersection() function has returned the intersection of the two indexes. The ordering of the labels has been maintained based on the calling Index. Example #2: Use Index.intersection() function to find the set intersection of two Indexes. The Index contains NaN values.
# importing pandas as pdimport pandas as pd  # Creating the first Indexidx1 = pd.Index(['2015-10-31', '2015-12-02', None, '2016-01-03',                       '2016-02-08', '2017-05-05', '2014-02-11'])  # Creating the second Indexidx2 = pd.Index(['2015-10-31', '2015-10-02', '2018-01-03',           '2016-02-08', '2017-06-05', '2014-07-11', None])  # Print the first and second Indexprint(idx1, '\n', idx2)
Output :
Now we find the intersection of idx1 and idx2.
# find intersection and maintain # ordering of labels based on idx1idx1.intersection(idx2)
Output :Note : The missing values in both the indexes are considered common to each other.
Python pandas-indexing
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Unbounded Knapsack (Repetition of items allowed) | Set 2

21 Jul, 2021
Given an integer W, arrays val[] and wt[], where val[i] and wt[i] are the values and weights of the ith item, the task is to calculate the maximum value that can be obtained using weights not exceeding W.Note: Each weight can be included multiple times.
Examples:
Input: W = 4, val[] = {6, 18}, wt[] = {2, 3}Output: 18Explaination: The maximum value that can be obtained is 18, by selecting the 2nd item twice.
Input: W = 50, val[] = {6, 18}, wt[] = {2, 3}Output: 294
Naive Approach: Refer to the previous post to solve the problem using traditional Unbounded Knapsack algorithm.Time Complexity: O(N * W)Auxiliary Space: O(W)
Efficient Approach:  The above approach can be optimized based on the following observations:
Suppose the ith index gives us the maximum value per unit weight in the given data, which can be easily found in O(n).
For any weight X, greater than or equal to wt[i], the maximum reachable value will be dp[X – wt[i]] + val[i].
We can calculate the values of dp[] from 0 to wt[i] using the traditional algorithm and we can also calculate the number of instances of ith item we can fit in W weight.
So the required answer will be val[i] * (W/wt[i]) + dp[W%wt[i]]. 
Below is the implementation of  new algorithm.
Python3
# Python Program to implement the above approach  from fractions import Fraction  # Function to implement optimized# Unbounded Knapsack algorithmdef unboundedKnapsackBetter(W, val, wt):      # Stores most dense item    maxDenseIndex = 0      # Find the item with highest unit value    # (if two items have same unit value then choose the lighter item)    for i in range(1, len(val)):                if Fraction(val[i], wt[i]) \            > Fraction(val[maxDenseIndex], wt[maxDenseIndex]) \             or (Fraction(val[i], wt[i]) == Fraction(val[maxDenseIndex], wt[maxDenseIndex]) \             and wt[i] < wt[maxDenseIndex] ):                           maxDenseIndex = i      dp = [0 for i in range(W + 1)]      counter = 0    breaked = False    for i in range(W + 1):        for j in range(len(wt)):                          if (wt[j] <= i):                dp[i] = max(dp[i], dp[i - wt[j]] + val[j])                          if i - wt[maxDenseIndex] >= 0 \            and dp[i] - dp[i-wt[maxDenseIndex]] == val[maxDenseIndex]:                              counter += 1                          if counter>= wt[maxDenseIndex]:                                  breaked = True                # print(i)                break        else:            counter = 0      if not breaked:        return dp[W]    else:        start = i - wt[maxDenseIndex] + 1        times = (W - start) // wt[maxDenseIndex]        index = (W - start) % wt[maxDenseIndex] + start        return (times * val[maxDenseIndex] + dp[index])                    # Driver CodeW = 100val = [10, 30, 20]wt = [5, 10, 15]   print(unboundedKnapsackBetter(W, val, wt))
300

Time Complexity: O( N + min(wt[i], W) * N)Auxiliary Space: O(W)
knapsack
Dynamic Programming
Mathematical
Dynamic Programming
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Replace NaN with Blank or Empty String in Pandas?

22 Nov, 2021
In this article, we will discuss how to replace NaN with Blank or Empty string in Pandas.
For this, we will create dataframe using pandas dataframe() object.
Python3
# import pandas moduleimport pandas as pd  # import numpy moduleimport numpy as np  # create dataframe with 3 columnsdata = pd.DataFrame({      "name": ['sravan', np.nan, 'harsha', 'ramya'],    "subjects": [np.nan, 'java', np.nan, 'html/php'],    "marks": [98, np.nan, np.nan, np.nan]})  # displaydata
Output:
We can replace the NaN with an empty string using replace() function. This function will replace an empty string inplace of the NaN value
Syntax: dataframe.replace(np.nan, ”)
where
dataframe is the input dataframe
first parameter takes Nan value
second parameter replace the NaN with empty string
Example:
Python3
# import pandas moduleimport pandas as pd  # import numpy moduleimport numpy as np  # create dataframe with 3 columnsdata = pd.DataFrame({      "name": ['sravan', np.nan, 'harsha', 'ramya'],    "subjects": [np.nan, 'java', np.nan, 'html/php'],    "marks": [98, np.nan, np.nan, np.nan]})  # replace nan with empty string# using replace() functiondata.replace(np.nan, '')
Output:
This is used to replace multiple columns NaN values with an empty string.
Syntax: dataframe[[‘columns’ ]].fillna(”)
where
dataframe is the input dataframe
columns are the multiple columns in the dataframe
Example:
Python3
# import pandas moduleimport pandas as pd  # import numpy moduleimport numpy as np  # create dataframe with 3 columnsdata = pd.DataFrame({      "name": ['sravan', np.nan, 'harsha', 'ramya'],    "subjects": [np.nan, 'java', np.nan, 'html/php'],    "marks": [98, np.nan, np.nan, np.nan]})  # replace nan with empty string# using fillna() functiondata[['name', 'subjects', 'marks']].fillna('')
Output:
dataframe.fillna('')
Example:
Python3
# import pandas moduleimport pandas as pd  # import numpy moduleimport numpy as np  # create dataframe with 3 columnsdata = pd.DataFrame({      "name": ['sravan', np.nan, 'harsha', 'ramya'],    "subjects": [np.nan, 'java', np.nan, 'html/php'],    "marks": [98, np.nan, np.nan, np.nan]})  # replace nan with empty string# using fillna() functiondata.fillna('')
Output:
pandas-dataframe-program
Picked
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Indices list of matching element from other list

10 Oct, 2019
Sometimes, while working with Python list, we have a problem in which we have to search for a element in list. But this can be extended to a list and need to find the exact places where elements occur in other list. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using loop + count()This is the brute method to perform this task. In this we can just count the occurrence of an element in other list and if we find it, then we add it’s index to the result list.
# Python3 code to demonstrate working of# Indices list of matching element from other list# Using loop + count()  # initializing liststest_list1 = [5, 7, 8, 9, 10, 11]test_list2 = [8, 10, 11]  # printing original listsprint("The original list 1 is : " + str(test_list1))print("The original list 2 is : " + str(test_list2))  # Indices list of matching element from other list# Using loop + count()res = []i = 0while (i < len(test_list1)):    if (test_list2.count(test_list1[i]) > 0):        res.append(i)    i += 1  # printing result print("The matching element Indices list : " + str(res))
The original list 1 is : [5, 7, 8, 9, 10, 11]
The original list 2 is : [8, 10, 11]
The matching element Indices list : [2, 4, 5]

 
Method #2 : Using list comprehension + set() + enumerate()The combination of above functions can be used to perform the task. In these we just convert the list to set and then check for index and value together for existence using enumerate() and append the index if found.
# Python3 code to demonstrate working of# Indices list of matching element from other list# Using list comprehension + set() + enumerate()  # initializing liststest_list1 = [5, 7, 8, 9, 10, 11]test_list2 = [8, 10, 11]  # printing original listsprint("The original list 1 is : " + str(test_list1))print("The original list 2 is : " + str(test_list2))  # Indices list of matching element from other list# Using list comprehension + set() + enumerate()temp = set(test_list2)res = [i for i, val in enumerate(test_list1) if val in temp]  # printing result print("The matching element Indices list : " + str(res))
The original list 1 is : [5, 7, 8, 9, 10, 11]
The original list 2 is : [8, 10, 11]
The matching element Indices list : [2, 4, 5]

Akanksha_Rai
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sort list of tuples by specific ordering in Python

When it is required to sort the list of tuples in a specific order, the 'sorted' method can be used.
The 'sorted' method is used to sort the elements of a list.
A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on). A list of tuple basically contains tuples enclosed in a list.
Below is a demonstration for the same −
Live Demo
def tuple_sort(my_tup):
   return(sorted(my_tup, key = lambda x: x[1]))

my_tuple = [('Mahe', 11), ('Aisha', 33), ('Will', 50), ('Root', 65)]

print("The list of tuple is : ")
print(my_tuple)
print("The tuple after placing in a specific order is : ")
print(tuple_sort(my_tuple))
The list of tuple is :
[('Mahe', 11), ('Aisha', 33), ('Will', 50), ('Root', 65)]
The tuple after placing in a specific order is :
[('Mahe', 11), ('Aisha', 33), ('Will', 50), ('Root', 65)]
A method named 'tuple_sort' is defined that takes a list of tuple as parameter.
It uses the 'sorted' method to sort the list of tuple in the order based on the first element in every tuple inside the list of tuple.
A list of tuple is defined, and is displayed on the console.
The function is called by passing this list of tuple as parameter.
This operation's data is stored in a variable.
This variable is the output that is displayed on the console.
Print a Formatted string in R Programming – sprintf() Function

03 Jun, 2020
sprintf() function in R Language uses Format provided by the user to return the formatted string with the use of the values in the list.
Syntax: sprintf(format, values)
Parameter:format: Format of printing the valuesvalues: to be passed into format
Example 1:
# R program to illustrate # the use of sprintf() function  # Initializing valuesx1 <- "Welcome"x2 <- "GeeksforGeeks"  # Calling sprintf() functionsprintf("% s to % s", x1, x2)
Output:
[1] "Welcome to GeeksforGeeks"

Example 2:
# R program to illustrate # the use of sprintf() function  # Initializing valuesx1 <- "GeeksforGeeks"x2 <- 100x3 <- "success"  # Calling sprintf() functionsprintf("% s gives %.0f percent % s", x1, x2, x3)
Output:
[1] "GeeksforGeeks gives 100 percent success"

R String-Functions
R-basics
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Create variables in MySQL stored procedure with DECLARE keyword

Use MySQL DECLARE for variables in stored procedure −
DECLARE anyVariableName int DEFAULT anyValue;
Let us implement the above syntax in order to create variables in stored procedure −
mysql> DELIMITER //
mysql> CREATE PROCEDURE variable_Demo()
    -> BEGIN
    -> DECLARE lastInsertedId int DEFAULT -1;
    -> select lastInsertedId;
    -> set @providedLastId=10001;
    -> select @providedLastId;
    -> END
    -> //
Query OK, 0 rows affected (0.32 sec)
mysql> DELIMITER ;
Now you can call the above stored procedure using CALL command −
mysql> call variable_Demo();
This will produce the following output −
+----------------+
| lastInsertedId |
+----------------+
|             -1 |
+----------------+
1 row in set (0.00 sec)

+-----------------+
| @providedLastId |
+-----------------+
|           10001 |
+-----------------+
1 row in set (0.02 sec)
Query OK, 0 rows affected (0.04 sec)
Tryit Editor v3.6 - Show Python

import matplotlib.pyplot as plt
numpy.random.seed(2)
​
x = numpy.random.normal(3, 1, 100)
y = numpy.random.normal(150, 40, 100) / x
How to create a data frame in R with list elements?

If a list has the same length of elements (not sub-elements) as the length of each vector for which we want to create the data frame then we first need to create the data frame of vectors then we can easily add the list into the data frame. But if we have a list and other vectors then data frame cannot be created as data.frame function will read each value of the list separately.
Live Demo
> df1<-data.frame(x=rpois(20,5),y=rpois(20,1))
> df1
   x y
1  6 1
2  8 1
3  6 2
4  8 1
5  5 1
6  3 1
7  6 1
8  7 1
9  7 1
10 7 2
11 5 0
12 5 2
13 2 2
14 4 0
15 2 1
16 3 1
17 4 0
18 6 4
19 6 2
20 4 1
> df1$z<-list(1:3,4:5,6:10,12:15,16:17,18:20,21:22,23:25,26:27,28:30,31:35,36:38,39:42,43:45,46:48,49:55,56:60,61:62,63:65,66:70)
> df1
  x y z
1 6 1            1, 2, 3
2 8 1            4, 5
3 6 2      6, 7, 8, 9, 10
4 8 1      12, 13, 14, 15
5 5 1          16, 17
6 3 1          18, 19, 20
7 6 1          21, 22
8 7 1          23, 24, 25
9 7 1          26, 27
10 7 2         28, 29, 30
11 5 0     31, 32, 33, 34, 35
12 5 2         36, 37, 38
13 2 2         39, 40, 41, 42
14 4 0         43, 44, 45
15 2 1         46, 47, 48
16 3 1 49, 50, 51, 52, 53, 54, 55
17 4 0     56, 57, 58, 59, 60
18 6 4         61, 62
19 6 2     63, 64, 65
20 4 1     66, 67, 68, 69, 70
Let’s have a look at another example:
> df2<-data.frame(F1=sample(LETTERS[1:4],20,replace=TRUE),F2=sample(LETTERS[21:26],20,replace=TRUE))
> df2
F1 F2
1 C W
2 B Z
3 A V
4 D W
5 D V
6 A X
7 C X
8 D Y
9 C Y
10 B V
11 D X
12 B W
13 D V
14 A U
15 A X
16 C X
17 C Z
18 B X
19 C Z
20 A V
> df2$F3<-list(rep(c("A","B")))
> df2
  F1 F2 F3
1 C W A, B
2 B Z A, B
3 A V A, B
4 D W A, B
5 D V A, B
6 A X A, B
7 C X A, B
8 D Y A, B
9 C Y A, B
10 B V A, B
11 D X A, B
12 B W A, B
13 D V A, B
14 A U A, B
15 A X A, B
16 C X A, B
17 C Z A, B
18 B X A, B
19 C Z A, B
20 A V A, B
Levenshtein Distance in JavaScript

The Levenshtein distance is a string metric for measuring the difference between two sequences. It is the minimum number of single-character edits required to change one word into the other.
For example −
Consider, we have these two strings −
const str1 = 'hitting';
const str2 = 'kitten';
The Levenshtein distance between these two strings is 3 because we are required to make these three edits −
kitten → hitten (substitution of "h" for "k")
kitten → hitten (substitution of "h" for "k")
hitten → hittin (substitution of "i" for "e")
hitten → hittin (substitution of "i" for "e")
hittin → hitting (insertion of "g" at the end)
hittin → hitting (insertion of "g" at the end)
We are required to write a JavaScript function that takes in two strings and calculates the Levenshtein distance between them.
Following is the code −
const str1 = 'hitting';
const str2 = 'kitten';
const levenshteinDistance = (str1 = '', str2 = '') => {
   const track = Array(str2.length + 1).fill(null).map(() =>
   Array(str1.length + 1).fill(null));
   for (let i = 0; i <= str1.length; i += 1) {
      track[0][i] = i;
   }
   for (let j = 0; j <= str2.length; j += 1) {
      track[j][0] = j;
   }
   for (let j = 1; j <= str2.length; j += 1) {
      for (let i = 1; i <= str1.length; i += 1) {
         const indicator = str1[i - 1] === str2[j - 1] ? 0 : 1;
         track[j][i] = Math.min(
            track[j][i - 1] + 1, // deletion
            track[j - 1][i] + 1, // insertion
            track[j - 1][i - 1] + indicator, // substitution
         );
      }
   }
   return track[str2.length][str1.length];
};
console.log(levenshteinDistance(str1, str2));
Following is the output on console −
3
D3.js axisBottom() Function - GeeksforGeeks

28 Jul, 2020
Axes can be drawn using built-in D3 functions. This is made of Lines, Ticks and Labels. The d3.axisBottom() function in D3.js is used to create a bottom horizontal axis. This function will construct a new bottom-oriented axis generator for the given scale, with empty tick arguments, a tick size of 6 and padding of 3.
Axis API can be configured using the following script.
<script src = "https://d3js.org/d3-axis.v1.min.js"></script>

Syntax:
d3.axisBottom(scale)

Parameters: This function accepts only one parameter as mentioned above and described below:
scale: This parameter holds the used scale.
Return Value: This function returns the created bottom horizontal axis.
Below programs illustrate the d3.axisBottom() function in D3.js:
Example 1:
HTML
<!DOCTYPE html><html>  <head>    <title>        D3.js | d3.axisBottom() Function    </title>    <script type="text/javascript"         src="https://d3js.org/d3.v4.min.js">    </script></head>  <body>    <script>        var width = 400, height = 400;        var svg = d3.select("body")            .append("svg")            .attr("width", width)            .attr("height", height);          var xscale = d3.scaleLinear()            .domain([0, 100])            .range([0, width - 50]);          var x_axis = d3.axisBottom(xscale);          svg.append("g")            .attr("transform", "translate(20,100)")            .call(x_axis)    </script></body>  </html>
Output:
Example 2:
HTML
<!DOCTYPE html><html>  <head>    <title>        D3.js | d3.axisBottom() Function    </title>    <script type="text/javascript"         src="https://d3js.org/d3.v4.min.js">    </script>          <style>        svg text {            fill: green;            font: 15px sans-serif;            text-anchor: center;        }    </style></head>  <body>    <script>        var width = 400, height = 400;        var data = [10, 12, 14, 16, 18, 20];        var svg = d3.select("body")            .append("svg")            .attr("width", width)            .attr("height", height);          var xscale = d3.scaleLinear()            .domain([d3.min(data), d3.max(data)])            .range([0, width - 60]);          var x_axis = d3.axisBottom(xscale);          var xAxisTranslate = height / 2;          svg.append("g")            .attr("transform", "translate(50, "            + xAxisTranslate + ")")            .call(x_axis)    </script></body>  </html>
Output:
D3.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to Open URL in New Tab using JavaScript ?
Remove elements from a JavaScript Array
Roadmap to Become a Web Developer in 2022
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to delete a column from a table in MySQL?

We can delete a column from a table with the help of ALTER command. Let’s say we have create a table and have a requirement to deleted some columns in it. We can achieve this using the ALTER and DRO[ command.
Let us see an example. First, we will create a table.
mysql> create table DeleteColumnNameDemo
   -> (
   -> Id int,
   -> Name varchar(200),
   -> Age int,
   -> Address varchar(200)
   -> );
Query OK, 0 rows affected (0.59 sec)
Above, we have created a table with four columns. Here is the query through which we can see all the details about the table.
mysql> desc DeleteColumnNameDemo;
The following is the output.
+---------+--------------+------+-----+---------+-------+
| Field   | Type         | Null | Key | Default | Extra |
+---------+--------------+------+-----+---------+-------+
| Id      | int(11)      | YES  |     | NULL    |       |
| Name    | varchar(200) | YES  |     | NULL    |       |
| Age     | int(11)      | YES  |     | NULL    |       |
| Address | varchar(200) | YES  |     | NULL    |       |
+---------+--------------+------+-----+---------+-------+
4 rows in set (0.00 sec)

Now we have 4 columns in our table. Now let us see the syntax to delete a column. The syntax is as follows.
alter table yourTableName
drop column yourColumnName1,
drop column yourColumnName2,
.
.
.
drop column yourColumnNameN,
Now, let us delete the column “Age” and “Address” from “DeleteColumnNameDemo” table. Apply the above syntax to delete the columns. The query is as follows.
mysql> ALTER table DeleteColumnNameDemo
   -> drop column Age,
   -> drop column Address;
Query OK, 0 rows affected (3.11 sec)
Records: 0  Duplicates: 0  Warnings: 0
We have deleted both the columns, Age and Address from the table. Let us now check the columns have been deleted or not with the help of DESC command.
mysql> desc DeleteColumnNameDemo;
The following is the output. We cannot see the two columns “Age’ and “Address” because we have deleted the before.
+-------+--------------+------+-----+---------+-------+
| Field | Type         | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| Id    | int(11)      | YES  |     | NULL    |       |
| Name  | varchar(200) | YES  |     | NULL    |       |
+-------+--------------+------+-----+---------+-------+
2 rows in set (0.05 sec)
How to save as PDF on Chrome using Selenium

We can save a pdf file on Chrome using the Selenium webdriver. To download the pdf file in a specific location we have to take the help of the Options class.
We shall create an object of this class and apply add_experimental_option on it. Then pass the values - prefs and the path where the pdf is to be downloaded as parameters to this method.
o = Options()
o.add_experimental_option("prefs" ,
{"download.default_directory": "../downloads"} )
Code Implementation
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
#object of Options
o = Options()
#path of downloaded pdf
o.add_experimental_option("prefs",{"download.default_directory": "../downloads"})
#pass Option to driver
driver = webdriver.Chrome(executable_path='../drivers/chromedriver', options=o)
#implicit wait
driver.implicitly_wait(0.5)
#url launch
driver.get("http://demo.automationtesting.in/FileDownload.html")
#maximize browser
driver.maximize_window()
#identify elements
l = driver.find_element_by_id('pdfbox')
l.send_keys("test")
m = driver.find_element_by_id('createPdf')
m.click()
n = driver.find_element_by_id('pdf-link-to-download')
n.click()
#driver quit
driver.quit()