code-rag-bench/online-tutorials huggingface dataset:
Python groupby method to remove all consecutive duplicates - GeeksforGeeks

27 Dec, 2017
Given a string S, remove all the consecutive duplicates.
Examples:
Input  : aaaaabbbbbb
Output : ab

Input : geeksforgeeks
Output : geksforgeks

Input : aabccba
Output : abcba

We have existing solution for this problem please refer Remove all consecutive duplicates from the string link. We can solve this problem in python quickly using itertools.groupby() method.
Group by method takes two input one is iterable (list,tuple,dictionary) and second is key function which calculates keys for each element present in iterable. It returns key and iterable of grouped items. If key function not specified or is None, key defaults to an identity function and returns the element unchanged. For example,
numbers = [1, 1, 1, 3, 3, 2, 2, 2, 1, 1]import itertoolsfor (key,group) in itertools.groupby(numbers):    print (key,list(group))
Output:
(1, [1, 1, 1])
(3, [3, 3])
(2, [2, 2])
(1, [1, 1])

# function to remove all consecutive duplicates # from the string in Python  from itertools import groupbydef removeAllConsecutive(input):         # group all consecutive characters based on their      # order in string and we are only concerned     # about first character of each consecutive substring     # in given string, so key value will work for us     # and we will join these keys without space to      # generate resultant string     result = []     for (key,group) in groupby(input):          result.append(key)       print (''.join(result))       # Driver programif __name__ == "__main__":    input = 'aaaaabbbbbb'    removeAllConsecutive(input)
References :https://docs.python.org/3/library/itertools.html
Output:
ab

python-string
Python
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Reverse a string in Java
Write a program to reverse an array or string
Longest Common Subsequence | DP-4
Write a program to print all permutations of a given string
C++ Data Types
Can we declare a try catch block within another try catch block in Java?

Yes, we can declare a try-catch block within another try-catch block, this is called nested try-catch block.
If an inner try statement does not have a matching catch statement for a particular exception, the control is transferred to the next try statement catch handlers that are expected for a matching catch statement.
This continues until one of the catch statements succeeds, or until all of the nested try statements are done.
If no one catch statements match, then the Java run-time system will handle the exception.
When nested try blocks are used, the inner try block is executed first. Any exception thrown in the inner try block is caught in the corresponding catch block. If a matching catch block is not found, then catch block of the outer try block are inspected until all nested try statements are exhausted. If no matching blocks are found, the Java Runtime Environment handles the execution.
try {
   statement 1;
   statement 2;
   try {
      statement 1;
      statement 2;
   }
   catch(Exception e) {
      // catch the corresponding exception  
   }  
}
catch(Exception e) {
   // catch the corresponding exception
}
   .............
Live Demo
import java.io.*;
public class NestedTryCatchTest {
   public static void main (String args[]) throws IOException {
    int n = 10, result = 0;
      try { // outer try block
         FileInputStream fis = null;
         fis = new FileInputStream (new File (args[0]));
         try { // inner trty block
            result = n/0;
            System.out.println("The result is"+result);
         }  
         catch(ArithmeticException e) { // inner catch block
            System.out.println("Division by Zero");
         }
      }
      catch (FileNotFoundException e) { // outer catch block
         System.out.println("File was not found");
      }
      catch(ArrayIndexOutOfBoundsException e) { // outer catch block
         System.out.println("Array Index Out Of Bounds Exception occured ");
      }
      catch(Exception e) { // outer catch block
         System.out.println("Exception occured"+e);
      }
   }
}
Array Index Out Of Bounds Exception occured
Tryit Editor v3.7

Tryit: HTML round table borders
Explain C++ Singleton design pattern.

Singleton design pattern is a software design principle that is used to restrict the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. For example, if you are using a logger, that writes logs to a file, you can use a singleton class to create such a logger. You can create a singleton class using the following code −
#include <iostream>

using namespace std;

class Singleton {
   static Singleton *instance;
   int data;
 
   // Private constructor so that no objects can be created.
   Singleton() {
      data = 0;
   }

   public:
   static Singleton *getInstance() {
      if (!instance)
      instance = new Singleton;
      return instance;
   }

   int getData() {
      return this -> data;
   }

   void setData(int data) {
      this -> data = data;
   }
};

//Initialize pointer to zero so that it can be initialized in first call to getInstance
Singleton *Singleton::instance = 0;

int main(){
   Singleton *s = s->getInstance();
   cout << s->getData() << endl;
   s->setData(100);
   cout << s->getData() << endl;
   return 0;
}
This will give the output −
0
100
Django - Dealing with warnings - GeeksforGeeks

22 Jul, 2021
Prerequisite : Django – Creating project
Django is a great framework which provides you a lot of pre-defined services and workflow so that one can work flawlessly. Django apps are designed to make your code clean and reusable. Django works on the concept of DRY which means Don’t Repeat Yourself.
After creating project , your directory should look like this:
Doesn’t it look a little confusing? Two folders with the same name? So, here is good news. You can change the name of the outer folder because it is just a folder containing your project but please don’t change the name of the inner folder. Let’s rename the outer folder as geeksforgeeks.
Now, it should look like:
Unapplied migrations
After completing Set 2, you have got Django server worked –but did you notice the warning in red color?
You have 15 unapplied migrations...
We will discuss about such warnings later. For the sake of simplicity, let’s remove the warnings for now. Stop your server using CTRL+C. Run the following command in your terminal:
python manage.py migrate
Now on your command prompt, you will see something like this:
Now run command
python manage.py runserver
Congratulations, you have silenced all warnings
We can get rid of views.py because Django apps are supposed to handle with views. Also, remove these two lines from related files.
from geeks_site.views import hello_geeks
path('geek/', hello_geek),

Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
*args and **kwargs in Python
How To Convert Python Dictionary To JSON?
What is covariant return type in Java?

Covariant return type refers to return type of an overriding method. It allows to narrow down return type of an overridden method without any need to cast the type or check the return type. Covariant return type works only for non-primitive return types.
From Java 5 onwards, we can override a method by changing its return type only by abiding the condition that return type is a subclass of that of overridden method return type.
Following example showcases the same.
Live Demo
class SuperClass {
   SuperClass get(){
      System.out.println("SuperClass");
      return this;
   }
}
public class Tester extends SuperClass {
   Tester get(){
      System.out.println("SubClass");
      return this;
   }
   public static void main(String[] args) {
      SuperClass tester = new Tester();
 
      tester.get();
   }  
}
How to Iterate through a String word by word in C++ - GeeksforGeeks

18 Oct, 2019
Given a String comprising of many words separated by space, the task is to iterate over these words of the string in C++.
Example:
Input: str = {“GeeksforGeeks is a computer science portal for Geeks”};Output:GeeksforGeeksisacomputerscienceportalforGeeks
Input: str = {“Geeks for Geeks”};Output:GeeksforGeeks
Approach: istringstream class is best suitable for this purpose. When a string is given split by whitespace, this class can be used to easily fetch and use each word of the String.
Syntax:
string str = {"Geeks for Geeks"};
istringstream iss(str);

Below is the implementation of the above approach:
// C++ program to Iterate through// a String word by word  #include <iostream>#include <sstream>#include <string>  using namespace std;  // Driver codeint main(){      // Get the String    string str = "GeeksforGeeks is a computer "                 "science portal for Geeks";      // Initialise the istringstream    // with the given string    istringstream iss(str);      // Iterate the istringstream    // using do-while loop    do {        string subs;          // Get the word from the istringstream        iss >> subs;          // Print the word fetched        // from the istringstream        cout << subs << endl;      } while (iss);      return 0;}
GeeksforGeeks
is
a
computer
science
portal
for
Geeks

cpp-string
cpp-stringstream
C++ Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Passing a function as a parameter in C++
Program to implement Singly Linked List in C++ using class
Const keyword in C++
cout in C++
Dynamic _Cast in C++
Iterative Letter Combinations of a Phone Number
Setting up Sublime Text for C++ Competitive Programming Environment
How to sort an Array in descending order using STL in C++?
Return by reference in C++ with Examples
Why it is important to write "using namespace std" in C++ program?
File getName() method in Java with Examples - GeeksforGeeks

30 Jan, 2019
The getName() method is a part of File class. This function returns the Name of the given file object. The function returns a string object which contains the Name of the given file object.If the abstract path does not contain any name then a null string is returned.
Function Signature:
public String getName()
Function Syntax:
file.getName()
Parameters: This function does not accept any parameters.
Return value: This function returns a String value which is the Name of the given File object.
Below programs will illustrate the use of the getName() function:
Example 1: We are given a file object of a file, we have to get the Name of the file object.
// Java program to demonstrate the// use of getName() function  import java.io.*;  public class solution {    public static void main(String args[])    {          // try-catch block to handle exceptions        try {              // Create a file object            File f = new File("c:\\users\\program.txt");              // Get the Name of the given file f            String Name = f.getName();              // Display the file Name of the file object            System.out.println("File Name : " + Name);        }        catch (Exception e) {            System.err.println(e.getMessage());        }    }}
Output:
File Name : program.txt

Example 2: We are given a file object of a directory, we have to get the Name of the file object.
// Java program to demonstrate the// use of getName() function  import java.io.*;  public class solution {    public static void main(String args[])    {        // try-catch block to handle exceptions        try {              // Create a file object            File f                = new File("c:\\users\\program");              // Get the Name of the given file f            String Name = f.getName();              // Display the file Name            // of the file object            System.out.println("File Name : "                               + Name);        }        catch (Exception e) {            System.err.println(e.getMessage());        }    }}
Output:
File Name :program

The programs might not run in an online IDE. please use an offline IDE and set the Name of the file
Java-File Class
Java-Functions
Java-IO package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Stream In Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java
Python | os.path.isfile() method - GeeksforGeeks

28 Aug, 2019
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.path module is sub module of OS module in Python used for common path name manipulation.
os.path.isfile() method in Python is used to check whether the specified path is an existing regular file or not.
Syntax: os.path.isfile(path)
Parameter:path: A path-like object representing a file system path. A path-like object is either a string or bytes object representing a path.
Return Type: This method returns a Boolean value of class bool. This method returns True if specified path is an existing regular file, otherwise returns False.
Code #1: Use of os.path.isfile() method
# Python program to explain os.path.isfile() method     # importing os module import os  # Pathpath = '/home/User/Desktop/file.txt'  # Check whether the # specified path is # an existing fileisFile = os.path.isfile(path)print(isFile)    # Pathpath = '/home/User/Desktop/'  # Check whether the # specified path is # an existing fileisFile = os.path.isfile(path)print(isFile)
True
False

Reference: https://docs.python.org/3/library/os.path.html
nidhi_biet
python-os-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
HTML5 | translate Attribute - GeeksforGeeks

10 Aug, 2021
The translate attribute in HTML is used to specify whether the content of an element is translated or not. This attribute is new in HTML5.Supported Tags: It supports all HTML elements. 
Syntax:  
<element translate = "yes|no">
Attribute Values: The translate attribute contains two value which are listed below:  
yes: This attribute is used to specify that the content of element can be translated.
no: This attribute is used to specify that the content of element can not be translated.
Example:  
html
<!DOCTYPE html><html>    <head>        <title>translate attribute</title>        <style>            body {                text-align:center;            }            h1 {                color:green;            }        </style>    </head>    <body>        <h1>GeeksforGeeks</h1>        <h2><strong >translate attribute</strong></h2>        <p translate="no">Don't translate this!</p>          <p>This can be translated to any language.</p>     </body></html>
Output:  
Supported Browsers: Major browsers are not supported by translate Attribute. 
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
ManasChhabra2
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to update Node.js and NPM to next version ?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Operator precedence in JavaScript - GeeksforGeeks

25 Jun, 2020
Operator precedence refers to the priority given to operators while parsing a statement that has more than one operator performing operations in it. It is important to ensure the correct result and also to help the compiler understand what the order of operations should be. Operators with higher priorities are resolved first. But as one goes down the list, the priority decreases and hence their resolution.
Precedence and Associativity: Associativity in general states that irrespective of the order of operands for a given operation the result remains the same. Precedence is used to tell the compiler what operations should be performed first. For example, consider three numbers 2, 3, and 4. Now consider two operations:
( 2 + 3 ) + 4 = 2 + ( 3 + 4 )
( 2 >= 3 ) or ( 1 != 4 )
The first operation is associativity where the order does not matter. The second case is precedence, where in order to reach the desired result there has to be a proper order in which operations will be performed. 
Associativity is not a singular concept while dealing with precedence operations has to be dealt either with left-to-right or right-to-left associativity. This completely depends on the operation and tells the parser from which direction the operation should start.
Example: 
// left-to-right associativity : division 
3/4

// right-to-left associativity : assignment 
a = 3 

Operator Precedence Table: The operator precedence table can help one know the precedence of an operator relative to other operators. As one goes down the table, the precedence of these operators decreases over each other, that is, the priority of an operator is lower than the operators above it and higher than the ones below it. The operators in the same row have the same priority.
In this table, 1 is the highest precedence and 19 is the lowest precedence.
javascript-basics
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to Add Multiple Columns in PySpark Dataframes ? - GeeksforGeeks

30 Jun, 2021
In this article, we will see different ways of adding Multiple Columns in PySpark Dataframes. 
Let’s create a sample dataframe for demonstration:
Dataset Used: Cricket_data_set_odi
Python3
# import pandas to read json fileimport pandas as pd  # importing moduleimport pyspark  # importing sparksession from pyspark.sql# modulefrom pyspark.sql import SparkSession  # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate()    # create Dataframedf=spark.read.option(    "header",True).csv("Cricket_data_set_odi.csv")  # Display Schemadf.printSchema()  # Show Dataframedf.show()
Output:
withColumn() is used to add a new or update an existing column on DataFrame
Syntax: df.withColumn(colName, col)
Returns: A new :class:`DataFrame` by adding a column or replacing the existing column that has the same name. 
Code:
Python3
df.withColumn(    'Avg_runs', df.Runs / df.Matches).withColumn(    'wkt+10', df.Wickets+10).show()
Output:
You can also add multiple columns using select.
Syntax: df.select(*cols)
Code:
Python3
# Using select() to Add Multiple Columndf.select('*', (df.Runs / df.Matches).alias('Avg_runs'),          (df.Wickets+10).alias('wkt+10')).show()
Output :
Let’s create a new column with constant value using lit() SQL function, on the below code. The lit() function present in Pyspark is used to add a new column in a Pyspark Dataframe by assigning a constant or literal value.
Python3
from pyspark.sql.functions import col, lit    df.select('*',lit("Cricket").alias("Sport")).withColumn("Fitness",lit(("Good"))).show()
Output:
Picked
Python-Pyspark
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?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
How to resize a tensor in PyTorch?

To resize a PyTorch tensor, we use the .view() method. We can increase or decrease the dimension of the tensor, but we have to make sure that the total number of elements in a tensor must match before and after the resize.
Import the required library. In all the following Python examples, the required Python library is torch. Make sure you have already
installed it.
Import the required library. In all the following Python examples, the required Python library is torch. Make sure you have already
installed it.
Create a PyTorch tensor and print it.
Create a PyTorch tensor and print it.
Resize the above-created tensor using .view() and assign the value to a variable. .view() does not resize the original tensor; it only gives a view with the new size, as its name suggests.
Resize the above-created tensor using .view() and assign the value to a variable. .view() does not resize the original tensor; it only gives a view with the new size, as its name suggests.
Finally, print the tensor after the resize.
Finally, print the tensor after the resize.
# Python program to resize a tensor in PyTorch
# Import the library
import torch

# Create a tensor
T = torch.Tensor([1, 2, 3, 4, 5, 6])
print(T)

# Resize T to 2x3
x = T.view(2,3)
print("Tensor after resize:\n",x)

# Other way to resize T to 2x3
x = T.view(-1,3)
print("Tensor after resize:\n",x)

# Other way resize T to 2x3
x = T.view(2,-1)
print("Tensor after resize:\n",x)
When you run the above Python 3 code, it will produce the following output
tensor([1., 2., 3., 4., 5., 6.])
Tensor after resize:
tensor([[1., 2., 3.],
         [4., 5., 6.]])
Tensor after resize:
tensor([[1., 2., 3.],
         [4., 5., 6.]])
Tensor after resize:
tensor([[1., 2., 3.],
         [4., 5., 6.]])
# Import the library
import torch

# Create a tensor shape 4x3
T = torch.Tensor([[1,2,3],[2,1,3],[2,3,5],[5,6,4]])
print(T)

# Resize T to 3x4
x = T.view(-1,4)
print("Tensor after resize:\n",x)

# Other way to esize T to 3x4
x = T.view(3,-1)
print("Tensor after resize:\n",x)

# Resize T to 2x6
x = T.view(2,-1)
print("Tensor after resize:\n",x)
When you run the above Python 3 code, it will produce the following output
tensor([[1., 2., 3.],
         [2., 1., 3.],
         [2., 3., 5.],
         [5., 6., 4.]])
Tensor after resize:
tensor([[1., 2., 3., 2.],
         [1., 3., 2., 3.],
         [5., 5., 6., 4.]])
Tensor after resize:
tensor([[1., 2., 3., 2.],
         [1., 3., 2., 3.],
         [5., 5., 6., 4.]])
Tensor after resize:
tensor([[1., 2., 3., 2., 1., 3.],
         [2., 3., 5., 5., 6., 4.]])
Transparency for Poly3DCollection plot in Matplotlib

To plot a transparent Poly3DCollection plot in Matplotlib, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots
Create a new figure or activate an existing figure.
Add an '~.axes.Axes' to the figure as part of a subplot arrangement with projection=3d.
Create x, y and z data points.
Make a list of vertices.
Convert x, y and z data points into a zipped list of tuples.
Get a list of instance of Poly3d.
Add a 3D collection object to the plot using add_collection3d() method.
Turn off the axes.
To display the figure, use show() method.
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d.art3d import Poly3DCollection, Line3DCollection

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

fig = plt.figure()

ax = fig.add_subplot(111, projection='3d')

x = [0, 2, 1, 1]
y = [0, 0, 1, 0]
z = [0, 0, 0, 1]

vertices = [[0, 1, 2], [0, 1, 3], [0, 2, 3], [1, 2, 3]]
tupleList = list(zip(x, y, z))
poly3d = [[tupleList[vertices[ix][iy]]
   for iy in range(len(vertices[0]))]
   for ix in range(len(vertices))]

ax.scatter(x, y, z)
ax.add_collection3d(Poly3DCollection(poly3d, facecolors='w', linewidths=1, alpha=0.5))
ax.add_collection3d(Line3DCollection(poly3d, colors='k', linewidths=2, linestyles='--'))

plt.axis('off')

plt.show()
How can I see the CREATE TABLE statement of an existing MySQL table?

We can see the create table statement of an existing table by using SHOW CREATE TABLE query.
SHOW CREATE TABLE table_name;
mysql> Show create table employee\G
*************************** 1. row ***************************
Table: employee
Create Table: CREATE TABLE `employee` (
   `Id` int(11) DEFAULT NULL,
   `Name` varchar(20) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1
1 row in set (0.00 sec)
The query above gives the CREATE TABLE statement of ‘Employee’ table.
CSS - Fade In Up Effect

The image come or cause to come gradually into or out of view, or to merge into another shot.
@keyframes fadeIn {
   0% {opacity: 0;}
   100% {opacity: 1;} 
} 
Transform − Transform applies to 2d and 3d transformation to an element.
Transform − Transform applies to 2d and 3d transformation to an element.
<html>
   <head>
      <style>
         .animated {
            background-image: url(/css/images/logo.png);
            background-repeat: no-repeat;
            background-position: left top;
            padding-top:95px;
            margin-bottom:60px;
            -webkit-animation-duration: 10s;
            animation-duration: 10s;
            -webkit-animation-fill-mode: both;
            animation-fill-mode: both;
         }
         
         @-webkit-keyframes fadeIn {
            0% {opacity: 0;}
            100% {opacity: 1;}
         }
         
         @keyframes fadeIn {
            0% {opacity: 0;}
            100% {opacity: 1;}
         }
         
         .fadeIn {
            -webkit-animation-name: fadeIn;
            animation-name: fadeIn;
         }
      </style>
   </head>

   <body>
   
      <div id = "animated-example" class = "animated fadeIn"></div>
      <button onclick = "myFunction()">Reload page</button>
        
      <script>
         function myFunction() {
            location.reload();
         }
      </script>
      
   </body>
</html>
It will produce the following result −


 Academic Tutorials
 Big Data & Analytics 
 Computer Programming 
 Computer Science 
 Databases 
 DevOps 
 Digital Marketing 
 Engineering Tutorials 
 Exams Syllabus 
 Famous Monuments 
 GATE Exams Tutorials
 Latest Technologies 
 Machine Learning 
 Mainframe Development 
 Management Tutorials 
 Mathematics Tutorials
 Microsoft Technologies 
 Misc tutorials 
 Mobile Development 
 Java Technologies 
 Python Technologies 
 SAP Tutorials 
Programming Scripts 
 Selected Reading 
 Software Quality 
 Soft Skills 
 Telecom Tutorials 
 UPSC IAS Exams 
 Web Development 
 Sports Tutorials 
 XML Technologies 
 Multi-Language
 Interview Questions


 Academic Tutorials
 Big Data & Analytics 
 Computer Programming 
 Computer Science 
 Databases 
 DevOps 
 Digital Marketing 
 Engineering Tutorials 
 Exams Syllabus 
 Famous Monuments 
 GATE Exams Tutorials
 Latest Technologies 
 Machine Learning 
 Mainframe Development 
 Management Tutorials 
 Mathematics Tutorials
 Microsoft Technologies 
 Misc tutorials 
 Mobile Development 
 Java Technologies 
 Python Technologies 
 SAP Tutorials 
Programming Scripts 
 Selected Reading 
 Software Quality 
 Soft Skills 
 Telecom Tutorials 
 UPSC IAS Exams 
 Web Development 
 Sports Tutorials 
 XML Technologies 
 Multi-Language
 Interview Questions
Selected Reading
UPSC IAS Exams Notes
Developer's Best Practices
Questions and Answers
Effective Resume Writing
HR Interview Questions
Computer Glossary
Who is Who
 Print
 Add Notes
 Bookmark this page
C program to print characters and strings in different formats.

An algorithm is given below to explain the process which is included in the C programming language to print the characters and strings in different formats.
Step 1: Read a character to print.
Step 2: Read a name at compile time.
Step 3: Output of characters in different formats by using format specifiers.
printf("%c\n%3c\n%5c\n", x,x,x);
printf("%3c\n%c\n", x,x);
printf("\n");
Step 4: Output of strings in different formats by using format specifiers.
printf("%s\n", name);
printf("%20s\n", name);
printf("%20.10s\n", name);
printf("%.5s\n", name);
printf("%-20.10s\n", name);
printf("%5s\n", name);
Following is the C program to print the characters and strings in different formats −
 Live Demo
#include<stdio.h>
main(){
   char x = 'T';
   static char name[20] = "Tutorials Point";
   printf("OUTPUT OF CHARACTERS\n\n");
   printf("%c\n%3c\n%5c\n", x,x,x);
   printf("%3c\n%c\n", x,x);
   printf("\n");
   printf("OUTPUT OF STRINGS\n\n");
   printf("%s\n", name);
   printf("%20s\n", name);
   printf("%20.10s\n", name);
   printf("%.5s\n", name);
   printf("%-20.10s\n", name);
   printf("%5s\n", name);
}
When the above program is executed, it produces the following output −
OUTPUT OF CHARACTERS
T
  T
   T
  T
T
OUTPUT OF STRINGS
Tutorials Point
Tutorials Point
Tutorials
Tutor
Tutorials
Tutorials Point
Consider another program to check different format −
 Live Demo
#include<stdio.h>
main() {
   char x = 'T';
   static char name[20] = "Tutorials Point";
   printf("OUTPUT OF CHARACTERS\n\n");
   printf("%c\n", x);
   printf("%c\n%3c\n%5c\n", x,x,x);
   printf("%3c\n%c\n", x,x);
   printf("%c\n%3c\n%5c\n", x,x,x);
   printf("%3c\n%c\n", x,x);
   printf("\n");
   printf("OUTPUT OF STRINGS\n\n");
   printf("%.5s\n", name);
   printf("%-10.10s\n", name);
   printf("%.20s\n", name);
   printf("%20.10s\n", name);
   printf("%20s\n", name);
   printf("%10s\n", name);
}
When the above program is executed, it produces the following output −
OUTPUT OF CHARACTERS
T
T
  T
    T
  T
T
T
   T
     T
   T
T
OUTPUT OF STRINGS
Tutor
Tutorials
Tutorials Point
Tutorials
Tutorials Point
Tutorials Point
Date.toLocaleDateString() function in JavaScript

The Date object is a data type built into the JavaScript language. Date objects are created with the new Date( ) as shown below.
Once a Date object is created, a number of methods allow you to operate on it. Most methods simply allow you to get and set the year, month, day, hour, minute, second, and millisecond fields of the object, using either local time or UTC (universal, or GMT) time.
The toLocaleDateString() function of the date object returns the date portion of the current date
Its Syntax is as follows
dateObj.toLocaleDateString()
 Live Demo
<html>
<head>
   <title>JavaScript Example</title>
</head>
<body>
   <script type="text/javascript">
      var dateObj = new Date('September 26, 89 12:4:25:96');
      document.write("Current Date: "+dateObj.toLocaleDateString());
   </script>
</body>
</html>
Current Date: 9/26/1989
If you do not pass parameters to the Date constructor the toLocaleDateString() function returns the date string of the local time of the current system.
 Live Demo
<html>
<head>
   <title>JavaScript Example</title>
</head>
<body>
   <script type="text/javascript">
      var dateObj = new Date();
      document.write("Current Date: "+dateObj.toLocaleDateString());
   </script>
</body>
</html>
Current Date: 18/10/2018
SQLite - Injection

If you take user input through a webpage and insert it into a SQLite database there's a chance that you have left yourself wide open for a security issue known as SQL Injection. In this chapter, you will learn how to help prevent this from happening and help you secure your scripts and SQLite statements.
Injection usually occurs when you ask a user for input, like their name, and instead of a name they give you a SQLite statement that you will unknowingly run on your database.
Never trust user provided data, process this data only after validation; as a rule, this is done by pattern matching. In the following example, the username is restricted to alphanumerical chars plus underscore and to a length between 8 and 20 chars - modify these rules as needed.
if (preg_match("/^\w{8,20}$/", $_GET['username'], $matches)){
   $db = new SQLiteDatabase('filename');
   $result = @$db->query("SELECT * FROM users WHERE username = $matches[0]");
} else {
   echo "username not accepted";
}

To demonstrate the problem, consider this excerpt −
$name = "Qadir'; DELETE FROM users;";
@$db->query("SELECT * FROM users WHERE username = '{$name}'");

The function call is supposed to retrieve a record from the users table where the name column matches the name specified by the user. Under normal circumstances, $name would only contain alphanumeric characters and perhaps spaces, such as the string ilia. However in this case, by appending an entirely new query to $name, the call to the database turns into a disaster: the injected DELETE query removes all records from users.
There are databases interfaces which do not permit query stacking or executing multiple queries in a single function call. If you try to stack queries, the call fails but SQLite and PostgreSQL, happily perform stacked queries, executing all of the queries provided in one string and creating a serious security problem.
You can handle all escape characters smartly in scripting languages like PERL and PHP. Programming language PHP provides the function string sqlite_escape_string() to escape input characters that are special to SQLite.
if (get_magic_quotes_gpc()) {
   $name = sqlite_escape_string($name);
}
$result = @$db->query("SELECT * FROM users WHERE username = '{$name}'");
Although the encoding makes it safe to insert the data, it will render simple text comparisons and LIKE clauses in your queries unusable for the columns that contain the binary data.
Note − addslashes() should NOT be used to quote your strings for SQLite queries; it will lead to strange results when retrieving your data.

    25 Lectures 
     4.5 hours 

 Sandip Bhattacharya

    17 Lectures 
     1 hours 

 Laurence Svekis

    5 Lectures 
     51 mins

 Vinay Kumar
 Print
 Add Notes
 Bookmark this page
How to override derived properties in JavaScript?

Following is the code to override derived properties in JavaScript −
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result,
   .sample {
      font-size: 18px;
      font-weight: 500;
      color: rebeccapurple;
   }
   .result {
      color: red;
   }
</style>
</head>
<body>
<h1>Override derived properties</h1>
<div class="sample">Before overriding <br /></div>
<br />
<div class="result">After overriding <br /></div>
<br />
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to override the above properties</h3>
<script>
   let sampleEle = document.querySelector(".sample");
   let resEle = document.querySelector(".result");
   let BtnEle = document.querySelector(".Btn");
   let objPerson = {name: "Rahul",age: 12,class: 7,};
   let Person1 = Object.create(objPerson);
   sampleEle.innerHTML += "Person1.name = " + Person1.name + "<br>";
   sampleEle.innerHTML += "Person1.age = " + Person1.age + "<br>";
   sampleEle.innerHTML += "Person1.class = " + Person1.class + "<br>";
   BtnEle.addEventListener("click", () => {
      Person1.name = "Shawn";
      Person1.age = 18;
      Person1.class = 12;
      resEle.innerHTML += "Person1.name = " + Person1.name + "<br>";
      resEle.innerHTML += "Person1.age = " + Person1.age + "<br>";
      resEle.innerHTML += "Person1.class = " + Person1.class + "<br>";
   });
</script>
</body>
</html>
On clicking the ‘CLICK HERE’ button −
Can we store objects in an array in Java?

Array is a container which can hold a fix number of items and these items should be of the same type. Most of the data structures make use of arrays to implement their algorithms. Following are the important terms to understand the concept of Array.
Element: Each item stored in an array is called an element.
Index: Each location of an element in an array has a numerical index, which is used to identify the element.
Yes, since objects are also considered as datatypes (reference) in Java, you can create an array of the type of a particular class and, populate it with instances of that class.
Following Java example have a class named Std and later in the program we are creating an array of type Std, populating it, and invoking a method on all the elements of the array.
class Std {
   private static int year = 2018;
   private String name;
   private int age;
   public Std(String name, int age){
      this.name = name;
      this.age = age;
   }
   public void setName(String name) {
      this.name = name;
   }
   public void setAge(int age) {
      this.age = age;
   }
   public void display(){
      System.out.println("Name: "+this.name);
      System.out.println("Age: "+this.age);
      System.out.println("Year: "+Std.year);
   }
}
public class Sample {
   public static void main(String args[]) throws Exception {
      //Creating an array to store objects of type Std
      Std st[] = new Std[4];
      //Populating the array
      st[0] = new Std("Bala", 18);
      st[1] = new Std("Rama", 17);
      st[2] = new Std("Raju", 15);
      st[3] = new Std("Raghav", 20);
      //Invoking display method on each object in the array
      for(int i = 0; i<st.length; i++) {
         st[i].display();
         System.out.println(" ");
      }
   }
}
Name: Bala
Age: 18
Year: 2018

Name: Rama
Age: 17
Year: 2018

Name: Raju
Age: 15
Year: 2018

Name: Raghav
Age: 20
Year: 2018
Sum of squares of first n natural numbers in C Program?

The sum of squares of the first n natural numbers is found by adding up all the squares.
Input - 5Output - 55Explanation - 12 + 22 + 32 + 42 + 52
There are two methods to find the Sum of squares of first n natural numbers −
Using Loops − the code loops through the digits until n and find their square, then add this to a sum variable that outputs the sum.
#include <iostream>
using namespace std;
int main() {
   int n = 5;
   int sum = 0;
   for (int i = 1; i >= n; i++)
      sum += (i * i);
   cout <<"The sum of squares of first "<<n<<" natural numbers is "<<sum;
   return 0;
}
The sum of squares of first 5 natural numbers is 55
Using Formula − To decrease the load on the program you can use mathematical formula to find the sum of squares on first n natural numbers. The mathematical formula is : n(n+1)(2n+1)/6
#include <stdio.h>
int main() {
   int n = 10;
   int sum = (n * (n + 1) * (2 * n + 1)) / 6;
   printf("The sum of squares of %d natural numbers is %d",n, sum);
   return 0;
}
The sum of squares of 10 natural numbers is 385
Random name generator function in JavaScript

We are required to write a JavaScript function that takes in a number n and returns a random string of length n containing no other than the 26 English lowercase alphabets
Let us write the code for this function −
const num = 8;
const randomNameGenerator = num => {
   let res = '';
   for(let i = 0; i < num; i++){
      const random = Math.floor(Math.random() * 27);
      res += String.fromCharCode(97 + random);
   };
   return res;
};
console.log(randomNameGenerator(num));
Following is the output in the console −
kdcwping
Note − This is one of many possible outputs. Console output is expected to differ every time/
How to determine whether C++ code has been compiled in 32 or 64 bit?

In C++, there is no direct way to check the environment architecture. There are two Macros for Windows systems, that can be used to check the architecture. These macros are _WIN64, and _WIN32. When the system is 64-bit, then the _WIN64 will be 1, otherwise the _WIN32 will be 1. So using macro checking, we can identify the architecture
#include <iostream>
using namespace std;
int main() {
   #ifdef _WIN64
      cout << "This is 64 bit system" << endl;
   #elif _WIN32
      cout << "This is 32 bit system" << endl;
   #endif
}
This is 64 bit system
Differentiate between categorical and numerical independent variables in R.

For categorical variable, each level is considered as an independent variable and is
recognized by factor function. On the other hand, the numerical independent variable is
either continuous or discrete in nature.
Check out the Example given below for linear regression model summary to understand
the difference between categorical and numerical independent variables.
Following snippet creates a sample data frame −
x<-rpois(20,2)
y<-rpois(20,5)
df<-data.frame(x,y)
df
The following dataframe is created
   x y
1  1 1
2  4 5
3  3 10
4  3 4
5  1 6
6  3 4
7  1 2
8  1 10
9  1 6
10 2 5
11 1 2
12 3 4
13 0 5
14 1 5
15 4 5
16 4 7
17 3 5
18 2 4
19 1 3
20 2 6
To create linear model for data in df and find the model summary on the above created
data frame, add the following code to the above snippet −
x<-rpois(20,2)
y<-rpois(20,5)
df<-data.frame(x,y)
Model_1<-lm(y~x,data=df)
summary(Model_1)
If you execute all the above given snippets as a single program, it generates the following Output −
Call:
lm(formula = y ~ x, data = df)

Residuals:
   Min     1Q  Median    3Q   Max
-3.549 -1.313  -0.503 1.128 5.451
Coefficients:
         Estimate Std. Error t value Pr(|t|)
(Intercept) 4.168      1.013   4.11  0.00065 ***
x           0.382      0.426   0.90  0.38249
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 2.29 on 18 degrees of freedom
Multiple R-squared: 0.0426, Adjusted R-squared: -0.0106
F-statistic: 0.801 on 1 and 18 DF, p-value: 0.382
To create linear model for data in df with as a factor variable and find the model
summary on the above created data frame, add the following code to the above snippet −
x<-rpois(20,2)
y<-rpois(20,5)
df<-data.frame(x,y)
Model_1<-lm(y~x,data=df)
Model_2<-lm(y~factor(x),data=df)
summary(Model_2)
If you execute all the above given snippets as a single program, it generates the following Output −
Call:
lm(formula = y ~ factor(x), data = df)

Residuals:
   Min     1Q  Median    3Q   Max
-3.375 -1.400  -0.533 1.083 5.625

Coefficients:
           Estimate Std.   Error t value   Pr(|t|)
(Intercept) 5.00e+00     2.50e+00  2.00    0.064 .
factor(x)1 -6.25e-01     2.65e+00 -0.24    0.817
factor(x)2 -3.92e-15     2.89e+00  0.00    1.000
factor(x)3  4.00e-01     2.74e+00  0.15    0.886
factor(x)4  6.67e-01     2.89e+00  0.23    0.820
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 2.5 on 15 degrees of freedom
Multiple R-squared: 0.0526, Adjusted R-squared: -0.2
F-statistic: 0.208 on 4 and 15 DF, p-value: 0.93
PyQt5 QCalendarWidget - Setting Selected Date - GeeksforGeeks

04 Jul, 2021
In this article we will see how we can set the selected date of QCalendarWidget, selected date is the date that is currently highlighted user can change the selected date using the mouse and cursor by default selected date is the real-time date although we can set the selected date any time.Note: The selected date must be within the date range specified by the minimumDate and maximumDate properties. 
In order to do this we will use setSelectedDate method with the QCalendarWidget object.Syntax : calendar.setSelectedDate(date)Argument : It takes QDate object as argumentReturn : It returns None  
Below is the implementation  
Python3
# importing librariesfrom PyQt5.QtWidgets import *from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import *from PyQt5.QtCore import *import sys  class Window(QMainWindow):     def __init__(self):        super().__init__()         # setting title        self.setWindowTitle("Python ")         # setting geometry        self.setGeometry(100, 100, 600, 400)         # calling method        self.UiComponents()         # showing all the widgets        self.show()     # method for components    def UiComponents(self):         # creating a QCalendarWidget object        calendar = QCalendarWidget(self)         # setting geometry to the calendar        calendar.setGeometry(10, 10, 400, 250)         # date        date = QDate(2021, 1, 1)         # setting selected date        calendar.setSelectedDate(date)  # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :  
 
clintra
Python PyQt-QCalendarWidget
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Reading and Writing to text files in Python
C++ Program to find size of int, float, double and char in Your System

There are many data types in C++ but the most frequently used are int, float, double and char. Some details about these data types are as follows −
int - This is used for integer data types which normally require 4 bytes of memory space.
int - This is used for integer data types which normally require 4 bytes of memory space.
float - This is used for storing single precision floating point values or decimal values. float variables normally require 4 bytes of memory space.
float - This is used for storing single precision floating point values or decimal values. float variables normally require 4 bytes of memory space.
double - This is used for storing double precision floating point values or decimal values. Double variables normally require 8 bytes of memory space.
double - This is used for storing double precision floating point values or decimal values. Double variables normally require 8 bytes of memory space.
char - This is used for storing characters. Characters normally require 1 byte of memory space.
char - This is used for storing characters. Characters normally require 1 byte of memory space.
The sizeof operator is used to find the size of the data types. It is a compile time operator that determines the size of different variables and data types in bytes. The syntax of the sizeof operator is as follows −
sizeof (data type);
A program that finds the size of int, float, double and char is as follows −
 Live Demo
#include <iostream>
using namespace std;
int main() {
   cout<<"Size of int is "<<sizeof(int)<<" bytes"<<endl;
   cout<<"Size of float is "<<sizeof(float)<<" bytes"<<endl;
   cout<<"Size of double is "<<sizeof(double)<<" bytes"<<endl;
   cout<<"Size of char is "<<sizeof(char)<<" byte"<<endl;
   return 0;
}
Size of int is 4 bytes
Size of float is 4 bytes
Size of double is 8 bytes
Size of char is 1 byte
In the above program, the sizeof operator is used to find the size of int, float, double and char. This is displayed using the cout object.
cout<<"Size of int is "<<sizeof(int)<<" bytes"<<endl;
cout<<"Size of float is "<<sizeof(float)<<" bytes"<<endl;
cout<<"Size of double is "<<sizeof(double)<<" bytes"<<endl;
cout<<"Size of char is "<<sizeof(char)<<" byte"<<endl;