code-rag-bench/online-tutorials huggingface dataset:
expandtabs() method in Python - GeeksforGeeks

13 Oct, 2020
expandtabs is a method specified in Strings in Python 3.
Sometimes, there is a need of specifying the space in the string, but the amount of space to be left is uncertain and depending upon the environment and conditions. For these cases, the need to modify the string, again and again, is a tedious task. Hence python in its library has “expandtabs()” which specifies the amount of space to be substituted with the “\t” symbol in the string.
Syntax : expandtabs(space_size)
Parameters :space_size : Specifies the space that is to be replaced with the “\t” symbol in the string. By default the space is 8.
Returns : Returns the modified string with tabs replaced by the space.
 Code #1 : Code to demonstrate expandtabs()
# Python3 code to demonstrate# working of expandtabs()  # initializing string str = "i\tlove\tgfg"  # using expandtabs to insert spacingprint("Modified string using default spacing: ", end ="")print(str.expandtabs())  print("\r")  # using expandtabs to insert spacingprint("Modified string using less spacing: ", end ="")print(str.expandtabs(2))  print("\r")  # using expandtabs to insert spacingprint("Modified string using more spacing: ", end ="")print(str.expandtabs(12))  print("\r")
Output:
Modified string using default spacing: i       love    gfg

Modified string using less spacing: i love  gfg

Modified string using more spacing: i           love        gfg

Exception :The exception of using this method is that it doesn’t accept the floating-point number if we want to decide the exact precision of the space we require.
 Code #2 : Code to demonstrate exception of expandtabs()
# Python3 code to demonstrate# exception of expandtabs()  # initializing string st = "i\tlove\tgfg"  # using expandtabs to insert spacingtry:    print("Modified string using default spacing: ")    print(st.expandtabs(10.5))      except Exception as e:    print("Error !! The error occurred is :")    print(str(e))
Output:
Modified string using default spacing: 
Error !! The error occurred is :
integer argument expected, got float

Applications :There are many possible applications where this can be used such as text formatting or documentation where user requirements keep on changing.
Python-Built-in-functions
Python-Functions
python-string
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
Ruby | Array delete() operation - GeeksforGeeks

21 Aug, 2021
Array#delete() : delete() is a Array class method which returns the array after deleting the mentioned elements. It can also delete a particular element in the array. 
Syntax:  Array.delete()

Parameter:  obj - specific element to delete

Return:  last deleted values from the array. 
Code #1 : Example for delete() method
Ruby
# Ruby code for delete() method# to delete elements # declaring arraya = [18, 22, 33, nil, 5, 6] # declaring arrayb = [1, 4, 1, 1, 88, 9] # declaring arrayc = [18, 22, nil, nil, 50, 6] # delete 5puts "delete : #{a.delete(5)}\n\n" # delete 10# printing if no such element is foundputs "delete : #{b.delete(10){"no such element"}}\n\n" # delete 20puts "delete : #{c.delete(20)}\n\n"
Output : 
delete : 5

delete : no such element

delete : 
Code #2 : Example for delete() method 
Ruby
# Ruby code for delete() method# to delete elements # declaring arraya = ["abc", "nil", "dog"] # declaring arrayb = ["cow", nil, "dog"] # declaring arrayc = ["cat", nil, nil] # deleteputs "delete : #{a.delete("abc")}\n\n" # delete# printing if no such element is foundputs "delete : #{b.delete("geek"){"no such element"}}\n\n" # deleteputs "delete : #{c.delete("cat")}\n\n"
Output : 
delete : abc

delete : no such element

delete : cat
 
singghakshay
Ruby Array-class
Ruby Collections
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Ruby | Types of Variables
Ruby | Enumerator each_with_index function
Ruby | Decision Making (if, if-else, if-else-if, ternary) | Set - 1
Ruby For Beginners
Ruby Mixins
Ruby | Array collect() operation
Ruby | Array shift() function
Ruby | String concat Method
Ruby | Array reject() function
Ruby | unless Statement and unless Modifier
divmod() in Python and its application

The divmod() is part of python’s standard library which takes two numbers as parameters and gives the quotient and remainder of their division as a tuple. It is useful in many mathematical applications like checking for divisibility of numbers and establishing if a number is prime or not.
Syntax: divmod(a, b)
a and b : b divides a
a and b are integers or floats
In the below example see the cases of both integers and floats. On the application of divmod() they give us a resulting tuple which is can also contain integers and float values.
# with integers
print("5 and 2 give:",divmod(5,2))
print("25 and 5 give:",divmod(25,5))

# with Floats
print("5.6 and 2 give:",divmod(5.6,2))
print("11.3 and 9.2 give:",divmod(11.3,9.2))
Running the above code gives us the following result −
5 and 2 give: (2, 1)
25 and 5 give: (5, 0)
5.6 and 2 give: (2.0, 1.5999999999999996)
11.3 and 9.2 give: (1.0, 2.1000000000000014)
If the first argument is zero then we get (0,0). And If the second argument is zero then we get Zerodivision error as expected.
# With first argument as zero
print("0 and 8 give:",divmod(0,8))

# With second argument as zero
print("8 and 0 give:",divmod(8,0))
Running the above code gives us the following result −
0 and 8 give: (0, 0)
Traceback (most recent call last):
File "xxx.py", line 6, in
print("8 and 0 give:",divmod(8,0))
ZeroDivisionError: integer division or modulo by zero
If the second value of the tuple after division is 0 then we say that the first number is divisible by second. Else it is not divisible. The below example illustrates this.
m = 12
n = 4
quotient,remainder = divmod(m,n)
print(quotient)
print(remainder)
if (remainder==0):
   print(m,' is divisible by ',n)
else:
   print(m,' is not divisible by ',n)
Running the above code gives us the following result −
3
0
12 is divisible by 4
We can use divmod() to keep track of the reminders it generates when we start dividing a number by each number starting with itself till 1. For a prime number the count of zero remainder will be only one as no number other than itself will divide it perfectly. If the count of zero remainder is greater than 1 then the number is not prime,.
num = 11
a = num
# counter the number of remainders with value zero
count = 0
while a != 0:
   q, r = divmod(num, a)
   a -= 1
   if r == 0:
      count += 1
if count > 2:
   print(num, 'is not Prime')
else:
   print(num, 'is Prime')
Running the above code gives us the following result −
11 is Prime
Check if a number is positive, negative or zero using bit operators in C++

Here we will check whether a number is positive, or negative or zero using bit operators. If we perform shifting like n >> 31, then it will convert every negative number to -1, every other number to 0. If we perform –n >> 31, then for positive number it will return -1. When we do for 0, then n >> 31, and –n >> 31, both returns 0. for that we will use another formula as below −
1+(n>>31)−(−n>>31)
So now, if
n is negative: 1 + (-1) – 0 = 0
n is positive: 1 + 0 – (-1) = 2
n is 0: 1 + 0 – 0 = 1
 Live Demo
#include <iostream>
#include <cmath>
using namespace std;
int checkNumber(int n){
   return 1+(n >> 31) - (-n >> 31);
}
int printNumberType(int n){
   int res = checkNumber(n);
   if(res == 0)
      cout << n << " is negative"<< endl;
   else if(res == 1)
      cout << n << " is Zero" << endl;
   else if(res == 2)
      cout << n << " is Positive" << endl;
}
int main() {
   printNumberType(50);
   printNumberType(-10);
   printNumberType(70);
   printNumberType(0);
}
50 is Positive
-10 is negative
70 is Positive
0 is Zero
Graph Coloring

Graph coloring problem is a special case of graph labeling. In this problem, each node is colored into some colors. But coloring has some constraints. We cannot use the same color for any adjacent vertices.
For solving this problem, we need to use the greedy algorithm, but it does not guaranty to use minimum color.
Input:
Adjacency matrix of the graph.
0 0 1 0 1
0 0 1 1 1
1 1 0 1 0
0 1 1 0 1
1 1 0 1 0

Output:
Node: 0, Assigned with Color: 0
Node: 1, Assigned with Color: 0
Node: 2, Assigned with Color: 1
Node: 3, Assigned with Color: 2
Node: 4, Assigned with Color: 1
graphColoring(graph)
Input − The given graph.
Output − Each node with some color assigned to it.
Begin
   declare a list of colors
   initially set the color 0 for first node
   define an array colorUsed to track which color is used, and which colors have never used.

   for all vertices i except first one, do
      mark i as unassigned to any color
   done

   mark colorUsed to false for all vertices
   for all vertices u in the graph except 1st vertex, do
      for all vertex v adjacent with u, do
         if color[v] is unassigned, then
            mark colorUsed[color[v]] := true
      done

      for all colors col in the color list, do
         if color is not used, then
            stop the loop
      done

      color[u] := col
      for each vertex v which is adjacent with u, do
         if color[v] is unassigned, then
            colorUsed[color[v]] := false
      done
   done

   for all vertices u in the graph, do
      display the node and its color
   done
End
#include<iostream>
#define NODE 6
using namespace std;

int graph[NODE][NODE] = {
   {0, 1, 1, 1, 0, 0},
   {1, 0, 0, 1, 1, 0},
   {1, 0, 0, 1, 0, 1},
   {1, 1, 1, 0, 1, 1},
   {0, 1, 0, 1, 0, 1},
   {0, 0, 1, 1, 1, 0}
};

void graphColoring() {
   int color[NODE];
   color[0] = 0;    //Assign first color for the first node
   bool colorUsed[NODE];    //Used to check whether color is used or not

   for(int i = 1; i<NODE; i++)
      color[i] = -1;    //initialize all other vertices are unassigned

   for(int i = 0; i<NODE; i++)
      colorUsed[i] = false;    //initially any colors are not chosen
         
   for(int u = 1; u<NODE; u++) {    //for all other NODE - 1 vertices
      for(int v = 0; v<NODE; v++) {
         if(graph[u][v]){
            if(color[v] != -1)    //when one color is assigned, make it unavailable
               colorUsed[color[v]] = true;
         }
     }

     int col;
     for(col = 0; col<NODE; col++)
        if(!colorUsed[col])    //find a color which is not assigned
           break;
         
     color[u] = col;    //assign found color in the list
         
     for(int v = 0; v<NODE; v++) {    //for next iteration make color availability to false
        if(graph[u][v]) {
           if(color[v] != -1)
              colorUsed[color[v]] = false;
        }
     }  
  }
   
  for(int u = 0; u<NODE; u++)
     cout <<"Color: " << u << ", Assigned with Color: " <<color[u] <<endl;
}

main() {
   graphColoring();
}
Node: 0, Assigned with Color: 0
Node: 1, Assigned with Color: 0
Node: 2, Assigned with Color: 1
Node: 3, Assigned with Color: 2
Node: 4, Assigned with Color: 1
C# Linq Intersect Method

Find common elements between two arrays using the Intersect() method.
The following are our arrays −
int[] val1 = { 15, 20, 40, 60, 75, 90 };
int[] val2 = { 17, 25, 35, 55, 75, 90 };
To perform intersection.
val1.AsQueryable().Intersect(val2);
Let us see the entire example.
 Live Demo
using System;
using System.Collections.Generic;
using System.Linq;
class Demo {
   static void Main() {
      int[] val1 = { 15, 20, 40, 60, 75, 90 };
      int[] val2 = { 17, 25, 35, 55, 75, 90 };
      IEnumerable<int> res = val1.AsQueryable().Intersect(val2);
      Console.WriteLine("Intersection of both the lists...");
      foreach (int a in res)
      Console.WriteLine(a);
   }
}
Intersection of both the lists...
75
90
How to print date in a regular format in Python?

If you print the dates directly using a print function, you'd get regular dates, 
import datetime
today = datetime.date.today()
print(today)
You will get the output −
2018-1-2
which is exactly what you want. But when you append this to a list and then try to print it, 
import datetime
my_list = []
today = datetime.date.today()
my_list.append(today)
print(my_list)
You will get the output −
[datetime.date(2018, 1, 2)]
This is happening because datetimes are objects. Therefore, when you manipulate them, you manipulate objects, not strings, not timestamps nor anything. Any object in Python have TWO string representations. The regular representation that is used by "print", can be get using the str() function. This one is implemented using the __str__ function in the class for that object. The alternative representation that is used to represent the object nature (as a data). It can be get using the repr() function.
So in order to get the correct representation, you need to call str explicitly on your datetime objects. 
import datetime
my_list = []
today = datetime.date.today()
my_list.append(str(today))
print(my_list)
You will get the output −
['2018-01-02']
Declaring a Fallback Color in CSS

Fallback color is used to specify the color for a situation when the browser doesn’t support RGBA colors. Some browsers that doesn’t support fallback colors are opera 9 and below, IE 8 and below etc. Specify a solid color before a RGBA color so the solid color can still work if the browser doesn’t support the RGBA colors.
Following is the code for declaring a fallback color in CSS −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
body{
   font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
div {
   padding:20px;
   font-size: 24px;
   background-color: purple; /*fallback color*/
   background-color: rgba(128, 0, 128, 0.527);
   color:white;
}
</style>
</head>
<body>
<h1>Fallback color example</h1>
<div>Some random text inside this div</div>
</body>
</html>
The above code will produce the following output −
Associative arrays in C++

In c++ programming language, an associative array is a special type of array in which the index value can be of any data type i.e. it can be char, float, string, etc. These associative arrays are also known as maps or dictionaries. Also, the indexes are given a different name which is key and the data that is stored at the position of the key is value.
So, we can define the associative array as a key-value pair.
Let's define an associative array of bikes and their top speed.
Bike top speed
Ninja 290
S1000rr 310
Bullet 127
Duke 135
R1 286
 Live Demo
#include <bits/stdc++.h>
using namespace std;
int main(){
   map<string, int> speed{ { "ninja", 290 },
   { "s1000rr", 310 }, { "bullet", 127 },
   { "Duke", 135 }, { "R1", 286 } };
   map<string, int>::iterator i;
   cout << "The topspeed of bikes are" << endl;
   for (i = speed.begin(); i != speed.end(); i++)
   cout<<i->first<<" "<<i->second <<endl;
   cout << endl;
   cout << "The top speed of bullet is "<< speed["bullet"] << endl;
}
The topspeed of bikes are
Duke    135
R1      286
Bullet  127
ninja   290
s1000rr 310
The top speed of bullet is 127
How to resolve "Expected BEGIN_OBJECT but was BEGIN_ARRAY" using Gson in Java?

While deserializing, a Gson can expect a JSON object but it can find a JSON array. Since it can't convert from one to the other, it can throw an error as "JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY" at the runtime.
import com.google.gson.Gson;
public class GsonErrorTest {
   public static void main(String args[]) throws Exception {
      String json = "{\"employee\":[{\"name\":\"Raja Ramesh\", \"technology\":\"java\"}]}";
      Gson gson = new Gson();
      Software software = gson.fromJson(json, Software.class);
      System.out.println(software);
   }
}
class Software {
   Employee employee;
}
class Employee {
   String name;
   String technology;
}
Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 14
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:176)at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:93)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:172)at com.google.gson.Gson.fromJson(Gson.java:795)
at com.google.gson.Gson.fromJson(Gson.java:761)
at com.google.gson.Gson.fromJson(Gson.java:710)
at com.google.gson.Gson.fromJson(Gson.java:682)
at BeginObjectError.main(BeginObjectError.java:7)
Caused by: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 14
at com.google.gson.stream.JsonReader.expect(JsonReader.java:339)
at com.google.gson.stream.JsonReader.beginObject(JsonReader.java:322)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:165)
We need to resolve it by changing our POJO type to a Collection or Array type. In the below example, we can use a List collection in our POJO class.
import java.util.List;
import com.google.gson.Gson;
public class GsonListTest {
   public static void main(String args[]) throws Exception {
      String jsonString = "{\"employees\":[{\"name\":\"Raja Ramesh\", \"technology\":\"Java\"}]}";
      Gson gson = new Gson();
      Software software = gson.fromJson(jsonString, Software.class);
      System.out.println(software);
   }
}
class Software {
   List<Employee> employees;
   @Override
   public String toString() {
      return "Software [employees=" + employees + "]";
   }
}
class Employee {
   String name;
   String technology;
   @Override
   public String toString() {
      return "Employee [name=" + name + ", technology=" + technology + "]";
   }
}
Software [employees=[Employee [name=Raja Ramesh, technology=Java]]]
Static functions in C - GeeksforGeeks

24 Aug, 2020
Prerequisite : Static variables in C
In C, functions are global by default. The “static” keyword before a function name makes it static. For example, below function fun() is static.
static int fun(void){  printf("I am a static function ");}
Unlike global functions in C, access to static functions is restricted to the file where they are declared. Therefore, when we want to restrict access to functions, we make them static. Another reason for making functions static can be reuse of the same function name in other files.
For example, if we store following program in one file file1.c
/* Inside file1.c */ static void fun1(void){  puts("fun1 called");}
And store following program in another file file2.c
/* Inside file2.c  */ int main(void){  fun1();   getchar();  return 0;  }
Now, if we compile the above code with command “gcc file2.c file1.c”, we get the error “undefined reference to `fun1’” . This is because fun1() is declared static in file1.c and cannot be used in file2.c.
Please write comments if you find anything incorrect in the above article, or want to share more information about static functions in C.
akhileshkasturi
C-Functions
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
fork() in C
Function Pointer in C
Substring in C++
rand() and srand() in C/C++
std::string class in C++
Enumeration (or enum) in C
Command line arguments in C/C++
TCP Server-Client implementation in C
Structures in C
Different methods to reverse a string in C/C++
Lodash - groupBy method

_.groupBy(collection, [iteratee=_.identity])

Creates an object composed of keys generated from the results of running each element of collection thru iteratee. The order of grouped values is determined by the order they occur in collection. The corresponding value of each key is an array of elements responsible for generating the key. The iteratee is invoked with one argument: (value).
collection (Array|Object) − The collection to iterate over.
collection (Array|Object) − The collection to iterate over.
[iteratee=_.identity] (Function) − The iteratee to transform keys.
[iteratee=_.identity] (Function) − The iteratee to transform keys.
(Object) − Returns the composed aggregate object.
(Object) − Returns the composed aggregate object.
var _ = require('lodash');
var list = [1.1 ,1.4, 2.1, 2.3];
 
var result = _.groupBy(list, Math.floor);
console.log(result);

result = _.groupBy(['one', 'two', 'three'], 'length');
console.log(result);
Save the above program in tester.js. Run the following command to execute this program.
\>node tester.js

{ '1': [ 1.1, 1.4 ], '2': [ 2.1, 2.3 ] }
{ '3': [ 'one', 'two' ], '5': [ 'three' ] }

 Print
 Add Notes
 Bookmark this page
How to generate random number in given range using JavaScript? - GeeksforGeeks

23 Apr, 2019
A number generated by a process, whose outcome is unpredictable is called Random Number. In JavaScript, this can be achieved by using Math.random() function. This article describes how to generate a random number using JavaScript.
Method 1: Using Math.random() function: The Math.random() function is used to return a floating-point pseudo-random number between range [0,1) , 0 (inclusive) and 1 (exclusive). This random number can then be scaled according to the desired range.
Syntax:
Math.random();
Example 1: This example generate an integer random number between 1(min) and 5(max).
<script>   // Function to generate random number function randomNumber(min, max) {     return Math.random() * (max - min) + min;}   document.write("Random Number between 1 and 5: ")   // Function calldocument.write( randomNumber(1, 5) ); </script>                                  
Output:
Random Number between 1 and 5: 1.0573617826058959
Method 2: Using Math.floor() function: The Math.floor() function in JavaScript is used to round off the number passed as parameter to its nearest integer in Downward direction of rounding i.e towards the lesser value.
Syntax:
Math.floor(value)
Example 2: This example generate random integer number between 1(min) and 100(max).
<script>   // Function to generate random number function randomNumber(min, max) {     return Math.floor(Math.random() * (max - min) + min);}   document.write("Random Number between 1 and 100: ")   // Function calldocument.write( randomNumber(1, 100) ); </script>                                     
Output:
Random Number between 1 and 100: 87
Example 3: This example generate random whole number between 1(min) and 10(max) both inclusive.
<script>   // Function to generate random number function randomNumber(min, max) {     min = Math.ceil(min);    max = Math.floor(max);    return Math.floor(Math.random() * (max - min + 1)) + min;}   document.write("Random Number between 1 and 10: ")   // Function calldocument.write( randomNumber(1, 10) ); </script>                                
Output:
Random Number between 1 and 10: 3
JavaScript-Misc
Picked
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
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 append HTML code to a div using 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 ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
SIGN() Function in SQL Server - GeeksforGeeks

30 Dec, 2020
SIGN() function :This function in SQL Server is used to return the sign of the specified number. It returns 1 if the number is positive, -1 if the number is negative and 0 for zero number.
Features :
This function is used to find the sign of the given number i.e., that given number is positive or negative or zero.
This function accepts only all type of numbers i.e., positive, negative, zero.
This function also accepts fraction numbers.
This function always returns 1 if the number is positive, -1 if the number is negative and 0 for zero number.
Syntax :
SIGN(number)
Parameter :This method accepts a parameter as given below :
number : Specified number to return the sign for.
Returns :It returns the sign of the specified number.
Example-1 :Getting the result as 1 i.e., positive for the specified number 2.
SELECT SIGN(2);
Output :
1
Example-2 :Getting the result as -1 i.e., negative for the specified number -7.
SELECT SIGN(-7);
Output :
-1
Example-3 :Using SIGN() function with a variable and getting the result as 0 for the specified number 0.
DECLARE @Parameter_Value INT;
SET @Parameter_Value = 0;
SELECT SIGN(@Parameter_Value);

Output :
0
Example-4 :Getting the result as 1 i.e., positive for the result of “5/2”.
SELECT SIGN(5/2);
Output :
1
Example-5 :Using SIGN() function with a variable and getting the result as 1 i.e., positive for the float value “5.75”.
DECLARE @Parameter_Value FLOAT;
SET @Parameter_Value = 5.75;
SELECT SIGN(@Parameter_Value);

Output :
1.0
Application :This function is used to return the sign of the specified number.
DBMS-SQL
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
How to Create a Table With Multiple Foreign Keys in SQL?
What is Temporary Table in SQL?
SQL | Subquery
SQL Query to Convert VARCHAR to INT
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL using Python
How to Write a SQL Query For a Specific Date Range and Date Time?
How to Select Data Between Two Dates and Times in SQL Server?
SQL Query to Compare Two Dates
PHP | mysqli_real_escape_string() Function - GeeksforGeeks

16 Oct, 2021
The mysqli_real_escape_string() function is an inbuilt function in PHP which is used to escape all special characters for use in an SQL query. It is used before inserting a string in a database, as it removes any special characters that may interfere with the query operations. When simple strings are used, there are chances that special characters like backslashes and apostrophes are included in them (especially when they are getting data directly from a form where such data is entered). These are considered to be part of the query string and interfere with its normal functioning.  
php
<?php $connection = mysqli_connect(    "localhost", "root", "", "Persons");        // Check connectionif (mysqli_connect_errno()) {    echo "Database connection failed.";}  $firstname = "Robert'O";$lastname = "O'Connell";  $sql="INSERT INTO Persons (FirstName, LastName)            VALUES ('$firstname', '$lastname')";    if (mysqli_query($connection, $sql)) {         // Print the number of rows inserted in    // the table, if insertion is successful    printf("%d row inserted.\n",            $mysqli->affected_rows);}else {         // Query fails because the apostrophe in    // the string interferes with the query    printf("An error occurred!");}  ?>
In the above code, the query fails because the apostrophes are considered as part of the query when it is executed using mysqli_query(). The solution is to use mysqli_real_escape_string() before using the strings in the query. 
php
<?php  $connection = mysqli_connect(        "localhost", "root", "", "Persons"); // Check connectionif (mysqli_connect_errno()) {    echo "Database connection failed.";}      $firstname = "Robert'O";$lastname = "O'Connell";  // Remove the special characters from the// string using mysqli_real_escape_string  $lastname_escape = mysqli_real_escape_string(                    $connection, $lastname);                     $firstname_escape = mysqli_real_escape_string(                    $connection, $firstname);  $sql="INSERT INTO Persons (FirstName, LastName)            VALUES ('$firstname_escape', '$lastname_escape')"; if (mysqli_query($connection, $sql)) {         // Print the number of rows inserted in    // the table, if insertion is successful    printf("%d row inserted.\n", $mysqli->affected_rows);}  ?>
Output:  
1 row inserted. 
 
ezequieldesimone
PHP-function
PHP-MySQL
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to execute PHP code using command line ?
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
PHP in_array() Function
How to pop an alert message box using PHP ?
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 ?
How to insert spaces/tabs in text using HTML/CSS?
How to store Data Triplet in a Vector in C++?

06 Jul, 2017
Given a vector, how can we store 3 elements in one cell of vector.
Examples:
Input : 2 5 10
        3 6 15
Output : (2, 5, 10)  // In first cell of vector
         (3, 6, 15)  // In second cell of vector

One solution is to create a user defined class or structure. We create a structure with three members, then create a vector of this structure.
// C++ program to store data triplet in a vector// using user defined structure.#include<bits/stdc++.h>using namespace std;  struct Test{   int x, y, z;};  int main(){    // Creating a vector of Test    vector<Test> myvec;      // Inserting elements into vector. First    // value is assigned to x, second to y    // and third to z.    myvec.push_back({2, 31, 102});    myvec.push_back({5, 23, 114});    myvec.push_back({9, 10, 158});      int s = myvec.size();    for (int i=0;i<s;i++)    {        // Accessing structure members using their        // names.        cout << myvec[i].x << ", " << myvec[i].y             << ", " << myvec[i].z << endl;    }    return 0;}
Output :
2, 31, 102
5, 23, 114
9, 10, 158

 
Another solution is to use pair class in C++ STL. We make a pair with first element as normal element and second element as another pair, therefore storing 3 elements simultaneously.
// C++ program to store data triplet in a vector// using pair class#include<bits/stdc++.h>using namespace std;  int main(){    // We make a pair with first element as normal    // element and second element as another pair.    // therefore 3 elements simultaneously.    vector< pair<int, pair<int, int> > > myvec;      // For inserting element in pair use    // make_pair().    myvec.push_back(make_pair(2, make_pair(31, 102)));    myvec.push_back(make_pair(5, make_pair(23, 114)));    myvec.push_back(make_pair(9, make_pair(10, 158)));      int s = myvec.size();    for (int i=0; i<s; i++)    {        // The elements can be directly accessed        // according to first or second element        // of the pair.        cout << myvec[i].first << ", " << myvec[i].second.first              << ", " << myvec[i].second.second << endl;    }    return 0;} 
Output:
2, 31, 102
5, 23, 114
9, 10, 158

This article is contributed by Jatin Goyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
cpp-algorithm-library
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
Friend class and function in C++
Pair in C++ Standard Template Library (STL)
std::string class in C++
Queue in C++ Standard Template Library (STL)
Unordered Sets in C++ Standard Template Library
std::find in C++
List in C++ Standard Template Library (STL)
Inline Functions in C++
SAP ABAP - If...Else Statement

In case of IF....ELSE statements, if the expression evaluates to true then the IF block of code will be executed. Otherwise, ELSE block of code will be executed.
The following syntax is used for IF....ELSE statement.
IF<condition_1>.  
   <statement block 1>.  
ELSE.   
   <statement block 2>.  
ENDIF.

Report YH_SEP_15.
  
Data Title_1(20) TYPE C.  
     Title_1 = 'Tutorials'.
	
IF Title_1 = 'Tutorial'.  
   write 'This is IF Statement'.  
ELSE.  
   write 'This is ELSE Statement'.
  
ENDIF.
The above code produces the following output −
This is ELSE Statement.

Sometimes nesting of the IF statements can make the code difficult to understand. In such cases, the ELSEIF statement is used to avoid nesting of the IF statement.
When using IF, ELSEIF and ELSE statements there are a few points to consider −
An IF statement can have zero or one ELSE statement and it must come after any ELSEIF statement.
An IF statement can have zero or one ELSE statement and it must come after any ELSEIF statement.
An IF statement can have zero to many ELSEIF statements and they must come before the ELSE statement.
An IF statement can have zero to many ELSEIF statements and they must come before the ELSE statement.
If an ELSEIF statement succeeds, none of the remaining ELSEIF statements or ELSE statement will be tested.
If an ELSEIF statement succeeds, none of the remaining ELSEIF statements or ELSE statement will be tested.
The following syntax is used for the IF....ELSEIF....ELSE statement.
IF<condition_1>.
  
<statement block 1>.
  
ELSEIF<condition_2>.
  
<statement block 2>.
  
ELSEIF<condition_3>. 
 
<statement block 3>. 
...... 
...... 
...... 
...... 
ELSE.
  
<statement block>.  

ENDIF.

In the above syntax, the execution of the processing block is based on the result of one or more logical conditions associated with the processing block. Here −
condition_1 of IF statement represents a logical condition that evaluates a true or false condition.
condition_1 of IF statement represents a logical condition that evaluates a true or false condition.
condition_2 shows the second condition specified in the ELSEIF statement, which is executed when the IF statement condition turns out to be false.
condition_2 shows the second condition specified in the ELSEIF statement, which is executed when the IF statement condition turns out to be false.
ENDIF denotes the end of the IF statement block.
ENDIF denotes the end of the IF statement block.
Report YH_SEP_15.  
Data Result TYPE I VALUE 65.  
   IF Result < 0.  
	
Write / 'Result is less than zero'.  
   ELSEIF Result < 70.  
	
Write / 'Result is less than seventy'.  
ELSE.  

Write / 'Result is greater than seventy'.
  
   ENDIF.
The above code produces the following output −
Result is less than seventy.
Lodash _.hasIn() Method

09 Sep, 2020
The _.hasIn() method is used to check whether the path is a direct or inherited property of object or not. It returns true if path exists, else it returns false.
Syntax:
_.hasIn(object, path)

Parameters: This method accepts two parameters as mentioned above and described below:
object: This parameter holds the object to query.
path: This parameter holds the path to check. The path will be array or string.
Return Value: This method returns true if path exists, else false
Example 1:
Javascript
// Requiring the lodash library  const _ = require("lodash");    // Given objectvar object =  _.create({ 'a': _.create({ 'b': 2 }) });  // Use of _.hasIn method console.log(_.hasIn(object, 'a')); console.log(_.hasIn(object, ['a'])); console.log(_.hasIn(object, ['b'])); 
Output:
true
true
false

Example 2:  
Javascript
// Requiring the lodash library  const _ = require("lodash");    // Given objectvar object =  _.create({ 'a': _.create({ 'b': 2 }) });  // Use of _.hasIn method console.log(_.hasIn(object, 'a.b')); console.log(_.hasIn(object, ['a','b'])); console.log(_.hasIn(object, ['a','b','c'])); 
Output:
true
true
false

JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
JavaScript | Promises
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
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 ?
How do I plot Shapely polygons and objects using Matplotlib?

To plot shapely polygons and objects using matplotlib, the steps are as follows −
Create a polygon object using (x, y) data points.
Create a polygon object using (x, y) data points.
Get x and y, the exterior data, and the array using polygon.exterior.xy.
Get x and y, the exterior data, and the array using polygon.exterior.xy.
Plot x and y data points using plot() method with red color.
Plot x and y data points using plot() method with red color.
from shapely.geometry import Polygon
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
polygon1 = Polygon([(0, 5),
   (1, 1),
   (3, 0),
   (4, 6),
])
x, y = polygon1.exterior.xy
plt.plot(x, y, c="red")
plt.show()
Node.js - Path Module

Node.js path module is used for handling and transforming file paths. This module can be imported using the following syntax.
var path = require("path")

path.normalize(p)
Normalize a string path, taking care of '..' and '.' parts.
path.join([path1][, path2][, ...])
Join all the arguments together and normalize the resulting path.
path.resolve([from ...], to)
Resolves to an absolute path.
path.isAbsolute(path)
Determines whether the path is an absolute path. An absolute path will always resolve to the same location, regardless of the working directory.
path.relative(from, to)
Solve the relative path from from to to.
path.dirname(p)
Return the directory name of a path. Similar to the Unix dirname command.
path.basename(p[, ext])
Return the last portion of a path. Similar to the Unix basename command.
path.extname(p)
Return the extension of the path, from the last '.' to end of string in the last portion of the path. If there is no '.' in the last portion of the path or the first character of it is '.', then it returns an empty string.
path.parse(pathString)
Returns an object from a path string.
path.format(pathObject)
Returns a path string from an object, the opposite of path.parse above.
path.sep
The platform-specific file separator. '\\' or '/'.
path.delimiter
The platform-specific path delimiter, ; or ':'.
path.posix
Provide access to aforementioned path methods but always interact in a posix compatible way.
path.win32
Provide access to aforementioned path methods but always interact in a win32 compatible way.
Create a js file named main.js with the following code −
var path = require("path");

// Normalization
console.log('normalization : ' + path.normalize('/test/test1//2slashes/1slash/tab/..'));

// Join
console.log('joint path : ' + path.join('/test', 'test1', '2slashes/1slash', 'tab', '..'));

// Resolve
console.log('resolve : ' + path.resolve('main.js'));

// extName
console.log('ext name : ' + path.extname('main.js'));
Now run the main.js to see the result −
$ node main.js

Verify the Output.
normalization : /test/test1/2slashes/1slash
joint path : /test/test1/2slashes/1slash
resolve : /web/com/1427176256_27423/main.js
ext name : .js
Multiline Strings in Perl

If you want to introduce multiline strings into your programs, you can use the standard single quotes as below −
 Live Demo
#!/usr/bin/perl
$string = 'This is
a multiline
string';
print "$string\n";
This will produce the following result −
This is
a multiline
string
You can use "here" document syntax as well to store or print multiline as below −
 Live Demo
#!/usr/bin/perl
print <<EOF;
This is
a multiline
string
EOF
This will also produce the same result −
This is
a multiline
string
How to check if array contains a duplicate number using C#?

Firstly, set an array −
int[] arr = {
   87,
   55,
   23,
   87,
   45,
   23,
   98
};
Now declare a dictionary and loop through the array and get the count of all the elements. The value you get from the dictionary displays the occurrence of numbers −
foreach(var count in arr) {
   if (dict.ContainsKey(count))
   dict[count]++;
   else
   dict[count] = 1;
}
Let us see the complete example −
using System;
using System.Collections.Generic;
namespace Demo {
   public class Program {
      public static void Main(string[] args) {
     
         int[] arr = {
            87,
            55,
            23,
            87,
            45,
            23,
            98
         };
         var dict = new Dictionary < int, int > ();
         foreach(var count in arr) {
            if (dict.ContainsKey(count))
            dict[count]++;
            else
            dict[count] = 1;
         }
         foreach(var val in dict)
         Console.WriteLine("{0} occurred {1} times", val.Key, val.Value);
      }
   }
}
Java Program to Check If a Number is Spy number or not - GeeksforGeeks

04 Jan, 2021

A number is said to be a Spy number if the sum of all the digits is equal to the product of all digits. For performing the task we need to reverse through the number which will take log(N) time.
  Example:
Input : 22
Output:  Given number is a SPY number.
Explanation: Sum of the number is 4 (2 + 2)
             Product of the number is as 4 (2 * 2) 
Input : 1241
Output:  Given number is not a SPY number.
Approach:

Calculate the sum of digits of the input Number.
Calculate the product of digits of the input Number.
If the sum of digits equals the product of digits then the number is Spy number otherwise not.

Calculate the sum of digits of the input Number.
Calculate the product of digits of the input Number.
If the sum of digits equals the product of digits then the number is Spy number otherwise not.
Below is the implementation of the above approach:
Java
 

 
 










// Java Program to Check If a Number is Spy number or not 
import java.io.*; 
  
class GFG { 
    public static void main(String[] args) 
    { 
        int product = 1, sum = 0, ld; 
        int n = 22; 
  
        // calculate sum and product of the number here. 
        while (n > 0) { 
            ld = n % 10; 
            sum = sum + ld; 
            product = product * ld; 
            n = n / 10; 
        } 
  
        // compare the sum and product. 
        if (sum == product) 
            System.out.println( 
                "Given number is spy number"); 
        else
            System.out.println( 
                "Given number is not spy number"); 
    } 
}






Given number is spy number

Complexity: O(log(n))

Picked


Java


Java Programs

Writing code in comment? 
                                    Please use ide.geeksforgeeks.org, 
                                    generate link and share the link here.
                                
Functional Interfaces in Java
Stream In Java
Constructors in Java
Different ways of Reading a text file in Java
Exceptions in Java
Convert a String to Character array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
How to iterate over dictionaries using 'for' loops in Python?

Even though dictionary itself is not an iterable object, the items(), keys() and values methods return iterable view objects which can be used to iterate through dictionary.
The items() method returns a list of tuples, each tuple being key and value pair.
>>> d1={'name': 'Ravi', 'age': 23, 'marks': 56}
>>> for t in d1.items():
print (t)

('name', 'Ravi')
('age', 23)
('marks', 56)
Key and value out of each pair can be separately stored in two variables and traversed like this −
>>> d1={'name': 'Ravi', 'age': 23, 'marks': 56}
>>> for k,v in d1.items():
print (k,v)

name Ravi
age 23
marks 56
Using iterable of keys() method each key and associated value can be obtained as follows −
>>> for k in d1.keys():
print (k, d1.get(k))

name Ravi
age 23
marks 56
Matplotlib.figure.Figure.colorbar() in Python

30 Apr, 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 colorbar() method of figure module of matplotlib library is used to add a colorbar to a plot.
Syntax: colorbar(self, mappable, cax=None, ax=None, use_gridspec=True, **kw)
Parameters: This accept the following parameters that are described below:
mappable: This parameter is mandatory for the Figure.colorbar method.
cax : This parameter is the Axes into which the colorbar will be drawn.
ax : This parameter is the parent axes from which space for a new colorbar axes will be stolen.
use_gridspec : This parameter is used to create an instance of Subplot using the gridspec module.
Returns: This method does not return any value.
Below examples illustrate the matplotlib.figure.Figure.colorbar() function in matplotlib.figure:
Example 1:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport matplotlib.tri as mtriimport numpy as np       # Create triangulation.x = np.asarray([0, 1, 2, 3, 0.5,                1.5, 2.5, 1, 2,                 1.5])  y = np.asarray([0, 0, 0, 0, 1.0,                1.0, 1.0, 2, 2,                 3.0])  triangles = [[0, 1, 4], [1, 5, 4],              [2, 6, 5], [4, 5, 7],             [5, 6, 8], [5, 8, 7],             [7, 8, 9], [1, 2, 5],              [2, 3, 6]]  triang = mtri.Triangulation(x, y, triangles)z = np.cos(3 * x) * np.cos(6 * y)+np.sin(6 * x)       fig, axs = plt.subplots()t = axs.tricontourf(triang, z)axs.tricontour(triang, z, colors ='white')fig.colorbar(t)  fig.suptitle('matplotlib.figure.Figure.colorbar() \function Example\n\n', fontweight ="bold")  plt.show()
Output:
Example 2:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport matplotlib.tri as triimport numpy as np     n_angles = 26n_radii = 10min_radius = 0.35radii = np.linspace(min_radius,                    0.95,                    n_radii)   angles = np.linspace(0, 2 * np.pi,                     n_angles,                     endpoint = False)  angles = np.repeat(angles[..., np.newaxis],                    n_radii,                   axis = 1)  angles[:, 1::2] += np.pi / n_angles   x = (10 * radii * np.cos(angles)).flatten()y = (10 * radii * np.sin(angles)).flatten()z = (np.cos(4 * radii) * np.cos(3 * angles)).flatten()   triang = tri.Triangulation(x, y)   triang.set_mask(np.hypot(x[triang.triangles].mean(axis = 1),                         y[triang.triangles].mean(axis = 1))                < min_radius)     fig1, ax1 = plt.subplots()ax1.set_aspect('equal')tcf = ax1.tricontourf(triang, z)fig1.colorbar(tcf)ax1.tricontour(triang, z, colors ='g')  fig1.suptitle('matplotlib.figure.Figure.colorbar()\function Example\n\n', fontweight ="bold")  plt.show()
Output:
Matplotlib figure-class
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.