code-rag-bench/online-tutorials huggingface dataset:
How to shift a column in a Pandas DataFrame?

We can use the shift() method in Pandas to shift the columns of a DataFrame without having to rewrite the whole DataFrame. shift() takes the following parameters
shift(self, periods=1, freq=None, axis=0, fill_value=None)
periods  Number of periods to shift. It can take a negative number too.
axis  It takes a Boolean value; 0 if you want to shift index and 1 if you want to shift column
fill_value  It will replace the missing value.
Let's take an example and see how to use this shift() method.
Create a two-dimensional, size-mutable, potentially heterogeneous tabular data, df.
Print the input DataFrame, df.
Select a column and shift it by using df["column_name]=df.column_name.shift()
Print the updated DataFrame.
import pandas as pd

df = pd.DataFrame(
   dict(
      name=['John', 'Jacob', 'Tom', 'Tim', 'Ally'],
      marks=[89, 23, 100, 56, 90],
      subjects=["Math", "Physics", "Chemistry", "Biology", "English"]
   )
)

print "Input DataFrame is:\n", df

df["name"] = df.name.shift(1)
print "After shifting column name by 1:\n", df

df["marks"] = df.marks.shift(2)
print "After shifting column marks by 2:\n", df

df["subjects"] = df.subjects.shift(-1)
print "After shifting column subjects by -1:\n", df
Input DataFrame is:
     name   marks   subjects
0    John    89         Math
1   Jacob    23      Physics
2     Tom   100    Chemistry
3     Tim    56      Biology
4    Ally    90      English

After shifting column name by 1:
     name   marks   subjects
0     NaN    89         Math
1    John    23      Physics
2   Jacob   100    Chemistry
3     Tom    56      Biology
4     Tim    90      English

After shifting column marks by 2:
     name   marks   subjects
0     NaN    100       Math
1    John    100    Physics
2   Jacob     89  Chemistry
3     Tom     23    Biology
4     Tim    100    English

After shifting column subjects by -1:
     name   marks   subjects
0     NaN   100      Physics
1    John   100    Chemistry
2   Jacob    89      Biology
3     Tom    23      English
4     Tim   100          NaN
Fetch specific field values in MongoDB

To fetch specific field values, use inoperator.Thein selects the documents where the value of a field equals any value in the specified array.
Let us first create a collection with documents −
> db.indexesDemo.createIndex({"StudentFirstName":1});
{
   "createdCollectionAutomatically" : true,
   "numIndexesBefore" : 1,
   "numIndexesAfter" : 2,
   "ok" : 1
}
> db.indexesDemo.insertOne({"StudentFirstName":"John","StudentLastName":"Smith"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e06de4d25ddae1f53b621dd")
}
> db.indexesDemo.insertOne({"StudentFirstName":"Chris","StudentLastName":"Brown"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e06de5825ddae1f53b621de")
}
> db.indexesDemo.insertOne({"StudentFirstName":"John","StudentLastName":"Doe"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e06de6725ddae1f53b621df")
}
> db.indexesDemo.insertOne({"StudentFirstName":"David","StudentLastName":"Miller"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e06de7225ddae1f53b621e0")
}
Following is the query to display all documents from a collection with the help of find() method −
> db.indexesDemo.find();
This will produce the following output −
{ "_id" : ObjectId("5e06de4d25ddae1f53b621dd"), "StudentFirstName" : "John", "StudentLastName" : "Smith" }
{ "_id" : ObjectId("5e06de5825ddae1f53b621de"), "StudentFirstName" : "Chris", "StudentLastName" : "Brown" }
{ "_id" : ObjectId("5e06de6725ddae1f53b621df"), "StudentFirstName" : "John", "StudentLastName" : "Doe" }
{ "_id" : ObjectId("5e06de7225ddae1f53b621e0"), "StudentFirstName" : "David", "StudentLastName" : "Miller" }
Following is the query to indexes −
> db.indexesDemo.find(
... { StudentFirstName: { $in: [ "John", "David" ] } },
... { _id: 0, StudentLastName: 0 }
... );
This will produce the following output −
{ "StudentFirstName" : "David" }
{ "StudentFirstName" : "John" }
{ "StudentFirstName" : "John" }
Python - Difference in keys of two dictionaries

Two python dictionaries may contain some common keys between them. In this article we will find how to get the difference in the keys present in two given dictionaries.
Here we take two dictionaries and apply set function to them. Then we subtract the two sets to get the difference. We do it both ways, by subtracting second dictionary from first and next subtracting first dictionary form second. Those keys which are not common are listed in the result set.
 Live Demo
dictA = {'1': 'Mon', '2': 'Tue', '3': 'Wed'}
print("1st Distionary:\n",dictA)
dictB = {'3': 'Wed', '4': 'Thu','5':'Fri'}
print("1st Distionary:\n",dictB)

res1 = set(dictA) - set(dictB)
res2 = set(dictB) - set(dictA)
print("\nThe difference in keys between both the dictionaries:")
print(res1,res2)
Running the above code gives us the following result −
1st Distionary:
{'1': 'Mon', '2': 'Tue', '3': 'Wed'}
1st Distionary:
{'3': 'Wed', '4': 'Thu', '5': 'Fri'}
The difference in keys between both the dictionaries:
{'2', '1'} {'4', '5'}
In another approach we can use a for loop to iterate through the keys of one dictionary and check for its presence using the in clause in the second dictionary.
 Live Demo
dictA = {'1': 'Mon', '2': 'Tue', '3': 'Wed'}
print("1st Distionary:\n",dictA)
dictB = {'3': 'Wed', '4': 'Thu','5':'Fri'}
print("1st Distionary:\n",dictB)

print("\nThe keys in 1st dictionary but not in the second:")
for key in dictA.keys():
   if not key in dictB:
      print(key)
Running the above code gives us the following result −
1st Distionary:
{'1': 'Mon', '2': 'Tue', '3': 'Wed'}
1st Distionary:
{'3': 'Wed', '4': 'Thu', '5': 'Fri'}

The keys in 1st dictionary but not in the second:
1
2
Print all the cycles in an undirected graph in C++

In this problem, we are given an undirected graph and we have to print all the cycles that are formed in the graph.
Undirected Graph is a graph that is connected together. All the edges of the unidirectional graph are bidirectional. It is also known as an undirected network.
Cycle in a graph data structure is a graph in which all vertices form a cycle.
Let’s see an example to understand the problem better −
Graph-
Output-
Cycle 1: 2 3 4 5
Cycle 2: 6 7 8
For this, we will make use of a few properties of the graph. You need to use graph coloring method and color all the vertices which occur in a cyclic graph. Also, if a vertex is partially visited, it will give rise to a cyclic graph. So, we will color this vertex and all next vertex till the same is reached again.
Step 1: call DFS traversal for the graph which can color the vertices.
Step 2: If a partially visited vertex is found, backtrack till the vertex is
reached again and mark all vertices in the path with a counter which is cycle number.
Step 3: After completion of traversal, iterate for cyclic edge and push them
into a separate adjacency list.
Step 4: Print the cycles number wise from the adjacency list.
#include <bits/stdc++.h>
using namespace std;
const int N = 100000;
vector<int> graph[N];
vector<int> cycles[N];
void DFSCycle(int u, int p, int color[], int mark[], int par[], int&amp; cyclenumber){
   if (color[u] == 2) {
      return;
   }
   if (color[u] == 1) {
      cyclenumber++;
      int cur = p;
      mark[cur] = cyclenumber;
      while (cur != u) {
         cur = par[cur];
         mark[cur] = cyclenumber;
      }
      return;
   }
   par[u] = p;
   color[u] = 1;
   for (int v : graph[u]) {
      if (v == par[u]) {
         continue;
      }
      DFSCycle(v, u, color, mark, par, cyclenumber);
   }
   color[u] = 2;
}
void insert(int u, int v){
   graph[u].push_back(v);
   graph[v].push_back(u);
}
void printCycles(int edges, int mark[], int&amp; cyclenumber){
   for (int i = 1; i <= edges; i++) {
      if (mark[i] != 0)
         cycles[mark[i]].push_back(i);
   }
   for (int i = 1; i <= cyclenumber; i++) {
      cout << "Cycle " << i << ": ";
      for (int x : cycles[i])
         cout << x << " ";
      cout << endl;
   }
}
int main(){
   insert(1, 2);
   insert(2, 3);
   insert(3, 4);
   insert(4, 5);
   insert(5, 2);
   insert(5, 6);
   insert(6, 7);
   insert(7, 8);
   insert(6, 8);
   int color[N];
   int par[N];
   int mark[N];
   int cyclenumber = 0;
   cout<<"Cycles in the Graph are :\n";
   int edges = 13;
   DFSCycle(1, 0, color, mark, par, cyclenumber);
   printCycles(edges, mark, cyclenumber);
}
Cycles in the Graph are −
Cycle 1: 2 3 4 5
Cycle 2: 6 7 8
Java Program for Anagram Substring Search

Following is an example for Anagram Substring Search in Java −
 Live Demo
public class Demo{
   static final int max_val = 256;
   static boolean compare_vals(char my_arr_1[], char my_arr_2[]){
      for (int i = 0; i < max_val; i++)
      if (my_arr_1[i] != my_arr_2[i])
      return false;
      return true;
   }
   static void search_subs(String my_pattern, String my_text){
      int pat_len = my_pattern.length();
      int txt_len = my_text.length();
      char[] count_pat = new char[max_val];
      char[] count_txt = new char[max_val];
      for (int i = 0; i < pat_len; i++){
         (count_pat[my_pattern.charAt(i)])++;
         (count_txt[my_text.charAt(i)])++;
      }
      for (int i = pat_len; i < txt_len; i++){
         if (compare_vals(count_pat, count_txt))
         System.out.println("The element was found at index " + (i - pat_len));
         (count_txt[my_text.charAt(i)])++;
         count_txt[my_text.charAt(i-pat_len)]--;
      }
      if (compare_vals(count_pat, count_txt))
      System.out.println("The element was found at index " + (txt_len - pat_len));
   }
   public static void main(String args[]){
      String my_text = "ABNFGHABNJGH";
      String my_pattern = "NFGH";
      search_subs(my_pattern, my_text);
   }
}
The element was found at index 2
A class named Demo defines a constant value and a Boolean function that takes in two arrays. It iterates over both the arrays till the constant value is reached. It returns true or false depending on whether the elements in the array that compared were compared were equal or unequal.
Another static function takes in the text and the pattern that needs to be checked for in the text and iterate over the pattern and string. Both the counts of pattern and string are incremented. Again a ‘for’ loop is run and the counts of both the pattern and text are compared. If they are equal, the index is displayed. Otherwise, a relevant message is displayed. In the main class, the pattern and the text are defined and the function is called.
How to use email input type in HTML?

The email input type is used in HTML using the <input type="email">. Using this, allow the users to add an e-mail address. On some browsers, the email entered will be validated i.e. if you miss @ and. (period), while adding e-mail, then it won’t submit the form and will show an error i.e. “Please enter an email address”.
Use the multiple Boolean attributes, if you want to allow adding more than one email address.
Note − The input type email is not supported in Internet Explorer 9 and earlier.
You can try to run the following code to learn how to use email input type in HTML −
<!DOCTYPE html>
<html>
   <head>
      <title>HTML input email</title>
   </head>

   <body>
      <form action = "" method = "get">
         Details:<br><br>
         Student Name<br><input type = "name" name = "sname"><br>
         Student E-mail<br><input type = "email" name = "email"><br>
         <input type = "submit" value = "Submit">
      </form>
   </body>
</html>
How to print Unicode character in C++?

To print the Unicode characters, the process is very similar to the actual printing process in C++.
We can put the Unicode value with the prefix \u. Thus we can successfully print the Unicode character.
Note: If the console does not support Unicode, then you cannot get the correct result. Here we have used the Linux system to solve this problem.
#include <iostream>
using namespace std;
int main() {
   cout << "Character: \u092E\n";
   cout << "Character: \u0938\n";
   cout << "Character: \u0915\n";
}
Character: म
Character: म
Character: म
Overriding Methods in Python

You can always override your parent class methods. One reason for overriding parent's methods is because you may want special or different functionality in your subclass.
 Live Demo
#!/usr/bin/python
class Parent: # define parent class
   def myMethod(self):
      print 'Calling parent method'
class Child(Parent): # define child class
   def myMethod(self):
      print 'Calling child method'
c = Child()    # instance of child
c.myMethod()   # child calls overridden method
When the above code is executed, it produces the following result −
Calling child method
Fibonacci series program in Java without using recursion.

Following is the required program.
Live Demo
public class Tester {
   public static void main(String args[]) {
       int n1 = 0, n2 = 1, n3, i, max = 5;
       System.out.print(n1 + " " + n2);
       for (i = 2; i < max; ++i) {
          n3 = n1 + n2;
          System.out.print(" " + n3);
          n1 = n2;
          n2 = n3;
       }
    }
 }
0 1 1 2 3
Python | sympy.Mul() method - GeeksforGeeks

11 Jul, 2019
With the help of sympy.Mul() method, we can multiply two variables and can form a mathematical expression.
Syntax : sympy.Mul()Return : Return the product of two variables.
Example #1 :In this example we can see that by using sympy.Mul() method, we are able two multiply the two variables and we can also form mathematical expression.
# import sympyfrom sympy import * x, y = symbols('x y')  # Use sympy.Mul() methodmul = Mul(x, y)    print(mul)
Output :
x*y
Example #2 :
# import sympyfrom sympy import * x, y = symbols('x y')  # Use sympy.Mul() method mul = Mul(x, y) + Mul(x, x)    print(mul)
Output :
x**2 + x*y
SymPy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
Python | Get unique values from a list
Add Background Image in Python Arcade - GeeksforGeeks

26 Oct, 2021
In this article, we will learn how to add background images to arcade games in Python.
We are going to use the below image as our background image.
So to add this image as our background image we are going to use load_texture() and draw_texture_rectangle() function.
load_texture function is used to import texture from file in arcade.
Syntax: arcade.load_texture(name, x, y, width, height)
Parameters:
name: Name of the file to that holds the texture.
x: X position of the crop area of the texture
y: Y position of the crop area of the texture
width: width of the texture
height: height of the texture
draw_texture_rectangle function used to import texture with specific coordinated.
Syntax: arcade.draw_texture_rectangle(x, y, width, height, texture, angle, alpha)
x:  x coordinate of rectangle center.
y:  y coordinate of rectangle center.
width:  width of texture
height: height of the texture
texture: identifier of texture returned from load_texture() call
angle:  rotation of the rectangle
alpha: Transparency of image
Below is the implementation:
Python3
# Importing arcade moduleimport arcade # Creating MainGame classclass MainGame(arcade.Window):    def __init__(self):        super().__init__(600, 600, title = "Background Image")         # Loading the background image        self.background = arcade.load_texture("BACKGROUND.png")     # Creating on_draw() function to draw on the screen    def on_draw(self):        arcade.start_render()                 # Drawing the background image        arcade.draw_texture_rectangle(300, 300, 600,                                      600, self.background) # Calling MainGame classMainGame()arcade.run()
Output:
surinderdawra388
Python-Arcade
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Pandas dataframe.groupby()
Create a directory in Python
Defaultdict in Python
Python | Get unique values from a list
NavigableMap Interface in Java with Example

NavigableMap is an extension of the SortedMap collection framework. It is used to arrange the elements in a uniform fashion. NavigableMap has different methods to iterate over the elements in the Map.
Following is an example −
 Live Demo
import java.util.NavigableMap;
import java.util.TreeMap;
public class Demo {
   public static void main(String[] args) {
      NavigableMap<String, Integer> my_map = new TreeMap<String, Integer>();
      my_map.put("A", 856);
      my_map.put("M", 349);
      my_map.put("Z", 567);
      System.out.printf("The descending set is : %s%n", my_map.descendingKeySet());
      System.out.printf("The floor entry is : %s%n", my_map.floorEntry("A"));
      System.out.printf("The first key : %s%n", my_map.firstKey());
      System.out.printf("The reversed map : %s%n", my_map.descendingMap());
   }
}
The descending set is : [Z, M, A]
The floor entry is : A=856
The first key : A
The reversed map : {Z=567, M=349, A=856}
A class named Demo contains the main function. An instance of the NavigableMap is created, and elements are added to the map with the help of the ‘put’ function. The relevant function are used to display the map in descending order, the first element of the map, the first key of the map, and the reversed version of the map.
Python String maketrans() Method

Python string  method maketrans() returns a translation table that maps each character in the intabstring into the character at the same position in the outtab string. Then this table is passed to the translate() function.
Note − Both intab and outtab must have the same length.
Following is the syntax for maketrans() method −
str.maketrans(intab, outtab)

intab − This is the string having actual characters.
intab − This is the string having actual characters.
outtab − This is the string having corresponding mapping character.
outtab − This is the string having corresponding mapping character.
This method returns a translate table to be used translate() function.
The following example shows the usage of maketrans() method. Under this, every vowel in a string is replaced by its vowel position −
#!/usr/bin/python

from string import maketrans   # Required to call maketrans function.

intab = "aeiou"
outtab = "12345"
trantab = maketrans(intab, outtab)

str = "this is string example....wow!!!"
print str.translate(trantab)
When we run above program, it produces following result −
th3s 3s str3ng 2x1mpl2....w4w!!!


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
Find a specific element in a C# List

Set a list −
List<int> myList = new List<int>() {
   5,
   10,
   17,
   19,
   23,
   33
};
Let us say you need to find an element that is divisible by 2. For that, use the Find() method −
int val = myList.Find(item => item % 2 == 0);
Here is the complete code −
 Live Demo
using System;
using System.Collections.Generic;
using System.Linq;
class Demo {
   static void Main() {
      List<int> myList = new List<int>() {
         5,
         10,
         17,
         19,
         23,
         33
      };
      Console.WriteLine("List: ");
      foreach(int i in myList) {
         Console.WriteLine(i);
      }
      int val = myList.Find(item => item % 2 == 0);
      Console.WriteLine("Element that divides by zero: "+val);
   }
}
List:
5
10
17
19
23
33
Element that divides by zero: 10
Stream toArray() in Java with Examples

06 Dec, 2018
Stream toArray() returns an array containing the elements of this stream. It is a terminal operation i.e, it may traverse the stream to produce a result or a side-effect. After the terminal operation is performed, the stream pipeline is considered consumed, and can no longer be used.
Syntax :
Object[] toArray()

Return Value : The function returns an array containing the elements of this stream.
Example 1 :
// Java code for Stream toArray()import java.util.*;import java.util.stream.Stream;  class GFG {      // Driver code    public static void main(String[] args)    {        // Creating a Stream of Integers        Stream<Integer> stream = Stream.of(5, 6, 7, 8, 9, 10);          // Using Stream toArray()        Object[] arr = stream.toArray();          // Displaying the elements in array arr        System.out.println(Arrays.toString(arr));    }}
Output :
[5, 6, 7, 8, 9, 10]

Example 2 :
// Java code for Stream toArray()import java.util.*;import java.util.stream.Stream;  class GFG {      // Driver code    public static void main(String[] args)    {        // Creating a Stream of Strings        Stream<String> stream = Stream.of("Geeks", "for",                                          "Geeks", "GeeksQuiz");          // Using Stream toArray()        Object[] arr = stream.toArray();          // Displaying the elements in array arr        System.out.println(Arrays.toString(arr));    }}
Output :
[Geeks, for, Geeks, GeeksQuiz]

Example 3 :
// Java code for Stream toArray()import java.util.*;import java.util.stream.Stream;  class GFG {      // Driver code    public static void main(String[] args)    {        // Creating a Stream of Strings        Stream<String> stream = Stream.of("Geeks", "for",                                          "gfg", "GeeksQuiz");          // Using Stream toArray() and filtering        // the elements that starts with 'G'        Object[] arr = stream.filter(str                                     -> str.startsWith("G"))                           .toArray();          // Displaying the elements in array arr        System.out.println(Arrays.toString(arr));    }}
Output :
[Geeks, GeeksQuiz]

array-stream
Java - util package
Java-Functions
java-stream
Java-Stream interface
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TimeUnit sleep() method in Java with Examples

15 Oct, 2018
The sleep() method of TimeUnit Class is used to performs a Thread.sleep using this time unit. This is a convenience method that sleeps time arguments into the form required by the Thread.sleep method.
Syntax:
public void sleep(long timeout)
           throws InterruptedException
Parameters: This method accepts a mandatory parameters timeout which is the minimum time to sleep. If this is less than or equal to zero, then do not sleep at all.
Return Value: This method does not return anything.
Exception: This method throws InterruptedException if interrupted while sleeping.
Below program illustrate the implementation of TimeUnit sleep() method:
Program 1:
// Java program to demonstrate// sleep() method of TimeUnit Class  import java.util.concurrent.*;  class GFG {    public static void main(String args[])    {        // Get time to sleep        long timeToSleep = 0L;          // Create a TimeUnit object        TimeUnit time = TimeUnit.SECONDS;          try {              System.out.println("Going to sleep for "                               + timeToSleep                               + " seconds");              // using sleep() method            time.sleep(timeToSleep);              System.out.println("Slept for "                               + timeToSleep                               + " seconds");        }          catch (InterruptedException e) {            System.out.println("Interrupted "                               + "while Sleeping");        }    }}
Going to sleep for 0 seconds
Slept for 0 seconds

Program 2:
// Java program to demonstrate// sleep() method of TimeUnit Class  import java.util.concurrent.*;  class GFG {    public static void main(String args[])    {        // Get time to sleep        long timeToSleep = 10L;          // Create a TimeUnit object        TimeUnit time = TimeUnit.SECONDS;          try {              System.out.println("Going to sleep for "                               + timeToSleep                               + " seconds");              // using sleep() method            time.sleep(timeToSleep);              System.out.println("Slept for "                               + timeToSleep                               + " seconds");        }          catch (InterruptedException e) {            System.out.println("Interrupted "                               + "while Sleeping");        }    }}
Going to sleep for 10 seconds
Slept for 10 seconds

Java - util package
Java-Functions
Java-TimeUnit
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Multidimensional Arrays in Java
Collections in Java
Stream In Java
Set in Java
Singleton Class in Java
Initializing a List in Java
Introduction to Java
Writer write(String) method in Java with Examples

29 Jan, 2019
The write(String) method of Writer Class in Java is used to write the specified String on the stream. This String value is taken as a parameter.
Syntax:
public void write(String string)
Parameters: This method accepts a mandatory parameter string which is the String to be written in the Stream.
Return Value: This method do not returns any value.
Below methods illustrates the working of write(String) method:
Program 1:
// Java program to demonstrate// Writer write(String) method  import java.io.*;  class GFG {    public static void main(String[] args)    {          try {              // Create a Writer instance            Writer writer                = new PrintWriter(System.out);              // Write the String 'GeeksForGeeks'            // to this writer using write() method            // This will put the string in the stream            // till it is printed on the console            writer.write("GeeksForGeeks");              writer.flush();        }        catch (Exception e) {            System.out.println(e);        }    }}
GeeksForGeeks

Program 2:
// Java program to demonstrate// Writer write(String) method  import java.io.*;  class GFG {    public static void main(String[] args)    {          try {              // Create a Writer instance            Writer writer                = new PrintWriter(System.out);              // Write the String 'GFG'            // to this writer using write() method            // This will put the string in the stream            // till it is printed on the console            writer.write("GFG");              writer.flush();        }        catch (Exception e) {            System.out.println(e);        }    }}
GFG

Java-Functions
Java-IO package
Java-Writer
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python MariaDB – Insert into Table using PyMySQL

14 Oct, 2020
MariaDB is an open source Database Management System and its predecessor to MySQL. The pymysql client can be used to interact with MariaDB similar to that of MySQL using Python.
In this article we will look into the process of inserting rows to a table of the database using pymysql. You can insert one row or multiple rows at once. The connector code is required to connect the commands to the particular database. To insert data use the following syntax:
Syntax: INSERT INTO table_name column1, column2 VALUES (value1, value2)
Note: The INSERT query is used to insert one or multiple rows in a table.
Example : 
To insert one row in table PRODUCT.
Python3
# import the mysql client for python  import pymysql    # Create a connection object# IP address of the MySQL database serverHost = "localhost"  # User name of the database serverUser = "user"       # Password for the database userPassword = ""             database = "database_name"  conn  = pymysql.connect(host=Host, user=User, password=Password, database)  # Create a cursor objectcur  = conn.cursor()  PRODUCT_ID = '1201'price = 10000PRODUCT_TYPE = 'PRI'  query = f"INSERT INTO PRODUCT (PRODUCT_ID, price,PRODUCT_TYPE) VALUES ('{PRODUCT_ID}', '{price}', '{PRODUCT_TYPE}')"  cur.execute(query)print(f"{cur.rowcount} details inserted")conn.commit()conn.close()
Output :
To insert multiple values at once, executemany() method is used. This method iterates through the sequence of parameters, passing the current parameter to the execute method.
Example : 
To insert multiple row in table PRODUCT.
Python3
query = "INSERT INTO PRODUCT (PRODUCT_ID, price,PRODUCT_TYPE) VALUES ('%s', %d, '%s')"  values = [("1203",1000,"ILL"),          ("1523",1500,"broadband"),          ("154",14782,"Voice"),        ]cur.execute(query,values)print(f"{cur.rowcount}, details inserted")conn.commit()conn.close()
Output :
Note :
The cursor() is used in order to iterate through the rows.
Without the command conn.commit() the changes will not be saved.
Python-MariaDB
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Get the starting index for all occurrences of given substring

18 Dec, 2019
Given a string and a substring, the task to find out the starting index for all the occurrences of a given substring in a string. Let’s discuss a few methods to solve the given task.
Method #1: Using Naive Method
# Python3 code to demonstrate# to find all occurrences of substring in# a string  # Initialising stringini_string = 'xbzefdgstbzefzexezef'  # Initialising sub-stringsub_string = 'zef'  # Printing initial string and sub-stringprint ("initial_strings : ", ini_string, "\nsubstring : ", sub_string)  res = []flag = 0k = 0  # Finding all occurrences of substring# in a string using Naive methodfor i in range(0, len(ini_string)):    k = i    flag = 0    for j in range(0, len(sub_string)):        if ini_string[k] != sub_string[j]:            flag = 1        if flag:            break        k = k + 1    if flag == 0:        res.append(i)    # printing result(print ("resultant positions", str(res))
initial_strings :  xbzefdgstbzefzexezef 
substring :  zef
resultant positions [2, 10, 17]

&nsbp;Method #2: Using list comprehension
# Python3 code to demonstrate# to find all occurrences of substring in# a string  # Initialising stringini_string = 'xbzefdgstbzefzexezef'  # Initialising sub-stringsub_string = 'zef'  # Printing initial string and sub-stringprint ("initial_strings : ", ini_string, "\nsubstring : ", sub_string)  res = []# Finding all occurrences of substring# in a string using list comprehensionres = [i for i in range(len(ini_string))        if ini_string.startswith(sub_string, i)]  # printing result(print ("resultant positions", str(res))
initial_strings :  xbzefdgstbzefzexezef 
substring :  zef
resultant positions [2, 10, 17]

 Method #3: Using regex
# Python3 code to demonstrate# to find all occurrences of substring in# a stringimport re  # Initialising stringini_string = 'xbzefdgstbzefzexezef'  # Initialising sub-stringsub_string = 'zef'  # Printing initial string and sub-stringprint ("initial_strings : ", ini_string, "\nsubstring : ", sub_string)  res = []# Finding all occurrences of substring# in a string using re.finditerres = [m.start() for m in re.finditer(sub_string, ini_string)]  # printing result(print ("resultant positions", str(res))
initial_strings :  xbzefdgstbzefzexezef 
substring :  zef
resultant positions [2, 10, 17]

nidhi_biet
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
numpy.poly1d() in Python

04 Dec, 2020
The numpy.poly1d() function helps to define a polynomial function. It makes it easy to apply “natural operations” on polynomials.
Syntax: numpy.poly1d(arr, root, var)Parameters :arr : [array_like] The polynomial coefficients are given in decreasing order of powers. If the second parameter (root) is set to True then array values are the roots of the polynomial equation.
root : [bool, optional] True means polynomial roots. Default is False.var : variable like x, y, z that we need in polynomial [default is x].
Arguments :c : Polynomial coefficient.coef : Polynomial coefficient.coefficients : Polynomial coefficient.order : Order or degree of polynomial.o : Order or degree of polynomial.r : Polynomial root.roots : Polynomial root.
Return: Polynomial and the operation applied
For example: poly1d(3, 2, 6) = 3x2 + 2x + 6poly1d([1, 2, 3], True) = (x-1)(x-2)(x-3) = x3 – 6x2 + 11x -6
Code 1 : Explaining poly1d() and its argument
# Python code explaining# numpy.poly1d()  # importing librariesimport numpy as np  # Constructing polynomialp1 = np.poly1d([1, 2])p2 = np.poly1d([4, 9, 5, 4])  print ("P1 : ", p1)print ("\n p2 : \n", p2)  # Solve for x = 2print ("\n\np1 at x = 2 : ", p1(2))print ("p2 at x = 2 : ", p2(2))  # Finding Rootsprint ("\n\nRoots of P1 : ", p1.r)print ("Roots of P2 : ", p2.r)  # Finding Coefficientsprint ("\n\nCoefficients of P1 : ", p1.c)print ("Coefficients of P2 : ", p2.coeffs)  # Finding Orderprint ("\n\nOrder / Degree of P1 : ", p1.o)print ("Order / Degree of P2 : ", p2.order)
Output :
P1 :   
1 x + 2

 p2 : 
    3     2
4 x + 9 x + 5 x + 4


p1 at x = 2 :  4
p2 at x = 2 :  82


Roots of P1 :  [-2.]
Roots of P2 :  [-1.86738371+0.j         -0.19130814+0.70633545j -0.19130814-0.70633545j]


Coefficients of P1 :  [1 2]
Coefficients of P2 :  [4 9 5 4]


Order / Degree of P1 :  1
Order / Degree of P2 :  3
 Code 2 : Basic mathematical operation on polynomial
# Python code explaining# numpy.poly1d()  # importing librariesimport numpy as np  # Constructing polynomialp1 = np.poly1d([1, 2])p2 = np.poly1d([4, 9, 5, 4])  print ("P1 : ", p1)print ("\n p2 : \n", p2)  print ("\n\np1 ^ 2 : \n", p1**2)print ("p2 ^ 2 : \n", np.square(p2))  p3 = np.poly1d([1, 2], variable = 'y')print ("\n\np3 : ", p3)    print ("\n\np1 * p2 : \n", p1 * p2)print ("\nMultiplying two polynimials : \n",        np.poly1d([1, -1]) * np.poly1d([1, -2]))
Output :
P1 :   
1 x + 2

 p2 : 
    3     2
4 x + 9 x + 5 x + 4


p1 ^ 2 : 
    2
1 x + 4 x + 4
p2 ^ 2 : 
 [16 81 25 16]


p3 :   
1 y + 2


p1 * p2 : 
    4      3      2
4 x + 17 x + 23 x + 14 x + 8

Multiplying two polynimials : 
    2
1 x - 3 x + 2
Python numpy-polynomials
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How i can replace number with string using Python?

For this purpose let us use a dictionary object having digit as key and its word representation as value −
dct={'0':'zero','1':'one','2':'two','3':'three','4':'four',
     '5':'five','6':'six','7':'seven','8':'eight','9':'nine'
Initializa a new string object 
newstr=''
Using a for loop traverse each character  ch from input string at check if it is a digit with the help of isdigit() function. 
If it is digit, use it as key and find corresponding value from dictionary and append it to newstr. If not append the character ch itself to newstr. Complete code is as follows:
string='I have 3 Networking books, 0 Database books, and 8 Programming books.'
dct={'0':'zero','1':'one','2':'two','3':'three','4':'four',
     '5':'five','6':'six','7':'seven','8':'eight','9':'nine'}
newstr=''
for ch in string:
    if ch.isdigit()==True:
        dw=dct[ch]
        newstr=newstr+dw
    else:
        newstr=newstr+ch
print (newstr)      
The output is as desired
I have three Networking books, zero Database books, and eight Programming books.
Java Type Casting

Type casting is when you assign a value of one primitive data type to another type.
In Java, there are two types of casting:
Widening Casting (automatically) - converting a smaller type 
to a larger type size
byte -> short -> char -> int -> long -> float -> double

Narrowing Casting (manually) - converting a larger type 
to a smaller size type
double -> float -> long -> int -> char -> short -> byte

Widening casting is done automatically when passing a smaller size type to a 
larger size type:
public class Main {
  public static void main(String[] args) {
    int myInt = 9;
    double myDouble = myInt; // Automatic casting: int to double

    System.out.println(myInt);      // Outputs 9
    System.out.println(myDouble);   // Outputs 9.0
  }
}


Try it Yourself »

Narrowing casting must be done manually by placing the type in parentheses 
in front of the value:
public class Main {
  public static void main(String[] args) {
    double myDouble = 9.78d;
    int myInt = (int) myDouble; // Manual casting: double to int

    System.out.println(myDouble);   // Outputs 9.78
    System.out.println(myInt);      // Outputs 9
  }
}


Try it Yourself »

We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
Combine Rows into String in SQL Server - GeeksforGeeks

09 Mar, 2021
Imagine we need to select all the data from any given list. We could use multiple queries to combine rows in SQL Server to form a String. 
Example-1 :Let us suppose we have below table named “geek_demo” –
Approach-1 :In the below example, we will combine rows using the COALESCE Function.
Query to Concatenate Rows in SQL Server –
DECLARE @Names VARCHAR(MAX)  
SELECT @Names = COALESCE(@Names + ', ', '') + [FirstName] 
FROM [geek_demo]
SELECT @Names AS [List of All Names]
Output :
Approach-2 :In the below example, we will combine the LastName rows also.
Query to Concatenate Rows in SQL Server –
DECLARE @FirstNames VARCHAR(MAX)
DECLARE @LastNames VARCHAR(MAX)
SELECT @FirstNames = COALESCE(@FirstNames + ', ', '') + [FirstName] 
FROM [geek_demo]   
SELECT @LastNames = COALESCE(@LastNames + ', ', '') + [LastName] 
FROM [geek_demo] 
SELECT @FirstNames AS [List of All First Names],
            @LastNames AS [List of All Last Names]
Output :
Approach-3 :In the below example, we will concatenate the Last Name rows as well.
Query to Concatenate Rows in SQL Server –
DECLARE @FirstNames VARCHAR(MAX)
DECLARE @LastNames VARCHAR(MAX)
SELECT @FirstNames = CONCAT(@FirstNames + ', ', '') + [FirstName] 
FROM [geek_demo]  
SELECT @LastNames = CONCAT(@LastNames + ', ', '') + [LastName] 
FROM [geek_demo]
SELECT @FirstNames AS [List of First All Names],
   @LastNames AS [List of All Last Names]
Output :
Approach-4 :In the below example, we will combine the rows from two columns (FirstName & LastName) using the stuff function and for the XML path.
Query to Concatenate Rows in SQL Server –
SELECT STUFF((
   SELECT ',' + SPACE(1) + [FirstName],
   ' ' + SPACE(1) + [LastName]
 FROM [geek_demo]
  FOR XML PATH(''), TYPE).value('.', 'VARCHAR(MAX)'), 1, 1, '')
AS [List Of All Names]
Output :
Example-2 :Let us suppose we have below table named “geek_demo1” –
Approach-1 :In the below example, we will combine rows into a string using the CONCAT Function in SQL Server.
Query to Concatenate Rows in SQL Server –
DECLARE @Names VARCHAR(MAX)
DECLARE @Emails VARCHAR(MAX)
SELECT @Names = CONCAT(@Names + ', ', '') + [Name] 
FROM [geek_demo1]  
SELECT @Emails = CONCAT(@Emails + ', ', '') + [Email] 
FROM [geek_demo]  
SELECT @Names AS [List of All Names],
            @Emails AS [List of All Emails]
Output :
Approach-2 :In the below example, we will combine rows in SQL Server using the SPACE and for XML path.
Query to Concatenate Rows in SQL Server –
SELECT STUFF((
  SELECT ',' + SPACE(1) + [Email]
  FROM [geek_demo]
  FOR XML PATH(''), TYPE).value('.', 'VARCHAR(MAX)'), 1, 1, '')
AS [List Of All Emails]
Output :
SQL-Server
DBMS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
SQL Trigger | Student Database
Introduction of B-Tree
Difference between Clustered and Non-clustered index
Introduction of DBMS (Database Management System) | Set 1
Introduction of ER Model
SQL | DDL, DQL, DML, DCL and TCL Commands
How to find Nth highest salary from a table
SQL | ALTER (RENAME)
SQL Trigger | Student Database
SQL | Views
Write a program in Python to read sample data from an SQL Database

Assume you have a sqlite3 database with student records and the result for reading all the data is,
  Id Name
0 1 stud1
1 2 stud2
2 3 stud3
3 4 stud4
4 5 stud5
To solve this, we will follow the steps given below −
Define a new connection. It is shown below,
Define a new connection. It is shown below,
con = sqlite3.connect("db.sqlite3")
Read sql data from the database using below function,
Read sql data from the database using below function,
pd.read_sql_query()
Select all student data from table using read_sql_query with connection,
Select all student data from table using read_sql_query with connection,
pd.read_sql_query("SELECT * FROM student", con)
Let us see the complete implementation to get a better understanding −
import pandas as pd
import sqlite3
con = sqlite3.connect("db.sqlite3")
df = pd.read_sql_query("SELECT * FROM student", con)
print(df)
  Id Name
0 1 stud1
1 2 stud2
2 3 stud3
3 4 stud4
4 5 stud5
How to find the mean squared error for linear model in R?

To find the mean squared error for linear model, we can use predicted values of the model and find the error from dependent variable then take its square and the mean of the whole output. For example, if we have a linear model called M for a data frame df then we can find the mean squared error using the command mean((df$y-predict(M))^2).
Consider the below data frame −
 Live Demo
x1<-rnorm(20)
y1<-rnorm(20)
df1<-data.frame(x1,y1)
df1
      x1          y1
1  -0.64419775  -0.655535847
2  -2.02925533  -0.074246704
3   1.42639556   0.226413529
4   0.21841252  -0.799586646
5  -0.08272931   0.021258680
6   1.36349138  -0.358914344
7   0.58243090   0.334064031
8  -0.18839329   0.596566815
9   1.97993745   1.808762160
10 -0.31676008   0.812349831
11 -0.06732802  -0.189255661
12  1.76175840  -0.317888508
13 -0.29681017   0.947048363
14 -1.02210007   0.428273333
15 -0.33408154   2.273976129
16  0.49158882  -0.483902966
17 -0.71446066   0.001058688
18 -0.98031110   0.011280707
19  0.78912612   0.620691096
20  0.63751954  -0.668467539
Creating linear model for y1 and x1 then finding predicted values and the mean squared error −
Model1<-lm(y1~x1,data=df1)
predict(Model1)
     1         2        3         4         5         6        7         8
0.1936091 0.1343150 0.2822509 0.2305373 0.2176455 0.2795580 0.2461209 0.2131220
     9        10         11       12       13        14        15        16
0.3059479 0.2076267 0.2183048 0.2966077 0.2084807 0.1774312 0.2068852 0.2422320
    17        18        19        20
0.1906012 0.1792202 0.2549695 0.2484792
mean((df1$y1-predict(Model1))^2)
[1] 0.6022432
 Live Demo
iv1<-rpois(20,2)
iv2<-rpois(20,3)
iv3<-rpois(20,1)
Y<-rpois(20,6)
df2<-data.frame(iv1,iv2,iv3,Y)
df2
  iv1 iv2 iv3 Y
1  3   5   1  5
2  6   2   0 12
3  1   1   0 10
4  5   2   1  6
5  5   1   0  6
6  4   4   0  5
7  1   2   0  2
8  1   1   0  6
9  2   5   0  5
10 2   4   0  6
11 4   6   2  8
12 3   4   1  4
13 2   5   2  6
14 4   3   1  4
15 3   3   2 10
16 2   2   1  7
17 2   4   0 14
18 2   1   0  7
19 1   3   1  7
20 2   4   1  4
Creating linear model for Y, iv1, iv2, iv3 then finding predicted values and the mean squared error −
Model2<-lm(Y~iv1+iv2+iv3,data=df2)
predict(Model2)
     1        2       3         4       5        6         7       8
6.368896 7.886330 6.659550 7.545170 7.802283 6.911692 6.457914 6.659550
    9         10     11        12       13       14        15      16
6.138690 6.340326 6.397466 6.570532 6.027735 7.057851 6.716690 6.688120
    17       18      19        20
6.340326 6.945233 6.200801 6.284848
mean((df2$Y-predict(Model2))^2)
[1] 7.745138
Styling Links with CSS

To style links with CSS, at first we should know the following link states: link, visited, hover and active. Use the pseudo-classes of anchor element to style links −
a:link for link
a:visited forvisited link
a:link for hover on link
a:active for active link
Let us now see an example −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
a:link {
   color: orange;
   text-decoration: underline;
}
a:hover {
   color: red;
   text-decoration: underline;
}
a:active {
   color: green;
   text-decoration: underline;
}
</style>
</head>
<body>
<h1>Tutorials</h1>
<p><a href="https://www.tutorialspoint.com/java">Java</a></p>
<p><a href="https://www.tutorialspoint.com/chsharp">C#</a></p>
<p><a href="https://www.tutorialspoint.com/jquery">jQuery</a></p>
<p><a href="https://www.tutorialspoint.com/ruby">Ruby</a></p>
<p><a href="https://www.tutorialspoint.com/pytorch">PyTorch</a></p>
</body>
</html>
Let us now see another example −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
a:link {
   color: blue;
   text-decoration: none;
}
a:hover {
   color: blue;
   text-decoration: none;
}
a:active {
   color: blue;
   text-decoration: none;
}
</style>
</head>
<body>
<h1>Demo Heading</h1>
<div>
<p>This is the <a href="https://tutorialspoint.com">reference</a></p>
</div>
</body>
</html>
C library function - putchar()

The C library function int putchar(int char) writes a character (an unsigned char) specified by the argument char to stdout.
Following is the declaration for putchar() function.
int putchar(int char)
char − This is the character to be written. This is passed as its int promotion.
char − This is the character to be written. This is passed as its int promotion.
This function returns the character written as an unsigned char cast to an int or EOF on error.
The following example shows the usage of putchar() function.
#include <stdio.h>

int main () {
   char ch;

   for(ch = 'A' ; ch <= 'Z' ; ch++) {
      putchar(ch);
   }
   
   return(0);
}
Let us compile and run the above program that will produce the following result −
ABCDEFGHIJKLMNOPQRSTUVWXYZ


    12 Lectures 
     2 hours 

 Nishant Malik

    12 Lectures 
     2.5 hours 

 Nishant Malik

    48 Lectures 
     6.5 hours 

 Asif Hussain

    12 Lectures 
     2 hours 

 Richa Maheshwari

    20 Lectures 
     3.5 hours 

 Vandana Annavaram

    44 Lectures 
     1 hours 

 Amit Diwan
 Print
 Add Notes
 Bookmark this page