code-rag-bench/online-tutorials huggingface dataset:
Electron - Debugging

We have two processes that run our application – the main process and the renderer process.
Since the renderer process is the one being executed in our browser window, we can use the Chrome Devtools to debug it. To open DevTools, use the shortcut "Ctrl+Shift+I" or the <F12> key. You can check out how to use devtools here.
When you open the DevTools, your app will look like as shown in the following screenshot −
The DevTools in an Electron browser window can only debug JavaScript that is executed in that window (i.e., the web pages). To debug JavaScript that is executed in the main process you will need to use an external debugger and launch Electron with the --debug or the --debug-brk switch.
Electron will listen for the V8 debugger protocol messages on the specified port; an external debugger will need to connect on this port. The default port is 5858.
Run your app using the following −
$ electron --debug = 5858 ./main.js

Now you will need a debugger that supports the V8 debugger protocol. You can use VSCode or node-inspector for this purpose. For example, let us follow these steps and set up VSCode for this purpose. Follow these steps to set it up −
Download and install VSCode. Open your Electron project in VSCode.
Add a file .vscode/launch.json with the following configuration −
{
   "version": "1.0.0",
   "configurations": [
      {
         "name": "Debug Main Process",
         "type": "node",
         "request": "launch",
         "cwd": "${workspaceRoot}",
         "runtimeExecutable": "${workspaceRoot}/node_modules/.bin/electron",
         "program": "${workspaceRoot}/main.js"
      }
   ]
}
Note − For Windows, use "${workspaceRoot}/node_modules/.bin/electron.cmd" for runtimeExecutable.
Set some breakpoints in main.js, and start debugging in the Debug View. When you hit the breakpoints, the screen will look something like this −
The VSCode debugger is very powerful and will help you rectify errors quickly. You also have other options like node-inspector for debugging electron apps.

    251 Lectures 
     35.5 hours 

 Gowthami Swarna

    9 Lectures 
     41 mins

 Ashraf Said

    8 Lectures 
     32 mins

 Ashraf Said

    25 Lectures 
     1 hours 

 Ashraf Said

    17 Lectures 
     1 hours 

 Ashraf Said

    8 Lectures 
     25 mins

 Ashraf Said
 Print
 Add Notes
 Bookmark this page
What is an anonymous function in JavaScript?

A function expression is similar to and has the same syntax as a function
declaration One can define "named" function expressions (where the name of the expression might be used in the call stack for example) or "anonymous" function expressions.
An example of an anonymous function expression (the name is not used) −
var myFunction = function() {
   // Function code
}
This function can be invoked using the variable name referring to it −
myFunction()
In conclusion, an anonymous function is a function that is not stored but is associated with a variable. Anonymous functions can accept inputs and return outputs, just as standard functions
Sort the Matrix Diagonally in C++

Suppose we have N x M matrix, we have to sort this diagonally in increasing order from top-left to the bottom right. So if the matrix is like −
The output matrix will be −
To solve this, we will follow these steps −
Define a method called solve(), this will take si, sj and matrix mat
Define a method called solve(), this will take si, sj and matrix mat
n := number of rows and m := number of columns
n := number of rows and m := number of columns
make an array called temp
make an array called temp
i:= si and j := sj, and index := 0
i:= si and j := sj, and index := 0
while i < n and j < minsert m[i, j] into temp, then increase i and j by 1
while i < n and j < m
insert m[i, j] into temp, then increase i and j by 1
insert m[i, j] into temp, then increase i and j by 1
sort temp array
sort temp array
set index := 0, i := si and j := sj
set index := 0, i := si and j := sj
while i < n and j < mmat[i, j] := temp[index]increase i, j and index by 1
while i < n and j < m
mat[i, j] := temp[index]
mat[i, j] := temp[index]
increase i, j and index by 1
increase i, j and index by 1
from the main method, do the following −
from the main method, do the following −
n := number of rows and m := number of columns
n := number of rows and m := number of columns
for i in range 0 to n – 1solve(i, 0, mat)
for i in range 0 to n – 1
solve(i, 0, mat)
solve(i, 0, mat)
for j in range 1 to m – 1solve(0, j, mat)
for j in range 1 to m – 1
solve(0, j, mat)
solve(0, j, mat)
return mat
return mat
Let us see the following implementation to get a better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<vector<auto> > v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
      cout << "[";
      for(int j = 0; j <v[i].size(); j++){
         cout << v[i][j] << ", ";
      }
      cout << "],";
   }
   cout << "]"<<endl;
}
class Solution {
public:
   void solve(int si, int sj, vector < vector <int> > &mat){
      int n = mat.size();
      int m = mat[0].size();
      vector <int> temp;
      int i = si;
      int j = sj;
      int idx = 0;
      while(i < n && j < m){
         temp.push_back(mat[i][j]);
         i++;
         j++;
      }
      sort(temp.begin(), temp.end());
      idx = 0;
      i = si;
      j = sj;
      while(i < n && j < m){
         mat[i][j] = temp[idx];
         i++;
         j++;
         idx++;
      }
   }
   vector<vector<int>> diagonalSort(vector<vector<int>>& mat) {
      int n = mat.size();
      int m = mat[0].size();
      for(int i = 0; i <n; i++){
         solve(i, 0, mat);
      }
      for(int j = 1; j < m; j++){
         solve(0, j, mat);
      }
      return mat;
   }
};
main(){
   vector<vector<int>> v = {{3,3,1,1},{2,2,1,2},{1,1,1,2}};
   Solution ob;
   print_vector(ob.diagonalSort(v));
}
[[3,3,1,1],[2,2,1,2],[1,1,1,2]]
[[1,1,1,1],[1,2,2,2],[1,2,3,3]]
How to insert an item in a list at a given position in C#?

To insert an item in an already created List, use the Insert() method.
Firstly, set elements −
List <int> list = new List<int>();
list.Add(989);
list.Add(345);
list.Add(654);
list.Add(876);
list.Add(234);
list.Add(909);
Now, let’s say you need to insert an item at 4th position. For that, use the Insert() method −
// inserting element at 4th position
list.Insert(3, 567);
Let us see the complete example −
using System;
using System.Collections.Generic;

namespace Demo {
   public class Program {
      public static void Main(string[] args) {
         List < int > list = new List < int > ();

         list.Add(989);
         list.Add(345);
         list.Add(654);
         list.Add(876);
         list.Add(234);
         list.Add(909);

         Console.WriteLine("Count: {0}", list.Count);

         Console.Write("List: ");
         foreach(int i in list) {
            Console.Write(i + " ");
         }
         // inserting element at 4th position
         list.Insert(3, 567);
         Console.Write("\nList after inserting a new element: ");
         foreach(int i in list) {
            Console.Write(i + " ");
         }
         Console.WriteLine("\nCount: {0}", list.Count);
      }
   }
}
Python 3 - continue statement

The continue statement in Python returns the control to the beginning of the current loop. When encountered, the loop starts next iteration without executing the remaining statements in the current iteration.
The continue statement can be used in both while and for loops.
continue

#!/usr/bin/python3

for letter in 'Python':     # First Example
   if letter == 'h':
      continue
   print ('Current Letter :', letter)

var = 10                    # Second Example
while var > 0:              
   var = var -1
   if var == 5:
      continue
   print ('Current variable value :', var)
print ("Good bye!")
When the above code is executed, it produces the following result −
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : o
Current Letter : n
Current variable value : 9
Current variable value : 8
Current variable value : 7
Current variable value : 6
Current variable value : 4
Current variable value : 3
Current variable value : 2
Current variable value : 1
Current variable value : 0
Good bye!


    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
Solidity - if...else if... statement.

The if...else if... statement is an advanced form of if...else that allows Solidity to make a correct decision out of several conditions.
The syntax of an if-else-if statement is as follows −
if (expression 1) {
   Statement(s) to be executed if expression 1 is true
} else if (expression 2) {
   Statement(s) to be executed if expression 2 is true
} else if (expression 3) {
   Statement(s) to be executed if expression 3 is true
} else {
   Statement(s) to be executed if no expression is true
}

There is nothing special about this code. It is just a series of if statements, where each if is a part of the else clause of the previous statement. Statement(s) are executed based on the true condition, if none of the conditions is true, then the else block is executed.
pragma solidity ^0.5.0;

contract SolidityTest {
   uint storedData; // State variable
   constructor() public {
      storedData = 10;   
   }
   function getResult() public view returns(string memory) {
      uint a = 1; 
      uint b = 2;
      uint c = 3;
      uint result
      
      if( a > b && a > c) {   // if else statement
         result = a;
      } else if( b > a && b > c ){
         result = b;
      } else {
         result = c;
      }       
      return integerToString(result); 
   }
   function integerToString(uint _i) internal pure 
      returns (string memory) {
      
      if (_i == 0) {
         return "0";
      }
      uint j = _i;
      uint len;
      
      while (j != 0) {
         len++;
         j /= 10;
      }
      bytes memory bstr = new bytes(len);
      uint k = len - 1;
      
      while (_i != 0) {
         bstr[k--] = byte(uint8(48 + _i % 10));
         _i /= 10;
      }
      return string(bstr);//access local variable
   }
}
Run the above program using steps provided in Solidity First Application chapter.
0: string: 3


    38 Lectures 
     4.5 hours 

 Abhilash Nelson

    62 Lectures 
     8.5 hours 

 Frahaan Hussain

    31 Lectures 
     3.5 hours 

 Swapnil Kole
 Print
 Add Notes
 Bookmark this page
How to prevent loops going into infinite mode in Python?

Loops formed with for statement in Python traverse one item at a time in a collection. Hence there is less likelihood of for loop becoming infinite.
The while loop however needs to be controlled by making some provision inside the body of the loop to drive the condition mentioned in the beginning to false.This is usually done by keeping count of iterations
x=0
while x<5:
   x=x+1
   print (x)
Loop repetition can also be controlled by using break to take an early exit from the iterations
while True:
   stmt1
   stmt2
   if expr==True: break
   stmt3
   ..
Remove spaces from column names in Pandas - GeeksforGeeks

29 Aug, 2020
Removing spaces from column names in pandas is not very hard we easily remove spaces from column names in pandas using replace() function. We can also replace space with another character. Let’s see the example of both one by one.
Example 1: remove the space from column name
Python
# import pandasimport pandas as pd  # create data frameData = {'Employee Name': ['Mukul', 'Rohan', 'Mayank',                          'Shubham', 'Aakash'],                  'Location': ['Saharanpur', 'Meerut', 'Agra',                      'Saharanpur', 'Meerut'],                  'Sales Code': ['muk123', 'roh232', 'may989',                       'shu564', 'aka343']}  df = pd.DataFrame(Data)  # print original data frameprint(df)  # remove special characterdf.columns = df.columns.str.replace(' ', '')  # print file after removing special characterprint("\n\n", df)
Output:
Example 2: replace space with another character
Python
# import pandasimport pandas as pd  # create data frameData = {'Employee Name': ['Mukul', 'Rohan', 'Mayank',                          'Shubham', 'Aakash'],                  'Location': ['Saharanpur', 'Meerut', 'Agra',                      'Saharanpur', 'Meerut'],                  'Sales Code': ['muk123', 'roh232', 'may989',                       'shu564', 'aka343']}  df = pd.DataFrame(Data)  # print original data frameprint(df)  # replace space with another characterdf.columns = df.columns.str.replace(' ', '_')  # print file after removing special characterprint("\n\n", df)
Output:
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Reading and Writing to text files in Python
sum() function in Python
Create a Pandas DataFrame from Lists
Draw a triangle in C++ graphics - GeeksforGeeks

02 Sep, 2020
Prerequisite: graphics.h, How to include graphics.h in CodeBlocks?
The task is to write a C program to make a triangle with the line function of graphics.
To run the program we have to include the below header file:
#include <graphic.h>

Approach: The idea is to create a triangle with the help of several lines. We will draw a line in graphics by passing 4 numbers to line() function as:
line(a, b, c, d)The above function will draw a line from coordinates (a, b) to (c, d) in the output window. 
Below is the implementation of the above approach:
C++
// C++ program for drawing a triangle#include <graphics.h>#include <iostream>  // Driver codeint main(){    // gm is Graphics mode which    // is a computer display    // mode that generates    // image using pixels.    // DETECT is a macro    // defined in "graphics.h"    // header file    int gd = DETECT, gm;      // initgraph initializes    // the graphics system    // by loading a graphics    // driver from disk    initgraph(&gd, &gm, "");      // Triangle      // line for x1, y1, x2, y2    line(150, 150, 450, 150);      // line for x1, y1, x2, y2    line(150, 150, 300, 300);      // line for x1, y1, x2, y2    line(450, 150, 300, 300);      // closegraph function closes    // the graphics mode and    // deallocates all memory    // allocated by graphics system    getch();      // Close the initialized gdriver    closegraph();}
Output:Below is the output of the above program:
computer-graphics
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Operator Overloading in C++
Iterators in C++ STL
Friend class and function in C++
Polymorphism in C++
Sorting a vector in C++
Convert string to char array in C++
List in C++ Standard Template Library (STL)
Inline Functions in C++
std::string class in C++
Destructors in C++
C++ Algorithm Library - includes() Function

The C++ function std::algorithm::includes() test whether first set is subset of another or not. This member function expects elements in sorted order. It use operator< for comparison.
Following is the declaration for std::algorithm::includes() function form std::algorithm header.
template <class InputIterator1, class InputIterator2>
bool includes(InputIterator1 first1, InputIterator1 last1,
   InputIterator2 first2, InputIterator2 last2);

first1 − Input iterator to the initial position of the first sequence.
first1 − Input iterator to the initial position of the first sequence.
last1 − Input iterator to the final position of the first sequence.
last1 − Input iterator to the final position of the first sequence.
first2 − Input iterator to the initial position of the second sequence.
first2 − Input iterator to the initial position of the second sequence.
last2 − Input iterator to the final position of the second sequence.
last2 − Input iterator to the final position of the second sequence.
Returns true if first set is subset of another otherwise returns false.
Throws exception if element comparison or an operation on an iterator throws exception.
Please note that invalid parameters cause undefined behavior.
Linear.
The following example shows the usage of std::algorithm::includes() function.
#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

int main(void) {
   vector<int> v1 = {1, 2, 3, 4, 5};
   vector<int> v2 = {3, 4, 5};
   bool result;

   result = includes(v1.begin(), v1.end(), v2.begin(), v2.end());

   if (result == true)
      cout << "Vector v2 is subset of v1" << endl;

   v2 = {10};

   result = includes(v1.begin(), v1.end(), v2.begin(), v2.end());

   if (result == false)
      cout << "Vector v2 is not subset of v1" << endl;

   return 0;
}
Let us compile and run the above program, this will produce the following result −
Vector v2 is subset of v1
Vector v2 is not subset of v1

 Print
 Add Notes
 Bookmark this page
Select the date records between two dates in MySQL

To select the date records between two dates, you need to use the BETWEEN keyword. Let us first create a table −
mysql> create table DemoTable681(AdmissionDate datetime);
Query OK, 0 rows affected (0.75 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable681 values('2019-01-21');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable681 values('2019-11-01');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable681 values('2019-12-03');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable681 values('2019-07-03');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable681 values('2019-02-04');
Query OK, 1 row affected (0.34 sec)
Display all records from the table using select statement:
mysql> select *from DemoTable681;
This will produce the following output −
+---------------------+
| AdmissionDate       |
+---------------------+
| 2019-01-21 00:00:00 |
| 2019-11-01 00:00:00 |
| 2019-12-03 00:00:00 |
| 2019-07-03 00:00:00 |
| 2019-02-04 00:00:00 |
+---------------------+
5 rows in set (0.00 sec)
Following is the query to select the date records between two dates −
mysql> select *from DemoTable681 where AdmissionDate between '2019-02-01' and '2019-12-01';
This will produce the following output −
+---------------------+
| AdmissionDate       |
+---------------------+
| 2019-11-01 00:00:00 |
| 2019-07-03 00:00:00 |
| 2019-02-04 00:00:00 |
+---------------------+
3 rows in set (0.00 sec)
Multi-Line printing in Python

We have usually seen the print command in python printing one line of output. But if we have multiple lines to print, then in this approach multiple print commands need to be written. This can be avoided by using another technique involving the three single quotes as seen below.
 Live Demo
print('''
Motivational Quote :\n
Sometimes later becomes never, Do it now.
Great things never come from comfort zones.
The harder you work for something, the greater you'll feel when you achieve it.
''')

Running the above code gives us the following result:
Motivational Quote :

Sometimes later becomes never, Do it now.
Great things never come from comfort zones.
The harder you work for something, the greater you'll feel when you achieve it.
We can use multiline printing to produce nicely formatted text also as seen below.
print('''
===========================================
||                                       ||
|| WORK                                  ||
|| HARD                                  ||
||                                       ||
||                                       ||
||                                       ||
===========================================
''')

Running the above code gives us the following result:
=============================
||                         ||
|| WORK                    ||
|| HARD                    ||
||                         ||
||                         ||
||                         ||
=============================
MongoDB query to group by _id

To group by _id in MongoDB, use $group. Let us create a collection with documents −
> db.demo529.insertOne({"Score":10});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e8b1d5bef4dcbee04fbbbe4")
}
> db.demo529.insertOne({"Score":20});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e8b1d5fef4dcbee04fbbbe5")
}
> db.demo529.insertOne({"Score":10});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e8b1d61ef4dcbee04fbbbe6")
}
> db.demo529.insertOne({"Score":10});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e8b1d62ef4dcbee04fbbbe7")
}
Display all documents from a collection with the help of find() method −
> db.demo529.find();
This will produce the following output −
{ "_id" : ObjectId("5e8b1d5bef4dcbee04fbbbe4"), "Score" : 10 }
{ "_id" : ObjectId("5e8b1d5fef4dcbee04fbbbe5"), "Score" : 20 }
{ "_id" : ObjectId("5e8b1d61ef4dcbee04fbbbe6"), "Score" : 10 }
{ "_id" : ObjectId("5e8b1d62ef4dcbee04fbbbe7"), "Score" : 10 }
Following is the query to group by _id −
> db.demo529.aggregate( [
... {
...    $group: {
...       _id: null,
...       count: { $sum: 1 }
...    }
... }
... ] )
This will produce the following output −
{ "_id" : null, "count" : 4 }
C# program to list the difference between two lists

To get the difference between two lists, firstly set two lists in C# −
// first list
List < string > list1 = new List < string > ();
list1.Add("A");
list1.Add("B");
list1.Add("C");
list1.Add("D");

// second list
List < string > list2 = new List < string > ();
list2.Add("C");
list2.Add("D");
foreach(string value in list2) {
   Console.WriteLine(value);
}
To get the difference, use IEnumerable and Except() as shown below. The difference is shown in the third list −
IEnumerable < string > list3;
list3 = list1.Except(list2);
The following is the complete code −
 Live Demo
using System;
using System.Collections.Generic;
using System.Linq;

public class Demo {
   public static void Main() {
      List < string > list1 = new List < string > ();
      list1.Add("A");
      list1.Add("B");
      list1.Add("C");
      list1.Add("D");

      Console.WriteLine("First list...");
      foreach(string value in list1) {
         Console.WriteLine(value);
      }

      Console.WriteLine("Second list...");
      List < string > list2 = new List < string > ();

      list2.Add("C");
      list2.Add("D");
      foreach(string value in list2) {
         Console.WriteLine(value);
      }

      Console.WriteLine("Difference in the two lists...");
      IEnumerable < string > list3;
      list3 = list1.Except(list2);
      foreach(string value in list3) {
         Console.WriteLine(value);
      }

   }
}
First list...
A
B
C
D
Second list...
C
D
Difference in the two lists...
A
B
How to set the left position of a positioned element with JavaScript?

Use the left property to set the left position of a positioned element, such as a button.
You can try to run the following code to set the left position of a positioned element with JavaScript −
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <style>
         #myID {
            position: absolute;
         }
      </style>
   </head>
   <body>
      <h1>Heading 1</h1>
      <p>This is Demo Text.</p>
      <button type="button" id="myID" onclick="display()">Change Left Position</button>
      <script>
         function display() {
            document.getElementById("myID").style.left = "150px";
         }
      </script>
   </body>
</html>
strcat() function in C/C++ with Example - GeeksforGeeks

14 Oct, 2021
In C/C++, strcat() is a predefined function used for string handling, under string library (string.h in C, and cstring in C++).
This function appends the string pointed to by src to the end of the string pointed to by dest. It will append a copy of the source string in the destination string. plus a terminating Null character. The initial character of the string(src) overwrites the Null-character present at the end of the string(dest).
The behavior is undefined if:
the destination array is not large enough for the contents of both src and dest and the terminating null character
if the string overlaps.
if either dest or src is not a pointer to a null-terminated byte string.
Syntax:
char *strcat(char *dest, const char *src)
Parameters: The method accepts the following parameters:
dest: This is a pointer to the destination array, which should contain a C string, and should be large enough to contain the concatenated resulting string.
src: This is the string to be appended. This should not overlap the destination.
Return value: The strcat() function returns dest, the pointer to the destination string.
Application: Given two strings src and dest in C++, we need to append string pointed by src to the end of the string pointed by dest.
Examples:
Input: src = "ForGeeks"
       dest = "Geeks"
Output: "GeeksForGeeks"

Input: src = "World"
       dest = "Hello "
Output: "Hello World"
Below is the C program to implement the above approach:
C
// C program to implement// the above approach#include <stdio.h>#include <string.h>  // Driver codeint main(int argc,         const char* argv[]){    // Define a temporary variable    char example[100];      // Copy the first string into    // the variable    strcpy(example, "Geeks");      // Concatenate this string    // to the end of the first one    strcat(example, "ForGeeks");      // Display the concatenated strings    printf("%s\n", example);      return 0;}
GeeksForGeeks

Note: The target string should be made big enough to hold the final string.
C-Functions
C-String
CPP-Functions
cpp-strings-library
TrueGeek-2021
C Language
C++
TrueGeek
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
TCP Server-Client implementation in C
Exception Handling in C++
Multithreading in C
Arrow operator -> in C/C++ with Examples
'this' pointer in C++
Vector in C++ STL
Initialize a vector in C++ (6 different ways)
Map in C++ Standard Template Library (STL)
Inheritance in C++
Constructors in C++
MongoDB checking for not null?

Use $ne to check for not null. Let us create a collection with documents −
> db.demo764.insertOne({"LoginUserName":"Chris","LoginPassword":"Chris_12"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5eb04ee55637cd592b2a4afc")
}
> db.demo764.insertOne({"LoginUserName":"Chris","LoginPassword":null});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5eb04eee5637cd592b2a4afd")
}
> db.demo764.insertOne({"LoginUserName":"Chris","LoginPassword":""});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5eb04ef35637cd592b2a4afe")
}
Display all documents from a collection with the help of find() method −
> db.demo764.find();
This will produce the following output −
{ "_id" : ObjectId("5eb04ee55637cd592b2a4afc"), "LoginUserName" : "Chris", "LoginPassword" : "Chris_12" }
{ "_id" : ObjectId("5eb04eee5637cd592b2a4afd"), "LoginUserName" : "Chris", "LoginPassword" : null }
{ "_id" : ObjectId("5eb04ef35637cd592b2a4afe"), "LoginUserName" : "Chris", "LoginPassword" : "" }
Following is the query to check for not null −
> db.demo764.find({"LoginUserName":"Chris","LoginPassword" : { '$ne': null } });
This will produce the following output −
{ "_id" : ObjectId("5eb04ee55637cd592b2a4afc"), "LoginUserName" : "Chris", "LoginPassword" : "Chris_12" }
{ "_id" : ObjectId("5eb04ef35637cd592b2a4afe"), "LoginUserName" : "Chris", "LoginPassword" : "" }
How to Create Pivot Tables in R? - GeeksforGeeks

19 Dec, 2021
In this article, we will discuss how to create the pivot table in the R Programming Language.
The Pivot table is one of Microsoft Excel’s most powerful features that let us extract the significance from a large and detailed data set. A Pivot Table often shows some statistical value about the dataset by grouping some values from a column together, To do so in the R programming Language, we use the group_by() and the summarize() function of the dplyr package library. The dplyr package in the R Programming Language is a structure of data manipulation that provides a uniform set of verbs that help us in preprocessing large data. The group_by() function groups the data using one or more variables and then summarize function creates the summary of data by those groups using aggregate function passed to it.
Syntax:
df %>% group_by( grouping_variables) %>% summarize( label = aggregate_fun() )
Parameter:
df: determines the data frame in use.
grouping_variables: determine the variable used to group data.
aggregate_fun(): determines the function used for summary. for example, sum, mean, etc.
Example 1: Create pivot tables
R
# create sample data framesample_data <- data.frame(label=c('Geek1', 'Geek2', 'Geek3', 'Geek1',                                   'Geek2', 'Geek3', 'Geek1', 'Geek2',                                  'Geek3'),                             value=c(222, 18, 51, 52, 44, 19, 100, 98, 34))  # load library dplyrlibrary(dplyr)  # create pivot table with sum of value as summarysample_data %>% group_by(label) %>% summarize(sum_values = sum(value))
Output:
# A tibble: 3 x 2
 label sum_values
 <chr>      <dbl>
1 Geek1        374
2 Geek2        160
3 Geek3        104
Example 2: Create pivot table
R
# create sample data framesample_data <- data.frame(label=c('Geek1', 'Geek2', 'Geek3', 'Geek1',                                   'Geek2', 'Geek3', 'Geek1', 'Geek2',                                  'Geek3'),                             value=c(222, 18, 51, 52, 44, 19, 100, 98, 34))  # load library dplyrlibrary(dplyr)  # create pivot table with sum of value as summarysample_data %>% group_by(label) %>% summarize(average_values = mean(value))
Output:
# A tibble: 3 x 2
 label average_values
 <chr>          <dbl>
1 Geek1          125.  
2 Geek2           53.3
3 Geek3           34.7
Picked
R Dplyr
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
Replace Specific Characters in String in R
How to filter R dataframe by multiple conditions?
R - if statement
How to import an Excel File into R ?
Time Series Analysis in R
Class or Static Variables in Python?

When we declare a variable inside a class but outside any method, it is called as class or static variable in python.
Class or static variable can be referred through a class but not directly through an instance.
Class or static variable are quite distinct from and does not conflict with any other member variable with the same name. Below is a program to demonstrate the use of class or static variable −
class Fruits(object):
count = 0
def __init__(self, name, count):
self.name = name
self.count = count
Fruits.count = Fruits.count + count

def main():
apples = Fruits("apples", 3);
pears = Fruits("pears", 4);
print (apples.count)
print (pears.count)
print (Fruits.count)
print (apples.__class__.count) # This is Fruit.count
print (type(pears).count) # So is this

if __name__ == '__main__':
main()
3
4
7
7
7
Another example to demonstrate the use of variable defined on the class level −
class example:
staticVariable = 9 # Access through class

print (example.staticVariable) # Gives 9

#Access through an instance
instance = example()
print(instance.staticVariable) #Again gives 9

#Change within an instance
instance.staticVariable = 12
print(instance.staticVariable) # Gives 12
print(example.staticVariable) #Gives 9
9
9
12
9
C library function - atof()

The C library function double atof(const char *str) converts the string argument str to a floating-point number (type double).
Following is the declaration for atof() function.
double atof(const char *str)
str − This is the string having the representation of a floating-point number.
str − This is the string having the representation of a floating-point number.
This function returns the converted floating point number as a double value. If no valid conversion could be performed, it returns zero (0.0).
The following example shows the usage of atof() function.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main () {
   float val;
   char str[20];
   
   strcpy(str, "98993489");
   val = atof(str);
   printf("String value = %s, Float value = %f\n", str, val);

   strcpy(str, "tutorialspoint.com");
   val = atof(str);
   printf("String value = %s, Float value = %f\n", str, val);

   return(0);
}
Let us compile and run the above program that will produce the following result −
String value = 98993489, Float value = 98993488.000000
String value = tutorialspoint.com, Float value = 0.000000


    12 Lectures 
     2 hours 

 Nishant Malik

    12 Lectures 
     2.5 hours 

 Nishant Malik

    48 Lectures 
     6.5 hours 

 Asif Hussain

    12 Lectures 
     2 hours 

 Richa Maheshwari

    20 Lectures 
     3.5 hours 

 Vandana Annavaram

    44 Lectures 
     1 hours 

 Amit Diwan
 Print
 Add Notes
 Bookmark this page
jQuery.getScript() Method

The jQuery.getScript( url, [callback] ) method loads and executes a JavaScript file using an HTTP GET request.
The method returns XMLHttpRequest object.
Here is the simple syntax to use this method −
$.getScript( url, [callback] )

Here is the description of all the parameters used by this method −
url − A string containing the URL to which the request is sent
url − A string containing the URL to which the request is sent
callback − This optional parameter represents a function to be executed whenever the data is loaded successfully.
callback − This optional parameter represents a function to be executed whenever the data is loaded successfully.
Assuming we have following JavaScript content in result.js file −
function CheckJS(){
   alert("This is JavaScript");
}
Following is a simple example a simple showing the usage of this method −
<html>
   <head>
      <title>The jQuery Example</title>
      <script type = "text/javascript" 
         src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
      </script>
		
      <script type = "text/javascript" language = "javascript">
         $(document).ready(function() {
			
            $("#driver").click(function(event){
               $.getScript('result.js', function(jd) {
                  // Call custom function defined in script
                  CheckJS();
               });
            });
				
         });
      </script>
   </head>
	
   <body>
      <p>Click on the button to load result.js file −</p>
		
      <div id = "stage" style = "background-color:cc0;">
         STAGE
      </div>
		
      <input type = "button" id = "driver" value = "Load Data" />
   </body>
</html>
This should produce following result −
Click on the button to load result.js file −

    27 Lectures 
     1 hours 

 Mahesh Kumar

    27 Lectures 
     1.5 hours 

 Pratik Singh

    72 Lectures 
     4.5 hours 

 Frahaan Hussain

    60 Lectures 
     9 hours 

 Eduonix Learning Solutions

    17 Lectures 
     2 hours 

 Sandip Bhattacharya

    12 Lectures 
     53 mins

 Laurence Svekis
 Print
 Add Notes
 Bookmark this page
Private Constructors and Singleton Classes in C#

A private constructor is used in classes containing only static member as shown below −
class Demo {
   // private constructor
   private Demo() { }

   public static a = 10;
}
A singleton class has normal methods and you can call it using an instance.
To prevent multiple instances of the class, the private constructor is used.
Let us see an example −
public class Singleton {
   static Singleton a = null;
   private Singleton() {
   }
}
How to Change the position of MessageBox using Python Tkinter

Let us suppose that we want to create a dialogue box using tkinter. To create the
dialogue box we can use the MessageBox library which contains several functions
to quickly create dialogue types.
To adjust the position of the created Dialogue Box, we can use its “toplevel”
property which basically gives the priority to the current box and keeps all the other
processes in the backend.
It contains some other functions like title, message, and details. To change the position of the MessageBox widget, we will use geometry method.
#import the tkinter library

from tkinter import *

#define the messagebox function
def messagebox():

#toplevel function creates MessageBox dialog which appears on top of the screen
   top=Toplevel(win)
   top.title("Click Me")
   #Define the position of the MessageBox
   x_position = 600
   y_position = 400
   top.geometry(f"600x200+{x_position}+{y_position}")
   #Define the property of the messageBox
   l1=Label(top, text= "Hello! TutorialsPoint",bg= "green", fg=
"white",font=('Times New Roman', 24),height=50, width= 50).pack()

#Create an instance of the tkinter frame
#And resize the frame
win = Tk()
win.geometry("600x200")
win.title("Window-1")
Button(win, text="Click Me", command=messagebox,
width=8).pack(pady=80)

win.mainloop()
Running the above code will generate the following output window.
When you click the “Click Me” button, it will open the following dialogue box which
can be positioned later.
Java Program to convert integer to hexadecimal

Use the + Integer.toHexString() method in Java to convert integer to hexadecimal.
Let’s say the following is our integer.
int val = 768;
Let us convert it to a hexadecimal value.
Integer.toHexString(val)
The following is the final example with the output.
 Live Demo
public class Demo {
    public static void main(String[] args) {
       int val = 768;
       // integer
       System.out.println("Integer: "+val);
       // hex
       System.out.println("Hex String = " + Integer.toHexString(val));
    }
}
Integer: 768
Hex String = 300
How to avoid inserting duplicate rows in MySQL?

To avoid inserting duplicate rows in MySQL, you can use UNIQUE(). The syntax is as follows −
ALTER TABLE yourTableName ADD UNIQUE(yourColumnName1,yourColumnName2,...N);
To understand the above syntax, let us create a table. 
The query to create a table is as follows −
mysql> create table avoidInsertingDuplicateRows
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> FirstValue int,
   -> SecondValue int
   -> );
Query OK, 0 rows affected (0.53 sec)
Now check the description of table using desc command. 
The query is as follows −
mysql> desc avoidInsertingDuplicateRows;
Sample The following is The output −
+-------------+---------+------+-----+---------+----------------+
| Field       | Type    | Null | Key | Default | Extra          |
+-------------+---------+------+-----+---------+----------------+
| Id          | int(11) | NO   | PRI | NULL    | auto_increment |
| FirstValue  | int(11) | YES  |     | NULL    |                |
| SecondValue | int(11) | YES  |     | NULL    |                |
+-------------+---------+------+-----+---------+----------------+
3 rows in set (0.00 sec)
Here is the query to avoid inserting duplicate rows in MySQL. We will set it with the insert command to insert records in the table −
mysql> insert into avoidInsertingDuplicateRows(FirstValue,SecondValue) values(10,20);
Query OK, 1 row affected (0.24 sec)
mysql> insert into avoidInsertingDuplicateRows(FirstValue,SecondValue) values(10,20);
ERROR 1062 (23000): Duplicate entry '10-20' for key 'FirstValue'
Display all records from the table using select statement. 
The query is as follows −
mysql> select *from avoidInsertingDuplicateRows;
Here is the output −
+----+------------+-------------+
| Id | FirstValue | SecondValue |
+----+------------+-------------+
| 1  | 10         | 20          |
+----+------------+-------------+
1 row in set (0.00 sec)
Swing Examples - Using Checkboxes

Following example showcase how to use standard checkboxes in a Java Swing application.
We are using the following APIs.
JCheckBox − To create a standard checkbox.
JCheckBox − To create a standard checkbox.
JCheckBox.setEnabled(false); − To disable a checkbox.
JCheckBox.setEnabled(false); − To disable a checkbox.
JCheckBox.setMnemonic(KeyEvent.VK_C) − To set a keyboard shortcut a checkbox.
JCheckBox.setMnemonic(KeyEvent.VK_C) − To set a keyboard shortcut a checkbox.
JCheckBox.setSelected(true) − To set a checkbox selected.
JCheckBox.setSelected(true) − To set a checkbox selected.
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;

import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class SwingTester {
   public static void main(String[] args) {
      createWindow();
   }

   private static void createWindow() {    
      JFrame frame = new JFrame("Swing Tester");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      createUI(frame);
      frame.setSize(560, 200);      
      frame.setLocationRelativeTo(null);  
      frame.setVisible(true);
   }

   private static void createUI(final JFrame frame){  
      JPanel panel = new JPanel();
      LayoutManager layout = new FlowLayout();  
      panel.setLayout(layout);       

      JCheckBox checkBox1 = new JCheckBox("Check Me 1");
      JCheckBox checkBox2 = new JCheckBox("Check Me 2");
      checkBox2.setEnabled(false);
      JCheckBox checkBox3 = new JCheckBox("Check Me 3");
      checkBox3.setMnemonic(KeyEvent.VK_C);

      checkBox1.addActionListener(new ActionListener() {
         @Override
         public void actionPerformed(ActionEvent e) {
            Object source = e.getSource();
            JOptionPane.showMessageDialog(frame, 
               ((JCheckBox)source).getText() + ": " + ((JCheckBox)source).isSelected());
         }
      });  

      panel.add(checkBox1);
      panel.add(checkBox2);
      panel.add(checkBox3);

      frame.getContentPane().add(panel, BorderLayout.CENTER);    
   }
}
 Print
 Add Notes
 Bookmark this page
How to setup Anaconda path to environment variable ? - GeeksforGeeks

06 Nov, 2021
Anaconda is open-source software that contains Jupyter, spyder, etc that are used for large data processing, data analytics, heavy scientific computing. Anaconda works for R and python programming languages. Spyder(sub-application of Anaconda) is used for python. Opencv for python will work in spyder. Package versions are managed by the package management system called conda. 
Environment variables basically define the behavior of the environment. They can affect the processes ongoing or the programs that are executed in the environment. The region from which this variable can be accessed or over which it is defined is termed as the scope of the variable.  
Download Anaconda for Python. Make sure to download the “Python 3.7 Version” for the appropriate architecture. 
After the download is over, go through How to install Anaconda on windows? and follow the given instructions. 
After the installation is done, we need to set up the environment variable. Go to Control Panel -> System and Security -> System Under the Advanced System Setting option click on Environment Variables as shown below: 
Now, we have to alter the “Path” variable under System variables so that it also contains the path to the Anaconda environment. Select the “Path” variable and click on the Edit button as shown below: 
We will see a list of different paths, click on the New button and then add the path where Anaconda is installed. 
Click on OK, Save the settings and it is done !! Now to check whether the installation is done correctly, open the command prompt and type anaconda-navigator. It will start the anaconda navigator App if installed correctly. 
In Linux, there are several ways to install Anaconda. But we will refer to the simplest and easy way to install Anaconda using the terminal. Go through How to install Anaconda on Linux? and follow the instructions. Generally, the Path variable is automatically set in Linux at the time of installation, but it can also be set manually by the following steps: 
Go to Application -> Accessories -> Terminal
For setting up Environment Variable, type the following command in the Terminal with the use of the Installation path: 
export ANACONDA = /home/nikhil/anaconda3
For setting up the Environment Value, type the following command in the Terminal with the use of the Installation path: 
export PATH = $PATH:/home/nikhil/anaconda3/bin
It is done!! Now to check whether the installation is done correctly, open Terminal and type anaconda-navigator. It will start the anaconda navigator App if installed correctly.  
 
reenadevi98412200
python-basics
How To
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Align Text in HTML?
How to Install OpenCV for Python on Windows?
How to filter object array based on attributes?
Java Tutorial
How to Install FFmpeg on Windows?
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Associative Arrays in PHP

Associative array will have their index as string so that you can establish a strong association between key and values. The associative arrays have names keys that is assigned to them.
Let us see an example−
$arr = array( "p"=>"150", "q"=>"100", "r"=>"120", "s"=>"110", "t"=>"115");
Above, we can see key and value pairs in the array.
To implement Associative Arrays in PHP, the code is as follows −
 Live Demo
<?php
   $arr = array( "p"=>"150", "q"=>"100", "r"=>"120", "s"=>"110", "t"=>"115", "u"=>"103", "v"=>"105", "w"=>"125" );
   echo "Value 1 = " .reset($arr);
?>
This will produce the following output−
Value 1 = 150
Let us now see another example −
 Live Demo
<?php
   $salaries = array("jack" => 2000, "qadir" => 1000);
   echo "Salary of jack is ". $salaries['jack'] . "\n";
   $salaries['jack'] = "high";
   $salaries['tom'] = "low";
   echo "Salary of jack is ". $salaries['jack'] . "\n";
?>
This will produce the following output−
Salary of jack is 2000
Salary of jack is high