code-rag-bench/online-tutorials huggingface dataset:
Beautiful Sequence | Practice | GeeksforGeeks

A beautiful sequence is a strictly increasing sequence, in which the term Ai divides all Aj, where j>i. Given N find a beautiful sequence whose last term is N and the length of the sequence is the maximum possible. If there are multiple solutions return any.
 
Example 1:
Input: N = 10
Output: 1 5 10
Explanation: 10 is divisible by
1 and 5, 5 is divisible by 1.

Example 2:
Input: N = 3
Output: 1 3
Explanation: 3 is divisible by 1.

 
Your Task:
You don't need to read or print anything. Your task is to complete the function FindSequenece() which takes N as an input parameter and returns a list of beautiful sequences. The driver will print two space-separated integers the length of the sequence and an integer x where x = 1 if your sequence is beautiful otherwise x = 0.
 
Expected Time Complexity: O(sqrt(N))
Expected Space Complexity: O(sqrt(N))
 
Constraints:
1 < N < 109
0
piyushkrs7 months ago
    vector<int> FindSequenece(int N) {       // Code here       vector<int> ans;       int r=sqrt(N);              /*Check if any number is factor of N, N%i==0 i.e. N/i is a factor of N close to N. Now check for factor of N/i then it will be factor of N also thats why we are changing N to N/i here.*/                     for(int i=2;i<=r;i++){           while(N%i==0){               ans.push_back(N);               N=N/i;           }       }              /*We didn't start from N=1 because we will end up in an infinite loop. If number is still greater than 1 then it is prime push it as well as 1 otherwise push 1 only.*/
       if(N>1)           ans.push_back(N);       ans.push_back(1);       reverse(ans.begin(),ans.end());       return ans;                 }
0
Sourashis1 year ago
Sourashis
N should not be pushed in the vector of sequence for getting the code accepted
0
fullmetal1 year ago
fullmetal
test case are wrong(no need of number itself in vector)10=(1 5)3=(1)
0
Nastik2 years ago
Nastik
This is a Good Question with low submissions. Please only add Hints.
Hint from my Side: https://cp-algorithms.com/a...This will help in getting out of TLE
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
Check if a queue can be sorted into another queue using a stack in Python

Suppose we have a Queue with first n natural numbers (unsorted). We have to check whether the given Queue elements can be sorted in non-decreasing sequence in another Queue by using a stack. We can use following operations to solve this problem −
Push or pop elements from stack
Delete element from given Queue.
Insert element in the other Queue.
So, if the input is like Que = [6, 1, 2, 3, 4, 5], then the output will be True as we can pop 6 from Que, then push it into stack. Now pop all remaining elements from Que to another queue, then pop 6 from stack and push into the second queue, so all elements in the new queue will be sorted in non-decreasing sequence.
To solve this, we will follow these steps −
n := size of que
stk := a new stack
exp_val := 1
front := null
while que is not empty, dofront := front element of queremove front element from queif front is same as exp_val, thenexp_val := exp_val + 1otherwise,if stk is empty, thenpush front into stkotherwise when stk is not empty and top of stk < front, thenreturn Falseotherwise,push front into stkwhile stk is not empty and top of stack is same as exp_val, dopop from stkexp_val := exp_val + 1
front := front element of que
remove front element from que
if front is same as exp_val, thenexp_val := exp_val + 1
exp_val := exp_val + 1
otherwise,if stk is empty, thenpush front into stkotherwise when stk is not empty and top of stk < front, thenreturn Falseotherwise,push front into stk
if stk is empty, thenpush front into stk
push front into stk
otherwise when stk is not empty and top of stk < front, thenreturn False
return False
otherwise,push front into stk
push front into stk
while stk is not empty and top of stack is same as exp_val, dopop from stkexp_val := exp_val + 1
pop from stk
exp_val := exp_val + 1
if exp_val - 1 is same as n and stk is empty, thenreturn True
return True
return False
Let us see the following implementation to get better understanding −
 Live Demo
from queue import Queue
def solve(que):
   n = que.qsize()
   stk = []
   exp_val = 1
   front = None
   while (not que.empty()):
      front = que.queue[0]
      que.get()
      if (front == exp_val):
         exp_val += 1
      else:
         if (len(stk) == 0):
            stk.append(front)
         elif (len(stk) != 0 and stk[-1] < front):
            return False
         else:
            stk.append(front)
   while (len(stk) != 0 and stk[-1] == exp_val):
      stk.pop()
      exp_val += 1
   if (exp_val - 1 == n and len(stk) == 0):
      return True
   return False
que = Queue()
items = [6, 1, 2, 3, 4, 5]
for i in items:
   que.put(i)
print(solve(que))
[6, 1, 2, 3, 4, 5]
True
Jackson Annotations - @JsonIgnoreType

@JsonIgnoreType is used at mark a property of special type to be ignored.
import java.io.IOException;
import com.fasterxml.jackson.annotation.JsonIgnoreType;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonTester {
   public static void main(String args[]){
      ObjectMapper mapper = new ObjectMapper();
      try {
         Student student = new Student(1,11,"1ab","Mark");       
         String jsonString = mapper
            .writerWithDefaultPrettyPrinter()
            .writeValueAsString(student);
         System.out.println(jsonString);
      }
      catch (IOException e) { 
         e.printStackTrace();
      }     
   }
}
class Student { 
   public int id;
   @JsonIgnore
   public String systemId;
   public int rollNo;
   public Name nameObj;

   Student(int id, int rollNo, String systemId, String name){
      this.id = id;
      this.systemId = systemId;
      this.rollNo = rollNo;
      nameObj = new Name(name);
   }

   @JsonIgnoreType
   class Name {
      public String name;
      Name(String name){
         this.name = name;
      }       
   }
}
{
   "id" : 1,
   "systemId" : "1ab",
   "rollNo" : 11
}

 Print
 Add Notes
 Bookmark this page
AtomicInteger incrementAndGet() method in Java with examples - GeeksforGeeks

13 Dec, 2021
The java.util.concurrent.atomic.AtomicInteger.incrementAndGet() is an inbuilt method in java that increases the previous value by one and returns the value after updation which is of data-type int.
Syntax: 
public final int incrementAndGet()
Parameters: The function does not accepts a single parameter. Return value: The function returns the value after increment operation is performed to the previous value. 
Program below demonstrates the function:
Program 1:  
Java
// Java program that demonstrates// the incrementAndGet() function import java.util.concurrent.atomic.AtomicInteger; public class GFG {    public static void main(String args[])    {         // Initially value as 0        AtomicInteger val            = new AtomicInteger(0);         System.out.println("Previous value: "                           + val);         // Increment and get        int res            = val.incrementAndGet();         // Prints the updated value        System.out.println("Current value: "                           + res);    }}
Previous value: 0
Current value: 1
 
Program 2: 
Java
// Java program that demonstrates// the incrementAndGet() function import java.util.concurrent.atomic.AtomicInteger; public class GFG {    public static void main(String args[])    {         // Initially value as 18        AtomicInteger val            = new AtomicInteger(18);         System.out.println("Previous value: "                           + val);         // Increment and get new value        int res = val.incrementAndGet();         // Prints the updated value        System.out.println("Current value: "                           + res);    }}
Previous value: 18
Current value: 19
 
Reference: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicInteger.html#incrementAndGet– 
surindertarika1234
Java - util package
Java-AtomicInteger
Java-Functions
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
HashMap in Java with Examples
Initialize an ArrayList in Java
Object Oriented Programming (OOPs) Concept in Java
Interfaces in Java
ArrayList in Java
How to iterate any Map in Java
Multidimensional Arrays in Java
Singleton Class in Java
Stack Class in Java
Multithreading in Java
Create a Count Plot with SeaBorn – Python Pandas

Count Plot in Seaborn is used to display the counts of observations in each categorical bin using bars. The seaborn.countplot() is used for this.
Let’s say the following is our dataset in the form of a CSV file − Cricketers.csv
At first, import the required 3 libraries −
import seaborn as sb
import pandas as pd
import matplotlib.pyplot as plt
Load data from a CSV file into a Pandas DataFrame −
dataFrame = pd.read_csv("C:\\Users\\amit_\\Desktop\\Cricketers.csv")

Following is the code −
import seaborn as sb
import pandas as pd
import matplotlib.pyplot as plt

# Load data from a CSV file into a Pandas DataFrame
dataFrame = pd.read_csv("C:\\Users\\amit_\\Desktop\\Cricketers.csv")

# plotting count plot with Age column
sb.countplot(dataFrame["Age"])

# display
plt.show()
This will produce the following output −
Let us see another example wherein we have used the hue parameter −
import seaborn as sb
import pandas as pd
import matplotlib.pyplot as plt

# Load data from a CSV file into a Pandas DataFrame
dataFrame = pd.read_csv("C:\\Users\\amit_\\Desktop\\Cricketers.csv")

# plotting count plot with Role column and hue as Academy
sb.countplot( x= "Role", hue="Academy", data=dataFrame)

# display
plt.show()
This will produce the following output −
Set the coordinates of the area in an image map in HTML?

Use the cords attribute in HTML to set the coordinates of the area in an image map in HTML.
You can try to run the following code to implement the cords attribute −
<!DOCTYPE html>
<html>
   <head>
      <title>HTML coords attribute</title>
   </head>
   <body>
      <img src = "/images/html.gif" alt = "HTML Map" border = "0" usemap = "#html"/>
      <map name = "html">
         <area shape = "circle" coords = "154,150,59" href = "about/about_team.htm"
            alt = "Team" target = "_self" />
      </map>
   </body>
</html>
Tryit Editor v3.7

Tryit: Using the animation-timing-function property
GATE | GATE-CS-2017 (Set 2) | Question 29 - GeeksforGeeks

29 Sep, 2021
Given the following binary number in 32 bit (single precision) IEEE-754 format:
00111110011011010000000000000000

The decimal value closest to this floating-point number is:(A) 1.45 X 101(B) 1.45 X 10-1(C) 2.27 X 10-1(D) 2.27 X 101Answer: (C)Explanation: In 32-bit IEEE-754 format
1st bit represent sign
2-9th bit represent exponent
and 10-32 represent Mantissa (Fraction part)

Sign = 0, so positive2-9 bits — 01111100 when subtracted by 01111111 i.e., 126 decimal value gives -> 0000 0011Which is -3.(negative as the value is less than 126)As number is less than 126 it is subtracted otherwise 126 would have been subtracted from it in 32 bit representation.(https://www3.ntu.edu.sg/home/ehchua/programming/java/datarepresentation.html)
Mantissa is normal ,hence, 1.M can be used .Which is 1.1101101.Thus,Data + 1.1101101 * 2^-3 (±M * B^(±e) )Mantissa shift right 3 times ->+0.0011101101= 0.228= 2.28 * 10^-1
Thus, option c is correct.
This explanation is contributed by Shashank Shanker.
YouTubeGeeksforGeeks GATE Computer Science16.1K subscribersFloating Point Representation with Rishabh Setiya | GeeksforGeeks GATEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0011:55 / 24:34•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=M91XDWNNVU8" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question
GATE-CS-2017 (Set 2)
GATE-GATE-CS-2017 (Set 2)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE CS 1997 | Question 25
GATE | GATE CS 2012 | Question 54
GATE | GATE-CS-2014-(Set-1) | Question 65
GATE | GATE CS 2019 | Question 50
GATE | GATE CS 2008 | Question 69
GATE | GATE CS 2018 | Question 45
GATE | GATE CS 2020 | Question 16
GATE | GATE CS 2011 | Question 65
GATE | GATE CS 2011 | Question 43
GATE | GATE CS 2010 | Question 33
Java Recursion

Recursion is the technique of making a function call itself. This technique provides a way
to break complicated problems down into simple problems which are easier to solve.
Recursion may be a bit difficult to understand. The
best way to figure out how it works is to experiment with it.
Adding two numbers together is easy to do, but adding a range of numbers is more
complicated. In the following example, recursion is used to add a range of numbers
together by breaking it down into the simple task of adding two numbers:
Use recursion to add all of the numbers up to 10.
public class Main {
  public static void main(String[] args) {
    int result = sum(10);
    System.out.println(result);
  }
  public static int sum(int k) {
    if (k > 0) {
      return k + sum(k - 1);
    } else {
      return 0;
    }
  }
}

Try it Yourself »

When the sum() function is called, it adds parameter k to the sum of all numbers smaller
than k and returns the result. When k becomes 0, the function just returns 0. When
running, the program follows these steps:
Since the function does not call itself when k is 0, the program stops there and returns the
result.
Just as loops can run into the problem of infinite looping, recursive functions can run into
the problem of infinite recursion. Infinite recursion is when the function never stops calling
itself. Every recursive function should have a halting condition, which is the condition
where the function stops calling itself. In the previous example, the halting condition is
when the parameter k becomes 0.
It is helpful to see a variety of different examples to better understand the concept. In this
example, the function adds a range of numbers between a start and an end. The halting
condition for this recursive function is when end is not greater than start:
Use recursion to add all of the numbers between 5 to 10.
public class Main {
  public static void main(String[] args) {
    int result = sum(5, 10);
    System.out.println(result);
  }
  public static int sum(int start, int end) {
    if (end > start) {
      return end + sum(start, end - 1);
    } else {
      return end;
    }
  }
}

Try it Yourself »

The developer should be very careful with recursion as it can be quite easy to slip into writing a function which never terminates, or one that uses excess amounts of memory or processor power. However, when written correctly recursion can be a very efficient and mathematically-elegant approach to programming.
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.
Use ListIterator to traverse an ArrayList in the reverse direction in Java

A ListIterator can be used to traverse the elements in the forward direction as well as the reverse direction in the List Collection. So the ListIterator is only valid for classes such as LinkedList, ArrayList etc.
The method hasPrevious( ) in ListIterator returns true if there are more elements in the List while traversing in the reverse direction and false otherwise. The method previous( ) returns the previous element in the List and reduces the cursor position backward.
A program that demonstrates this is given as follows −
 Live Demo
import java.util.ArrayList;
import java.util.ListIterator;
public class Demo {
   public static void main(String[] args) {
      ArrayList<String> aList = new ArrayList<String>();
      aList.add("Amanda");
      aList.add("Peter");
      aList.add("Julie");
      aList.add("James");
      aList.add("Emma");
      ListIterator<String> li = aList.listIterator();
      while (li.hasNext()) {
         li.next();
      }
      System.out.println("The ArrayList elements in the reverse direction are: ");
      while (li.hasPrevious()) {
         System.out.println(li.previous());
      }
   }
}
The ArrayList elements in the reverse direction are:
Emma
James
Julie
Peter
Amanda
Now let us understand the above program.
The ArrayList is created and ArrayList.add() is used to add the elements to the ArrayList. A code snippet which demonstrates this is as follows −
ArrayList<String> aList = new ArrayList<String>();
aList.add("Amanda");
aList.add("Peter");
aList.add("Julie");
aList.add("James");
aList.add("Emma");
Then the ListIterator interface is used to display the ArrayList elements in the reverse direction. A code snippet which demonstrates this is as follows −
ListIterator<String> li = aList.listIterator();
while (li.hasNext()) {
   li.next();
}
System.out.println("The ArrayList elements in the reverse direction are: ");
while (li.hasPrevious()) {
   System.out.println(li.previous());
}
Convert.ToDateTime(String, IFormatProvider) Method in C#

The Convert.ToDateTime() method in C# converts the specified string representation of a number to an equivalent date and time, using the specified culture-specific formatting information.
Following is the syntax −
public static DateTime ToDateTime (string val, IFormatProvider provider);
Above, value is a string that contains a date and time to convert, whereas the provider is an object that supplies culture-specific formatting information.
Let us now see an example to implement the Convert.ToDateTime() method −
using System;
using System.Globalization;
public class Demo {
   public static void Main(){
      CultureInfo cultures = new CultureInfo("en-US");
      String val = "11/11/2019";
      Console.WriteLine("Converted DateTime value...");
      DateTime res = Convert.ToDateTime(val, cultures);
      Console.Write("{0}", res);
   }
}
This will produce the following output −
Converted DateTime value...
11/11/2019 12:00:00 AM
How to align two divs horizontally in HTML?

To align two divs horizontally in HTML, use the float CSS property with left value. You can try to run the following code to learn how to align divs horizontally −
Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
.demo div {
    float: left;
    clear: none;
}
</style>
</head>
<body>
<div class="demo">
     <div>
        <span>div1</span>
        <select size="5">
           <option value="c1">India</option>
           <option value="c2">US</option>
           <option value="c3">UK</option>
           <option value="c4">Australia</option>
        </select>
    </div>
    <div>
        <span>div2</span>
        <select size="5">
           <option value="r1">1</option>
           <option value="r2">2</option>
           <option value="r3">3</option>
           <option value="r4">4</option>
        </select>
    </div>
</div>
</body>
</html>
MongoDB - Delete Multiple Documents Using MongoShell - GeeksforGeeks

27 Feb, 2020
In MongoDB, you are allowed to delete the existing documents from the collection using db.collection.deleteMany() method. This method deletes multiple documents from the collection according to the filter.
deleteMany() is a mongo shell method, which can delete multiple documents. This method can be used in the multi-document transactions. If you use this method in capped collection, then it will throw an exception.
Syntax:
db.collection.deleteMany(
    <filter>,
   {
      writeConcern: <document>,
     collation: <document>
   }
)
Parameters:
fileter: First parameter of this method. It specifies the selection criteria for the delete using query operators. The type of this parameter is document. If it contains empty document, i.e, {}, then this method will delete all the documents from the collection.
Optional Parameters:
writeConcern: It is only used when you do not want to use the default write concern. The type of this parameter is document.
collation: It specifies the use of the collation for operations. It allows users to specify the language-specific rules for string comparison like rules for lettercase and accent marks. The type of this parameter is document.
Return: This method will return a document that contains a boolean acknowledged as true (if the write concern is enabled) or false (if the write concern is disabled) and deletedCount that represents the total number of deleted documents.
Examples:
In the following examples, we are working with:
Database: GeeksforGeeks
Collection: contributor
Document: four documents that contain the details of the contributors in the form of field-value pairs.
In this example, we are deleting multiple documents from the contributor collection that matches the filter, i.e., language: “C#”. Or in other words, we are removing those contributors who are working with C# language from the database.
In this example, we are deleting all the documents from the contributor collection by passing empty document in the db.collection.deleteMany() method.
db.contributor.deleteMany({})
MongoDB
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Copying Files to and from Docker Containers
Principal Component Analysis with Python
An introduction to Machine Learning
Fuzzy Logic | Introduction
OpenCV - Overview
Mounting a Volume Inside Docker Container
Classifying data using Support Vector Machines(SVMs) in Python
Getting Started with System Design
How to create a REST API using Java Spring Boot
Basics of API Testing Using Postman
PHP | imagecrop() Function - GeeksforGeeks

23 Aug, 2019
The imagecrop() function is an inbuilt function in PHP which is used to crop an image to the given rectangle. This function crops an image to the given rectangular area and returns the resulting image. The given image is not modified.
Syntax:
resource imagecrop ( $image, $rect )
Parameters: This function accepts two parameters as mentioned above and described below:
$image: It is returned by one of the image creation functions, such as imagecreatetruecolor(). It is used to create size of image.
$rect: The cropping rectangle as array with keys x, y, width and height.
Return Value: This function return cropped image resource on success or False on failure.
Below programs illustrate the imagecrop() function in PHP:
Program:
<?php  // Create an image from given image$im = imagecreatefrompng('https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-9.png');  // find the size of image$size = min(imagesx($im), imagesy($im));  // Set the crop image size $im2 = imagecrop($im, ['x' => 0, 'y' => 0, 'width' => 250, 'height' => 150]);if ($im2 !== FALSE) {    header("Content-type: image/png");       imagepng($im2);    imagedestroy($im2);}imagedestroy($im);?>
output:
Related Articles:
PHP | gd_info() Function
PHP | imagearc() Function
Reference: http://php.net/manual/en/function.imagecrop.php
Image-Processing
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to Upload Image into Database and Display it using PHP ?
How to check whether an array is empty using PHP?
How to receive JSON POST with PHP ?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
nested loops in C

C programming allows to use one loop inside another loop. The following section shows a few examples to illustrate the concept.
The syntax for a nested for loop statement in C is as follows −
for ( init; condition; increment ) {

   for ( init; condition; increment ) {
      statement(s);
   }
   statement(s);
}

The syntax for a nested while loop statement in C programming language is as follows −
while(condition) {

   while(condition) {
      statement(s);
   }
   statement(s);
}

The syntax for a nested do...while loop statement in C programming language is as follows −
do {
   statement(s);

   do {
      statement(s);
   }while( condition );

}while( condition );

A final note on loop nesting is that you can put any type of loop inside any other type of loop. For example, a 'for' loop can be inside a 'while' loop or vice versa.
The following program uses a nested for loop to find the prime numbers from 2 to 100 −
#include <stdio.h>
 
int main () {

   /* local variable definition */
   int i, j;
   
   for(i = 2; i<100; i++) {

      for(j = 2; j <= (i/j); j++) 
      if(!(i%j)) break; // if factor found, not prime
      if(j > (i/j)) printf("%d is prime\n", i);
   }
 
   return 0;
}
When the above code is compiled and executed, it produces the following result −
2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime
53 is prime
59 is prime
61 is prime
67 is prime
71 is prime
73 is prime
79 is prime
83 is prime
89 is prime
97 is prime

 Print
 Add Notes
 Bookmark this page
Tryit Editor v3.7

Tryit: HTML background-color
Convert an Array to a Circular Doubly Linked List in C++

In this tutorial, we will be discussing a program to convert an array to a circular doubly linked list.
For this we will be provided with an array. Our task is to take the elements of the array and get it converted into a circular doubly linked list.
 Live Demo
#include<iostream>
using namespace std;
//node structure for doubly linked list
struct node{
   int data;
   struct node *next;
   struct node *prev;
};
//node creation
struct node* getNode(){
   return ((struct node *)malloc(sizeof(struct node)));
}
//printing the list
int print_list(struct node *temp){
   struct node *t = temp;
   if(temp == NULL)
   return 0;
   else {
      cout<<"List: ";
      while(temp->next != t) {
         cout<<temp->data<<" ";
         temp = temp->next;
      }
      cout<<temp->data;
      return 1;
   }
}
//converting array to linked list
void convert_array(int arr[], int n, struct node **start) {
   //declaring new pointer
   struct node *newNode,*temp;
   int i;
   //moving through all the elements
   for(i=0;i<n;i++){
      newNode = getNode();
      newNode->data = arr[i];
      if(i==0) {
         *start = newNode;
         newNode->prev = *start;
         newNode->next = *start;
      } else  {
         //calculating the last node
         temp = (*start)->prev;
         temp->next = newNode;
         newNode->next = *start;
         newNode->prev = temp;
         temp = *start;
         temp->prev = newNode;
      }
   }
}
int main(){
   int arr[] = {1,2,3,4,5};
   int n = sizeof(arr) / sizeof(arr[0]);
   struct node *start = NULL;
   convert_array(arr, n, &start);
   print_list(start);
   return 0;
}
List: 1 2 3 4 5
Adding binary strings together JavaScript

We are required to write a JavaScript function that takes in two binary strings. The function should return the sum of those two-binary string as another binary string.
For example −
If the two strings are −
const str1 = "1010";
const str2 = "1011";
Then the output should be −
const output = '10101';
const str1 = "1010";
const str2 = "1011";
const addBinary = (str1, str2) => {
   let carry = 0;
   const res = [];
   let l1 = str1.length, l2 = str2.length;
   for (let i = l1 - 1, j = l2 - 1; 0 <= i || 0 <= j; --i, --j) {
      let a = 0 <= i ? Number(str1[i]) : 0,
      b = 0 <= j ? Number(str2[j]) : 0;
      res.push((a + b + carry) % 2);
      carry = 1 < a + b + carry;
   };
   if (carry){
      res.push(1);
   }
   return res.reverse().join('');
};
console.log(addBinary(str1, str2));
And the output in the console will be −
10101
Floyd Cycle Detection Algorithm to detect the cycle in a linear Data Structure

Floyd Cycle is one of the cycle detection algorithms to detect the cycle in a given singly linked list.
In the Floyd Cycle algorithm, we have two pointers that initially point at the head. In Hare and Tortoise’s story, Hare moves twice as fast as Tortoise, and whenever the hare reaches the end of the path, the tortoise reaches the middle of the path.
Initialize Hare and Tortoise at the head node of the List.
Initialize Hare and Tortoise at the head node of the List.
Initially, the hare moves twice as fast as the tortoise.
Initially, the hare moves twice as fast as the tortoise.
Move the hare and tortoise both and find if the hare reaches the end of the Linked List, return as there is no loop in the list.
Move the hare and tortoise both and find if the hare reaches the end of the Linked List, return as there is no loop in the list.
Otherwise, both Hare and Tortoise will go forward.
Otherwise, both Hare and Tortoise will go forward.
If Hare and Tortoise are at the same Node, then return since we have found the list cycle.
If Hare and Tortoise are at the same Node, then return since we have found the list cycle.
Else, start with step 2.
Else, start with step 2.
tortoise := headNode
hare := headNode
foreach:
   if hare == end
      return 'There is No Loop Found.'
   hare := hare.next
   if hare == end
      return 'No Loop Found'
   hare = hare.next
   tortoise = tortoise.next
   if hare == tortoise
      return 'Cycle Detected'
What are unary operators in C#?

The following are the unary operators in C# −
+ - ! ~ ++ -- (type)* & sizeof
Let us learn about the sizeof operator. The sizeof returns the size of a data type.
Let’s say you need to find the size of int datatype −
sizeof(int)
For double datatype −
sizeof(double)
Let us see the complete example to find the size of various datatypes −
 Live Demo
using System;

namespace Demo {

   class Program {

      static void Main(string[] args) {

         Console.WriteLine("The size of int is {0}", sizeof(int));
         Console.WriteLine("The size of int is {0}", sizeof(char));
         Console.WriteLine("The size of short is {0}", sizeof(short));
         Console.WriteLine("The size of long is {0}", sizeof(long));
         Console.WriteLine("The size of double is {0}", sizeof(double));

         Console.ReadLine();
      }
   }
}
The size of int is 4
The size of int is 2
The size of short is 2
The size of long is 8
The size of double is 8
Get values from all rows and display it a single row separated by comma with MySQL

For this, use GROUP_CONCAT(). Do not use GROUP BY clause, since GROUP_CONTACT() is a better and quick solution.
Let us first create a table −
mysql> create table DemoTable1371
   -> (
   -> Id int,
   -> CountryName varchar(40)
   -> );
Query OK, 0 rows affected (0.89 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1371 values(100,'US');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable1371 values(100,'UK');
Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable1371 values(101,'AUS');
Query OK, 1 row affected (0.27 sec)
mysql> insert into DemoTable1371 values(101,'Angola');
Query OK, 1 row affected (0.14 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1371;
This will produce the following output −
+------+-------------+
| Id   | CountryName |
+------+-------------+
|  100 | US          |
|  100 | UK          |
|  101 | AUS         |
|  101 | Angola      |
+------+-------------+
4 rows in set (0.00 sec)
Here is the query to get values from all rows and display it a single row separated by comma −
mysql> select group_concat(CountryName separator ',') from DemoTable1371;
This will produce the following output −
+-----------------------------------------+
| group_concat(CountryName separator ',') |
+-----------------------------------------+
| US,UK,AUS,Angola                        |
+-----------------------------------------+
1 row in set (0.00 sec)
C++ Program to Implement Interpolation Search Algorithm

For the binary search technique, the lists are divided into equal parts. For the interpolation searching technique, the procedure will try to locate the exact position using interpolation formula. After finding the estimated location, it can separate the list using that location. As it tries to find exact location every time, so the searching time reduces. This technique can find items easily if the items are uniformly distributed.
Time Complexity: O(log2(log2 n)) for average case, and O(n) for worst case (when items are distributed exponentially)
Time Complexity: O(log2(log2 n)) for average case, and O(n) for worst case (when items are distributed exponentially)
Space Complexity: O(1)
Space Complexity: O(1)
Input − A sorted list of data
10 13 15 26 28 50 56 88 94 127 159 356 480 567 689 699 780 850 956 995. 
The search key 780
Output − Item found at location: 16
Input: An sorted array, start and end location, and the search key
Output: location of the key (if found), otherwise wrong location.
Begin
   while start <= end AND key >= array[start] AND key <= array[end] do
      dist := key – array[start]
      valRange := array[end] – array[start]
      fraction := dist / valRange
      indexRange := end – start
      estimate := start + (fraction * indexRange)
      if array[estimate] = key then
         return estimate position
      if array[estimate] < key then
         start := estimate + 1
      else
         end = estimate -1
   done
   return invalid position
End
#include<iostream>
using namespace std;
int interpolationSearch(int array[], int start, int end, int key) {
   int dist, valRange, indexRange, estimate;
   float fraction;
   while(start <= end && key >= array[start] && key <= array[end]) {
      dist = key - array[start];
      valRange = array[end] - array[start];     //range of value
      fraction = dist / valRange;
      indexRange = end - start;
      estimate = start + (fraction * indexRange);      //estimated position of the key
      if(array[estimate] == key)
         return estimate;
      if(array[estimate] < key)
         start = estimate +1;
      else
         end = estimate - 1;
   }
   return -1;
}
int main() {
   int n, searchKey, loc;
   cout << "Enter number of items: ";
   cin >> n;
   int arr[n];      //create an array of size n
   cout << "Enter items: " << endl;
   for(int i = 0; i< n; i++) {
      cin >> arr[i];
   }
   cout << "Enter search key to search in the list: ";
   cin >> searchKey;
   if((loc = interpolationSearch(arr, 0, n-1, searchKey)) >= 0)
      cout << "Item found at location: " << loc << endl;
   else
      cout << "Item is not found in the list." << endl;
}
Enter number of items: 20
Enter items:
10 13 15 26 28 50 56 88 94 127 159 356 480 567 689 699 780 850 956
995
Enter search key to search in the list: 780
Item found at location: 16
Python String encode() Method

Python string  method encode() returns an encoded version of the string. Default encoding is the current default string encoding. The errors may be given to set a different error handling scheme.
str.encode(encoding='UTF-8',errors='strict')

encoding − This is the encodings to be used. For a list of all encoding schemes please visit: Standard Encodings.
encoding − This is the encodings to be used. For a list of all encoding schemes please visit: Standard Encodings.
errors − This may be given to set a different error handling scheme. The default for errors is 'strict', meaning that encoding errors raise a UnicodeError. Other possible values are 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' and any other name registered via codecs.register_error().
errors − This may be given to set a different error handling scheme. The default for errors is 'strict', meaning that encoding errors raise a UnicodeError. Other possible values are 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' and any other name registered via codecs.register_error().
Decoded string.
#!/usr/bin/python

str = "this is string example....wow!!!";
print "Encoded String: " + str.encode('base64','strict')
Encoded String: dGhpcyBpcyBzdHJpbmcgZXhhbXBsZS4uLi53b3chISE=


    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
jQuery - hasClass( class ) Method

The hasClass( class ) method returns true if the specified class is present on at least one of the set of matched elements otherwise it returns false.
Here is the simple syntax to use this method −
selector.hasClass( class )

Here is the description of all the parameters used by this method −
class − The name of CSS class.
class − The name of CSS class.
Following example would check which para has class red −
<html>
   <head>
      <title>The Selecter Example</title>
      <script type = "text/javascript" 
         src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
      </script>
   
      <script type = "text/javascript" language = "javascript">
         $(document).ready(function() {
            $("#result1").text( $("p#pid1").hasClass("red") );
            $("#result2").text( $("p#pid2").hasClass("red") );
         });
      </script>
		
      <style>
         .red { color:red; }
         .green { color:green; }
      </style>
   </head>
	
   <body>
      <p class = "red" id = "pid1">This is first paragraph.</p>
      <p class = "green" id = "pid2">This is second paragraph.</p>

      <div id = "result1"></div>
      <div id = "result2"></div>
   </body>
</html>
This will produce following result −
This is first paragraph.
This is second paragraph.

    27 Lectures 
     1 hours 

 Mahesh Kumar

    27 Lectures 
     1.5 hours 

 Pratik Singh

    72 Lectures 
     4.5 hours 

 Frahaan Hussain

    60 Lectures 
     9 hours 

 Eduonix Learning Solutions

    17 Lectures 
     2 hours 

 Sandip Bhattacharya

    12 Lectures 
     53 mins

 Laurence Svekis
 Print
 Add Notes
 Bookmark this page
Changing Ownership of schema in SAP HANA Database

I don’t think you can change ownership of schema in database. Easiest way to change ownership of schema is by exporting a schema, drop it from the database and then recreate the schema owned by the target user and import the objects back into the database.
In recent version, you can create schema and set other users as an owner of the schema however you can’t change it later −
Create SCHEMA TEST123 owned by Demo;
In same way, you can collect the script for "Create procedure" from database and drop the procedures in the earlier user schema and then these can be recreated in new user schema. You can do in the script with the dynamic SQL which would create the object into the target schema and drop the object in source schema.
How to aggregate two lists if at least one element matches in MongoDB?

For this, use groupinMongoDB.Withinthat,useunwind, group,addToSet, etc. Let us create a collection with documents −
> db.demo456.insertOne(
... { _id: 101, StudentName: ["Chris", "David"] }
... );
{ "acknowledged" : true, "insertedId" : 101 }
>
> db.demo456.insertOne(
... { _id: 102, StudentName: ["Mike", "Sam"] }
... );
{ "acknowledged" : true, "insertedId" : 102 }
> db.demo456.insertOne(
... { _id: 103, StudentName: ["John", "Jace"] }
... );
{ "acknowledged" : true, "insertedId" : 103 }
> db.demo456.insertOne(
... { _id: 104, StudentName: ["Robert", "John"] }
... );
{ "acknowledged" : true, "insertedId" : 104 }
Display all documents from a collection with the help of find() method −
> db.demo456.find();
This will produce the following output −
{ "_id" : 101, "StudentName" : [ "Chris", "David" ] }
{ "_id" : 102, "StudentName" : [ "Mike", "Sam" ] }
{ "_id" : 103, "StudentName" : [ "John", "Jace" ] }
{ "_id" : 104, "StudentName" : [ "Robert", "John" ] }
Following is the query to aggregate two lists if at least one element matches −
> db.demo456.aggregate([
... {$unwind:"$StudentName"},
... {$group:{_id:"$StudentName", combine:{$addToSet:"$_id"}, size:{$sum:1}}},
... {$match:{size: {$gt: 1}}},
... {$project:{_id: 1, combine:1, size: 1, combine1: "$combine"}},
... {$unwind:"$combine"},
... {$unwind:"$combine1"},
... {$group:{_id:"$combine", l:{$first:"$_id"}, size:{$sum: 1}, set: {$addToSet:"$combine1"}}},
... {$sort:{size:1}},
... {$group:{_id: "$l", combineIds:{$last:"$set"}, size:{$sum:1}}},
... {$match: {size:{$gt:1}}}
... ])
This will produce the following output −
{ "_id" : "John", "combineIds" : [ 103, 104 ], "size" : 2 }
Write a java program to reverse each word in string?

StringBuffer class of the java.lang package provides reverse() method. This method returns a reverse sequence of the characters in the current String. Using this method you can reverse a string in Java.
To reverse each word in a string you need to split the string, store it in an array of strings and reverse each word using the reverse() method of the StringBuffer class.
Live Demo
import java.lang.*;
public class StringBufferDemo {
   public static void main(String[] args) {
      StringBuffer buff = new StringBuffer("tutorials point");
      System.out.println("buffer = " + buff);

      // reverse characters of the buffer and prints it
      System.out.println("reverse = " + buff.reverse());

      // reverse of the buffer is equivalent to the actual buffer
      buff = new StringBuffer("malyalam");
      System.out.println("buffer = " + buff);

      // reverse characters of the buffer and prints it
      System.out.println("reverse = " + buff.reverse());
   }
}
buffer = tutorials point
reverse = tniop slairotut
buffer = malyalam
reverse = malaylam
Set vs Map in C++ STL

Set is an abstract data type in which each element has to be unique because the value of the element identifies it. The value of the element cannot be modified once it is added to the set, but it is possible to remove and add the modified value of that element.
A Map is an associative container that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have the same key values.
So, it is clear from above that, set contains the only key, and map contains a value with the key, both should have unique and sorted value.
For unordered and unsorted elements there are unordered_set/unordered_map,multiset/multimap.
 Live Demo
#include<iostream>
#include <bits/stdc++.h>
using namespace std;
int main() {
   set<int> s; //initializing a empty set container
   set<int>::iterator it; //Initializing a set container as iterator
   s.insert(7); //inserting elements in the set container s
   s.insert(6);
   s.insert(1);
   s.insert(4);
   s.insert(2);
   s.insert(9);
   s.insert(10);
   cout << "Elements are in set:\n";
   for ( auto it : s)
      cout << it << " "; //printing elements of the set container
   return 0;
}
1 2 4 6 7 9 10
 Live Demo
#include<iostream>
#include <bits/stdc++.h>
using namespace std;

int main()
{
   map<char, int> m;                     //initialize a map
   map<char, int>::iterator iter;       //initializing a map as iterator
   m.insert (pair<char, int>('a', 10)); //inserting values to the map
   m.insert (pair<char, int>('b', 20));

   cout << "Elements in map:\n";
   for (iter=m.begin();iter!=m.end();iter++)
   cout << "[ " << iter->first << ", "<< iter->second << "]\n"; //printing the values of the map
   return 0;
}
Elements in map: 
[ a, 10] 
[ b, 20]
HTML5 Canvas - Animations

HTML5 canvas provides necessary methods to draw an image and erase it completely. We can take Javascript help to simulate good animation over a HTML5 canvas.
Following are the two important Javascript methods which would be used to animate an image on a canvas −
setInterval(callback, time);
This method repeatedly executes the supplied code after a given timemilliseconds.
setTimeout(callback, time);
This method executes the supplied code only once after a given time milliseconds.
Following is a simple example which would rotate a small image repeatedly −
<!DOCTYPE HTML>

<html>
   <head>
      
      <script type = "text/javascript">
         var pattern = new Image();
         
         function animate() {
            pattern.src = '/html5/images/pattern.jpg';
            setInterval(drawShape, 100);
         }
         
         function drawShape() {
            
            // get the canvas element using the DOM
            var canvas = document.getElementById('mycanvas');
            
            // Make sure we don't execute when canvas isn't supported
            if (canvas.getContext) {
            
               // use getContext to use the canvas for drawing
               var ctx = canvas.getContext('2d');
               
               ctx.fillStyle = 'rgba(0,0,0,0.4)';
               ctx.strokeStyle = 'rgba(0,153,255,0.4)';
               ctx.save();
               ctx.translate(150,150); 
               
               var time = new Date(); 
               ctx.rotate( ((2*Math.PI)/6)*time.getSeconds() + ( (2*Math.PI)/6000)*time.getMilliseconds() );
               ctx.translate(0,28.5);
               ctx.drawImage(pattern,-3.5,-3.5);
               ctx.restore();
            } else {
               alert('You need Safari or Firefox 1.5+ to see this demo.');
            }
         }
      </script>
   </head>
   
   <body onload = "animate();">
      <canvas id = "mycanvas" width = "400" height = "400"></canvas>
   </body>
   
</html>
The above example would produce the following result −

    19 Lectures 
     2 hours 

 Anadi Sharma

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    18 Lectures 
     1.5 hours 

 Frahaan Hussain

    57 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)

    54 Lectures 
     6 hours 

 DigiFisk (Programming Is Fun)

    45 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)
 Print
 Add Notes
 Bookmark this page
SQL Tryit Editor v1.6

SELECT * FROM Customers
WHERE NOT Country='Germany';
​
Edit the SQL Statement, and click "Run SQL" to see the result.
This SQL-Statement is not supported in the WebSQL Database.
The example still works, because it uses a modified version of SQL.
Your browser does not support WebSQL.
Your are now using a light-version of the Try-SQL Editor, with a read-only Database.
If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time.
Our Try-SQL Editor uses WebSQL to demonstrate SQL.
A Database-object is created in your browser, for testing purposes.
You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button.
WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object.
WebSQL is supported in Chrome, Safari, Opera, and Edge(79).
If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.