code-rag-bench/online-tutorials huggingface dataset:
Computer Concepts - Programming Languages

A program is a set of instructions that help computer to perform tasks. This set of instructions is also called as scripts. Programs are executed by processor whereas scripts are interpreted. The languages that are used to write a program or set of instructions are called "Programming languages". Programming languages are broadly categorized into three types −
Machine level language
Assembly level language
High-level language
Machine language is lowest level of programming language. It handles binary data i.e. 0’s and 1’s. It directly interacts with system. Machine language is difficult for human beings to understand as it comprises combination of 0’s and 1’s. There is software which translate programs into machine level language. Examples include operating systems like Linux, UNIX, Windows, etc. In this language, there is no need of compilers and interpreters for conversion and hence the time consumption is less. However, it is not portable and non-readable to humans.
Assembly language is a middle-level language. It consists of a set of instructions in a specific format called commands. It uses symbols to represent field of instructions. It is very close to machine level language. The computer should have assembler to translate assembly level program to machine level program. Examples include ADA, PASCAL, etc. It is in human-readable format and takes lesser time to write a program and debug it. However, it is a machine dependent language.
High-level language uses format or language that is most familiar to users. The instructions in this language are called codes or scripts. The computer needs a compiler and interpreter to convert high-level language program to machine level language. Examples include C++, Python, Java, etc. It is easy to write a program using high level language and is less time-consuming. Debugging is also easy and is a human-readable language. Main disadvantages of this are that it takes lot of time for execution and occupies more space when compared to Assembly- or Machine-level languages. Following is a simple example for a high level language −
if age < 18 {
   printf("You are not eligible to vote");
} else{
   printf("You are eligible to vote");
}

    107 Lectures 
     13.5 hours 

 Arnab Chakraborty

    106 Lectures 
     8 hours 

 Arnab Chakraborty

    99 Lectures 
     6 hours 

 Arnab Chakraborty

    46 Lectures 
     2.5 hours 

 Shweta

    70 Lectures 
     9 hours 

 Abhilash Nelson

    52 Lectures 
     7 hours 

 Abhishek And Pukhraj
 Print
 Add Notes
 Bookmark this page
Python - Concatenate Tuple elements by delimiter - GeeksforGeeks

02 Sep, 2020
Given a tuple, concatenate each element of tuple by delimiter.
Input : test_tup = (“Gfg”, “is”, 4, “Best”), delim = “, ”Output : Gfg, is, 4, BestExplanation : Elements joined by “, “.
Input : test_tup = (“Gfg”, “is”, 4), delim = “, ”Output : Gfg, is, 4Explanation : Elements joined by “, “.
Method #1 : Using list comprehension
In this, we iterate for each element in tuple using loop in list comprehension and concatenate using + operator.
Python3
# Python3 code to demonstrate working of # Concatenate Tuple elements by delimiter# Using list comprehension  # initializing tupletest_tup = ("Gfg", "is", 4, "Best")  # printing original tupleprint("The original tuple is : " + str(test_tup))  # initializing delim delim = "-"  # using str() to convert elements to string # join to convert to stringres = ''.join([str(ele) + delim for ele in test_tup])  # striping stray char res = res[ : len(res) - len(delim)]  # printing result print("Concatenated Tuple : " + str(res)) 
The original tuple is : ('Gfg', 'is', 4, 'Best')
Concatenated Tuple : Gfg-is-4-Best

Method #2 : Using join() + map()
In this, we convert all chars to string using str() and map to perform str() to all elements, then concatenation using join().
Python3
# Python3 code to demonstrate working of # Concatenate Tuple elements by delimiter# Using join() + map()  # initializing tupletest_tup = ("Gfg", "is", 4, "Best")  # printing original tupleprint("The original tuple is : " + str(test_tup))  # initializing delim delim = "-"  # for joining, delim is used res = delim.join(map(str, test_tup))  # printing result print("Concatenated Tuple : " + str(res)) 
The original tuple is : ('Gfg', 'is', 4, 'Best')
Concatenated Tuple : Gfg-is-4-Best

Python tuple-programs
Python
Python Programs
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 dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
Python | Numpy np.unique() method - GeeksforGeeks

21 Nov, 2019
With the help of np.unique() method, we can get the unique values from an array given as parameter in np.unique() method.
Syntax : np.unique(Array)Return : Return the unique of an array.
Example #1 :In this example we can see that by using np.unique() method, we are able to get the unique values from an array by using this method.
# import numpyimport numpy as np  a = [1, 2, 2, 4, 3, 6, 4, 8]  # using np.unique() methodgfg = np.unique(a)  print(gfg)
Output :
[1 2 3 4 6 8]
Example #2 :
# import numpyimport numpy as np  a = [[10.2, 21.4, 3.6, 14.8], [1.0, 5.0, 10.0, 15.0]]  # using np.unique() methodgfg = np.unique(a)  print(gfg)
Output :
[1. 3.6 5. 10. 10.2 14.8 15. 21.4]
Python numpy-Matrix Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
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
How To Convert Python Dictionary To JSON?
How to compare two objects to determine the first object contains equivalent property values to the second object in JavaScript ? - GeeksforGeeks

23 Apr, 2021
Given two objects obj1 and obj2 and the task is to check the obj1 contains all the property values of obj2 in JavaScript.
Input: obj1: { name: "John", age: 23; degree: "CS" }
       obj2: {age: 23, degree: "CS"}
       
Output: true

Input: obj1: { name: "John", degree: "CS" }
       obj2: {name: "Max", age: 23, degree: "CS"}
       
Output: false
To solve this problem we follow the following approaches.
Approach 1: It is a naive approach to solve this problem. In this approach, we iterate the obj2 using the for..in loop and at every iteration, we check the current key of both objects are not equal we return false otherwise after completion the loop we return true.
Example:
Javascript
<script>      // Define the first object    let obj1 = {        name: "John",        age: 23,        degree: "CS"    }      // Define the second object    let obj2 = {        age: 23,        degree: "CS"    }      // Define the function check    function check(obj1, obj2) {          // Iterate the obj2 using for..in        for (key in obj2) {                          // Check if both objects do             // not have the equal values            // of same key            if (obj1[key] !== obj2[key]) {                return false;            }        }        return true    }      // Call the function    console.log(check(obj1, obj2))</script>
Output:
true
Approach 2: In this approach, we create an array of all the keys of obj2 by using the Object.keys() method and then using the Array.every() method we check if all the properties of obj2 are equal to obj1 or not.
Example:
Javascript
<script>      // Define the first object    let obj1 = {        name: "John",        age: 23,        degree: "CS"    }      // Define the Second object    let obj2 = {        age: 23,        degree: "CS"    }      // Define the function check    function check(obj1, obj2) {        return Object              // Get all the keys in array            .keys(obj2)            .every(val => obj1.hasOwnProperty(val)                 && obj1[val] === obj2[val])    }      // Call the function    console.log(check(obj1, obj2))</script>
Output:
true
JavaScript-Methods
javascript-object
JavaScript-Questions
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 ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
Finding roots of a quadratic equation – JavaScript

We are required to write a JavaScript function that takes in three numbers (representing the coefficient of quadratic term, coefficient of linear term and the constant respectively in a quadratic quadratic).
And we are required to find the roots, (if they are real roots) otherwise we have to return false. Let's write the code for this function
Following is the code −
const coefficients = [3, 12, 2];
const findRoots = co => {
   const [a, b, c] = co;
   const discriminant = (b * b) - 4 * a * c;
   if(discriminant < 0){
      // the roots are non-real roots
      return false;
   };
   const d = Math.sqrt(discriminant);
   const x1 = (d - b) / (2 * a);
   const x2 = ((d + b) * -1) / (2 * a);
   return [x1, x2];
};
console.log(findRoots(coefficients));
The output in the console −
[ -0.17425814164944628, -3.825741858350554 ]
Differential or Derivatives in MATLAB - GeeksforGeeks

23 Aug, 2021
Differentiation of a function y = f(x) tells us how the value of y changes with respect to change in x. It can also be termed as the slope of a function.
Derivative of a function f(x) wrt to x is represented as 
MATLAB allows users to calculate the derivative of a function using diff() method. Different syntax of diff() method are:
f’ = diff(f)
f’ = diff(f, a)
f’ = diff(f, b, 2)
It returns the derivative of function f(x) wrt variable x.
Example 1:
Matlab
% Create a symbolic expression in variable xsyms xf = cos(x);disp("f(x) :");disp(f); % Derivative of f(x)d = diff(f);disp("Derivative of f(x) :");disp(d);
Output :
Example 2: Evaluating the derivative of a function at a specified value using subs(y,x,k).
subs(y,x,k), it gives the value of function y at x = k.
Matlab
% Create a symbolic expression in# variable xsyms xf = cos(x);disp("f(x) :");disp(f); % Derivative of f(x)d = diff(f);val = subs(d,x,pi/2); disp("Value of f'(x) at x = pi/2:");disp(val);
Output :
It returns the derivative of function f with respect to variable a.
Matlab
% Create a symbolic expression in variable xsyms x t;f = sin(x*t);disp("f(x) :");disp(f); % Derivative of f(x,t) wrt td = diff(f,t);disp("Derivative of f(x,t) wrt t:");disp(d);
Output :
It returns the double derivative of function f with respect to variable b.
Example 1:
Matlab
% Create a symbolic expression in% variable x,nsyms x n;f = x^n;disp("f(x,n) :");disp(f); % Double Derivative of f(x,n) wrt xd = diff(f,x,2);disp("Double Derivative of f(x,n) wrt x:");disp(d);
Output :
In the same way, you can also calculate the k-order derivative of function f using diff(f,x,k).
Example 2: 
Calculating the partial derivative } using Jacobian matrix and determinant.
  
Matlab
% Create a symbolic expression in variable% u and vsyms u v;f = u^2;g = sin(v)*(3*u);disp("f(u,v) :");disp(f);disp("g(u,v) :");disp(g); % Jacobian matrix of function f(u,v) and% g(u,v)J = jacobian([f; g], [u v]);disp("Jacobian matrix :");disp(J); % Determinant of Jacobian matrixd = det(J);disp("Determinant of Jacobian matrix:");disp(d);
 
 
Output :
 
 
ruhelaa48
MATLAB-Maths
Picked
MATLAB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Remove Noise from Digital Image in Frequency Domain Using MATLAB?
Boundary Extraction of image using MATLAB
Laplacian of Gaussian Filter in MATLAB
Forward and Inverse Fourier Transform of an Image in MATLAB
How to Perform Contrast Enhancement of Color Image in MATLAB?
How to Solve Histogram Equalization Numerical Problem in MATLAB?
How to Normalize a Histogram in MATLAB?
Turn an Array into a Column Vector in MATLAB
Trigonometric Functions in MATLAB
Laplace Transform in MATLAB
Firebase - Detaching Callbacks

This chapter will show you how to detach callbacks in Firebase.
Let us say we want to detach a callback for a function with value event type.
var playersRef = firebase.database().ref("players/");

ref.on("value", function(data) {
   console.log(data.val());
}, function (error) {
   console.log("Error: " + error.code);
});
We need to use off() method. This will remove all callbacks with value event type.
playersRef.off("value");

When we want to detach all callbacks, we can use −
playersRef.off();


    60 Lectures 
     5 hours 

 University Code

    28 Lectures 
     2.5 hours 

 Appeteria

    85 Lectures 
     14.5 hours 

 Appeteria

    46 Lectures 
     2.5 hours 

 Gautham Vijayan

    13 Lectures 
     1.5 hours 

 Nishant Kumar

    85 Lectures 
     16.5 hours 

 Rahul Agarwal
 Print
 Add Notes
 Bookmark this page
Math.Pow() Method in C#

The Math.Pow() method in C# is used to compute a number raised to the power of some other number.
Following is the syntax −
public static double Pow(double val1, double val2)
Above, val1 is a double-precision floating-point number to be raised to a power., whereas val2 is a double-precision floating-point number that specifies a power.
Let us now see an example to implement Math.Pow() method −
using System;
public class Demo {
   public static void Main(){
      double res;
      res = Math.Pow(5, 0);
      Console.WriteLine("Math.Pow(5,0) = "+res);
      res = Math.Pow(0,5);
      Console.WriteLine("Math.Pow(0,5) = "+res);
   }
}
This will produce the following output −
Math.Pow(5,0) = 1
Math.Pow(0,5) = 0
Let us see another example to implement Math.Pow() method −
using System;
public class Demo {
   public static void Main(){
      int val1 = 10, val2 = 15;
      float val3 = 12.8f, val4 = 25.6f;
      double res = Math.Pow(3, 2);
      Console.WriteLine("Minimum Value from two int values = "+Math.Min(val1, val2));
      Console.WriteLine("Minimum Value from two float values = "+Math.Min(val3, val4));
      Console.WriteLine("Math.Pow(3,2) = "+res);
   }
}
This will produce the following output −
Minimum Value from two int values = 10
Minimum Value from two float values = 12.8
Math.Pow(3,2) = 9
Robot Return to Origin in C++

Suppose there is a robot and its starting position is (0, 0). If we have a sequence of its movements, we have to check whether this robot ends up at (0, 0) after it completes its moves.
The move sequence is given as a string, and the character moves[i] represents its ith move. Symbols are R for right, L for left, U for up, and D for down. If the robot returns to the origin after it finishes all of its moves, return true. Otherwise, return false.
So, if the input is like "RRULLD", then the output will be true, Right two-unit, then go up, then left two unit then again down, so this is the starting position.
To solve this, we will follow these steps −
l := size of moves array
l := size of moves array
if l is same as 0, then −return true
if l is same as 0, then −
return true
return true
lft := 0, up := 0
lft := 0, up := 0
for initialize i := 0, when i < l, update (increase i by 1), do −if moves[i] is same as 'L', then −(increase lft by 1)if moves[i] is same as 'R', then −(decrease lft by 1)if moves[i] is same as 'U', then −(increase up by 1)if moves[i] is same as 'D', then −(decrease up by 1)
for initialize i := 0, when i < l, update (increase i by 1), do −
if moves[i] is same as 'L', then −(increase lft by 1)
if moves[i] is same as 'L', then −
(increase lft by 1)
(increase lft by 1)
if moves[i] is same as 'R', then −(decrease lft by 1)
if moves[i] is same as 'R', then −
(decrease lft by 1)
(decrease lft by 1)
if moves[i] is same as 'U', then −(increase up by 1)
if moves[i] is same as 'U', then −
(increase up by 1)
(increase up by 1)
if moves[i] is same as 'D', then −(decrease up by 1)
if moves[i] is same as 'D', then −
(decrease up by 1)
(decrease up by 1)
if lft is same as 0 and up is same as 0, then −return true
if lft is same as 0 and up is same as 0, then −
return true
return true
return false
return false
Let us see the following implementation to get a better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   bool judgeCircle(string moves) {
      int l = moves.length();
      if (l == 0) {
         return true;
      }
      int lft = 0, up = 0;
      for (int i = 0; i < l; i++) {
         if (moves[i] == 'L') {
            lft++;
         }
         if (moves[i] == 'R') {
            lft--;
         }
         if (moves[i] == 'U') {
            up++;
         }
         if (moves[i] == 'D') {
            up--;
         }
      }
      if (lft == 0 && up == 0) {
         return true;
      }
      return false;
   }
};
main(){
   Solution ob;
   cout << (ob.judgeCircle("RRULLD"));
}
"RRULLD"
1
How to ceate right justified JTextField in Java?

To create right justified JTextField, set the alignment to be RIGHT. Here, we will be using the setHorizontalAlignment() method as well and within that the alignment would be set.
Create a JTextField −
JTextField emailId = new JTextField(20);
Now, align it to the right −
emailId.setHorizontalAlignment(JTextField.RIGHT);
The following is an example to create right justified JTextField −
package my;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
public class SwingDemo {
   public static void main(String[] args) throws Exception {
      JFrame frame = new JFrame("Enter emailid...");
      JLabel label;
      frame.setLayout(new FlowLayout());
      label = new JLabel("TextField (Right Justified)", SwingConstants.LEFT);
      JTextField emailId = new JTextField(20);
      emailId.setHorizontalAlignment(JTextField.RIGHT);
      frame.add(label);
      frame.add(emailId);
      frame.setSize(550,250);
      frame.setVisible(true);
   }
}
This will produce the following output. Now, if yiu will tyoe any text in the component, it would begin from the right −
Fruit Into Baskets in C++

Suppose we have a row of trees, the i-th tree produces fruit with type tree[i]. we can start at any tree of our choice, then repeatedly perform these steps −
Add one piece of fruit from this tree to our baskets. If there is no chance, then stop.
Move to the next tree to the right of the current one. If there is no tree to the right, then stop.
We have two baskets, and each basket can carry any quantity of fruit, but we want each basket should only carry one type of fruit each. We have to find the total amount of fruit that we can collect with this procedure? So if the trees are like [0, 1, 2, 2], then the output will be 3. We can collect [1,2,2], if we start from the first tree, then we would only collect [0, 1]
To solve this, we will follow these steps −
n := tree size, j := 0, ans := 0
create one map m
for i in range 0 to n – 1increase m[tree[i]] by 1while size of m is > 2 and j <= i, thendecrease m[tree[j]] by 1if m[tree[j]] = 0, then delete tree[j] from mincrease j by 1ans := max of i – j + 1 and ans
increase m[tree[i]] by 1
while size of m is > 2 and j <= i, thendecrease m[tree[j]] by 1if m[tree[j]] = 0, then delete tree[j] from mincrease j by 1
decrease m[tree[j]] by 1
if m[tree[j]] = 0, then delete tree[j] from m
increase j by 1
ans := max of i – j + 1 and ans
return ans
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int totalFruit(vector<int>& tree) {
      int n = tree.size();
      int j = 0;
      map <int, int> m;
      int ans = 0;
      for(int i = 0; i < n; i++){
         m[tree[i]] += 1;
         while(m.size() > 2 && j <= i){
            m[tree[j]]--;
            if(m[tree[j]] == 0)m.erase(tree[j]);
            j++;
         }
         ans = max(i - j + 1, ans);
      }
      return ans;
   }
};
main(){
   vector<int> v = {3,3,3,1,2,1,1,2,3,3,4};
   Solution ob;
   cout <<(ob.totalFruit(v));
}
[3,3,3,1,2,1,1,2,3,3,4]
5
Left justify output in Java

Including a minus sign after the %, makes it left justified.
Note − By default, output is right justified
Firstly, create a formatter object −
Formatter f = new Formatter();
Now, use the format() method to left justify output −
f.format("|%-15.5f|", 299.675796)
The following is an example −
 Live Demo
import java.util.*;
public class Demo {
   public static void main(String args[]) {
      Formatter f = new Formatter();
      // left justify
      f = new Formatter();
      System.out.println(f.format("|%-15.5f|", 299.675796));
   }
}
|299.67580 |
Compute the histogram of a set of data using NumPy in Python - GeeksforGeeks

05 Sep, 2020
Numpy provides us the feature to compute the Histogram for the given data set using NumPy.histogram() function. The formation of histogram depends on the data set, whether it is predefined or randomly generated.
Syntax : numpy.histogram(data, bins=10, range=None, normed=None, weights=None, density=None)
Case 1: Computing the Numpy Histogram with the help of Random Data set
Python3
# import Numpy and matplotlibfrom matplotlib import pyplot as pltimport numpy as np    # Creating random datasetdata_set = np.random.randint(100, size=(50))  # Creation of plotfig = plt.figure(figsize=(10, 6))  # plotting the Histogram with certain intervalsplt.hist(data_set, bins=[0, 10, 20, 30, 40, 50,                         60, 70, 80, 90, 100])  # Giving title to Histogramplt.title("Random Histogram")  # Displaying Histogramplt.show()
Output:
In the above example, we created a random data set using np.random.randint() and plot the Numpy Histogram
Case 2: Computing the Numpy Histogram with the help of Pre-defined Data set
Python3
# import Numpy and matplotlibfrom matplotlib import pyplot as pltimport numpy as np    # Using predefined datasetdata_set = [45, 85, 95, 10, 58, 77, 92, 72, 52,            22, 32, 5, 95, 2, 23, 24, 50, 40, 60,            69, 44, 80, 21, 15, 17, 55, 21, 88]  # Creation of plotfig = plt.figure(figsize=(10, 5))  # plotting the Histogram with certain intervalsplt.hist(data_set, bins=[0, 15, 30, 45, 60, 75, 90, 105])  # Giving title to Histogramplt.title("Predefined Histogram")  # Displaying Histogramplt.show()
In the above example, we take a predefined data set and plot the Numpy Histogram.
Python-matplotlib
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Python Classes and Objects
Create a directory in Python
Optional Parameters with Default Values

Function parameters can also be assigned values by default. However, such parameters can also be explicitly passed values.
function_name(param1,{param2= default_value}) { 
   //...... 
} 

void main() { 
   test_param(123); 
}  
void test_param(n1,{s1:12}) { 
   print(n1); 
   print(s1); 
}   
It should return the following output−
123 
12 

Note − All required parameters in a function must occur before optional parameters.

    44 Lectures 
     4.5 hours 

 Sriyank Siddhartha

    34 Lectures 
     4 hours 

 Sriyank Siddhartha

    69 Lectures 
     4 hours 

 Frahaan Hussain

    117 Lectures 
     10 hours 

 Frahaan Hussain

    22 Lectures 
     1.5 hours 

 Pranjal Srivastava

    34 Lectures 
     3 hours 

 Pranjal Srivastava
 Print
 Add Notes
 Bookmark this page
How to align items at the center of the container using CSS ?

17 Mar, 2021
An easy and common task for CSS is to align text or images into the center of any container.
Syntax:
.container{
          text-align: center;
}

Example 1: We use the text-align property of CSS to center the item horizontally followed by the vertical-align and display property to align the item to the center of the container vertically. Below examples illustrate the approach:
HTML
<!DOCTYPE html><html>    <head>        <style>            .container{                text-align: center;                height: 200px;                width : 200px;                display: table-cell;                vertical-align: middle;                border: 2px solid green;            }        </style>    </head>    <body>        <div class="container">            <p>Centered Text</p>        </div>    </body></html>
Output :
Text is centered in the container
Example 2: Another method is to use the text-align property to center the item horizontally with the line-height property to align the items at the center of the container vertically. Below examples illustrate the approach:
HTML
<!DOCTYPE html><html>    <head>        <style>            .container2{                width: 200px;                line-height: 180px;                height: 200px;                text-align: center;                border: 2px solid green;            }        </style>    </head>    <body>        <div class="container2">            <p>Centered Text</p>        </div>    </body></html>
Output:
Text is centered in the container
CSS-Properties
CSS-Questions
Picked
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What is Git-Ignore and How to Use it?

10 Jul, 2020
There are various types of files we might want the git to ignore before committing, for example, the files that are to do with our user settings or any utility setting, private files like passwords and API keys. These files are not of any use to anyone else and we do not want to clutter our git. We can do this with the help of “.gitignore”
.gitignore is an auto-generated file inside the project folder that ignores/prevents files to get committed to the local and remote repositories.
.gitignore can be used in Git with the help of following steps:
Step 1: Open your terminal/cmd and change your directory to the folder where your files are located. You can use ” ls -a” command to view its contents.
cd directory(or)folder
ls -a

Here, the project files are saved inside folder named story which is further inside web development. Here, we want git to ignore the secrets.txt file.
Step 2: Create .gitignore File inside the project folder.
Step 3: Write the name of the files you want to ignore in the .gitignore text file. Each file name should be written in a new line .
Step 4: Initialize git in your terminal. Add these files to your git repository and commit all the changes with an appropriate message.
git init
git add .
git commit -m "your message"

Step 5: Check the status of the repository. The file(s) added to the .gitignore text file will be ignored by the git every time you make any changes and commit.
git status
Some common patterns and format for Git-Ignore :
Blank Line: A blank line doesn’t refer to any file name, so we can use it to separate two file names for the ease of reading .
#: A line beginning with the # symbol refers to a comment .However if # is used as a pattern then use backslash (“\”) before the # symbol so that it is not misunderstood as a comment.
/: It is used as a directory separator i.e to include directories,  for example webdev/ .
*.extension_name: For example *.txt and *.log can be used to match ALL the files that have .txt and .log as their extension respectively.
**/any_name: It is used to match any file or directory with the name any_name.
any_name/**: It is used to match anything that is inside the directory of the name any_name. for example webdev/** matches all the files inside webdev directory.
Examples:
# Compiled class file
*.class

# Log file
*.log

# Mobile Tools for Java (J2ME)
.mtj.tmp/

# Package Files 
*.jar

*.war

*.nar

*.ear

*.zip

*.tar.gz

*.rar

Before using .gitignore to ignore certain files, if you have already committed files you didn’t want to here’s how you can undo it. Use the following command on Git Bash to undo a commit:
git rm --cached -r
Here, “rm” stands for remove while “r” stands for recursive.
Note: Head over to the GitHub and search for gitignore repositories, you will find a list of gitignore repositories contributed by various people.
GitHub
Git
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
statsmodels.durbin_watson() in Python

26 Mar, 2020
With the help of statsmodels.durbin_watson() method, we can get the durbin watson test statistics and it is equal to 2*(1-r), where r is autocorrelation between residual.
Syntax : statsmodels.durbin_watson(residual)Return : Return a single floating point value of durbin watson.
Example #1 :In this example we can see that by using statsmodels.durbin_watson() method, we are able to get the durbin watson test statistical value by using this method.
# import numpy and statsmodelsimport numpy as npfrom statsmodels.stats.stattools import durbin_watson  g = np.array([1, 2, 3])# Using statsmodels.durbin_watson() methodgfg = durbin_watson(g)  print(gfg)
Output :
0.14285714285714285
Example #2 :
# import numpy and statsmodelsimport numpy as npfrom statsmodels.stats.stattools import durbin_watson  g = np.array([1, 2, 3, 4, -3, -2, -1])# Using statsmodels.durbin_watson() methodgfg = durbin_watson(g)  print(gfg)
Output :
1.2272727272727273
Python-statsmodels
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
What does it mean by select 1 from MySQL table?

The statement ‘select 1’ from any table name means that it returns only 1. For example, If any table has 4 records then it will return 1 four times.
Let us see an example. Firstly, we will create a table using the CREATE command.
mysql> create table StudentTable
   -> (
   -> id int,
   -> name varchar(100)
   -> );
Query OK, 0 rows affected (0.51 sec)
mysql> insert into StudentTable values(1,'John'),(2,'Carol'),(3,'Smith'),(4,'Bob');
Query OK, 4 rows affected (0.21 sec)
Records: 4  Duplicates: 0  Warnings: 0
To display all the records.
mysql> select *from StudentTable;
Here is the output.
+------+-------+
| id   | name  |
+------+-------+
|    1 | John  |
|    2 | Carol |
|    3 | Smith |
|    4 | Bob   |
+------+-------+
4 rows in set (0.00 sec)

The following is the query to implement "select 1".
mysql> select 1 from StudentTable;
Here is the output.
+---+
| 1 |
+---+
| 1 |
| 1 |
| 1 |
| 1 |
+---+
4 rows in set (0.00 sec)

The above returns 1 four times for 4 records, and if we had 5 records then the above query would have returned 1 five times.
Note: It returns 1 N times, if the table has N records.
How to create a pandas DataFrame using a list of lists?

The pandas DataFrame can be created by using the list of lists, to do this we need to pass a python list of lists as a parameter to the pandas.DataFrame() function.
Pandas DataFrame will represent the data in a tabular format, like rows and columns. If we create a pandas DataFrame using a list of lists, the inner list will be transformed as a row in the resulting list.
# importing the pandas package
import pandas as pd
# creating a nested list
nested_list = [[1,2,3],[10,20,30],[100,200,300]]

# creating DataFrame
df = pd.DataFrame(nested_list, columns= ['A','B','C'])

print(df)# displaying resultant DataFrame
In this above Example, nested_list is having 3 sub-lists and each list is having 3 integer elements, by using the DataFrame constructor we create a DataFrame or a table shape of 3X3. The columns parameter is used to customize the default column labels from [0,1,2] to [A,B,C]. The resultant DataFrame can be seen below.
    A    B    C
0   1    2    3
1   10   20   30
2   100  200  300
The output DataFrame has 3 rows and 3 columns, with column label representation as A, B, C.
# importing the pandas package
import pandas as pd
# creating a nested list
nested_list = [['A','B','C'],['D','E'],['F','G','H']]

# creating DataFrame
df = pd.DataFrame(nested_list)

# displaying resultant DataFrame
print(df)
In this following example, we have created a pandas DataFrame object using the list of lists with different lengths. The second inner list has only 2 elements and the remaining inner lists have 3 elements, due to this we will get None value in the resultant DataFrame.
    0   1     2
0   A   B     C
1   D   E  None
2   F   G     H
We can see that there is a none value in the second-row third elements, which is due to the uneven length of inner lists.
How select specific rows in MySQL?

To select specific rows, use FIND_IN_SET() function in MySQL. Let us first create a table −
mysql> create table DemoTable
   (
   ListOfValues varchar(200)
   );
Query OK, 0 rows affected (0.31 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('112,114,567,Java,345');
Query OK, 1 row affected (0.06 sec)

mysql> insert into DemoTable values('222,214,256');
Query OK, 1 row affected (0.06 sec)

mysql> insert into DemoTable values('2,567,98,C');
Query OK, 1 row affected (0.06 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+----------------------+
| ListOfValues         |
+----------------------+
| 112,114,567,Java,345 |
| 222,214,256          |
| 2,567,98,C           |
+----------------------+
3 rows in set (0.00 sec)
Following is the query to select specific rows in MySQL −
mysql> select *from DemoTable where find_in_set('2',ListOfValues) >0;
This will produce the following output −
+--------------+
| ListOfValues |
+--------------+
| 2,567,98,C   |
+--------------+
1 row in set (0.03 sec)
Return all dates between two dates in an array in PHP

To return all dates between two dates, the code is as follows −
 Live Demo
<?php
   function displayDates($date1, $date2, $format = 'd-m-Y' ) {
      $dates = array();
      $current = strtotime($date1);
      $date2 = strtotime($date2);
      $stepVal = '+1 day';
      while( $current <= $date2 ) {
         $dates[] = date($format, $current);
         $current = strtotime($stepVal, $current);
      }
      return $dates;
   }
   $date = displayDates('2019-11-10', '2019-11-20');
   var_dump($date);
?>
This will produce the following output−
array(11) {
   [0]=>
   string(10) "10-11-2019"
   [1]=>
   string(10) "11-11-2019"
   [2]=>
   string(10) "12-11-2019"
   [3]=>
   string(10) "13-11-2019"
   [4]=>
   string(10) "14-11-2019"
   [5]=>
   string(10) "15-11-2019"
   [6]=>
   string(10) "16-11-2019"
   [7]=>
   string(10) "17-11-2019"
   [8]=>
   string(10) "18-11-2019"
   [9]=>
   string(10) "19-11-2019"
   [10]=>
   string(10) "20-11-2019" 
}
Find All Duplicate Characters from a String using Python

One String is given. Our task is to find those characters whose frequency is more than one in the given string.
As an example, we can see that the string “Hello World. Let’s learn Python” so the algorithm will find those letters which are occurring multiple times. In this case, the output will look like this -
e : 3
l : 4
o , 3)
<space> : 4 
r : 2
t : 2
n : 2

To implement this problem we are using Python Collections. From the collection, we can get the Counter() method. The Counter() method is used to count the hashtable objects. In this case, it separates the characters from the text and makes each character as a key of the dictionary, and the character count is the value of those keys.
Step 1: Find the key-value pair from the string, where each character is key and character counts are the values.
Step 2: For each key, check whether the value is greater than one or not. 
Step 3: If it is greater than one then, it is duplicate, so mark it. Otherwise, ignore the character 

from collections import Counter
defcalc_char_freq(string):
   freq_count = Counter(string) # get dictionary with letters as key and frequency as value
   for key in freq_count.keys():
      if freq_count.get(key) > 1: # for all different keys, list the letters and frequencies
         print("(" + key + ", " + str(freq_count.get(key)) + ")")
      myStr = 'Hello World. Let’s learn Python'    
      calc_char_freq(myStr)
(e, 3)
(l, 4)
(o, 3)
( , 4)
(r, 2)
(t, 2)
(n, 2)
Can the main method in Java return a value?

The public static void main(String args[]) is the entry point of a Java program Whenever you execute a program the JVM searches for the main method and starts executing the contents of it. If such method is not found the program gets executed successfully, but when you execute the program it generates an error.
As the matter of fact you should declare the main method with public static as modifiers, void return type and String arguments if you change anything, JVM doesn’t considers as the entry point method and prompts an error at run time.
Therefore, you cannot change the return type of main method from void, at the same time you cannot return any value from a method with void type.
public class Sample{
   public static void main(String args[]){
      System.out.println("Contents of the main method");
      return 20;
   }
}
Sample.java:4: error: incompatible types: unexpected return value
   return 20;
          ^
1 error
Therefore, you cannot return any value from main.
How to remove empty string/lines from PowerShell?

In many instances, you need to remove empty lines or strings from the PowerShell string array or the files. In this article instead of removing empty string, we will get the result or filter the output from lines that are not empty. In this way, we can get the output without empty lines.
Consider the example below, we have a file called EmptryString.txt and we need to remove empty lines from the content.
The content of the text file is as below.
PS C:\Windows\System32> Get-Content D:\Temp\EmptyString.txt
This is example of empty string
PowerShell
PowerShell DSC
String Array
Hello
You just need to apply the condition where the line is not empty. See the code below.
Get-Content D:\Temp\EmptyString.txt | where{$_ -ne ""}
This is example of empty string
PowerShell
PowerShell DSC
String Array
Hello
Similarly, you can use the above command to remove empty lines from the string array. For example,
$str = "Dog","","Cat","","Camel","","Tiger"
$str
PS C:\Windows\System32>
$str
Cat
Camel
TigerDog
Now apply the same logic to remove the empty lines.
$str | where{$_ -ne ""}
PS C:\Windows\System32> $str | where{$_ ne ""}
Dog
Cat
Camel
Tiger
How to show minor tick labels on a log-scale with Matplotlib?

To show minor tick labels on a log-scale with Matplotlib, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Create x and y data points using numpy.
Plot x and y data points using plot() method
Get the current axis using gca() method.
Set the yscale with log class by name.
Change the appearance of ticks and tick label using ick_params() method.
Set the minor axis formatter with format strings to format the tick.
To display the figure, use show() method.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import FormatStrFormatter

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

x = np.linspace(-2, 2, 10)
y = np.exp(x)

plt.plot(x, y)

ax = plt.gca()
ax.set_yscale('log')

plt.tick_params(axis='y', which='minor')
ax.yaxis.set_minor_formatter(FormatStrFormatter("%.1f"))

plt.show()
Find the roots of the polynomials using NumPy

05 Sep, 2020
In this article, let’s discuss how to find the roots of a polynomial of a NumPy array. It can be found using various methods, let’s see them in detail.
Method 1: Using np.roots()
This function returns the roots of a polynomial with coefficients given in p. The coefficients of the polynomial are to be put in an array in the respective order. 
For example, if the polynomial is x2 +3x + 1, then the array will be [1, 3, 1]
Syntax : numpy.roots(p)
Parameters :p : [array_like] Rank-1 array of polynomial coefficients.
Return : [ndarray] An array containing the roots of the polynomial.
Let’s see some examples:
Example 1: Find the roots of polynomial x2 +2x + 1
Python3
# import numpy libraryimport numpy as np    # Enter the coefficients of the poly in the arraycoeff = [1, 2, 1]print(np.roots(coeff))
Output:
[-1. -1.]
Example 2: Find the roots of the polynomial x3 +3 x2   + 2x +1
Python3
# import numpy libraryimport numpy as np    # Enter the coefficients of the poly # in the arraycoeff = [1, 3, 2, 1]print(np.roots(coeff))
Output:
[-2.32471796+0.j         -0.33764102+0.56227951j -0.33764102-0.56227951j]
Method 2: Using np.poly1D()
This function helps to define a polynomial function. It makes it easy to apply “natural operations” on polynomials. The coefficients of the polynomial are to be put in an array in the respective order.
For example, for the polynomial x2 +3x + 1, the array will be [1, 3, 1]
Approach:
Apply function np.poly1D() on the array and store it in a variable.
Find the roots by multiplying the variable by roots or r(in-built keyword) and print the result to get the roots of the given polynomial
Syntax: numpy.poly1d(arr, root, var):
Let’s see some examples:
Example 1: Find the roots of polynomial x2 +2x + 1
Python3
# import numpy libraryimport numpy as np    # enter the coefficients of poly # in the arrayp = np.poly1d([1, 2, 1])  # multiplying by r(or roots) to # get the rootsroot_of_poly = p.rprint(root_of_poly)
Output:
[-1. -1.]
Example 2: Find the roots of the polynomial x3 +3 x2   + 2x +1
Python3
# import numpy libraryimport numpy as np    # enter the coefficients of poly# in the arrayp = np.poly1d([1, 3, 2, 1])  # multiplying by r(or roots) to get # the rootsroot_of_poly = p.rprint(root_of_poly)
Output:
[-2.32471796+0.j         -0.33764102+0.56227951j -0.33764102-0.56227951j]
Python numpy-polynomials
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
Introduction To PYTHON
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
Transition diagram for Identifiers in Compiler Design

21 Nov, 2019
Transition diagram is a special kind of flowchart for language analysis. In transition diagram the boxes of flowchart are drawn as circle and called as states. States are connected by arrows called as edges. The label or weight on edge indicates the input character that can appear after that state.
Transition diagram of identifier is given below:
This transition diagram for identifier reading first letter and after that letter or digit until the next input character is delimiter for identifier, means the character that is neither letter nor digit. To turn up the transition diagram into a program we construct the program segment code for each state of transition diagram.
Program segment code for each state is given below:
State-0:
C=GETCHAR();
if LETTER(C) then goto State 1
else FAIL() 
State-1:
C=GETCHAR();
if LETTER(C) OR DIGIT(C) then goto State 1
else if DELIMITER(C) then goto State 2
else FAIL() 
State-2:
RETRACT();
RETURN(ID, INSTALL())
Where,Next character for input buffer we use GETCHAR() which return next character.LETTER(C) is a procedure which returns the true value if and only if C is a letter.FAIL(C) is a routine which RETRACT the look ahead pointer and start up the next transition diagram otherwise call error routine.DIGIT(C) is a procedure which returns the true value if and only if C is a digit.DELIMITER(C) is a procedure which returns the true value if and only if C Is a character that could follow the identifier for example blank symbol, arithmetic, logical operator, left parenthesis, right parenthesis, +, :, ; etc.Because DELIMITER is not part of identifier therefore we must RETRACT the look ahead pointer one character for this purpose we use the RETRACT() procedure .Because identifier has a value so to install the value of identifier in symbol table we use INSTALL() procedure.
Compiler Design
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Directed Acyclic graph in Compiler Design (with examples)
Type Checking in Compiler Design
Data flow analysis in Compiler
S - attributed and L - attributed SDTs in Syntax directed translation
Runtime Environments in Compiler Design
Compiler construction tools
Basic Blocks in Compiler Design
Token, Patterns, and Lexems
Compiler Design - Variants of Syntax Tree
Loop Optimization in Compiler Design
Python | Inverse Sorting String

11 May, 2020
Sometimes, while participating in a competitive programming test, we can be encountered with a problem in which we require to sort a pair in opposite orders by indices. This particular article focuses on solving a problem in which we require to sort the number in descending order and then the String in increasing order. This is the type of problem which is common in the sorting of pairs. Let’s discuss a way in which this can be solved.
Method : Using sorted() + lambdaThe combination of these functions can be used to perform this task. In these, we pass to lambda function the negative of the values so that the increasing order of number is evaluated as decreasing and hence a successful hack to perform this task.
# Python3 code to demonstrate working of# Inverse sorting String, Integer tuple list# Using sorted() + lambda  # initializing listtest_list = [("Geeks", 5), ("For", 3), ("Geeks", 6), ("Is", 5),              ("Best", 7 ), ("For", 5), ("CS", 3)]  # printing original listprint("The original list is : " + str(test_list))  # Inverse sorting String, Integer tuple list# Using sorted() + lambdares = sorted(test_list, key = lambda sub: (-sub[1], sub[0]))  # printing result print("The list after inverse sorted tuple elements : " + str(res))
The original list is : [(‘Geeks’, 5), (‘For’, 3), (‘Geeks’, 6), (‘Is’, 5), (‘Best’, 7), (‘For’, 5), (‘CS’, 3)]The list after inverse sorted tuple elements : [(‘Best’, 7), (‘Geeks’, 6), (‘For’, 5), (‘Geeks’, 5), (‘Is’, 5), (‘CS’, 3), (‘For’, 3)]
Python list-programs
Python-sort
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Create a directory in Python