code-rag-bench/online-tutorials huggingface dataset:
What are label statements in JavaScript?

JavaScript label statements are used to prefix a label to an identifier. A label can be used with break and continue statement to control the flow more precisely. A label is simply an identifier followed by a colon (:) that is applied to a statement or a block of code. We will see two different examples to understand how to use labels with break and continue.
You can try to run the following code to use labels to control the flow, with break statement
Live Demo
<html>
   <body>
      <script>
         document.write("Entering the loop!<br /> ");

         outerloop: // This is the label name
            for (var i = 0; i < 5; i++) {
               document.write("Outerloop: " + i + "<br />");

               innerloop:
                  for (var j = 0; j < 5; j++) {
                     if (j > 3 ) break ; // Quit the innermost loop
                     if (i == 2) break innerloop; // Do the same thing
                     if (i == 4) break outerloop; // Quit the outer loop
                     document.write("Innerloop: " + j + " <br />");
                  }
            }
            document.write("Exiting the loop!<br /> ");
      </script>
   </body>
</html>
You can try to run the following code to use labels to control the flow, with continue statement
Live Demo
<html>
   <body>
      <script>
         document.write("Entering the loop!<br /> ");
 
         outerloop: // This is the label name
         for (var i = 0; i < 3; i++) {
            document.write("Outerloop: " + i + "<br />");
            for (var j = 0; j < 5; j++) {
               if (j == 3) {
                  continue outerloop;
               }
               document.write("Innerloop: " + j + "<br />");
            }
         }
         document.write("Exiting the loop!<br /> ");
      </script>
   </body>
</html>
Standard header files in C

In C language, header files contain the set of predefined standard library functions. The “#include” preprocessing directive is used to include the header files with “.h” extension in the program.
Here is the table that displays some of the header files in C language,
Here is an example of header files in C language,
 Live Demo
#include <stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>

int main() {
   char s1[20] = "53875";
   char s2[10] = "Hello";
   char s3[10] = "World";
   int res;

   res = pow(8, 4);
   printf("Using math.h, The value is : %d\n", res);

   long int a = atol(s1);
   printf("Using stdlib.h, the string to long int : %d\n", a);
   
   strcpy(s2, s3);
   printf("Using string.h, the strings s2 and s3 : %s\t%s\n", s2, s3 );

   return 0;
}
Here is the output −
Using math.h, The value is : 4096
Using stdlib.h, the string to long int : 53875
Using string.h, the strings s2 and s3 : World World
Turing Machine for L = {a^n b^n | n>=1} - GeeksforGeeks

11 Nov, 2020
Prerequisite – Turing Machine
Task :
We have to design a Turing machine for anbn where n>=1.
Analysis :
We can analyze that we have equal no of a’s and b’s and in some order i.e., first all a’s will come and then all b’s will come.
Example :
Input-1:aabb
Output-1:YES

Input-2:aabbbb
Output-2:NO

Input-3:abab
Output-3:NO

Approach :
Let us understand the approach by taking the example “aabb”.
Scan the input from the left.
First, replace an ‘a’ with ‘X’ and move right. Then skip all the a’s and b’s and move right.
When the pointer reaches Blank(B) Blank will remain Blank(B) and the pointer turns left. Now it scans the input from the right and replaces the first ‘b’ with ‘Y’. Our Turing machine looks like this –
Again the pointer reaches Blank(B) or X. It now scans the input from left to right. The pointer moves forward and replaces ‘a’ with ‘X’.
Again the pointer reaches Blank(B) or Y. It now scans the input from the right to left. The pointer moves forward and replaces ‘b’ with ‘y’.
We repeat the same steps until we convert all the a’s to ‘X’ and b’s to ‘Y’.
When all the a’s converted to ‘X and all the b’s converted to ‘Y’ our machine will halt.
Technical Scripter 2020
Technical Scripter
Theory of Computation & Automata
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Turing Machine in TOC
Introduction of Pushdown Automata
Difference between DFA and NFA
Introduction of Finite Automata
Construct Pushdown Automata for given languages
Regular Expressions, Regular Grammar and Regular Languages
Pumping Lemma in Theory of Computation
Chomsky Hierarchy in Theory of Computation
Recursive and Recursive Enumerable Languages in TOC
Difference between Mealy machine and Moore machine
Vector isEmpty() Method in Java - GeeksforGeeks

14 Aug, 2018
The Java.util.Vector.isEmpty() method in Java is used to check and verify if a Vector is empty or not. It returns True if the Vector is empty else it returns False.
Syntax:
Vector.isEmpty()
Parameters: This method does not take any parameter.
Return Value: This function returns True if the Vectoris empty else it returns False.
Below programs illustrate the Java.util.Vector.isEmpty() method:
Program 1:
// Java code to illustrate isEmpty()import java.util.*;  public class VectorDemo {    public static void main(String args[])    {        // Creating an empty Vector        Vector<String> vec_tor = new Vector<String>();          // Use add() method to add elements into the Vector        vec_tor.add("Welcome");        vec_tor.add("To");        vec_tor.add("Geeks");        vec_tor.add("4");        vec_tor.add("Geeks");          // Displaying the Vector        System.out.println("Vector:  " + vec_tor);          // Verifying if the Vector is empty or not        System.out.println("Is the Vector empty? "                           + vec_tor.isEmpty());          // Clearing the Vector        vec_tor.clear();          // Displaying the Vector        System.out.println("Vector after clear(): "                           + vec_tor);          // Verifying if the Vector is empty or not        System.out.println("Is the Vector empty? "                           + vec_tor.isEmpty());    }}
Vector:  [Welcome, To, Geeks, 4, Geeks]
Is the Vector empty? false
Vector after clear(): []
Is the Vector empty? true

Program 2:
// Java code to illustrate isEmpty()import java.util.*;  public class VectorDemo {    public static void main(String args[])    {        // Creating an empty Vector        Vector<Integer> vec_tor = new Vector<Integer>();          // Displaying the Vector        System.out.println("Vector:  " + vec_tor);          // Verifying if the Vector is empty or not        System.out.println("Is the Vector empty? "                           + vec_tor.isEmpty());    }}
Vector:  []
Is the Vector empty? true

Java - util package
Java-Collections
Java-Functions
Java-Vector
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Object Oriented Programming (OOPs) Concept in Java
Arrays.sort() in Java with examples
HashMap in Java with Examples
Reverse a string in Java
Stream In Java
Interfaces in Java
How to iterate any Map in Java
Java Program to Demonstrate How User Authentication is Done - GeeksforGeeks

04 Nov, 2020
Authentication is the process of verifying the identity of users or information. User authentication is the process of verifying the identity of the user when that user logs in to a computer system. The main objective of authentication is to allow authorized users to access the computer and to deny access to unauthorized users.
Example
Default Assumption: User name = Geeks For Geeks , Password = Geeks For Geeks

Input: User name = Geeks For Geeks, Password = Geeks For Geeks
Output: Authentication Successful

Input: User name = Geeks For Geeks, Password = Hello world
Output: User name/ Password not matching

Approach
Take username and password as string input from the user.Check if the username matches the password or not.If it matches then welcome the user.Else display an appropriate message.
Take username and password as string input from the user.
Check if the username matches the password or not.
If it matches then welcome the user.
Else display an appropriate message.
Below is the implementation of the above approach
Java
// Java program to check the authentication of the user  // Importing the modulesimport java.util.*;  // Gfg Classpublic class Gfg {    // Main CLass    public static void main(String args[])    {        // Declaring the username and password        String user_name = "Geeks For Geeks";        String password = "Geeks For Geeks";                  // Checking the validity of the input        if(user_name.equals("Geeks For Geeks") && password.equals("Geeks For Geeks"))        {            // Printing Output            System.out.println("Authentication Successful");        }        else        {            // Printing Output            System.out.println("User name/ Password not matching");        }    }}
Authentication Successful


 
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
Program to print ASCII Value of a character
Why does sizeof(x++) not increment x in C? - GeeksforGeeks

10 Oct, 2018
According to C99 Standards, the sizeof() operator only takes into account the type of the operand, which may be an expression or the name of a type (i.e int, double, float etc) and not the value obtained on evaluating the expression. Hence, the operand inside the sizeof() operator is not evaluated. It is evaluated only if the type of the operand is variable length array because in that case, the size can be determined only after the expression is evaluated.
When the sizeof() method is passed a fixed size structure:
In this case, the sizeof() operator does not evaluate the parameter. Only the type of the parameter is checked and its size is returned.
Below figure shows the workflow of sizeof() operator in this scenario:
Example 1:
The output value of x after increment is still 3 as compared to the expected value which is 4. This is because sizeof operator doesn’t need to evaluate the expression to obtain the size as the data type of the operand doesn’t change and hence the size remains the same.
#include <stdio.h>  int main(){    int x = 3;    printf("%d\n", sizeof(x++));    printf("x = %d", x);      return 0;}
Output:
4
x = 3

When the sizeof() method is passed a variable size structure:
In this case, the sizeof() operator evaluates the parameter to see if there is any change of size. If found, then first the size is modified then the final size is returned.
Below example illustrate the sizeof() operator in this scenario:
Example 2:
In this example, the sizeof operator needs to evaluate the expression in order to calculate the size of the array which is shown in the figure. Hence, in this case, we get the value of x after incrementation.
#include <stdio.h>  int main(){    int x = 3;    printf("%d\n", sizeof(int[x++]));    printf("x = %d", x);      return 0;}
Output:
12
x = 4

Example 3:
Again in this example, the sizeof operator needs to evaluate the expression in order to calculate the size of the array which is shown in the figure. In this example, the post-increment operator is used and hence the output in the first line is 16. In the second line, the value of x is printed after incrementation.
#include <stdio.h>  int main(){    int x = 3;    printf("%d\n", sizeof(int[++x]));    printf("x = %d", x);      return 0;}
Output:
16
x = 4

rituraj_jain
cpp-sizeof
Picked
Technical Scripter 2018
C Language
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
Exception Handling in C++
Multithreading in C
'this' pointer in C++
Arrow operator -> in C/C++ with Examples
Ways to copy a vector in C++
Smart Pointers in C++ and How to Use Them
Multiple Inheritance in C++
Understanding "extern" keyword in C
How to split a string in C/C++, Python and Java?
Nullity of a Matrix - GeeksforGeeks

03 Jun, 2019
Prerequisite – Mathematics | System of Linear EquationsLet A be a matrix. Since, number of non-zero rows in the row reduced form of a matrix A is called the rank of A, denoted as rank(A) and Nullity is the complement to the rank of a matrix .Please go through the Prerequisite first and read the rank topic, then come to this topic.
Therefore, Nullity of a matrix is calculated from rank of the matrix using the following steps:Let A[m*n] matrix, then:
Calculate rank (r) of the Matrix.Use The Rank Plus Nullity Theorem, it saysNullity + rank = number of columns (n)Therefore, you will be able to calculate nullity asNullity = no. of columns(n) - rank(r) 
Calculate rank (r) of the Matrix.
Use The Rank Plus Nullity Theorem, it saysNullity + rank = number of columns (n)Therefore, you will be able to calculate nullity asNullity = no. of columns(n) - rank(r) 
Nullity + rank = number of columns (n)
Therefore, you will be able to calculate nullity as
Nullity = no. of columns(n) - rank(r) 
Consider the examples:
Example-1:
Input: mat[][] = {{10,   20,   10},
                 {20,   40,   20},
                 {30,   50,   0}}

Output: Rank is 2 and hence Nullity is 1 
Explanation: Ist and IInd rows are linearly dependent. But Ist and 3rd or IInd and IIIrd are independent, so Rank is 2 and hence Nullity is (3-2) = 1.
Example-2:
Input: mat[][] = {{1,   2,   1},
                 {2,   3,   1},
                 {1,   1,   2}}

Output: Rank is 3 and hence Nullity is 0 
Explanation: Ist and IInd and IIIrd rows are linearly dependent, so Rank is 3 and hence Nullity is (3-3) = 0.
Engineering Mathematics Questions
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Best Time to Buy and Sell Stock
Must Do Coding Questions for Product Based Companies
How to calculate MOVING AVERAGE in a Pandas DataFrame?
What is Transmission Control Protocol (TCP)?
How to Convert Categorical Variable to Numeric in Pandas?
Layers of OSI Model
ACID Properties in DBMS
TCP/IP Model
Types of Operating Systems
Normal Forms in DBMS
How to set font size of Matplotlib axis Legend? - GeeksforGeeks

05 Nov, 2021
Prerequisite: Matplotlib
In this article, we will see how to set the font size of matplotlib axis legend using Python. For this, we will use rcParams() methods to increase/decrease the font size. To use this we have to override the matplotlib.rcParams[‘legend.fontsize’] method.
Syntax: matplotlib.rcParams[‘legend.fontsize’] = font_size_value
Python3
# import required modulesimport numpyfrom matplotlib import pyplotimport matplotlib  # assign value to x axisx_axis = numpy.arange(1, 20, 0.5)  # get the value of log10y_axis_log10 = numpy.exp(x_axis)  # plot the graphpyplot.plot(x_axis, y_axis_log10, c="blue",            label="exponential")  # title of the graph/plotpyplot.title("Exponential Graph Plot")  # to set the font size of the legendmatplotlib.rcParams['legend.fontsize'] = 15  pyplot.legend(loc='best')  pyplot.show()
Output:
Python3
# import required modulesimport numpyfrom matplotlib import pyplotimport matplotlib  # assign value to x axisx_axis = numpy.arange(1, 20, 0.5)  # get the value of log10y_axis_log10 = numpy.exp(x_axis)  # plot the graphpyplot.plot(x_axis, y_axis_log10, c="blue", label="exponential")  # Title of the graph/ploypyplot.title("Exponential Graph Plot")  # to set the font size of the legendmatplotlib.rcParams['legend.fontsize'] = 25  pyplot.legend(loc='best')  pyplot.show()
Output:
Picked
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
Applying Gaussian Blur to an image using the Pillow library

In this program, we will blur an image using a Gaussian filter. The ImageFilter class in the pillow library contains a function called GaussianBlur() which helps to apply the gaussian blur filter. It takes only one parameter that is blur radius.
Step 1: Import Image and ImageFilter from Pillow.
Step 2: Open the image.
Step 3: Call the gaussianblur() method and specify the radius
Step 4: Display the output.
from PIL import Image, ImageFilter

im = Image.open('image_test.jpg')
im1 = im.filter(ImageFilter.GaussianBlur(radius = 9))
im1.show()
How to reconfigure Tkinter canvas items?

Using the Canvas widget, we can create text, images, graphics, and visual content to add to the Canvas widget. If you need to configure the Canvas item dynamically, then tkinter provides itemconfig(**options) method. You can use this method to configure the properties and attributes of the Canvas items. For example, if we create a line inside the Canvas widget, we can configure its color or width using itemconfig() method.
# Import the required libraries
from tkinter import *

# Create an instance of tkinter frame or window
win = Tk()

# Set the size of the tkinter window
win.geometry("700x350")

# Define a function to delete the shape
def on_click():
   canvas.itemconfig(line, fill="green")

# Create a canvas widget
canvas = Canvas(win, width=500, height=300)
canvas.pack()

# Add a line in canvas widget
line = canvas.create_line(100, 200, 200, 35, fill="yellow", width=5)

# Create a button to delete the button
Button(win, text="Update the Color", command=on_click).pack()

win.mainloop()
If you run the above code, it will display a window with a button and a line on the canvas.
Now, click the button to change the color of the canvas item.
Python Design Patterns - Prototype

Prototype design pattern helps to hide the complexity of the instances created by the class. The concept of the existing object will differ with that of the new object, which is created from scratch.
The newly copied object may have some changes in the properties if required. This approach saves time and resources that go in for the development of a product.
Let us now see how to implement a prototype pattern.
import copy

class Prototype:

   _type = None
   _value = None

   def clone(self):
      pass

   def getType(self):
      return self._type

   def getValue(self):
      return self._value

class Type1(Prototype):

   def __init__(self, number):
      self._type = "Type1"
      self._value = number

   def clone(self):
      return copy.copy(self)

class Type2(Prototype):

   """ Concrete prototype. """

   def __init__(self, number):
      self._type = "Type2"
      self._value = number

   def clone(self):
      return copy.copy(self)

class ObjectFactory:

   """ Manages prototypes.
   Static factory, that encapsulates prototype
   initialization and then allows instatiation
   of the classes from these prototypes.
   """

   __type1Value1 = None
   __type1Value2 = None
   __type2Value1 = None
   __type2Value2 = None

   @staticmethod
   def initialize():
      ObjectFactory.__type1Value1 = Type1(1)
      ObjectFactory.__type1Value2 = Type1(2)
      ObjectFactory.__type2Value1 = Type2(1)
      ObjectFactory.__type2Value2 = Type2(2)

   @staticmethod
   def getType1Value1():
      return ObjectFactory.__type1Value1.clone()

   @staticmethod
   def getType1Value2():
      return ObjectFactory.__type1Value2.clone()

   @staticmethod
   def getType2Value1():
      return ObjectFactory.__type2Value1.clone()

   @staticmethod
   def getType2Value2():
      return ObjectFactory.__type2Value2.clone()

def main():
   ObjectFactory.initialize()
   
   instance = ObjectFactory.getType1Value1()
   print "%s: %s" % (instance.getType(), instance.getValue())
   
   instance = ObjectFactory.getType1Value2()
   print "%s: %s" % (instance.getType(), instance.getValue())
   
   instance = ObjectFactory.getType2Value1()
   print "%s: %s" % (instance.getType(), instance.getValue())
   
   instance = ObjectFactory.getType2Value2()
   print "%s: %s" % (instance.getType(), instance.getValue())

if __name__ == "__main__":
   main()
The above program will generate the following output −
The output helps in creating new objects with the existing ones and it is clearly visible in the output mentioned above.

    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
Replacing upperCase and LowerCase in a string - JavaScript

We are required to write a JavaScript function that takes in a string and constructs a new string with all the uppercase characters converted to lowercase and all the lowercase characters converted to uppercase.
Let’s write the code for this function −
Following is the code −
const str = 'The Case OF tHis StrinG Will Be FLiPped';
const isUpperCase = char => char.charCodeAt(0) >= 65 && char.charCodeAt(0)
<= 90;
const isLowerCase = char => char.charCodeAt(0) >= 97 &&
char.charCodeAt(0) <= 122;
const flipCase = str => {
   let newStr = '';
   const margin = 32;
   for(let i = 0; i < str.length; i++){
      const curr = str[i];
      if(isLowerCase(curr)){
         newStr += String.fromCharCode(curr.charCodeAt(0) - margin);
      }else if(isUpperCase(curr)){
         newStr += String.fromCharCode(curr.charCodeAt(0) + margin);
      }else{
         newStr += curr;
      };
   };
   return newStr;
};
console.log(flipCase(str));
The output in the console: −
tHE cASE of ThIS sTRINg wILL bE flIpPED
Find Columns Shared By Two Data Frames - GeeksforGeeks

27 May, 2021
Pandas is the open-source Python library used for Data analysis and manipulation. It is fast, powerful, flexible, and easy to use. In this article, we will discuss how to find columns that are common between two Data Frames. Below is the different approach that can be used to find common columns.
Method 1: Using Numpy intersect1d method
In this example, we will create Pandas Dataframe from the list, and then we will use Numpy’s intersect1d() method which will return columns that are common between two Dataframes.
Python3
# Importing librariesimport pandas as pdimport numpy as np # Creating Dataframesa = [{'Name': 'abc', 'Age': 8, 'Grade': 3},{'Name': 'xyz', 'Age': 9, 'Grade': 3}]df1 = pd.DataFrame(a)b = [{'ID': 1,'Name': 'abc', 'Age': 8},{'ID': 2,'Name': 'xyz', 'Age': 9}]df2 = pd.DataFrame(b) # Printing Dataframesdisplay(df1)display(df2) # Finding Common columnsa = np.intersect1d(df2.columns, df1.columns) # Printing common columnsprint ("Common Columns:",a)
Output:
 Method 2: Using Pandas intersection method
In this example, we will create Pandas Dataframe from the list, and then we will use Panda’s intersection() method which will return columns that are common between two Dataframes. 
Python3
# Importing librariesimport pandas as pd # Creating Dataframesa = [{'Name': 'abc', 'Age': 8, 'Grade': 3},     {'Name': 'xyz', 'Age': 9, 'Grade': 3}] df1 = pd.DataFrame(a)b = [{'ID': 1,'Name': 'abc', 'Age': 8},     {'ID': 2,'Name': 'xyz', 'Age': 9}] df2 = pd.DataFrame(b) # Printing Dataframesdisplay(df1)display(df2) # Finding Common columnsa = df2.columns.intersection(df1.columns) # Printing common columnsprint ("Common Columns:",a)
 Output: 
 Method 3: In this example, we will use & operator to find common columns. 
Python3
# Importing librariesimport pandas as pd # Creating Dataframesa = [{'Name': 'abc', 'Age': 8, 'Grade': 3},     {'Name': 'xyz', 'Age': 9, 'Grade': 3}] df1 = pd.DataFrame(a)b = [{'ID': 1,'Name': 'abc', 'Age': 8},     {'ID': 2,'Name': 'xyz', 'Age': 9}] df2 = pd.DataFrame(b) # printing Dataframesdisplay(df1)display(df2) # Finding Common columnsa = df1.columns & df2.columns # Printing common columnsprint ("Common Columns:",a)
Output:
simmytarika5
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Defaultdict in Python
Selecting rows in pandas DataFrame based on conditions
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Python | Pandas dataframe.groupby()
Ccat – Colorize Cat Command Output command in Linux with Examples - GeeksforGeeks

23 Sep, 2021
ccat is a command-line tool for Linux and OSX, which is similar to the cat command in Linux. But the difference between cat and ccat is that the ccat shows the content of the file with the syntax highlighted. Currently, ccat supports the following programming languages.
JavaScript
Java
Ruby
Python
Go
C
JSON
First, we are going to see how to install the ccat on OSX then Linux.
For OSX to install ccat you can install the ccat with the help of the brew command:
$ brew install ccat
To install the ccat on the Linux systems first we need to install all prerequisites required to install ccat. The prerequisites are as follows:
Git
Go 1.4+
Before moving further, make sure that you have installed the required prerequisites. Then use the following command to install the ccat on your Linux system:
$  go install github.com/owenthereal/ccat@latest
Now let’s see how to use the ccat command in Linux.
The syntax ccat is very simple. To display the content of single file syntax is as follows:
$ ccat FILE_NAME
Example:
$ ccat index.html
To display the content of a file from another directory, ccat has the following syntax:
$ ccat PATH_TO_FILE
Example:
$ ccat /var/db/Makefile
To display the content of multiple files, mention the file names after the ccat command:
$ ccat FILE_NAME1 FILE_NAME2
Example:
$ cat index.html main.cpp
To set dark background, use the –bg option with the ccat command:
$ ccat --bg=dark FILENAME
Example:
$ ccat --bg=dark index.html
We can also set the color codes to the syntax of the output of ccat. Here is one example:
To show the color palette of ccat uses the following command:
$ ccat --palette
ccat also provides another best feature is that it can show the output in the HTML form also. To show the output in the HTML format, use the –html at the end pf ccat command
$ ccat FILENAME --html
Example:
$ ccat main.cpp --html
If you open the output in the browser, then you will see the output as follows:
Blogathon-2021
linux-command
Linux-file-commands
Blogathon
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Create a Table With Multiple Foreign Keys in SQL?
How to Connect Python with SQL Database?
How to build a basic CRUD app with Node.js and ReactJS ?
Changing CSS styling with React onClick() Event
Python - Gaussian fit
ZIP command in Linux with examples
TCP Server-Client implementation in C
tar command in Linux with examples
curl command in Linux with Examples
Conditional Statements | Shell Script
How to change status bar color to match app Android?

This example demonstrates how do I change the status bar color to match app Android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity">
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerInParent="true"
      android:layout_marginTop="30dp"
      android:text="Check the Color of the Status Bar"
      android:textAlignment="center"
      android:textSize="24sp"
      android:textStyle="bold" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
public class MainActivity extends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      Window window = MainActivity.this.getWindow();
      window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
      window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
      window.setStatusBarColor(ContextCompat.getColor(MainActivity.this, R.color.colorAccent));
   }
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
Click here to download the project code.
Python PostgreSQL - Create Database

You can create a database in PostgreSQL using the CREATE DATABASE statement. You can execute this statement in PostgreSQL shell prompt by specifying the name of the database to be created after the command.
Following is the syntax of the CREATE DATABASE statement.
CREATE DATABASE dbname;

Following statement creates a database named testdb in PostgreSQL.
postgres=# CREATE DATABASE testdb;
CREATE DATABASE
You can list out the database in PostgreSQL using the \l command. If you verify the list of databases, you can find the newly created database as follows −
postgres=# \l
                                           List of databases
Name       | Owner    | Encoding | Collate                    | Ctype       |
-----------+----------+----------+----------------------------+-------------+
mydb       | postgres | UTF8     | English_United States.1252 | ........... |
postgres   | postgres | UTF8     | English_United States.1252 | ........... |
template0  | postgres | UTF8     | English_United States.1252 | ........... |
template1  | postgres | UTF8     | English_United States.1252 | ........... |
testdb     | postgres | UTF8     | English_United States.1252 | ........... |
(5 rows)

You can also create a database in PostgreSQL from command prompt using the command createdb, a wrapper around the SQL statement CREATE DATABASE.
C:\Program Files\PostgreSQL\11\bin> createdb -h localhost -p 5432 -U postgres sampledb
Password:

The cursor class of psycopg2 provides various methods execute various PostgreSQL commands, fetch records and copy data. You can create a cursor object using the cursor() method of the Connection class.
The execute() method of this class accepts a PostgreSQL query as a parameter and executes it.
Therefore, to create a database in PostgreSQL, execute the CREATE DATABASE query using this method.
Following python example creates a database named mydb in PostgreSQL database.
import psycopg2

#establishing the connection
conn = psycopg2.connect(
   database="postgres", user='postgres', password='password', host='127.0.0.1', port= '5432'
)
conn.autocommit = True

#Creating a cursor object using the cursor() method
cursor = conn.cursor()

#Preparing query to create a database
sql = '''CREATE database mydb''';

#Creating a database
cursor.execute(sql)
print("Database created successfully........")

#Closing the connection
conn.close()
Database created successfully........


    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
Difference between Lossless and Lossy Join Decomposition - GeeksforGeeks

25 Aug, 2021
The process of breaking up of a relation into smaller subrelations is called Decomposition. Decomposition is required in DBMS to convert a relation into specific normal form which further reduces redundancy, anomalies, and inconsistency in the relation. 
There are mainly two types of decompositions in DBMS- 
Lossless DecompositionLossy Decomposition  
Lossless Decomposition
Lossy Decomposition  
Difference Between Lossless and Lossy Join Decomposition : 
Formally, Let R be a relation and R1, R2, R3 ... Rn be it’s decomposition, the decomposition is lossless if – 
 R1 ⨝ R2 ⨝ R3 .... ⨝ Rn = R
Formally, Let R be a relation and R1, R2, R3 ... Rn be it’s decomposition, the decomposition is lossy if – 
 R ⊂ R1 ⨝ R2 ⨝ R3 .... ⨝ Rn
Example-1: Example to check whether given Decomposition Lossless Join Decomposition. 
Let there be a relational schema R(A, B, C). R1(A, B) and R2(B, C) be it’s decompositions. 
Now for the decomposition to be lossless, 
R1 ⨝ R2 = R then, R1 ⨝ R2  is
As, R1 ⨝ R2 = R, 
This decomposition is Lossless. 
Example-2: Example to check whether given Decomposition Lossy Join Decomposition. 
Let there be a relational schema R(A, B, C). R1(A, B) and R2(A, C) be it’s decompositions. 
Now for the decomposition to be lossy, 
R ⊂ R1 ⨝ R2 then, R1 ⨝ R2  is
As, R ⊂ R1 ⨝ R2, 
This decomposition is Lossy. Thus, we can figure out whether decomposition is lossless or lossy.
arorakashish0911
DBMS
Difference Between
GATE CS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Types of Functional dependencies in DBMS
Introduction of Relational Algebra in DBMS
What is Temporary Table in SQL?
Two Phase Locking Protocol
KDD Process in Data Mining
Difference between BFS and DFS
Class method vs Static method in Python
Differences between TCP and UDP
Difference between var, let and const keywords in JavaScript
Difference between Process and Thread
C# | Creating a read-only wrapper for List - GeeksforGeeks

27 Jan, 2019
List<T>.AsReadOnly Method is used to get a read-only ReadOnlyCollection<T> wrapper for the current collection.
Syntax:
public System.Collections.ObjectModel.ReadOnlyCollection<T> AsReadOnly ();
Return Value: It returns an object that acts as a read-only wrapper around the current List<T>.
Example:
// C# code to create a read-only// wrapper for the List<T>using System;using System.Collections.Generic;  class GFG {      // Driver code    public static void Main()    {          // Creating an List<T> of Integers        List<int> mylist = new List<int>();          // Adding elements to List        mylist.Add(17);        mylist.Add(19);        mylist.Add(21);        mylist.Add(9);        mylist.Add(75);        mylist.Add(19);        mylist.Add(73);          Console.WriteLine("Before Wrapping: ");          // Displaying the elements        // in the mylist        foreach(int i in mylist)        {            Console.WriteLine(i);        }          // Creating a Read-Only packing        // around the List        IList<int> readlist = mylist.AsReadOnly();          Console.WriteLine("After Wrapping: ");          // Displaying the elements        // of Read-Only Collection        foreach(int j in readlist)        {            Console.WriteLine(j);        }                  // You can add elements to        // the original List i.e. mylist        Console.WriteLine("Adding new element to mylist: ");        mylist.Add(35);                  // Displaying the elements        // in the mylist        foreach(int k in mylist)        {            Console.WriteLine(k);        }          // But you cannot add elements        // into the Read-Only Collection        Console.WriteLine("Trying to add new element into readlist:");          // it will give error        readlist.Add(34);              }}
Output:
Before Wrapping: 
17
19
21
9
75
19
73
After Wrapping: 
17
19
21
9
75
19
73
Adding new element to mylist: 
17
19
21
9
75
19
73
35
Trying to add new element into readlist:

Runtime Error:
Unhandled Exception:System.NotSupportedException: Collection is read-only.
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.asreadonly?view=netframework-4.7.2
CSharp-Generic-List
CSharp-Generic-Namespace
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C# Dictionary with examples
C# | Method Overriding
C# | Class and Object
Difference between Ref and Out keywords in C#
C# | Constructors
Introduction to .NET Framework
C# | String.IndexOf( ) Method | Set - 1
C# | Abstract Classes
Top 50 C# Interview Questions & Answers
Different ways to sort an array in descending order in C#
destroy() method in Tkinter - Python

The destroy() method in Tkinter destroys a widget. It is useful in controlling the behavior of various widgets which depend on each other. Also when a process is complete by some user action we need to destroy the GUI components to free the memory as well as clear the screen. The destroy() method achieves all this.
In the below example we have screen with 3 buttons. Clicking the first button closes the window itself where as the clicking of the second button closes the 1st button and so on. This behavior is emulated by using the destroy method as shown in the program below.
from tkinter import *
from tkinter.ttk import *
#tkinter window
base = Tk()

#This button can close the window
button_1 = Button(base, text ="I close the Window", command = base.destroy)
#Exteral paddign for the buttons
button_1.pack(pady = 40)

#This button closes the first button
button_2 = Button(base, text ="I close the first button", command = button_1.destroy)
button_2.pack(pady = 40)

#This button closes the second button
button_3 = Button(base, text ="I close the second button", command = button_2.destroy)
button_3.pack(pady = 40)
mainloop()
Running the above code gives us the following result −
On clicking the various buttons we can observer different behaviors as mentioned in the program.
fc-cache command in Linux with Examples - GeeksforGeeks

15 May, 2019
The fc-cache command in Linux scans the font directories and build font cache for applications which use fontconfig for their font handling. When no arguments are passed fc-cache scans each directory for font files readable by FreeType. A cache is created which contains properties of each font and the associated file name, this cache is further used to speed up application when using fontconfig library during boot.
Synopsis:
fc-cache [ -EfrsvVh ] [ –error-on-no-fonts ] [ –force ] [ –really-force ] [ [ -y dir ] [ –sysroot dir ] ] [ –system-only ] [ –verbose ] [ –version ] [ –help ] [ dir... ]
Options:
-E(–error-on-no-fonts): When used this option an error will be thrown if their are no fonts present in dir or directories in the configuration.
-f(–force): When used this command there will be Force re-generation of apparently up-to-date cache files, overriding the timestamp checking.
-r(–really-force): This option will erase all the existing cache files and rescan.
-s(–system-only): This command will scan only the system-wide directories and omit the places located in /usr/home directory.
-v(–verbose): Will verbose the output while in process.
-V(–version): Will display the version and exit.
Example:
fc-cache -Ev
Note: fc-cache returns zero if cache is successfully generated else non-zero
linux-command
Linux-misc-commands
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
tar command in Linux with examples
UDP Server-Client implementation in C
Conditional Statements | Shell Script
Cat command in Linux with examples
touch command in Linux with Examples
echo command in Linux with Examples
Mutex lock for Linux Thread Synchronization
Tail command in Linux with examples
tee command in Linux with examples
Compiling with g++
How to get services based on start-type in PowerShell?

Below commands are useful to filter services based on their start types (Automatic, Manual or Disabled).
To get the Automatic start-type service. These services are started automatically when the system starts.
Get-Service | where{$_.StartType -eq "Automatic"} | Select Name, Starttype
SystemEventsBroker          Automatic
TeraCopyService             Automatic
Themes                      Automatic
TrkWks                      Automatic
UserManager                 Automatic
UsoSvc                      Automatic
VMUSBArbService             Automatic
WavesSysSvc                 Automatic
Wcmsvc                      Automatic
Winmgmt                     Automatic
WlanSvc                     Automatic
WpnService                  Automatic
WpnUserService_158379       Automatic
wscsvc                      Automatic
WSearch                     Automatic
ZeroConfigService           Automatic
To get the Manual start-type service. These services need to start manually and they are not started automatically when the system starts. They can be triggered by users or applications.
Get-Service | where{$_.StartType -eq "Manual"} | Select Name, Starttype

WinRM                                                     Manual
wisvc                                                     Manual
wlidsvc                                                   Manual
wlpasvc                                                   Manual
WManSvc                                                   Manual
wmiApSrv                                                  Manual
WMPNetworkSvc                                             Manual
workfolderssvc                                            Manual
WpcMonSvc                                                 Manual
WPDBusEnum                                                Manual


To get the Disabled start-type service. These types of services are disabled by the user or system administrators when they are not useful.
Get-Service | where{$_.StartType -eq "Disabled"} | Select Name, Starttype
Name              StartType
----              ---------
AppVClient         Disabled
NetTcpPortSharing  Disabled
RemoteAccess       Disabled
RemoteRegistry     Disabled
shpamsvc           Disabled
ssh-agent          Disabled
svcdemo            Disabled
tzautoupdate       Disabled
UevAgentService    Disabled
Bash Brace Expansion In Linux with Examples - GeeksforGeeks

25 Jan, 2021
Brасe exраnsiоn is а wаy by whiсh аrbitrаry strings саn be generаted frоm the terminаl оr by using any bаsh sсriрt, it allows you to create multiple modified command-line arguments out of a single argument. The syntаx fоr brасe exраnsiоn соnsists оf either a sequenсe sрeсifiсаtiоn оr а cоmmа seраrаted list оf dаtа inside сurly brасes “{}”.  The раttern shоuld nоt cоntаin embedded whitesрасe. There are two optional parts to Brace expansion — Preamble and Postscript. The Preamble is prefixed to each string contained within the braces, and the Postscript is then appended to each resulting string, expanding left to right.
Method 1: Using Comma-separated lists
echo {geeks,for,geeks}
echo {"hello","world"}
Method 2: Using Ranges, Different types of ranges can be used, like numeric, alphabetic, or both. A sequence consists of a starting and ending term separated by 2 periods “..” inside curly braces “{}”.
echo {A..D}
echo {3..8}
echo {A..C}{1..2}
Method 3: Using Preamble, Patterns to be brace expanded may contain a leading term called a preamble. The brace expression may contain either a comma-separated list or a range.
echo gfg{1..4}
echo gfg{1,5,9}
Method 4: Using Postscript, Like Preamble, it can also have an ending portion known as Postscript.
echo {1..3}gfg
echo {1,5,9}gfg
Bash Expansion can be nested.
echo {a,b{1..3},c}
Bash Expansion can be used with other commands also, like, we can make multiple folders with one command using Brace expansion with mkdir command.
Technical Scripter 2020
Linux-Unix
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
nohup Command in Linux with Examples
scp command in Linux with Examples
Thread functions in C/C++
mv command in Linux with examples
chown command in Linux with Examples
SED command in Linux | Set 2
Docker - COPY Instruction
Array Basics in Shell Scripting | Set 1
Basic Operators in Shell Scripting
nslookup command in Linux with Examples
Prime Factor in C++ Program

Prime Factor is a prime number which is the factor of the given number.
Factor of a number are the numbers that are multiplied to get the given number.
Prime Factorisation is the process of recursively dividing the number with its prime factors to find all the prime factors of the number.
Example :
N = 120
Prime factors = 2 5 3
Factorization : 2 * 2 * 2 * 3 * 5
Some points to remember about prime factors of a number
Set of prime factors of a number is unique.
Factorization is important in many mathematical calculations like divisibility, finding common denominators, etc.
It’s an important concept in cryptography.
Program to find prime factors of a number
 Live Demo
#include <iostream>
#include <math.h>
using namespace std;
void printPrimeFactors(int n) {
   while (n%2 == 0){
      cout<<"2\t";
      n = n/2;
   }
   for (int i = 3; i <= sqrt(n); i = i+2){
      while (n%i == 0){
         cout<<i<<"\t";
         n = n/i;
      }
   }
   if (n > 2)
   cout<<n<<"\t";
}
int main() {
   int n = 2632;
   cout<<"Prime factors of "<<n<<" are :\t";
   printPrimeFactors(n);
   return 0;
}
Prime factors of 2632 are :2   2   2   7   47
From JSON object to an array in JavaScript

We are required to create an array out of a JavaScript object, containing the values of all of the object's properties.
For example, given this object −
{
   "firstName": "John",
   "lastName": "Smith",
   "isAlive": "true",
   "a
}
We have to produce this array −
const myarray = ['John', 'Smith', 'true', '25'];
Therefore, let’s write the code for this function −
The code for this will be −
const obj = {
   "firstName": "John",
   "lastName": "Smith",
   "isAlive": "true",
   "age": "25"
};
const objectToArray = obj => {
   const keys = Object.keys(obj);
   const res = [];
   for(let i = 0; i < keys.length; i++){
      res.push(obj[keys[i]]);
   };
   return res;
};
console.log(objectToArray(obj));
The output in the console will be −
[ 'John', 'Smith', 'true', '25' ]
Another Solution: One line alternate −
const obj = {
   "firstName": "John",
   "lastName": "Smith",
   "isAlive": "true",
   "age": "25"
};
const res = Object.values(obj);
console.log(res);
Creating all possible unique permutations of a string in JavaScript

We are required to write a JavaScript function that takes in a string str. Our function should create all permutations of the input string and remove duplicates, if present. This means, we have to shuffle all letters from the input in all possible orders.
Following is the code −
 Live Demo
const str = 'aabb';
const permute = (str = '') => {
   if (!!str.length && str.length < 2 ){
      return str
   }
   const arr = [];
   for (let i = 0; i < str.length; i++){
      let char = str[i]
      if (str.indexOf(char) != i)
         continue
         let remainder = str.slice(0, i) + str.slice(i + 1, str.length)
         for (let permutation of permute(remainder)){
            arr.push(char + permutation)
         }
   }
   return arr
}
console.log(permute(str));
Following is the console output −
[ 'aabb', 'abab', 'abba', 'baab', 'baba', 'bbaa' ]