code-rag-bench/online-tutorials huggingface dataset:
Python | Pandas DatetimeIndex.freq

24 Dec, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas DatetimeIndex.freq attribute returns the frequency object if it is set in the DatetimeIndex object. If the frequency is not set then it returns None.
Syntax: DatetimeIndex.freq
Return: frequency object
Example #1: Use DatetimeIndex.freq attribute to find the frequency for the given DatetimeIndex object.
# importing pandas as pdimport pandas as pd  # Create the DatetimeIndex# Here 'BQ' represents Business quarter frequencydidx = pd.DatetimeIndex(start ='2014-08-01 10:05:45', freq ='BQ',                                periods = 5, tz ='Asia/Calcutta')  # Print the DatetimeIndexprint(didx)
Output :
Now we want to find the value of frequency for the given DatetimeIndex object.
# find the value of frequencydidx.freq
Output :As we can see in the output, the function has returned a frequency object for the given DatetimeIndex object. Example #2: Use DatetimeIndex.freq attribute to find the frequency for the given DatetimeIndex object.
# importing pandas as pdimport pandas as pd  # Create the DatetimeIndex# Here 'CBMS' represents custom business month start frequencydidx = pd.DatetimeIndex(start ='2000-01-10 06:30', freq ='CBMS',                               periods = 5, tz ='Asia/Calcutta')  # Print the DatetimeIndexprint(didx)
Output :Now we want to find the value of frequency for the given DatetimeIndex object.
# find the value of frequencydidx.freq
Output :As we can see in the output, the function has returned a frequency object for the given DatetimeIndex object. The didx DatetimeIndex object is having custom business month start frequency.
Python pandas-datetimeIndex
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multi-dimensional Arrays in C

C programming language allows multidimensional arrays. Here is the general form of a multidimensional array declaration −
type name[size1][size2]...[sizeN];

For example, the following declaration creates a three dimensional integer array −
int threedim[5][10][4];

The simplest form of multidimensional array is the two-dimensional array. A two-dimensional array is, in essence, a list of one-dimensional arrays. To declare a two-dimensional integer array of size [x][y], you would write something as follows −
type arrayName [ x ][ y ];

Where type can be any valid C data type and arrayName will be a valid C identifier. A two-dimensional array can be considered as a table which will have x number of rows and y number of columns. A two-dimensional array a, which contains three rows and four columns can be shown as follows −
Thus, every element in the array a is identified by an element name of the form a[ i ][ j ], where 'a' is the name of the array, and 'i' and 'j' are the subscripts that uniquely identify each element in 'a'.
Multidimensional arrays may be initialized by specifying bracketed values for each row. Following is an array with 3 rows and each row has 4 columns.
int a[3][4] = {  
   {0, 1, 2, 3} ,   /*  initializers for row indexed by 0 */
   {4, 5, 6, 7} ,   /*  initializers for row indexed by 1 */
   {8, 9, 10, 11}   /*  initializers for row indexed by 2 */
};
The nested braces, which indicate the intended row, are optional. The following initialization is equivalent to the previous example −
int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};

An element in a two-dimensional array is accessed by using the subscripts, i.e., row index and column index of the array. For example −
int val = a[2][3];

The above statement will take the 4th element from the 3rd row of the array. You can verify it in the above figure. Let us check the following program where we have used a nested loop to handle a two-dimensional array −
#include <stdio.h>
 
int main () {

   /* an array with 5 rows and 2 columns*/
   int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};
   int i, j;
 
   /* output each array element's value */
   for ( i = 0; i < 5; i++ ) {

      for ( j = 0; j < 2; j++ ) {
         printf("a[%d][%d] = %d\n", i,j, a[i][j] );
      }
   }
   
   return 0;
}
When the above code is compiled and executed, it produces the following result −
a[0][0]: 0
a[0][1]: 0
a[1][0]: 1
a[1][1]: 2
a[2][0]: 2
a[2][1]: 4
a[3][0]: 3
a[3][1]: 6
a[4][0]: 4
a[4][1]: 8

As explained above, you can have arrays with any number of dimensions, although it is likely that most of the arrays you create will be of one or two dimensions.
 Print
 Add Notes
 Bookmark this page
Python Program to Find all Numbers in a Range which are Perfect Squares and Sum of all Digits in the Number is Less than 10

When it is required to find all numbers in a range where there are perfect square, and sum of digits in the number is less than 10, list comprehension is used.
Below is the demonstration of the same −
 Live Demo
lower_limit = int(input(“Enter the lower range: “))
upper_limit = int(input(“Enter the upper range: “))
my_list = []
my_list = [x for x in range(lower_limit,upper_limit+1) if (int(x**0.5))**2==x and
sum(list(map(int,str(x))))<10]
print(“The result is : “)
print(my_list)
Enter the lower range: 5
Enter the upper range: 12
The result is :
[9]
The lower range and upper range are taken by the user.
The lower range and upper range are taken by the user.
An empty list is defined.
An empty list is defined.
The list comprehension is used, to iterate over the lower and upper limits.
The list comprehension is used, to iterate over the lower and upper limits.
The square root of the elements are found.
The square root of the elements are found.
The elements are summed up.
The elements are summed up.
It is converted to a list.
It is converted to a list.
This is assigned to a variable.
This is assigned to a variable.
The output is displayed on the console.
The output is displayed on the console.
How to read and parse CSV files in C++?

You should really be using a library to parsing CSV files in C++ as there are many cases that you can miss if you read files on your own. The boost library for C++ provides a really nice set of tools for reading CSV files. For example,
#include<iostream>
vector<string> parseCSVLine(string line){
   using namespace boost;

   std::vector<std::string> vec;

   // Tokenizes the input string
   tokenizer<escaped_list_separator<char> > tk(line, escaped_list_separator<char>
   ('\\', ',', '\"'));
   for (auto i = tk.begin();  i!=tk.end();  ++i)
   vec.push_back(*i);

   return vec;
}

int main() {
   std::string line = "hello,from,here";
   auto words = parseCSVLine(line);
   for(auto it = words.begin(); it != words.end(); it++) {
      std::cout << *it << std::endl;
   }
}
This will give the output −
hello
from
here
Another way is to use a delimiter to split a line and take it in an array −
Another way is to provide a custom delimiter to split the string by using the getline function −
#include <vector>
#include <string>
#include <sstream>

using namespace std;

int main() {
   std::stringstream str_strm("hello,from,here");
   std::string tmp;
   vector<string> words;
   char delim = ','; // Ddefine the delimiter to split by

   while (std::getline(str_strm, tmp, delim)) {
      // Provide proper checks here for tmp like if empty
      // Also strip down symbols like !, ., ?, etc.
      // Finally push it.
      words.push_back(tmp);
   }

   for(auto it = words.begin(); it != words.end(); it++) {
      std::cout << *it << std::endl;
   }
}
This will give the output −
hello
from
here
Tcl - Commands

As you know, Tcl is a Tool command language, commands are the most vital part of the language. Tcl commands are built in-to the language with each having its own predefined function. These commands form the reserved words of the language and cannot be used for other variable naming. The advantage with these Tcl commands is that, you can define your own implementation for any of these commands to replace the original built-in functionality.
Each of the Tcl commands validates the input and it reduces the work of the interpreter.
Tcl command is actually a list of words, with the first word representing the command to be executed. The next words represent the arguments. In order to group the words into a single argument, we enclose multiple words with "" or {}.
The syntax of Tcl command is as follows −
commandName argument1 argument2 ... argumentN
Let's see a simple example of Tcl command −
#!/usr/bin/tclsh

puts "Hello, world!"
When the above code is executed, it produces the following result −
Hello, world!

In the above code, ‘puts’ is the Tcl command and "Hello World" is the argument1. As said before, we have used "" to group two words.
Let's see another example of Tcl command with two arguments −
#!/usr/bin/tclsh

puts stdout "Hello, world!"
When the above code is executed, it produces the following result −
Hello, world!

In the above code, ‘puts’ is the Tcl command, ‘stdout’ is argument1, and "Hello World" is argument2. Here, stdout makes the program to print in the standard output device.
In command substitutions, square brackets are used to evaluate the scripts inside the square brackets. A simple example to add two numbers is shown below −
#!/usr/bin/tclsh

puts [expr 1 + 6 + 9]
When the above code is executed, it produces following result −
16

In variable substitutions, $ is used before the variable name and this returns the contents of the variable. A simple example to set a value to a variable and print it is shown below.
#!/usr/bin/tclsh

set a 3
puts $a
When the above code is executed, it produces the following result −
3

These are commonly called escape sequences; with each backslash, followed by a letter having its own meaning. A simple example for newline substitution is shown below −
#!/usr/bin/tclsh

puts "Hello\nWorld"
When the above code is executed, it produces the following result −
Hello
World

 Print
 Add Notes
 Bookmark this page
What are the differences between a static block and a constructor in Java?

The static blocks are executed at the time of class loading.
The static blocks are executed before running the main () method.
The static blocks don't have any name in its prototype.
If we want any logic that needs to be executed at the time of class loading that logic needs to placed inside the static block so that it will be executed at the time of class loading.
static {
   //some statements
}
Live Demo
public class StaticBlockTest {
   static {
      System.out.println("Static Block!");
   }
   public static void main(String args[]) {
      System.out.println("Welcome to Tutorials Point!");
   }
}
Static Block!
Welcome to Tutorials Point!
A Constructor will be executed while creating an object in Java.
A Constructor is called while creating an object of a class.
The name of a constructor must be always the same name as a class.
A Constructor is called only once for an object and it is called as many times as we can create an object. i.e The constructor gets executed automatically when the object is created.
public class MyClass {
   //This is the constructor
   MyClass() {
      // some statements
   }
}
Live Demo
public class ConstructorTest {
   static {
      //static block
      System.out.println("In Static Block!");
   }
   public ConstructorTest() {
      System.out.println("In a first constructor!");
   }
   public ConstructorTest(int c) {
      System.out.println("In a second constructor!");
   }
   public static void main(String args[]) {
      ConstructorTest ct1 = new ConstructorTest();
      ConstructorTest ct2 = new ConstructorTest(10);
   }
}
In Static Block!
In a first constructor!
In a second constructor!
Rexx - Decision Making

Decision making structures require that the programmer specify one or more conditions to be evaluated or tested by the program.
The following diagram shows the general form of a typical decision-making structure found in most of the programming languages.
There is a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false.
Let’s look at the various decision-making statements available in Rexx.
The first decision-making statement is the if statement. An if statement consists of a Boolean expression followed by one or more statements.
The next decision-making statement is the if-else statement. An if statement can be followed by an optional else statement, which executes when the Boolean expression is false.
Sometimes there is a requirement to have multiple if statements embedded inside each other, as is possible in other programming languages. In Rexx also this is possible.
if (condition1) then 
   do 
      #statement1 
   end 
else 
   if (condition2) then 
      do 
      #statement2 
   end

The flow diagram of nested if statements is as follows −
Let’s take an example of nested if statement −
/* Main program */ 
i = 50 
if (i < 10) then 
   do 
      say "i is less than 10" 
   end 
else 
if (i < 7) then 
   do 
      say "i is less than 7" 
   end 
else 
   do 
      say "i is greater than 10" 
   end 
The output of the above program will be −
i is greater than 10 

Rexx offers the select statement which can be used to execute expressions based on the output of the select statement.
The general form of this statement is −
select 
when (condition#1) then 
statement#1 

when (condition#2) then 
statement#2 
otherwise 

defaultstatement 
end 

The general working of this statement is as follows −
The select statement has a range of when statements to evaluate different conditions.
The select statement has a range of when statements to evaluate different conditions.
Each when clause has a different condition which needs to be evaluated and the subsequent statement is executed.
Each when clause has a different condition which needs to be evaluated and the subsequent statement is executed.
The otherwise statement is used to run any default statement if the previous when conditions do not evaluate to true.
The otherwise statement is used to run any default statement if the previous when conditions do not evaluate to true.
The flow diagram of the select statement is as follows
The following program is an example of the case statement in Rexx.
/* Main program */ 
i = 50 
select 
when(i <= 5) then 
say "i is less than 5" 

when(i <= 10) then 
say "i is less than 10" 

otherwise 
say "i is greater than 10" 
end
The output of the above program would be −
i is greater than 10 

 Print
 Add Notes
 Bookmark this page
How to add column using alter in MySQL?


Following is the syntax to add column using alter in MySQL:
alter table yourTableName add column yourColumnName yourDataType default yourValue;
Let us first create a table:
mysql> create table alterTableDemo
   -> (
   -> Id int,
   -> Name varchar(10)
   -> );
Query OK, 0 rows affected (0.69 sec)
Let us check the description of the table using DESC command. This displays Field, Type, Key, etc. of the table:
mysql> desc alterTableDemo;
This will produce the following output
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| Id    | int(11)     | YES  |     | NULL    |       |
| Name  | varchar(10) | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
2 rows in set (0.01 sec)
Now, add column Age with default value 18. If user won’t supply value for column Age then MySQL will use the default value for Age column. Following is the query to add column using alter command.
mysql> alter table alterTableDemo add column Age int default 18;
Query OK, 0 rows affected (0.67 sec)
Records: 0 Duplicates: 0 Warnings: 0
Let us check the table description once again:
mysql> desc alterTableDemo;
This will produce the following output
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| Id    | int(11)     | YES  |     | NULL    |       |
| Name  | varchar(10) | YES  |     | NULL    |       |
| Age   | int(11)     | YES  |     | 18      |       |
+-------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)
Let us insert record in the table using insert command.
Following is the query
mysql> insert into alterTableDemo(Id,Name,Age) values(100,'Chris',24);
Query OK, 1 row affected (0.16 sec)

mysql> insert into alterTableDemo(Id,Name) values(101,'Robert');
Query OK, 1 row affected (0.25 sec)
Following is the query to display all records from the table using select statement:
mysql> select *from alterTableDemo;
Following is the output. Since we haven’t set age for ‘Robert’, therefore the default 18 would be set for Age:
+------+--------+------+
| Id   | Name   | Age  |
+------+--------+------+
| 100  | Chris  | 24   |
| 101  | Robert | 18   |
+------+--------+------+
2 rows in set (0.00 sec)
Creating a MySQL table using Node.js

Generally, NoSQL databases (like MongoDB) are more popular among the Node developers. However, it totally depends upon your usecase and choice to choose any DBMS from different database options present. The type of databse you choose mainly depends upon one's project's requirements.
For example, if you need table creation or real-time inserts and want to deal with loads of data, then a NoSQL database is the way to go, whereas if your project deals with more complex queries and transactions, an SQL database will make much more sense.
In this article, we will explain how to connect to a MySQL and then create a new table in it.
Following are the steps to check your application connection with the MySQL database.
Create a new project with a name of your choice, and then navigate to that project.
Create a new project with a name of your choice, and then navigate to that project.
>> mkdir mysql-test
>> cd mysql-test
Create a package.json file using the following command
Create a package.json file using the following command
>> npm init -y
You will get the following output −
Wrote to /home/abc/mysql-test/package.json:
{
   "name": "mysql-test",
   "version": "1.0.0",
   "description": "",
   "main": "index.js",
   "scripts": {
      "test": "echo \"Error: no test specified\" && exit 1"
   },
   "keywords": [],
   "author": "",
   "license": "ISC"
}
Installing the MySQL module −
Installing the MySQL module −
   >> npm install mysql
+ mysql@2.18.1
added 11 packages from 15 contributors and audited 11 packages in 3.264s
found 0 vulnerabilities
Create a JS file with the following name – app.js
Create a JS file with the following name – app.js
Copy and Paste the code snippet given below
Copy and Paste the code snippet given below
Run the file using the following command −
Run the file using the following command −
   >> node app.js
// Checking the MySQL dependency in NPM
var mysql = require('mysql');

// Creating a mysql connection
var con = mysql.createConnection({
   host: "localhost",
   user: "yourusername",
   password: "yourpassword",
   database: "mydb"
});

con.connect(function(err) {
   if (err) throw err;
      console.log("Database connected!");
   var sql = "CREATE TABLE students (name VARCHAR(255), address VARCHAR(255))";
   con.query(sql, function (err, result) {
      if (err) throw err;
         console.log("Table created");
   });
});
The following output will be printed on the console −
Database connected!
Table created
string.find() function in Lua

string.find() is one of the most powerful library functions that is present inside the string library.
Lua doesn’t use the POSIX regular expression for pattern matching, as the implementation of the same takes 4,000 lines of code, which is actually bigger than all the Lua standard libraries together. In place of the POSIX pattern matching, the Lua’s implementation of pattern matching takes less than 500 lines.
The string.find() function is used to find a specific pattern in a given string, it normally takes two arguments, the first argument being the string in which the pattern we are trying to search, and the second argument is the pattern that we are trying to search.
There’s a third argument also, the third argument is an index that tells where in the subject string to start the search. This parameter is useful when we want to process all the indices where a given pattern appears. It is mainly used where there are chances that multiple times a same pattern will occur in the same string.
indexstart, indexend = string.find(s,”pattern”)
or
indexstart, indexend = string.find(s,”pattern”,indexstart + z)
In the above syntax, I mentioned both the types of the string.find() function that we can make use of.
Let’s consider a very simple example of the string.find() function where we will try to find a simple pattern in a given string.
Consider the example shown below −
 Live Demo
s = "hello world"
i, j = string.find(s, "hello")
print(i, j)
Notice that in the above code, the i identifier is the starting index where the pattern that we search was found, the j identifier is the ending index of that pattern.
1 5
There might be scenarios where we would want to use only one of these indexes and in those cases, we can simply write the code as follows.
Consider the example shown below −
_, y = string.find(s,"world")
print(y)
x, _ = string.find(s,"world")
print(x)
11
7
Let’s explore one more example where we will make use of the third argument.
Consider the example shown below −
s = "hello n hello y hello z"
index = string.find(s,"hello",i+1)
print(index)
9
C++ Program to Find the Number of Permutations of a Given String

We can arrange the characters of a string in different order. Here we will see how we can count the number of permutations can be formed from a given string.
We know that if one string is ‘abc’. It has three characters; we can arrange them into 3! = 6 different ways. So a string with n characters, we can arrange them into n! different ways. But now if there are same characters are present for multiple times, like aab, then there will not be 6 permutations.
aba
aab
baa
baa
aab
aba
Here the (1,6), (2, 5), (3,4) are same. So here the number of permutations is 3. This is basically (n!)/(sum of the factorials of all characters which is occurring more than one times).
To solve this problem, at first we have to calculate the frequency of all of the characters. Then count the factorial of n, then divide it by doing sum of all frequency values which are greater than 1.
#include<iostream>
using namespace std;
long fact(long n) {
   if(n == 0 || n == 1 )
      return 1;
   return n*fact(n-1);
}
int countPermutation(string str) {
   int freq[26] = {0};
   for(int i = 0; i<str.size(); i++) {
      freq[str[i] - 'a']++; //get the frequency of each characters individually
   }
   int res = fact(str.size()); //n! for string of length n
   for(int i = 0; i<26; i++) {
      if(freq[i] > 1)
         res /= fact(freq[i]); //divide n! by (number of occurrences of each characters)!
   }
   return res;
}
main(){
   string n;
   cout << "Enter a number to count number of permutations can be possible: ";
   cin >> n;
   cout << "\nThe number of permutations: " << countPermutation(n);
}
Enter a number to count number of permutations can be possible: abbc
The number of permutations: 12
How to deal with error “Error in eval(predvars, data, env) : numeric 'envir' arg not of length one” in R?

This error occurs when we do not pass the argument for independent variable as a data frame. The predict function will predict the value of the dependent variable for the provided values of the independent variable and we can also use the values of the independent variable using which the model is created.
Consider the below data frame −
set.seed(1)
x <-rnorm(20)
y <-runif(20,5,10)
df <-data.frame(x,y)
df
      x       y
1 -0.62645381 9.104731
2 0.18364332 8.235301
3 -0.83562861 8.914664
4 1.59528080 7.765182
5 0.32950777 7.648598
6 -0.82046838 8.946781
7 0.48742905 5.116656
8 0.73832471 7.386150
9 0.57578135 8.661569
10 -0.30538839 8.463658
11 1.51178117 7.388098
12 0.38984324 9.306047
13 -0.62124058 7.190486
14 -2.21469989 6.223986
15 1.12493092 5.353395
16 -0.04493361 5.497331
17 -0.01619026 6.581359
18 0.94383621 7.593171
19 0.82122120 8.310025
20 0.59390132 7.034151
Creating the linear model −
M <-lm(y~x,data=df)
Formula for prediction that results in error −
predict(M,newdata=df$x,interval="confidence")
Error in eval(predvars, data, env) :
numeric 'envir' arg not of length one
Formula for prediction that does not result in error −
predict(M,newdata=data.frame(df$x),interval="confidence")
      fit    lwr       upr
1 7.642084 6.814446 8.469722
2 7.536960 6.927195 8.146725
3 7.669228 6.738695 8.599762
4 7.353775 6.214584 8.492966
5 7.518031 6.900897 8.135166
6 7.667261 6.744547 8.589975
7 7.497538 6.854767 8.140310
8 7.464980 6.749018 8.180943
9 7.486073 6.821666 8.150480
10 7.600420 6.902430 8.298410
11 7.364611 6.273305 8.455917
12 7.510202 6.885355 8.135048
13 7.641408 6.816180 8.466635
14 7.848187 6.091378 9.604995
15 7.414811 6.530792 8.298831
16 7.566622 6.935903 8.197340
17 7.562892 6.936919 8.188865
18 7.438312 6.639516 8.237107
19 7.454223 6.706932 8.201514
20 7.483722 6.814287 8.153156
We can simply use the Model object as well, if we want to predict the dependent variable for the independent variable
predict(M)
1 2 3 4 5 6 7 8
7.642084 7.536960 7.669228 7.353775 7.518031 7.667261 7.497538 7.464980
9 10 11 12 13 14 15 16
7.486073 7.600420 7.364611 7.510202 7.641408 7.848187 7.414811 7.566622
17 18 19 20
7.562892 7.438312 7.454223 7.483722
predict(M,interval="confidence")
   fit       lwr       upr
1 7.642084 6.814446 8.469722
2 7.536960 6.927195 8.146725
3 7.669228 6.738695 8.599762
4 7.353775 6.214584 8.492966
5 7.518031 6.900897 8.135166
6 7.667261 6.744547 8.589975
7 7.497538 6.854767 8.140310
8 7.464980 6.749018 8.180943
9 7.486073 6.821666 8.150480
10 7.600420 6.902430 8.298410
11 7.364611 6.273305 8.455917
12 7.510202 6.885355 8.135048
13 7.641408 6.816180 8.466635
14 7.848187 6.091378 9.604995
15 7.414811 6.530792 8.298831
16 7.566622 6.935903 8.197340
17 7.562892 6.936919 8.188865
18 7.438312 6.639516 8.237107
19 7.454223 6.706932 8.201514
20 7.483722 6.814287 8.153156
C++ Vector Library - swap() Function

The C++ function std::vector::swap() exchanges the content of vector with contents of vector x.
Following is the declaration for std::vector::swap() function form std::vector header.
void swap (vector& x);

x − Another vector object of same type.
None
Constant i.e. O(1)
The following example shows the usage of std::vector::swap() function.
#include <iostream>
#include <vector>

using namespace std;

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

   v1.swap(v2);

   cout << "Vector v1 contains" << endl;
   for (int i = 0; i < v1.size(); ++i)
      cout << v1[i] << endl;

   return 0;
}
Let us compile and run the above program, this will produce the following result −
Vector v1 contains
1
2
3
4
5

 Print
 Add Notes
 Bookmark this page
Filter array of objects by a specific property in JavaScript?

Use the concept of map() along with ternary operator (?). Following are our array of objects −
let firstCustomerDetails =
[
   {firstName: 'John', amount: 100},
   {firstName: 'David', amount: 50},
   {firstName: 'Bob', amount: 80}
];
   let secondCustomerDetails =
[
   {firstName: 'John', amount: 400},
   {firstName: 'David', amount: 70},
   {firstName: 'Bob', amount: 40}
];
Let’s say, we need to filter array of objects by amount property. The one with the greatest
amount is considered.
let firstCustomerDetails =
[
   {firstName: 'John', amount: 100},
   {firstName: 'David', amount: 50},
   {firstName: 'Bob', amount: 80}
];
let secondCustomerDetails =
[
   {firstName: 'John', amount: 400},
   {firstName: 'David', amount: 70},
   {firstName: 'Bob', amount: 40}
];
var output = firstCustomerDetails.map((key, position) =>
key.amount > secondCustomerDetails[position].amount ? key :
secondCustomerDetails[position]
);
console.log(output);
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo83.js.
This will produce the following output −
PS C:\Users\Amit\JavaScript-code> node demo83.js
[
   { firstName: 'John', amount: 400 },
   { firstName: 'David', amount: 70 },
   { firstName: 'Bob', amount: 80 }
]
For Statement List Implementations

The "FOR" construct offers looping capabilities for batch files. Following is the common construct of the ‘for’ statement for working with a list of values.
FOR %%variable IN list DO do_something

The classic ‘for’ statement consists of the following parts −
Variable declaration – This step is executed only once for the entire loop and used to declare any variables which will be used within the loop. In Batch Script, the variable declaration is done with the %% at the beginning of the variable name.
Variable declaration – This step is executed only once for the entire loop and used to declare any variables which will be used within the loop. In Batch Script, the variable declaration is done with the %% at the beginning of the variable name.
List – This will be the list of values for which the ‘for’ statement should be executed.
List – This will be the list of values for which the ‘for’ statement should be executed.
The do_something code block is what needs to be executed for each iteration for the list of values.
The do_something code block is what needs to be executed for each iteration for the list of values.
The following diagram shows the diagrammatic explanation of this loop.
Following is an example of how the ‘goto’ statement can be used.
@echo off 
FOR %%F IN (1 2 3 4 5) DO echo %%F
The key thing to note about the above program is −
The variable declaration is done with the %% sign at the beginning of the variable name.
The variable declaration is done with the %% sign at the beginning of the variable name.
The list of values is defined after the IN clause.
The list of values is defined after the IN clause.
The do_something code is defined after the echo command. Thus for each value in the list, the echo command will be executed.
The do_something code is defined after the echo command. Thus for each value in the list, the echo command will be executed.
The above program produces the following output.
1 
2 
3 
4 
5

 Print
 Add Notes
 Bookmark this page
Java | Renaming a file - GeeksforGeeks

26 Mar, 2018
In Java we can rename a file using renameTo(newName) method that belongs to the File class.Declaration:
Following is the declaration for java.io.File.renameTo(File dest) method:
public boolean renameTo(File dest)

Parameters:
dest – The new abstract pathname for the existing abstract pathname.Exception:
SecurityException : If a security manager exists and its method denies write access to either the old or new pathnames.
NullPointerException : If parameter destination is null.
// Java program to rename a file.import java.io.File;  public class GeeksforGeeks {    public static void main(String[] args)    {        File oldName =         new File("C:\Users\Siddharth\Desktop\java.txt");        File newName =          new File("C:\Users\Siddharth\Desktop\GeeksforGeeks.txt");          if (oldName.renameTo(newName))             System.out.println("Renamed successfully");                else             System.out.println("Error");            }}
Renamed successfully

java-file-handling
Java-I/O
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Exceptions in Java
Constructors in Java
Different ways of Reading a text file in Java
Functional Interfaces in Java
Generics in Java
Comparator Interface in Java with Examples
PriorityQueue in Java
Introduction to Java
How to remove an element from ArrayList in Java?
Python Number fabs() Method

Python number  method fabs() returns the absolute value of x.
Following is the syntax for fabs() method −
import math

math.fabs( x )
Note − This function is not accessible directly, so we need to import math module and then we need to call this function using math static object.
x − This is a numeric value.
x − This is a numeric value.
This method returns absolute value of x.
The following example shows the usage of fabs() method.
#!/usr/bin/python
import math   # This will import math module

print "math.fabs(-45.17) : ", math.fabs(-45.17)
print "math.fabs(100.12) : ", math.fabs(100.12)
print "math.fabs(100.72) : ", math.fabs(100.72)
print "math.fabs(119L) : ", math.fabs(119L)
print "math.fabs(math.pi) : ", math.fabs(math.pi)
When we run above program, it produces following result −
math.fabs(-45.17) :  45.17
math.fabs(100.12) :  100.12
math.fabs(100.72) :  100.72
math.fabs(119L) :  119.0
math.fabs(math.pi) :  3.14159265359


    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
How to set dialog to show with full screen in Android?

This example demonstrates how do I set the dialog to show with full screen in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity">
<Button
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_centerHorizontal="true"
   android:layout_marginTop="40dp"
   android:onClick="ClickHere"
   android:text="Click here" />
<TextView
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_centerInParent="true"
   android:text="Hello World" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
   }
   public void ClickHere(View view) {
      Dialog dialog = new Dialog(this, android.R.style.Theme_Black_NoTitleBar_Fullscreen);
      dialog.setContentView(R.layout.activity_main);
      dialog.show();
   }
}

Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="app.com.sample">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
How to programmatically empty browser cache with HTML?

You can tell your browser not to cache your page by using the following meta tags −
<metahttp-equiv = 'cache-control' content = 'no-cache'>
<metahttp-equiv = 'expires' content = '0'>
<metahttp-equiv = 'pragma' content = 'no-cache'>
In addition, try the following:  Append a parameter/string to the filename in the script tag. Change it when the file changes.
<scriptsrc = "newfile.js?version = 1.0.0"></script>
Then the next time you update the file, just update the version i.e.
<scriptsrc = "newfile.js?version = 1.0.1"></script>
How to click on a link in Selenium with python?

We can click on a link on page with the help of locators available in Selenium. Link text and partial link text are the locators generally used for clicking links. Both these locators work with the text available inside the anchor tags.
Link Text – The text within the anchor tag is matched with the element to be identified. With this, the first matching element is returned. In case of not matching, NoSuchElementException is thrown.
Link Text – The text within the anchor tag is matched with the element to be identified. With this, the first matching element is returned. In case of not matching, NoSuchElementException is thrown.
Partial link Text – The partial text within the anchor tag is matched with the element to be identified. With this, the first matching element is returned. In case of not matching, NoSuchElementException is thrown.
Partial link Text – The partial text within the anchor tag is matched with the element to be identified. With this, the first matching element is returned. In case of not matching, NoSuchElementException is thrown.
Coding Implementation with link text
from selenium import webdriver
#browser exposes an executable file
#Through Selenium test we will invoke the executable file which will then #invoke #actual browser
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
# to maximize the browser window
driver.maximize_window()
#get method to launch the URL
driver.get("https://www.tutorialspoint.com/about/about_careers.htm")
#to refresh the browser
driver.refresh()
# identifying the link with the help of link text locator
driver.find_element_by_link_text("Company").click()
#to close the browser
driver.close()
Coding Implementation with partial link text.
from selenium import webdriver
#browser exposes an executable file
#Through Selenium test we will invoke the executable file which will then #invoke #actual browser
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
# to maximize the browser window
driver.maximize_window()
#get method to launch the URL
driver.get("https://www.tutorialspoint.com/about/about_careers.htm")
#to refresh the browser
driver.refresh()
# identifying the link with the help of partial link text locator
driver.find_element_by_partial_link_text("Privacy").click()
#to close the browser
driver.quit()
How to match underscore in a MySQL String?

To match underscore in a MySQL string, you can use the below syntax −
select *from yourTableName where yourColumnName LIKE '%\_%';
Let us first create a table −
mysql> create table DemoTable
(
   ClientId varchar(200)
);
Query OK, 0 rows affected (0.79 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('CLI_101');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values('CLI1110');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values('_CLI102');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values('CLI103_');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values('CLI1111');
Query OK, 1 row affected (0.16 sec)
Following is the query to display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+----------+
| ClientId |
+----------+
| CLI_101  |
| CLI1110  |
| _CLI102  |
| CLI103_  |
| CLI1111  |
+----------+
5 rows in set (0.00 sec)
Here is the query to match underscore in String using LIKE −
mysql> select *from DemoTable where ClientId LIKE '%\_%';
This will produce the following output displaying the strings with underscore −
+----------+
| ClientId |
+----------+
| CLI_101  |
| _CLI102  |
| CLI103_  |
+----------+
3 rows in set (0.00 sec)
You can use alternate query −
mysql> select *from DemoTable where ClientId REGEXP '_';
This will produce the following output −
+----------+
| ClientId |
+----------+
| CLI_101  |
| _CLI102  |
| CLI103_  |
+----------+
3 rows in set (0.00 sec)
Send mail from your Gmail account using Python

In this article, we will see how we can send email with attachments using Python. To send mail, we do not need any external library. There is a module called SMTPlib, which comes with Python. It uses SMTP (Simple Mail Transfer Protocol) to send the mail. It creates SMTP client session objects for mailing.
SMTP needs valid source and destination email ids, and port numbers. The port number varies for different sites. As an example, for google the port is 587.
At first we need to import the module to send mail.
import smtplib

Here we are also using the MIME (Multipurpose Internet Mail Extension) module to make it more flexible. Using MIME header, we can store the sender and receiver information and some other details.
We are using Google's Gmail service to send mail. So we need some settings (if required) for google's security purposes. If those settings are not set up, then the following code may not work, if the google doesnot support the access from third-party app.
To allow the access, we need to set 'Less Secure App Access' settings in the google account. If the two step verification is on, we cannot use the less secure access.
To complete this setup, go to the Google's Admin Console, and search for the Less Secure App setup.
Create MIME
Add sender, receiver address into the MIME
Add the mail title into the MIME
Attach the body into the MIME
Start the SMTP session with valid port number with proper security features.
Login to the system.
Send mail and exit
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
mail_content = '''Hello,
This is a simple mail. There is only text, no attachments are there The mail is sent using Python SMTP library.
Thank You
' ' '
#The mail addresses and password
sender_address = 'sender123@gmail.com'
sender_pass = 'xxxxxxxx'
receiver_address = 'receiver567@gmail.com'
#Setup the MIME
message = MIMEMultipart()
message['From'] = sender_address
message['To'] = receiver_address
message['Subject'] = 'A test mail sent by Python. It has an attachment.'   #The subject line
#The body and the attachments for the mail
message.attach(MIMEText(mail_content, 'plain'))
#Create SMTP session for sending the mail
session = smtplib.SMTP('smtp.gmail.com', 587) #use gmail with port
session.starttls() #enable security
session.login(sender_address, sender_pass) #login with mail_id and password
text = message.as_string()
session.sendmail(sender_address, receiver_address, text)
session.quit()
print('Mail Sent')
D:\Python TP\Python 450\linux>python 327.Send_Mail.py
Mail Sent
Increase the font size of a paragraph with Bootstrap

Use the .lead class in Bootstrap to increase the font size of a paragraph.
You can try to run the following code to implement lead class −
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Example</title>
      <link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet">
      <script src = "/scripts/jquery.min.js"></script>
      <script src = "/bootstrap/js/bootstrap.min.js"></script>
   </head>
   <body>
      <div class = "container">
         <h2>Football</h2>
         <h3>FIFA</h3>
         <p>The 2018 FIFA World Cup is the 21st FIFA World Cup.</p>
         <p class = "lead">FIFA, 2018 is going on in Russia.</p>
      </div>
   </body>
</html>
Python 3 - File readline() Method

The method readline()reads one entire line from the file. A trailing newline character is kept in the string. If the size argument is present and non-negative, it is a maximum byte count including the trailing newline and an incomplete line may be returned.
An empty string is returned only when EOF is encountered immediately.
Following is the syntax for readline() method −
fileObject.readline( size );

size − This is the number of bytes to be read from the file.
This method returns the line read from the file.
The following example shows the usage of readline() method.
Assuming that 'foo.txt' file contains following text:
This is 1st line
This is 2nd line
This is 3rd line
This is 4th line
This is 5th line

#!/usr/bin/python3

# Open a file
fo = open("foo.txt", "r+")
print ("Name of the file: ", fo.name)

line = fo.readline()
print ("Read Line: %s" % (line))

line = fo.readline(5)
print ("Read Line: %s" % (line))

# Close opened file
fo.close()
When we run the above program, it produces the following result −
Name of the file:  foo.txt
Read Line: This is 1st line

Read Line: This


    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
Logging in Node.js

01 Apr, 2021
Node.js is a JavaScript runtime that’s built on Chrome’s V8 JavaScript engine and its run-time environment includes everything which we’d like to execute a program written in JavaScript. Logging is an essential part of understanding the complete application life cycle of the Node.js program. From starting to debugging and adding new features, logs provide support by analyzing the data, and we can resolve bugs much easier and quicker by detecting errors as soon as they occur. There are common levels of logging in Node.js: error, warn, info, debug. Logging involves recording information about the application’s runtime behavior in a more persistent manner.
There are following ways to log in Node.js:
console.log: The original method of logging is console.log which is a function that writes a message to log on the debugging console, but you have little control over it where things log from outside the code.
Syntax:
console.log(level, message)
Debug module: The advantage of using debug is that a lot of packages use it. You can turn it on to urge additional information on what’s happening in web middleware like Express and Koa when your back-end gets an internet request. The good frameworks will offer you how to attach logging middleware, but you would possibly not get all the small print sent there too.
Middleware Middleware is simply something you’ll put into the request pipeline. Ways to setup logging middleware:
Application:JavascriptJavascriptconst app = express()const loggingMiddleware = require('my-logging-middleware')app.use(loggingMiddleware)
Javascript
const app = express()const loggingMiddleware = require('my-logging-middleware')app.use(loggingMiddleware)
Router:JavascriptJavascriptconst router = express.Router()const routeLoggingMiddleware = require('my-route-logging-middleware')router.use(routeLoggingMiddleware)
Javascript
const router = express.Router()const routeLoggingMiddleware = require('my-route-logging-middleware')router.use(routeLoggingMiddleware)
Winston Package: Winston includes storage options,different log levels & queries and a profiler. 
Javascript
const app = express()const winston = require('winston')const consoleTransport = new winston.transports.Console()const myWinstonOptions = {    transports: [consoleTransport]}const logger = new winston.createLogger(myWinstonOptions)  function logRequest(req, res, next) {    logger.info(req.url)    next()}app.use(logRequest)  function logError(err, req, res, next) {    logger.error(err)    next()}app.use(logError)
Node.js-Basics
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JWT Authentication with Node.js
Installation of Node.js on Windows
Difference between dependencies, devDependencies and peerDependencies
Mongoose Populate() Method
Express.js req.params Property
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Roadmap to Learn JavaScript For Beginners
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?