code-rag-bench/online-tutorials huggingface dataset:
Python String | replace()

08 Jul, 2022
replace() is an inbuilt function in the Python programming language that returns a copy of the string where all occurrences of a substring are replaced with another substring.  
Syntax : 
string.replace(old, new, count)
Parameters :  
old – old substring you want to replace. new – new substring which would replace the old substring.count – the number of times you want to replace the old substring with the new substring. (Optional )  
Return Value : It returns a copy of the string where all occurrences of a substring are replaced with another substring.  
Note: 
If count is not specified then all the occurrences of the old substring are replaced with the new substring.
This method returns the copy of the string i.e. it does not change the original string.  
Below is the code demonstrating replace() :  
Example 1: 
Python3
# Python3 program to demonstrate the # use of replace() method    string = "geeks for geeks geeks geeks geeks"    # Prints the string by replacing all# geeks by Geeks print(string.replace("geeks", "Geeks"))   # Prints the string by replacing only# 3 occurrence of Geeks  print(string.replace("geeks", "GeeksforGeeks", 3))
Output :  
Geeks for Geeks Geeks Geeks Geeks
GeeksforGeeks for GeeksforGeeks GeeksforGeeks geeks geeks
Example 2:
Python3
# Python3 program to demonstrate the# use of replace() method  string = "geeks for geeks geeks geeks geeks"  # Prints the string by replacing# e by aprint(string.replace("e", "a"))  # Prints the string by replacing only# 3 occurrence of ek by aprint(string.replace("ek", "a", 3))
Output:  
gaaks for gaaks gaaks gaaks gaaks
geas for geas geas geeks geeks
 
nidhi_biet
xav1f6wh5lioybigrv64zv6genhitzictg7xhha5
python-string
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Recursive Descent Parser

01 Jun, 2021
Prerequisite – Construction of LL(1) Parsing Table, Classification of top down parsers Parsing is the process to determine whether the start symbol can derive the program or not. If the Parsing is successful then the program is a valid program otherwise the program is invalid. There are generally two types of Parsers:  
Top-Down Parsers: In this Parsing technique we expand the start symbol to the whole program.Recursive Descent and LL parsers are the Top-Down parsers.Bottom-Up Parsers: In this Parsing technique we reduce the whole program to start symbol.Operator Precedence Parser, LR(0) Parser, SLR Parser, LALR Parser and CLR Parser are the Bottom-Up parsers.
Top-Down Parsers: In this Parsing technique we expand the start symbol to the whole program.Recursive Descent and LL parsers are the Top-Down parsers.
In this Parsing technique we expand the start symbol to the whole program.
Recursive Descent and LL parsers are the Top-Down parsers.
Bottom-Up Parsers: In this Parsing technique we reduce the whole program to start symbol.Operator Precedence Parser, LR(0) Parser, SLR Parser, LALR Parser and CLR Parser are the Bottom-Up parsers.
In this Parsing technique we reduce the whole program to start symbol.
Operator Precedence Parser, LR(0) Parser, SLR Parser, LALR Parser and CLR Parser are the Bottom-Up parsers.
Recursive Descent Parser: It is a kind of Top-Down Parser. A top-down parser builds the parse tree from the top to down, starting with the start non-terminal. A Predictive Parser is a special case of Recursive Descent Parser, where no Back Tracking is required. By carefully writing a grammar means eliminating left recursion and left factoring from it, the resulting grammar will be a grammar that can be parsed by a recursive descent parser.Example:
 
**Here e is EpsilonFor Recursive Descent Parser, we are going to write one program for every variable.  
Example:
Grammar: E --> i E'
E' --> + i E' | e
 
C
int main(){    // E is a start symbol.    E();     // if lookahead = $, it represents the end of the string    // Here l is lookahead.    if (l == '$')        printf("Parsing Successful");} // Definition of E, as per the given productionE(){    if (l == 'i') {        match('i');        E'();    }} // Definition of E' as per the given productionE'()  {    if (l == '+') {        match('+');        match('i');        E'();    }//The second condition of E'    else if ( l == 'e' )    {      match('e');    }        return ();} // Match functionmatch(char t){    if (l == t) {        l = getchar();    }    else        printf("Error");}
bibouda512
Ranajit pal
chakkritip
Compiler Design
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Issues in the design of a code generator
Peephole Optimization in Compiler Design
Directed Acyclic graph in Compiler Design (with examples)
Type Checking in Compiler Design
Difference between Compiler and Interpreter
Layers of OSI Model
ACID Properties in DBMS
TCP/IP Model
Types of Operating Systems
Normal Forms in DBMS
Angular ng Bootstrap Accordion Component

06 Jul, 2021
Angular ng bootstrap is a bootstrap framework used with angular to create components with great styling and this framework is very easy to use and is used to make responsive websites.
In this article we will know how to use Accordion in angular ng bootstrap. Accordion is used to display collapsible content that presents information in a limited amount of space.
Installation syntax:
ng add @ng-bootstrap/ng-bootstrap
Approach:
First, install the angular ng bootstrap using the above-mentioned command.
Import ng bootstrap module in module.tsimport { NgbModule } from '@ng-bootstrap/ng-bootstrap';

imports: [
  NgbModule
]

import { NgbModule } from '@ng-bootstrap/ng-bootstrap';

imports: [
  NgbModule
]

In app.component.html make a accordion component.
Serve the app using ng serve.
 
Example:
pp.component.html
<ngb-accordion #acc="ngbAccordion"               activeIds="ngb-panel-0">  <ngb-panel title="GeeksforGeeks">    <ng-template ngbPanelContent>      Content1    </ng-template>  </ngb-panel>  <ngb-panel>    <ng-template ngbPanelTitle>      <span>Angular 10</span>    </ng-template>    <ng-template ngbPanelContent>      Content2    </ng-template>  </ngb-panel>  <ngb-panel title="Ng bootstrap"             [disabled]="true">    <ng-template ngbPanelContent>      Content3    </ng-template>  </ngb-panel>4</ngb-accordion>
app.module.ts
import { NgModule } from '@angular/core';  // Importing forms moduleimport { FormsModule, ReactiveFormsModule  }from '@angular/forms';import { BrowserModule }from '@angular/platform-browser';import { BrowserAnimationsModule }from '@angular/platform-browser/animations';   import { AppComponent }   from './app.component';import { NgbModule } from '@ng-bootstrap/ng-bootstrap';   @NgModule({  bootstrap: [    AppComponent  ],  declarations: [    AppComponent  ],  imports: [    FormsModule,    BrowserModule,    BrowserAnimationsModule,    ReactiveFormsModule,    NgbModule  ]})export class AppModule { }
Output:
Reference: https://ng-bootstrap.github.io/#/components/accordion/examples
Angular-ng-bootstrap
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Scala Map tail() method with example

13 Aug, 2019
The tail() method is utilized to display all the elements of the map except the first one.
Method Definition: def tail: Map[A, B]
Return Type: It returns all the elements of the stated map except the first one.
Example #1:
// Scala program of tail()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Creating a map        val m1 = Map(3 -> "geeks", 4 -> "for", 2 -> "cs")                  // Applying tail method        val result = m1.tail                  // Displays output        println(result)          }}
Map(4 -> for, 2 -> cs)

Example #2:
// Scala program of tail()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Creating a map        val m1 = Map(3 -> "geeks", 4 -> "for", 3 -> "geeks")                  // Applying tail method        val result = m1.tail                  // Displays output        println(result)          }}
Map(4 -> for)

Scala
Scala-Map
Scala-Method
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
\theta - Tex Command

\theta - Used to create lower case Greek theta symbol.
{ \theta}
\theta command draws theta symbol.

\theta

θ



\theta

θ


\theta

    14 Lectures 
     52 mins

 Ashraf Said

    11 Lectures 
     1 hours 

 Ashraf Said

    9 Lectures 
     1 hours 

 Emenwa Global, Ejike IfeanyiChukwu

    29 Lectures 
     2.5 hours 

 Mohammad Nauman

    14 Lectures 
     1 hours 

 Daniel Stern

    15 Lectures 
     47 mins

 Nishant Kumar
 Print
 Add Notes
 Bookmark this page
Python program to display all second lowest grade student name from nested list

Suppose we have the names and grades for each student in a nested list we have to display the names of any students having the second lowest grade. If there are more than one students with the second lowest grade, reorder these in an alphabetical order and print each name on a new line.
So, if the input is like students = [['Amal',37],['Bimal',37],['Tarun',36],['Akash',41],['Himadri',39]],
then the output will be Amal, Bimal both have second least score 37, they are placed in alphabetic order.
To solve this, we will follow these steps −
min_mark := minimum of scores for all x in students
students := a list of students x for all x in students if score of > min_mark
min2_mark := minimum of scores for all x in students
students := sort the list [with names of x for all x in students if score of x is same as
min2_mark]
for each x in students, dodisplay x
display x
Let us see the following implementation to get better understanding
def solve(students):
   min_mark = min(x[1] for x in students)
   students = [x for x in students if x[1] > min_mark]
   min2_mark = min(x[1] for x in students)
   students = sorted([x[0] for x in students if x[1] == min2_mark])
   for x in students:
      print(x)

students = [['Amal',37],['Bimal',37],['Tarun',36],['Akash',41],['Himadri',39]]
solve(students)
[['Amal',37],['Bimal',37],['Tarun',36],['Akash',41],['Himadri',39]]
Amal
Bimal
How can we convert a JSON string to a JSON object in Java?

The JSON stands for JavaScript Object Notation and it can be used to transfer and storage of data.  The JSONObject can parse text from a String to produce a map-like object. The object provides methods for manipulating its contents, and for producing a JSON compliant object serialization. The JSONArray can parse text from a String to produce a vector-like object. The object provides methods for manipulating its contents, and for producing a JSON compliant array serialization.
In the below two examples, We can convert a JSON string to a JSON object.
import org.json.JSONObject;
import org.json.JSONArray;
public class StringToJSONTest {
   public static void main(String args[]) {
      String str = "[{\"No\":\"1\",\"Name\":\"Adithya\"},{\"No\":\"2\",\"Name\":\"Jai\"}, {\"No\":\"3\",\"Name\":\"Raja\"}]";
      JSONArray array = new JSONArray(str);
      for(int i=0; i < array.length(); i++) {
         JSONObject object = array.getJSONObject(i);
         System.out.println(object.getString("No"));
         System.out.println(object.getString("Name"));
      }
   }
}
1
Adithya
2
Jai
3
Raja
import org.json.*;
public class StringToJsonObjectTest {
   public static void main(String[] args) {
      String str = "{\"name\": \"Raja\", \"technology\": \"Java\"}";
      JSONObject json = new JSONObject(str);
      System.out.println(json.toString());
      String tech = json.getString("technology");
      System.out.println(tech);
   }
}
{"name":"Raja","technology":"Java"}
Java
10 Examples That Will Make You Use Pandas Query Function More Often | by Soner Yıldırım | Towards Data Science

Pandas is a widely-used data analysis and manipulation library. It provides numerous functions and methods to perform typical operations simply and efficiently.
A typical task in data analysis is filtering data points (or observations). In case of working with tabular data, a data point is represented by a row. We sometimes need to filter a row based on some feature (or column) values.
There are several Pandas methods for filtering data points. In this article, we will focus on one of these methods. It is the query function.
Let’s first import libraries and create a sample data frame.
import numpy as npimport pandas as pddf = pd.DataFrame(np.random.randint(10, size=(5,6)), columns=list("ABCDEF"))df
We can now start using the query function to filter this data frame.
The query function allows for applying filtering conditions as a string. It provides more flexibility than many other techniques.
df.query("A > 4")
We have selected rows in which the value in column A is greater than 4.
We can easily combine multiple conditions.
df.query("A > 4 and E == 5")
It is possible to use the “or” logic to combine multiple conditions as well.
df.query("A > 2 or F > 4")
The “not” operator can also be implemented as part of the filter in the query function.
df.query("not (A > 2 or F > 4)")
We can also use simple math operations inside the query function.
df.query("A*2 < 5")
The query function allows for using some built-in functions which provide us with more flexibility.
For instance, we can use the abs function which returns the absolute value of a number. Let’s first convert the values in column F to negative integers and then write a query that includes the abs function.
df.F = -1 * df.Fdf.query("abs(F) > 6")
It is possible to use the sort (square root) function as well.
df.query("sqrt(A) > 2")
The logical operators can also be used for filtering strings. Let’s add a column that contains strings. We can then filter the data frame based on the new column.
df["G"] = ["John", "Jane", "Ashley", "Luke", "Michael"]df.query("G > 'Jo'")
The query function comes in handy when working with dates and times as well. We can implement some functions under the dt accessor. In order to demonstrate this functionality, we need a column with dates or times.
df["Date"] = pd.date_range(start="2021-04-05", periods=5, freq="M")df
Consider we need to select the rows in which the month value is more than 6. Here is how we can accomplish this task.
df.query("Date.dt.month > 6")
We can also create a condition that compares two or more columns.
df.query("A + B < C")
Filtering values is an important part of both data analysis and manipulation. We might be interested in values that fit a certain condition. Similarly, we might want to explore values based on a set of filters.
Pandas offers a rich selection of techniques for filtering data frames. The query function is one of them and it comes in handy for many cases.
Thank you for reading. Please let me know if you have any feedback.
How to find contours of an image using scikit-learn in Python?

Scikit-learn, commonly known as sklearn is a library in Python that is used for the purpose of implementing machine learning algorithms. It is an open-source library hence it can be used free of cost. This library is built on Numpy, SciPy and Matplotlib libraries.
The method of ‘marching squares’ is used to find the contours in an image. The function ‘find_contours’ present in the ‘measure’ class of ‘skimage’ library is used. In this, the values present in the array are interpolated in a linear manner.
This way, the precision of the contours in the output image would be much better. If the contours in the image intersect, the contours are open, else they are closed.
Let us understand how to find contours in an image using scikit-learn library −
import numpy as np
import matplotlib.pyplot as plt
from skimage import measure
x, y = np.ogrid[-6.7:np.pi:215j, -1.2:np.pi:215j]
r = np.sin(np.exp((np.sin(x)**3 + np.cos(y)**2)))
contours = measure.find_contours(r, 0.8)
fig, ax = plt.subplots()
ax.imshow(r, cmap=plt.cm.gray)
for contour in contours:
ax.plot(contour[:, 1], contour[:, 0], linewidth=2)
ax.axis('Image')
ax.set_xticks([])
ax.set_yticks([])
plt.show()
The required packages are imported into the environment.
The required packages are imported into the environment.
Data is generated with the help of NumPy package.
Data is generated with the help of NumPy package.
The function ‘find_contours’ is used to determine the contours of the image.
The function ‘find_contours’ is used to determine the contours of the image.
The ‘subplot’ function is used to show the original image and the image with contours on the console.
The ‘subplot’ function is used to show the original image and the image with contours on the console.
Lex program for Decimal to Binary Conversion - GeeksforGeeks

02 May, 2019
Problem: Write a Lex program for Decimal to Binary conversion.
Explanation:FLEX (Fast Lexical Analyzer Generator) is a tool/computer program for generating lexical analyzers (scanners or lexers) written by Vern Paxson in C around 1987. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language. The function yylex() is the main flex function which runs the Rule Section.
Examples:
Input: 12 
Output: 1100

Input: 115
Output: 1110011

Input: 25
Output: 11001

Input: 220
Output: 11011100 
Implementation:
/* Lex program for decimal to binary conversion */  %{  /* Definition section */  #include<stdio.h>  int num, r, b=0, p=1;%}  DIGIT [0-9]/* Rule Section */%%{DIGIT}+   { num=atoi(yytext);             while (num > 0)             {              r= num % 2;              b+= r*p;              p*= 10;              num/= 2;             }              printf("%d", b);            }.|\n    ECHO;         %%  // driver code int main(){    yylex();    return 0;}      
Output:
Lex program
Compiler Design
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Symbol Table in Compiler
Code Optimization in Compiler Design
Intermediate Code Generation in Compiler Design
Types of Parsers in Compiler Design
Introduction of Compiler Design
Directed Acyclic graph in Compiler Design (with examples)
Syntax Directed Translation in Compiler Design
Ambiguous Grammar
Difference between Compiler and Interpreter
Shift Reduce Parser in Compiler
How to resize an image in an HTML 5 canvas ? - GeeksforGeeks

27 Aug, 2019
The canvas element is part of HTML 5 and it allows the rendering of 2D shapes and bitmap(also called “raster”) images.A canvas actually has two sizes:
the size of the element.
the size of the element’s drawing surface.
The element’s width and height attributes set both the size of the element and the size of the element’s drawing surface. CSS attributes affect only the element’s size and not the drawing surface.
Example:
<!DOCTYPE html><html>  <body>      <p>Image:</p>      <img id="forest" width="220" height="277" src="https://media.geeksforgeeks.org/wp-content/uploads/20190809013546/gfg_350X350.png"            alt="Forest">      <p>Canvas:</p>      <canvas id="Canvas" width="300" height="200"                style="border:15px solid #000066;">        Your browser not support the HTML5 canvas .    </canvas>      <script>        window.onload = function() {            var canvas = document.getElementById("Canvas");            var context = canvas.getContext("2d");            var img = document.getElementById("forest");            context.drawImage(img, 12, 8);        };    </script></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-Misc
Picked
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
HTML Cheat Sheet - A Basic Guide to HTML
How to Insert Form Data into Database using PHP ?
Types of CSS (Cascading Style Sheet)
Form validation using HTML and JavaScript
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 ?
Difference between var, let and const keywords in JavaScript
How to perform string matching in MySQL?

For string matching, use LIKE operator. Let us first create a table −
mysql> create table DemoTable
   -> (
   -> MonthName varchar(100)
   -> );
Query OK, 0 rows affected (0.63 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('JFMA');
Query OK, 1 row affected (0.19 sec)

mysql> insert into DemoTable values('JMA');
Query OK, 1 row affected (0.16 sec)

mysql> insert into DemoTable values('JDN');
Query OK, 1 row affected (0.16 sec)

mysql> insert into DemoTable values('JFOSA');
Query OK, 1 row affected (0.19 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
+-----------+
| MonthName |
+-----------+
| JFMA      |
| JMA       |
| JDN       |
| JFOSA     |
+-----------+
4 rows in set (0.00 sec)
Following is the query to perform string matching in MySQL −
mysql> select *from DemoTable WHERE MonthName LIKE '%J%M%';
+-----------+
| MonthName |
+-----------+
| JFMA      |
| JMA       |
+-----------+
2 rows in set (0.00 sec)
What is the equivalent of EXCEPT in MySQL?

You cannot use EXCEPT in MySQL, instead use the NOT IN operator. Let us first create a table −
mysql> create table DemoTable
   (
   Number1 int
   );
Query OK, 0 rows affected (0.71 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(100);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values(200);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(300);
Query OK, 1 row affected (0.13 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable;
This will produce the following output −
+---------+
| Number1 |
+---------+
| 100     |
| 200     |
| 300     |
+---------+
3 rows in set (0.00 sec)
Following is the query to create second table −
mysql> create table DemoTable2
   (
   Number1 int
   );
Query OK, 0 rows affected (0.52 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable2 values(100);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable2 values(400);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable2 values(300);
Query OK, 1 row affected (0.11 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable2;
This will produce the following output −
+---------+
| Number1 |
+---------+
| 100     |
| 400     |
| 300     |
+---------+
3 rows in set (0.00 sec)
Following is the query to use NOT IN operator in place of EXCEPT −
mysql> select Number1 from DemoTable
where Number1 not in (SELECT Number1 FROM DemoTable2);
This will produce the following output −
+---------+
| Number1 |
+---------+
| 200     |
+---------+
1 row in set (0.04 sec)
How to convert an integer to a hexadecimal string in Python?

We can use built in hex() function to convert any integer to its hexadecimal representation.
>>> hex(100)
'0x64'
>>> hex(4095)
'0xfff'
>>> hex(31)
'0x1f'
Are array members deeply copied? - GeeksforGeeks

28 May, 2017
In C/C++, we can assign a struct (or class in C++ only) variable to another variable of same type. When we assign a struct variable to another, all members of the variable are copied to the other struct variable. But what happens when the structure contains pointer to dynamically allocated memory and what if it contains an array?
In the following C++ program, struct variable st1 contains pointer to dynamically allocated memory. When we assign st1 to st2, str pointer of st2 also start pointing to same memory location. This kind of copying is called Shallow Copy.
# include <iostream># include <string.h>  using namespace std;  struct test{  char *str;};  int main(){  struct test st1, st2;    st1.str = new char[20];  strcpy(st1.str, "GeeksforGeeks");    st2 = st1;    st1.str[0] = 'X';  st1.str[1] = 'Y';    /* Since copy was shallow, both strings are same */  cout << "st1's str = " << st1.str << endl;  cout << "st2's str = " << st2.str << endl;    return 0;}
Output:st1’s str = XYeksforGeeksst2’s str = XYeksforGeeks
Now, what about arrays? The point to note is that the array members are not shallow copied, compiler automatically performs Deep Copy for array members.. In the following program, struct test contains array member str[]. When we assign st1 to st2, st2 has a new copy of the array. So st2 is not changed when we change str[] of st1.
# include <iostream># include <string.h>  using namespace std;  struct test{  char str[20];};  int main(){  struct test st1, st2;    strcpy(st1.str, "GeeksforGeeks");    st2 = st1;    st1.str[0] = 'X';  st1.str[1] = 'Y';    /* Since copy was Deep, both arrays are different */  cout << "st1's str = " << st1.str << endl;  cout << "st2's str = " << st2.str << endl;    return 0;}
Output:st1’s str = XYeksforGeeksst2’s str = GeeksforGeeks
Therefore, for C++ classes, we don’t need to write our own copy constructor and assignment operator for array members as the default behavior is Deep copy for arrays.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
C Array and String
pointer
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
rand() and srand() in C/C++
Command line arguments in C/C++
Left Shift and Right Shift Operators in C/C++
fork() in C
Different methods to reverse a string in C/C++
Substring in C++
Function Pointer in C
TCP Server-Client implementation in C
Enumeration (or enum) in C
Converting Strings to Numbers in C/C++
Extract numbers from list of strings in Python

While using python for data manipulation, we may come across lists whose elements are a mix of letters and numbers with a fixed pattern. In this article we will see how to separate the numbers form letters which can be used for future calculations.
The split functions splits a string by help of a character that is treated as a separator. In the program below the list elements have hyphen as their separator between letters and text. We will use that along with a for loop to capture each
 Live Demo
listA = ['Mon-2', 'Wed-8', 'Thu-2', 'Fri-7']

# Given list
print("Given list : " + str(listA))

# Extracting numbers
num_list = [int(i.split('-')[1]) for i in listA]

# print result
print("List only with numbers : ",num_list)
Running the above code gives us the following result −
Given list : ['Mon-2', 'Wed-8', 'Thu-2', 'Fri-7']
List only with numbers : [2, 8, 2, 7]
In this approach we go through each element and check for the numeric part present in each element. The map function is used to apply the same function repeatedly on each of the element.
listA = ['Mon-2', 'Wed-8', 'Thu-2', 'Fri-7']

# Given list
print("Given list : " + str(listA))

# Extracting numbers
num_list = list(map(lambda sub:int(''.join(
[i for i in sub if i.isnumeric()])), listA))

# print result
print("List only with numbers : ",num_list)
Running the above code gives us the following result −
Given list : ['Mon-2', 'Wed-8', 'Thu-2', 'Fri-7']
List only with numbers : [2, 8, 2, 7]
How to mute audio using HTML5 ? - GeeksforGeeks

14 Jul, 2020
In this article, we mute the audio by using the muted attribute in the <audio> tag of the HTML document. It is used to define that the audio should be muted on the webpage.
Syntax:
<audio controls muted>
Example:
<!DOCTYPE html> <html> <head>    <title>        How to mute an audio using HTML5?    </title></head>  <body>     <h2>        GeeksForGeeks    </h2>    <h2>       How to mute an audio using HTML5?    </h2>    <p>Audio Sample</p>       <audio controls muted>         <source src="test.mp3" type="audio/mp3">         <source src="test.ogg" type="audio/ogg">     </audio>   </body>   </html>                    
Output:Supported browsers are listed below:
Google Chrome 4.0
Internet Explorer 9.0
Firefox 3.5
Opera 10.5
Safari 4.0
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
HTML-Misc
HTML5
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
REST API (Introduction)
Design a web page using HTML and CSS
Form validation using jQuery
How to place text on image using HTML and CSS?
How to auto-resize an image to fit a div container using CSS?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
Exclude certain columns from SHOW COLUMNS in MySQL?

Let us first create a demo table
mysql> create table excludeCertainColumnsDemo
   -> (
   -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> StudentName varchar(100),
   -> StudentAge int,
   -> StudentMarks int,
   -> StudentAddress varchar(200)
   -> );
Query OK, 0 rows affected (0.50 sec)
Now you can check the description of table with the help of desc command. The query is as follows −
mysql> desc excludeCertainColumnsDemo;
The following is the output
+----------------+--------------+------+-----+---------+----------------+
| Field          | Type         | Null | Key | Default | Extra          |
+----------------+--------------+------+-----+---------+----------------+
| StudentId      | int(11)      | NO   | PRI | NULL    | auto_increment |
| StudentName    | varchar(100) | YES  |     | NULL    |                |
| StudentAge     | int(11)      | YES  |     | NULL    |                |
| StudentMarks   | int(11)      | YES  |     | NULL    |                |
| StudentAddress | varchar(200) | YES  |     | NULL    |                |
+----------------+--------------+------+-----+---------+----------------+
5 rows in set (0.01 sec)
Here is the query to exclude certain columns from SHOW COLUMNS. You need to exclude the column 'StudentAge' and 'StudentMarks'. The query is as follows −
mysql> SHOW COLUMNS FROM excludeCertainColumnsDemo WHERE Field NOT IN ('StudentAge', 'StudentMarks');
The following is the output
+----------------+--------------+------+-----+---------+----------------+
| Field          | Type         | Null | Key | Default | Extra          |
+----------------+--------------+------+-----+---------+----------------+
| StudentId      | int(11)      | NO   | PRI | NULL    | auto_increment |
| StudentName    | varchar(100) | YES  |     | NULL    |                |
| StudentAddress | varchar(200) | YES  |     | NULL    |                |
+----------------+--------------+------+-----+---------+----------------+
3 rows in set (0.00 sec)
LISP - Macros

Macros allow you to extend the syntax of standard LISP.
Technically, a macro is a function that takes an s-expression as arguments and returns a LISP form, which is then evaluated.
In LISP, a named macro is defined using another macro named defmacro. Syntax for defining a macro is −
(defmacro macro-name (parameter-list))
"Optional documentation string."
body-form
The macro definition consists of the name of the macro, a parameter list, an optional documentation string, and a body of Lisp expressions that defines the job to be performed by the macro.
Let us write a simple macro named setTo10, which will take a number and set its value to 10.
Create new source code file named main.lisp and type the following code in it.
(defmacro setTo10(num)
(setq num 10)(print num))
(setq x 25)
(print x)
(setTo10 x)
When you click the Execute button, or type Ctrl+E, LISP executes it immediately and the result returned is −
25
10


    79 Lectures 
     7 hours 

 Arnold Higuit
 Print
 Add Notes
 Bookmark this page
Reshape a pandas DataFrame using stack,unstack and melt method

08 Jan, 2019
Pandas use various methods to reshape the dataframe and series. Let’s see about the some of that reshaping method.
Let’s import a dataframe first.
# import pandas moduleimport pandas as pd  # making dataframedf = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv")  # it was print the first 5-rowsprint(df.head()) 
Output:
Using stack() method:
Stack method works with the MultiIndex objects in DataFrame, it returning a DataFrame with an index with a new inner-most level of row labels. It changes the wide table to a long table.
# import pandas moduleimport pandas as pd  # making dataframedf = pd.read_csv("nba.csv")  # reshape the dataframe using stack() methoddf_stacked = df.stack()  print(df_stacked.head(26))
Output: Using unstack() method:unstack is similar to stack method, It also works with multi-index objects in dataframe, producing a reshaped DataFrame with a new inner-most level of column labels.
# import pandas moduleimport pandas as pd  # making dataframedf = pd.read_csv("nba.csv")  # unstack() methoddf_unstacked = df_stacked.unstack()print(df_unstacked.head(10))
Using melt() method:Melt in pandas reshape dataframe from wide format to long format. It uses the “id_vars[‘col_names’]” for melt the dataframe by column names.
# import pandas moduleimport pandas as pd  # making dataframedf = pd.read_csv("nba.csv")  # it takes two columns "Name" and "Team"df_melt = df.melt(id_vars =['Name', 'Team']) print(df_melt.head(10))
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 Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Python | Pandas MultiIndex.nlevels

24 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 MultiIndex.nlevels attribute returns the integer number of levels in the MultiIndex.
Syntax: MultiIndex.nlevels
Example #1: Use MultiIndex.nlevels attribute to find the number of levels in the MultiIndex.
# importing pandas as pdimport pandas as pd  # Creating the arrayarray = [[1, 2, 3], ['Sharon', 'Nick', 'Bailey']]  # Print the arrayprint(array)
Output :
Now let’s create the MultiIndex using this array
# Creating the MultiIndexmidx = pd.MultiIndex.from_arrays(array, names =('Number', 'Names'))  # Print the MultiIndexprint(midx)
Output :
Now we will find the number of levels in the MultiIndex.
# Print the number of the levels in MultiIndexmidx.nlevels
Output :As we can see in the output, there are 2 levels in the midx MultiIndex. Example #2: Use MultiIndex.nlevels attribute to find the number of levels in the given MultiIndex.
# importing pandas as pdimport pandas as pd  # Creating the arrayarray = [[1, 2, 3], ['Sharon', 'Nick', 'Bailey'],            ['Doctor', 'Scientist', 'Physicist']]  # Print the arrayprint(array)
Output :
Now let’s create the MultiIndex using this array
# Creating the MultiIndexmidx = pd.MultiIndex.from_arrays(array,           names =('Ranking', 'Names', 'Profession'))  # Print the MultiIndexprint(midx)
Output :
Now we will find the number of levels in the MultiIndex.
# Print the number of level in MultiIndexmidx.nlevels
Output :As we can see in the output, midx MultiIndex has 3 levels.
Python pandas-multiIndex
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Create a directory in Python
Generalized Lists in Data Structure

In this section we will see the generalized lists. The generalized list can be defined as below −
A generalized list L is a finite sequence of n elements (n ≥ 0). The element ei is either an atom (single element) or another generalized list. The elements ei that are not atoms, they will be sub-list of L. Suppose L is ((A, B, C), ((D, E), F), G). Here L has three elements sub-list (A, B, C), sub-list ((D, E), F), and atom G. Again sub-list ((D, E), F) has two elements one sub-list (D, E) and atom F.
In C++, we can define the Generalized list structure like below −
class GeneralizedListNode{
   private:
      GeneralizedListNode *next;
      bool tag;
      union{
         char data;
         GeneralizedListNode *down;
      };
};
So if the tag is true, then element represented by the node is a sub-list. The down points to the first node in the sub-list. If tag is false, the element is atom. The next pointer points to the next element in the list. The list will be look like this.
Python – Sum of tuple elements

19 Feb, 2020
Sometimes, while programming, we have a problem in which we might need to perform summation among tuple elements. This is an essential utility as we come across summation operation many times and tuples are immutable and hence required to be dealt with. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using list() + sum()The above functions can be combined to perform this task. We can employ sum() to accumulate the result of summation logic. The list() function is used to perform interconversions.
# Python3 code to demonstrate working of # Tuple summation# Using list() + sum()  # initializing tup test_tup = (7, 8, 9, 1, 10, 7)   # printing original tupleprint("The original tuple is : " + str(test_tup))   # Tuple elements inversions# Using list() + sum()res = sum(list(test_tup))  # printing result print("The summation of tuple elements are : " + str(res)) 
The original tuple is : (7, 8, 9, 1, 10, 7)
The summation of tuple elements are : 42

 
Method #2 : Using map() + sum() + list()The combination of above functions can be used to perform this task. In this, we first convert the tuple to list, flatten it’s each list element using map(), perform summation of each using sum() and again employ sum() for overall summation of resultant list.
# Python 3 code to demonstrate working of # Tuple elements inversions# Using map() + list() + sum()  # initializing tup test_tup = ([7, 8], [9, 1], [10, 7])   # printing original tupleprint("The original tuple is : " + str(test_tup))   # Tuple elements inversions# Using map() + list() + sum()res = sum(list(map(sum, list(test_tup))))  # printing result print("The summation of tuple elements are : " + str(res)) 
The original tuple is : (7, 8, 9, 1, 10, 7)
The summation of tuple elements are : 42

Python tuple-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Finding Exploit offline using Searchsploit in Kali Linux

24 Dec, 2020
SearchSploit is a command-line search tool for Exploit-DB that allows you to take a copy of the Exploit Database with you. Searchsploit is included in the Exploit Database repository on GitHub. SearchSploit is very useful for security assessments when you don’t have Internet access because it gives you the power to perform detailed offline searches for exploits in the saved Exploit-DB.
Installing SearchSploit – To run SearchSploit in Kali Linux, open the terminal and type “searchsploit” to run SearchSploit as “exploitdb” package is already included in Kali Linux. However, if you are using the Kali Light variant or your custom-build ISO then you can install SearchSploit manually using the below-mentioned command.
sudo apt update && sudo apt -y install exploitdb
Updating SearchSploit:  In order to update SearchSploit, run the following command:
searchsploit -u
1. Basic Search – You can add any number of search terms you wish to look for. In the below image, we are searching for exploits containing the term “oracle” and “windows”.
In case you need help just type “searchsploit -h” in the terminal. By using -h, you can see all the options and features that are available to you:
2. Title Searching in SearchSploit: If you are performing Basic Search, searchsploit will check for both the path and the title of the exploit. Searches can be restricted to the titles by using the -t option as follows:
In the above search, we are looking for the exploits related to Oracle based on Windows OS. 
3. Copying Exploit to Clipboard and Directory: If you want to copy the exploit to clipboard use ‘-p’. For example – ” searchsploit -p XYZ ” , here XYZ is the exploit ID. If you want to copy the exploit in your current working directory use ‘-m’. For example – ” searchsploit -m XYZ “, where XYZ is the exploit ID.
4. Examine an Exploit: If you want to examine an exploit or want to study an exploit, use ‘–examine’. For example – “searchsploit XYZ –examine” , where XYZ is the exploit ID.
5. Eliminate Unwanted Results: If you want to eliminate unwanted results from your search simply use ‘–exclude’. You can also remove multiple terms by separating the terms with a “|” (pipe). For example – searchsploit –exclude “PoC”.
Kali-Linux
Technical Scripter 2020
Linux-Unix
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
scp command in Linux with Examples
chown command in Linux with Examples
SED command in Linux | Set 2
Introduction to Linux Operating System
nohup Command in Linux with Examples
Array Basics in Shell Scripting | Set 1
mv command in Linux with examples
chmod command in Linux with examples
screen command in Linux with Examples
Python Program for Depth First Search or DFS for a Graph

22 Jun, 2022
Depth First Traversal (or Search) for a graph is similar to Depth First Traversal of a tree. The only catch here is, unlike trees, graphs may contain cycles, so we may come to the same node again. To avoid processing a node more than once, we use a boolean visited array.
For example, in the following graph, we start traversal from vertex 2. When we come to vertex 0, we look for all adjacent vertices of it. 2 is also an adjacent vertex of 0. If we don\’t mark visited vertices, then 2 will be processed again and it will become a non-terminating process. A Depth First Traversal of the following graph is 2, 0, 1, 3.
See this post for all applications of Depth First Traversal.Following are implementations of simple Depth First Traversal. The C++ implementation uses adjacency list representation of graphs. STL\’s list container is used to store lists of adjacent nodes.
Python
# Python program to print DFS traversal for complete graphfrom collections import defaultdict # This class represents a directed graph using adjacency# list representationclass Graph:     # Constructor    def __init__(self):         # default dictionary to store graph        self.graph = defaultdict(list)     # function to add an edge to graph    def addEdge(self,u,v):        self.graph[u].append(v)     # A function used by DFS    def DFSUtil(self, v, visited):         # Mark the current node as visited and print it        visited[v]= True        print v,         # Recur for all the vertices adjacent to        # this vertex        for i in self.graph[v]:            if visited[i] == False:                self.DFSUtil(i, visited)      # The function to do DFS traversal. It uses    # recursive DFSUtil()    def DFS(self):        V = len(self.graph)  #total vertices         # Mark all the vertices as not visited        visited =[False]*(V)         # Call the recursive helper function to print        # DFS traversal starting from all vertices one        # by one        for i in range(V):            if visited[i] == False:                self.DFSUtil(i, visited)  # Driver code# Create a graph given in the above diagramg = Graph()g.addEdge(0, 1)g.addEdge(0, 2)g.addEdge(1, 2)g.addEdge(2, 0)g.addEdge(2, 3)g.addEdge(3, 3) print "Following is Depth First Traversal"g.DFS() # This code is contributed by Neelam Yadav
Time Complexity : O(V+E) where V is the number of vertices in graph and E is the number of edges in graphAuxiliary Space: O(V)Please refer complete article on Depth First Search or DFS for a Graph for more details!
ishankhandelwals
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PHP | unlink() Function

23 Nov, 2020
The unlink() function is an inbuilt function in PHP which is used to delete files. It is similar to UNIX unlink() function. The $filename is sent as a parameter that needs to be deleted and the function returns True on success and false on failure.
Syntax:
unlink( $filename, $context )

Parameters: This function accepts two parameters as mentioned above and described below: 
$filename: It is a mandatory parameter which specifies the filename of the file which has to be deleted.
$context: It is an optional parameter which specifies the context of the file handle which can be used to modify the nature of the stream.
Return Value: It returns True on success and False on failure.
Errors And Exception:
The unlink() function generates an E_WARNING level error on failure.
The web server user must have write permissions to the directory for using the unlink() function.
The unlink() function returns Boolean False but many times it happens that it returns a non-Boolean value which evaluates to False.
Below programs illustrate the unlink() function in PHP:
Suppose there is a file named as “gfg.txt”Program 1:
PHP
<?php// PHP program to delete a file named gfg.txt// using unlink() function $file_pointer = "gfg.txt"; // Use unlink() function to delete a fileif (!unlink($file_pointer)) {    echo ("$file_pointer cannot be deleted due to an error");}else {    echo ("$file_pointer has been deleted");} ?>
Output: 
gfg.txt has been deleted

Program 2:
PHP
<?php// PHP program to delete a file named gfg.txt// using unlink() function $file_pointer = fopen('gfg.txt', 'w+');   // writing on a file named gfg.txtfwrite($file_pointer, 'A computer science portal for geeks!');fclose($file_pointer);   // Use unlink() function to delete a fileif (!unlink($file_pointer)) {    echo ("$file_pointer cannot be deleted due to an error");}else {    echo ("$file_pointer has been deleted");}  ?>
Output: 
Warning: unlink() expects parameter 1 to be a valid path, resource
given in C:\xampp\htdocs\server.php on line 12
Resource id #3 cannot be deleted due to an error

Reference: http://php.net/manual/en/function.unlink.php 
iamabhishek
arorakashish0911
simranarora5sos
PHP-file-handling
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to convert array to string in PHP ?
PHP | Converting string to Date and DateTime
How to get parameters from a URL string in PHP?
Split a comma delimited string into an array in PHP
Download file from URL using PHP
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?