code-rag-bench/online-tutorials huggingface dataset:
How to check whether the day is a weekday or not using Pandas in Python?

29 Aug, 2020
Python is a very popular language because it is suitable for almost any type of data science task. And Pandas is one of the popular python-based data analysis toolkits and also provides pandas.bdate_range() function to return a fixed frequency DatetimeIndex. This function Returns a fixed frequency DatetimeIndex, with the business day(Mon to Fri) as the default frequency.
Syntax: pandas.bdate_range(start=None, end=None, periods=None, freq=’B’, tz=None, normalize=True, name=None, weekmask=None, holidays=None, closed=None, **kwargs)
Parameters :
start : string or datetime-like, default None.
end : string or datetime-like, default None.
periods : integer, default None.
freq :  string or DateOffset, default ‘B’ (business daily).
tz : string or None.
normalize : bool, default False
name : str, default None
weekmask : str or None, default None
holidays : list-like or None, default None
Approach : 
Import the Pandas module
Create a Parameter function that returns a boolean value
Check the given date is returning boolean with pd.bdate_range() inside function
Check if boolean is False then the date belongs to a weekday if boolean is true then is not weekday
Below is the implementation.
Python3
# importing Pandas moduleimport pandas as pd  # Creating a Functiondef check_weekday(date):          # computing the parameter date    # with len function    res=len(pd.bdate_range(date,date))          if res == 0 :        print("This is weekend")    else:        print("This is your working day")   # user inputdate = "2020-08-17"check_weekday(date)  date = "2020-08-16"check_weekday(date)
Output :
This is your working day
This is weekend
Python pandas-datetime
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function
Batch Script - toInt

A variable which has been set as string using the set variable can be converted to an integer using the /A switch which is using the set variable. The following example shows how this can be accomplished.
@echo off
set var = 13145
set /A var=%var% + 5
echo %var%
The above command produces the following output.
13150

Apart from this, strings have the following implementations which are available. Batch scripts have the following commands which are used to carry out string manipulation in strings.
%variable:~num_chars_to_skip% 
%variable:~num_chars_to_skip,num_chars_to_keep%

This can include negative numbers −
%variable:~num_chars_to_skip, -num_chars_to_keep%
%variable:~-num_chars_to_skip,num_chars_to_keep%
%variable:~-num_chars_to_skip,-num_chars_to_keep%

Let us discuss the possible string operations that can be performed by using the above commands.
 Print
 Add Notes
 Bookmark this page
Print array elements in alternatively increasing and decreasing order in C++

In this problem, we are given an array of number and we have to print the elements of the array in alternatively increasing and decreasing order while printing. The alternative order will be in such a way that 1st two elements are in increasing order and then the next three elements are in decreasing order again next four are in ascending order.
Let’s take an example to understand the problem better,
Input  : {1, 4, 0, 2, 7, 9, 3}
Output : 0 1 9 7 4 2 3
Explanation − the array in increasing order of elements is 0 1 2 3 4 7 9. The first 2 elements are 0 1. The last 3 elements are 9 7 4. Next 4 four elements are 2 3 (we could take 4 elements but there are only 2 in the array).
To solve this problem, we will first sort the array in ascending order. Now, we will use two pointers one for printing elements from start and one for printing element for the end. We will also use one flag element to check if the print is to be done from the start or from the end.
Step 1 : Sort elements of the array.
Step 2 : Initialise left = 0 , right = n-1 , flag = 2.
Step 3 : while l is less than equal to r. Do :
Step 4 : If flag%2 == 0. Do :
   Step 4.1 : loop from i = left to left + flag. And print arr[i].
   Step 4.2 : update left = i ; flag ++;
Step 5 : else. Do :
   Step 5.1 : loop from i = right to right - flag. And print arr[i].
   Step 5.2 : update right = i and flag ++.
Step 6 : EXIT
Now, let’s create a program to illustrate the working of this algorithm.
 Live Demo
#include <bits/stdc++.h>
using namespace std;
void printAlternateSeq(int arr[], int n){
   sort(arr, arr + n);
   int left = 0, right = n - 1, flag = 2, i;
   while (left <= right) {
      if (flag%2 == 0) {
         for (i = left; i < left + flag && i <= right; i++)
         cout<<arr[i]<<" ";
         left = i;
      } else {
         for (i = right; i > right - flag && i >= left; i--)
            cout<<arr[i]<<" ";
         right = i;
      }
      flag++;
   }
}
int main(){
   int n = 6;
   int arr[] = {23, 45, 78, 32, 89, 10 };
   printAlternateSeq(arr, n);
   return 0;
}
10 23 89 78 45 32
Python – Draw “GFG” logo using Turtle Graphics

13 Oct, 2020
Prerequisites: Turtle Programming in Python
Turtle is a Python feature like a drawing board, which let us command a turtle to draw all over it! We can use many turtle functions which can move the turtle around. Turtle comes into the turtle library. The turtle module can be used in both object-oriented and procedure-oriented ways.
Some of the commonly used methods are:
forward(length): moves the pen in the forward direction by x unit.
backward(length): moves the pen in the backward direction by x unit.
right(angle): rotate the pen in the clockwise direction by an angle x.
left(angle): rotate the pen in the anticlockwise direction by an angle x.
penup(): stop drawing of the turtle pen.
pendown(): start drawing of the turtle pen.
In this article, we will be drawing the logo of GeeksforGeeks which looks like this –  
 
Approach :
 
Importing Turtle.
Forming a window screen with size and color.
Then start to draw the logo:Form ‘C’ in the backward directionline 90 degree upline 90 degree rightline 90 degree downForm ‘C’ in forwarding direction
Form ‘C’ in the backward direction
line 90 degree up
line 90 degree right
line 90 degree down
Form ‘C’ in forwarding direction
 
Below is the implementation.
 
# importing turtle for graphics
import turtle

# Forming the window screen
tut = turtle.Screen()

# background color green
tut.bgcolor("White")

# object
pen = turtle.Turtle()

#speed of pen
pen.speed(10)

# object color
pen.color("Green")

# object width
pen.width(10)
tut = turtle.Screen()


# Code for symbol
# backward C
for x in range(180):
    pen.forward(1)
    pen.right(1)

# up
pen.right(90)
pen.forward(50)

# right
pen.right(90)
pen.forward(130)

# down
pen.right(90)
pen.forward(50)
pen.left(90)

# forward C
for x in range(180):
    pen.backward(1)
    pen.right(1)

turtle.done()
 Output : 
 
pulkitagarwal03pulkit
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Fibonacci Series in Bash

20 May, 2022
Prerequisite: Fibonacci Series Write a program to print the Fibonacci sequence up to nth digit using Bash. Examples:
Input : 5
Output :
Fibonacci Series is : 
0
1
1
2
3

Input :4
Output :
Fibonacci Series is : 
0
1
1
2
The Fibonacci numbers are the numbers in the following integer sequence .
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ........
Approach As we know F0 = 0 and F1 = 1 and the next value comes by adding the previous two values .
 FN =  FN-1 +  FN-2
Loop to Nth number adding previous two numbers. 
BASH
# Program for Fibonacci# Series  # Static input for NN=6 # First Number of the# Fibonacci Seriesa=0 # Second Number of the# Fibonacci Seriesb=1  echo "The Fibonacci series is : "  for (( i=0; i<N; i++ ))do    echo -n "$a "    fn=$((a + b))    a=$b    b=$fndone# End of for loop
Output:
Fibonacci Series is : 
0
1
1
2
3
5
8
varshagumber28
simmytarika5
Shell Script
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
HTML | <tbody> align Attribute

22 Feb, 2022
The HTML <tbody> align Attribute is used to set the horizontal alignment of text content inside the table body (tbody).
Syntax:
<tbody align="left | right | center | justify | char">
Attribute Value:
left: It sets the text left-align.
right: It sets the text right-align.
center: It sets the text center-align. By default, it is set to center.
justify: It stretches the text of paragraph to set the width of all lines equal.
char: It sets the text-align to a specific character.
Note: The <tbody> align Attribute is not supported by HTML 5.
Example:
<!DOCTYPE html><html>  <head>    <title>        HTML tbody align Attribute    </title></head>  <body>    <h1>GeeksforGeeks</h1>      <h2>HTML tbody align Attribute</h2>      <table border="1"            width="500">        <thead>            <tr>                <th>NAME</th>                <th>AGE</th>                <th>BRANCH</th>            </tr>        </thead>          <tbody align="center">            <tr>                <td>BITTU</td>                <td>22</td>                <td>CSE</td>            </tr>        </tbody>    </table></body>  </html>
Output:
Supported Browsers: The browser supported by HTML <tbody> align Attribute are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
hritikbhatnagar2182
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Types of CSS (Cascading Style Sheet)
Design a Tribute Page using HTML & CSS
HTTP headers | Content-Type
How to Insert Form Data into Database using PHP ?
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
LEFT() Function in MySQL

24 Sep, 2021
LEFT() function in MySQL is used to extract a specified number of characters from the left side of a given string. It uses its second argument to decide, how many characters it should return. 
Syntax :  
LEFT (str, len)
Parameter : This function accepts two parameters as mentioned above and described below : 
str : The given string from whose left side a number of characters are to be extracted.  
len : The number of characters to extract. If this parameter is larger than the number of characters in the string, this function will return the actual string.  
Returns : It returns a number of characters from a string (starting from left). 
Example-1 : Applying LEFT() Function to a given string.  
SELECT LEFT("geeksforgeeks", 4) AS Left_Str;
Output : 
Example-2 : Applying Left() Function to a number.  
SELECT LEFT(12345678, 4) AS Left_Num;
Output : 
Example-3 : Applying LEFT() Function to a given string when len > characters in the string.  
SELECT LEFT("geeksforgeeks", 20) AS Left_Str;
Output : 
Example-4 : Applying LEFT() Function to a column in a table. 
Table : Student_Details 
SELECT Student_Name, LEFT(Student_Email, 9) AS Email_Name 
FROM Student_Details;
Output : 
rajrishu784
DBMS-SQL
mysql
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to use multiple attribute in HTML?

The multiple attribute in HTML allows user to enter more than one value. It is a Boolean attribute and can be used on <input> as well as <select> element,
To allow multiple file uploads in HTML forms, use the multiple attribute. The multiple attribute works with email and file input types.
You can try to run the following code to learn how to use multiple attribute in HTML:
<!DOCTYPE html>
<html>
   <head>
      <title>HTML multiple attribute</title>
   </head>
   <body>
      <form>
         <input type="file" name="name" multiple><br><br>
         Upload multiple files, and click Submit.<br>
         <input type="submit" value="Submit">
      </form>
   </body>
</html>
Explain in detail about Reference-counting garbage collection in JavaScript?

This is the simplest garbage collection algorithm.This algorithm looks out for those objects which have no references   left.An object becomes eligible for garbage collection if it has no references attached to it.The garbage collection is   explained in the below example.
var obj = {
      x: { y: 2 }
         };
         // 2 objects created. One is referenced by the other as one of its properties.
         // Obviously, none can be garbage-collected
obj = 1; // what was the 'x' property of the object originally in obj
         // has zero references to it. It can be garbage collected.
When it comes to cycles there are limitations in Reference-counting garbage collection and it is explained in the below example.
In the following example,two objects were created and referenced one another there by creating a cycle. After a function call they will go out of scope, so they are effectively useless and could be freed.But the reference-counting algorithm considers that since each of the two objects is referenced at least once, neither can be garbage-collected.
function f() {
var obj1 = {};
var obj2 = {};
obj1.p = obj2; // o1 references o2
obj2.p = obj1; // o2 references o1. This creates a cycle.
}
f();
Compile and Run Java Programs in Sublime Text in Linux - GeeksforGeeks

11 Feb, 2021
Sublime Text is a free minimalist coding editor developed by Sublime HQ for desktop use. This development and IT program enable you to solely focus on your code, leaving all the other types of eye-candy out.
Procedure:
Open terminal and the specific command are entered there in order to check for the software is there or not. Existence will be displayed out there itself as followed commands.Configure the sublime text’s builds to run programsCreate a new build systemSave the build System and giving it a run
Open terminal and the specific command are entered there in order to check for the software is there or not. Existence will be displayed out there itself as followed commands.
Configure the sublime text’s builds to run programs
Create a new build system
Save the build System and giving it a run
Step 1: Prior to entering the command, make sure the Java compiler is Installed on the machine. Now open the terminal and enter the command ‘java -version’ which will tell what version of java is installed on the machine. This command is will let us acknowledge the version and assures java is there installed on the machine. 
$ java -version
If java is installed on your machine then you will see openjdk version number in the message as a response along with other info as pictorially been depicted below.
Step 2: Configure the sublime text’s builds to run java programs as if you don’t really want to open sublime text from GUI, just use this command and save yourself some mouse movements.
$ subl <file-name>
Step 3: Create a new build system that follows the two steps. First click on ‘tools → Build System → New Build System’. By far a new file named untitled.sublime-build opens. Lastly, simply copy and paste the following code into that file.
{
    "shell_cmd": "javac $file_name && java $file_base_name"
}
The above instruction runs the given command in shell replacing $file_name with your actual file-name and $file_base_name with the file-name without extension( file-name without .java extension) , whenever the code run command ( Ctrl + B ) is invoked in Sublime Text.
Step 4: Save the build System and giving it a run. 
First, give it a name like RunJava.sublime-build by hitting ‘Ctrl + S’
Open a new java file and write some basic code and save it.
Then click Tools→Build System → Choose your newly created build file RunJava (in this case).
At last to run the program, press Ctrl + B.
A new window appears at the bottom which shows output of your code. Do remember that this run window can’t take input. It can just show the output of your code. 
Java
Linux-Unix
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Functional Interfaces in Java
Stream In Java
Constructors in Java
Different ways of Reading a text file in Java
Exceptions in Java
Sed Command in Linux/Unix with examples
AWK command in Unix/Linux with examples
grep command in Unix/Linux
cut command in Linux with examples
TCP Server-Client implementation in C
jQuery - stopPropagation()  Method

The stopPropagation()  method stops the bubbling of an event to parent elements, preventing any parent handlers from being notified of the event. 
You can use the method event.isPropagationStopped() to know whether this method was ever called (on that event object).
Here is the simple syntax to use this method −
event.stopPropagation() 

Here is the description of all the parameters used by this method −
NA
NA
Following is a simple example a simple showing the usage of this method. This example demonstrate how you can prevent other event handlers from being called −
<html>
<head>
<title>the title</title>
   <script type="text/javascript" 
   src="/jquery/jquery-1.3.2.min.js">
      </script>
   <script type="text/javascript" language="javascript">
   
   $(document).ready(function() {

      $("div").click(function(event){
          alert("This is : " + $(this).text());
          // Comment the following to see the difference
          event.stopPropagation();
      });

   });

   </script>
   <style>
      div{ margin:10px;padding:12px;
             border:2px solid #666;
             width:160px;
           }
  </style>
</head>
<body>
   <p>Click on any box to see the effect:</p>
   <div id="div1" style="background-color:blue;">
       OUTER BOX
       <div id="div2" style="background-color:red;">
             INNER BOX
      </div> 
  </div>
</body>
</html>

To understand it in better way you can Try it yourself.

Advertisements


    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
Types of References in Java

There are four different kinds of references based on the way in which the data is garbage collected.
Strong references
Weak references
Soft references
Phantom references
It is the default type of reference object. An object that has active strong reference can’t be garbage
collected. It is possible only if the variable that is strongly referenced points to null.
Let us see an example −
class Demo {
   //Some functionality
}
public class Demo_example{
   public static void main(String[] args){
      Demo my_inst = new Demo();
      my_inst = null;
   }
}
They are not default class of reference object, hence need to be explicitly specified. It is generally
used with WeakHashmap, so as to reference entry objects. Such weak references are marked for
garbage collection by the Java Virtual Machine. Such references are created using the
‘java.lang.ref.WeakReference’ class.
Let us see an example −
 Live Demo
import java.lang.ref.WeakReference;
class Demo{
   public void display_msg(){
      System.out.println("Hello");
   }
}
public class Demo_sample{
   public static void main(String[] args){
      Demo inst = new Demo();
      inst.display_msg();
      WeakReference<Demo> my_weak_ref = new WeakReference<Demo>(inst);
      inst = null;
      inst = my_weak_ref.get();
      inst.display_msg();
}
Hello
Hello
A class named Demo has a function named ‘display_msg’. This function displays a relevant message.
In another class named ‘Demo_sample’, the main function is defined, and an instance of Demo class
is created. The ‘display_msg’ function is called on the instance. A weakReference to the Demo class
is created, and the Demo insatne is assigned to null, and the function is called on it again. The
relevant output is displayed on the console.
Chunking an array in JavaScript

We are required to write a function chunk() that takes in an array arr of string / number literals
as the first argument and a number n as second argument.
We are required to return an array of n subarrays, each of which contains at most arr.length / n
elements. And the distribution of elements should be like this −
The first element goes in the first subarray, second in second, third in third and so on. Once we
have one element in each subarray, we again start with filling the first subarray with its second
element. Similarly, when all subarrays have two elements only after that we fill the third element
in the first array and so on.
For example −
// if the input array is:
const input = [1, 2, 3, 4, 5, 6];
//then the output should be:
const output = [
   [1, 4],
   [2, 5],
   [3, 6]
];
Let’s write the code for this function, we will Array.prototype.reduce() method over the original
array to construct the desired array. The code for this will be −
const input = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const chunk = (arr, size) => {
   return arr.reduce((acc, val, ind) => {
      const subIndex = ind % size;
      if(!Array.isArray(acc[subIndex])){
         acc[subIndex] = [val];
      } else {
         acc[subIndex].push(val);
      };
      return acc;
   }, []);
};
console.log(chunk(input, 4));
The output in the console will be −
[ [ 1, 5, 9 ], [ 2, 6 ], [ 3, 7 ], [ 4, 8 ] ]
Context api in React.js

The React context api is safe to use in production with the version 16.3 or latest. The reason for adding context api is to avoid the passing of props if there is a chain of children components.
Without the use of context api, we have to pass the props through all the intermediate components. The other alternative solution is to use third party library such as Redux for maintaining a central store.
App.js → props for books → BookList.js → passing the books as props again → Book.js
With the increase in number of children components, the chain of passing the props goes on.
With context api, react provides a provider consumer approach to solve this issue.
Creating the context:
BaseContext.js
import React from 'react';
// this is the same to the createStore method of Redux
const BaseContext = React.createContext();
export default BaseContext;
import BaseContext from './BaseContext';
class BookProvider extends Component {
   state = {
      books: {
         book1: { name: 'React', price: 500 },
         book2: { name: 'Angular', price: 450 }
      }
   };
   render() {
      return (
         <BaseContext.Provider
            value={{
               books: this.state.books,
               incrementPrice: selectedID => {
                  const books = Object.assign({}, this.state.books);
                  books[selectedID].price =books[selectedID].price + 1;
                  this.setState({
                     books
                  });
               },
               decrementPrice: selectedID => {
                  const books = Object.assign({}, this.state.books);
                  books[selectedID].price =books[selectedID].price - 1;
                  this.setState({
                     books
                  });
               }
            }}
         >
         {this.props.children}
         </BaseContext.Provider>
      );
   }
}
class App extends Component {
   render() {
      return (
         <BookProvider>
            <div className="App">
               <header className="App-header">
                  <h1 className="App-title">Welcome to my book store</h1>
               </header>
               <ProductBookList />
            </div>
         </BookProvider>
      );
   }
}
In the children component, we can use the consumer −
const Books = () => (
   <BaseContext.Consumer>
      {context => (
         <Fragment>
            <h4>Books:</h4>
            {Object.keys(context.books).map(bookID => (
               <Car
                  key={bookID}
                  name={context.books[bookID].name}
                  price={context.books[bookID].price}
                  incrementPrice={() =>context.incrementPrice(bookID)}
                  decrementPrice={() =>context.decrementPrice(bookID)}
               />
            ))}
         </Fragment>
      )}
   </BaseContext.Consumer>
);
With the use of context api we can avoid the props drilling in React children components.
Minimum steps to make all the elements of the array divisible by 4 in C++

Given an array of size n, the task iss to find the minimum number of steps required to make all the elements of the array divisible by 4. A step is defined as removal of any two elements from the array and adding the sum of these elements to the array
If input array is {1, 2, 0, 2, 4, 3} then 3 operations are
required −
1 + 3 = 4
2 + 2 = 4
0 + 4 = 4
1. Sum of all the elements of the array should be divisible by If not, this task is not possible
2. Initialize an array namely modulus of size 4 to 0
3. Initialize a counter to 0. It will keep track of number of steps done
4. Traverse through the input array and take modulus 4 of each element
5. Increment the value of the mod 4 value in the modulus array by 1
6. modulus[0] is the count of elements that are already divisible by 4. So no need to pair them with any other element
7. modulus[1] and modulus[3] elements can be combined to get a number divisible by 4. So, increment count to the minimum value of the both
8. Every 2 elements of modulus[2] can be combined to get an element divisible to 4.
9. For the remaining elements, increment value modulus[2] by half of modulus[1] and modulus[3].
10. Now, increment count by half modulus[2]. We take half because every two elements are combined as one
11. The final value of count is the number of steps required to convert the all the elements of the input array divisible by 4
 Live Demo
#include <bits/stdc++.h>
using namespace std;
int getMinRequiredSteps(int arr[], int n) {
   int count = 0;
   int modulus[4] = {0};
   int sum = 0;
   for (int i = 0; i < n; i++) {
      int mod = arr[i] % 4;
      sum += mod;
      modulus[mod]++;
   }
   if (sum % 4 != 0) {
      return -1;
   } else {
      if (modulus[1] > modulus[3]) {
         count += modulus[3];
      }
      else {
         count += modulus[1];
      }
      modulus[1] -= count;
      modulus[3] -= count;
      modulus[2] += modulus[1] / 2;
      modulus[2] += modulus[3] / 2;
      count += modulus[1] / 2;
      count += modulus[3] / 2;
      count += modulus[2] / 2;
      return count;
   }
}
int main() {
   int arr[] = {1, 2, 0, 2, 4, 3};
   int n = sizeof(arr) / sizeof(arr[0]);
   cout << "Minimum required steps = " << getMinRequiredSteps(arr, n) << endl;
   return 0;
}
When you compile and execute above program. It generates following output
Minimum required steps = 2
PHP Type Juggling

PHP is known as a dynamically typed language. Explicit type declaration of a variable is neither needed nor supported in PHP. Contrary to C, C++ and Java, type of PHP variable is decided by the value assigned to it, and not other way around. Further, a variable when assigned value of different type, its type too changes. This approach of PHP to deal with dynamically changing value of variable is called type juggling.
$var="Hello"; // variable is string type
$var=100; //same variable now becomes int
Type juggling also takes place during calculation of expression. In this example, a string variable containing digits is automatically converted to integer for evaluation of addition expression
 Live Demo
<?php
$var1=100;
$var2="100";
$var3=$var1+$var2;
var_dump($var3);
?>
This will produce following result −
int(200)
If a string starts with digits, trailing non-numeric characters if any, are ignored while performing calculation. However, PHP parser issues a notice as shown below
<?php
$var1=100;
$var2="100 days";
$var3=$var1+var2;
var_dump($var3);
?>
This will produce following result −
PHP Notice: A non well formed numeric value encountered in ...
int(200)
Type casting forces a variable to be used as a certain type. Following script shows example of different type cast operators
 Live Demo
<?php
$var1=100;
$var2=(boolean)$var1;
$var3=(string)$var1;
$var4=(array)$var1;
$var5=(object)$var1;
var_dump($var2, $var3, $var4, $var5);
?>
This will produce following result −
bool(true)
string(3) "100"
array(1) {
   [0]=>
   int(100)
}
object(stdClass)#1 (1) {
   ["scalar"]=>
   int(100)
}
Casting a variable to string can also be done by enclosing in double quoted string
 Live Demo
<?php
$var1=100.50;
$var2=(string)$var1;
$var3="$var1";
var_dump($var2, $var3);
?>
This will produce following result −
string(5) "100.5"
string(5) "100.5"
Java Program to convert from integer to String

To convert integer to string, firstly set an integer.
int val = 150;
Now use the Integer.toString() method and pass the same int value. The method returns a string representation.
String myStr = Integer.toString(val);
Let us now see the complete example.
 Live Demo
public class Demo {
   public static void main( String args[] ) {
      int val = 150;
      // integer to string
      String myStr = Integer.toString(val);
      System.out.println("String: "+myStr);
   }
}
String: 150
What is a reference/ref parameter of an array type in C#?

Declare the reference parameters using the ref keyword. A reference parameter is a reference to a memory location of a variable. When you pass parameters by reference, unlike value parameters, a new storage location is not created for these parameters.
Declare a ref parameter −
public void swap(ref int x, ref int y) {}
Declare a ref parameter of array type −
static void Display(ref int[] myArr)
The following is an example showing how to work with ref parameter of an array type in C# −
class TestRef {
   static void Display(ref int[] myArr) {
      if (myArr == null) {
         myArr = new int[10];
      }

      myArr[0] = 345;
      myArr[1] = 755;
      myArr[2] = 231;
   }

   static void Main() {
      int[] arr = { 98, 12, 65, 45, 90, 34, 77 };

      Display(ref arr);

      for (int i = 0; i < arr.Length; i++) {
         System.Console.Write(arr[i] + " ");
      }

      System.Console.ReadKey();
   }
}
C# Program to Subtract Two TimeSpan

Firstly, set two TimeSpans −
TimeSpan t1 = TimeSpan.FromMinutes(2);
TimeSpan t2 = TimeSpan.FromMinutes(1);
To add it, use the Subtract() method −
imeSpan res = t1.Subtract(t2);
Here is the complete code −
 Live Demo
using System;
using System.Linq;
public class Demo {
   public static void Main() {
      TimeSpan t1 = TimeSpan.FromMinutes(2);
      TimeSpan t2 = TimeSpan.FromMinutes(1);
      Console.WriteLine("First TimeSpan: "+t1);
      Console.WriteLine("Second TimeSpan: "+t2);
      // Subtracting
      TimeSpan res = t1.Subtract(t2);
      Console.WriteLine("Resultant TimeSpan: "+res);
   }
}
First TimeSpan: 00:02:00
Second TimeSpan: 00:01:00
Resultant TimeSpan: 00:01:00
Python Program to find whether a no is power of two

06 Jan, 2022
Given a positive integer, write a function to find if it is a power of two or not.Examples :  
Input : n = 4
Output : Yes
22 = 4

Input : n = 7
Output : No

Input : n = 32
Output : Yes
25 = 32
1. A simple method for this is to simply take the log of the number on base 2 and if you get an integer then number is power of 2.  
Python3
# Python3 Program to find# whether a no is# power of twoimport math # Function to check# Log base 2def Log2(x):    return (math.log10(x) /            math.log10(2)); # Function to check# if x is power of 2def isPowerOfTwo(n):    return (math.ceil(Log2(n)) == math.floor(Log2(n))); # Driver Codeif(isPowerOfTwo(31)):    print("Yes");else:    print("No"); if(isPowerOfTwo(64)):    print("Yes");else:    print("No");     # This code is contributed# by mits
No
Yes
 
Time Complexity: O(log2n)
Auxiliary Space: O(1)
2. Another solution is to keep dividing the number by two, i.e, do n = n/2 iteratively. In any iteration, if n%2 becomes non-zero and n is not 1 then n is not a power of 2. If n becomes 1 then it is a power of 2. 
Python3
# Python program to check if given# number is power of 2 or not # Function to check if x is power of 2def isPowerOfTwo(n):    if (n == 0):        return False    while (n != 1):            if (n % 2 != 0):                return False            n = n // 2                 return True # Driver codeif(isPowerOfTwo(31)):    print('Yes')else:    print('No')if(isPowerOfTwo(64)):    print('Yes')else:    print('No') # This code is contributed by Danish Raza
No
Yes
 
3. All power of two numbers have only one bit set. So count the no. of set bits and if you get 1 then number is a power of 2. Please see Count set bits in an integer for counting set bits.4. If we subtract a power of 2 numbers by 1 then all unset bits after the only set bit become set; and the set bit become unset.For example for 4 ( 100) and 16(10000), we get following after subtracting 1 3 –> 011 15 –> 01111So, if a number n is a power of 2 then bitwise & of n and n-1 will be zero. We can say n is a power of 2 or not based on value of n&(n-1). The expression n&(n-1) will not work when n is 0. To handle this case also, our expression will become n& (!n&(n-1)) (thanks to https://www.geeksforgeeks.org/program-to-find-whether-a-no-is-power-of-two/Mohammad for adding this case). Below is the implementation of this method.  
Python3
# Python program to check if given# number is power of 2 or not # Function to check if x is power of 2def isPowerOfTwo (x):     # First x in the below expression    # is for the case when x is 0    return (x and (not(x & (x - 1))) ) # Driver codeif(isPowerOfTwo(31)):    print('Yes')else:    print('No')     if(isPowerOfTwo(64)):    print('Yes')else:    print('No')     # This code is contributed by Danish Raza   
No
Yes
 
Please refer complete article on Program to find whether a no is power of two for more details! 
souravmahato348
amartyaghoshgfg
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Ruby | Array sort() function

06 Dec, 2019
Array#sort() : sort() is a Array class method which returns a new array created by sorting self
Syntax: Array.sort()
Parameter: Array
Return: a new array created by sorting self
Example #1 :
# Ruby code for sort() method  # declaring arraya = ["abc", "nil", "dog"]  # declaring arrayc = ["cat", "efg", "geeks"]  # declaring arrayb = ["cow", "coal", "dog"]  arr = [a, b, c]  # sort method exampleputs "sort() method form : #{arr.sort()}\n\n"
Output :
sort() method form : [["abc", "nil", "dog"], ["cat", "efg", "geeks"], ["cow", "coal", "dog"]]


Example #2 :
# Ruby code for sort() method  # declaring arraya = ["abc", "nil", "dog"]  # declaring arrayc = ["cat", "efg", "geeks"]  # declaring arrayb = ["cow", "coal", "dog"]    # sort method exampleputs "sort() method form : #{a.sort()}\n\n"  puts "sort() method form : #{b.sort()}\n\n"  puts "sort() method form : #{c.sort()}\n\n"
Output :
sort() method form : ["abc", "dog", "nil"]

sort() method form : ["coal", "cow", "dog"]

sort() method form : ["cat", "efg", "geeks"]


Ruby Array-class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Make a Custom Array of Hashes in Ruby?
Ruby | Enumerator each_with_index function
Ruby | unless Statement and unless Modifier
Ruby on Rails Introduction
Ruby | String concat Method
Ruby | Array class find_index() operation
Ruby For Beginners
Ruby | Array shift() function
Ruby | Types of Variables
PHPUnit assertIsArray() Function

07 Aug, 2020
The assertIsArray() function is a builtin function in PHPUnit and is used to assert whether the given variable is an array or not. This assertion will return true in the case if the given variable is array else returns false. In case of true the asserted test case got passed else test case got failed.
Syntax:
assertIsArray($actual[, $message = ''])


Parameters: This function accepts two parameters as mentioned above and described below:
$variable: This parameter is of any type of variable which represents the actual data.
$message: This parameter takes a string value. When the test case got failed this string message got displayed as an error message.
Below example illustrate the assertIsArray() function in PHPUnit:
Example 1:
PHP
<?php use PHPUnit\Framework\TestCase;     class GeeksPhpunitTestCase extends TestCase {     public function testNegativeForassertIsArray()              {       $variable  =  ("apple/banana");        // Assert function to test whether assert        //  variable is array or not        $this->assertIsArray(            $variable,            "assert variable is array or not"        );              }    } ?> 
Output:
PHPUnit 8.5.8 by Sebastian Bergmann and contributors.

F                                                  1 / 1 (100%)

Time: 90 ms, Memory: 10.00 MB

There was 1 failure:

1) GeeksPhpunitTestCase::testNegativeForassertIsArray
assert variable is array or not
Failed asserting that 'apple/banana' is of type "array".

/home/lovely/Documents/php/test.php:15

FAILURES!
Tests: 1, Assertions: 1, Failures: 1.

Example 2:
PHP
<?php use PHPUnit\Framework\TestCase;     class GeeksPhpunitTestCase extends TestCase {     public function testPositiveForassertIsArray()              {       $variable  = array ("apple/banana");        // Assert function to test whether assert        //  variable is array or not        $this->assertIsArray(            $variable,            "assert variable is array or not"        );              }    } ?> 
Output:
PHPUnit 8.5.8 by Sebastian Bergmann and contributors.

.                                                  1 / 1 (100%)

Time: 88 ms, Memory: 10.00 MB

OK (1 test, 1 assertion)

Reference: https://phpunit.readthedocs.io/en/9.2/assertions.html#assertisiterable
PHP-PHPUnit
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Get the Number of Levels of a Factor in R Programming – nlevels() Function

16 Jun, 2020
nlevels() function in R Language is used to get the number of levels of a factor.
Syntax: nlevels(x)
Parameters:x: Factor Object
Example 1:
# R program to get the number# of levels of a factor  # Creating a factorx <- gl(3, 2)x  # Calling nlevels() function# to get the number of levelsnlevels(x)
Output:
[1] 1 1 2 2 3 3
Levels: 1 2 3
[1] 3

Example 2:
# R program to get the number# of levels of a factor  # Creating a factorgender <- factor(c("female", "male", "male", "female")); gender  # Calling nlevels() function# to get the number of levelsnlevels(gender)
Output:
[1] female male   male   female
Levels: female male
[1] 2

R Factor-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What does ** (double star) and * (star) do for parameters in Python?

In Python function, an argument with single asterisk (star) prefixed to it helps in receiving variable number of argument from calling environment
>>> def function(*arg):
      for i in arg:
        print (i)

>>> function(1,2,3,4,5)
1
2
3
4
5
Argument with double asterisks (stars) is used in function definition when variable number of keyword arguments have to be passed to a function
>>> def function(**arg):
      for i in arg:
        print (i,arg[i])


>>> function(a=1, b=2, c=3, d=4)
a 1
b 2
c 3
d 4
In Python 3, it is possible to define a variable with asterisk in assignment statement to enable extended unpacking of iterables.
>>> a,*b=[1,2,3,4]
>>> a
1
>>> b
[2, 3, 4]
>>> a,*b,c=[1,2,3,4]
>>> a
1
>>> b
[2, 3]
>>> c
4
Connell sequence in Python

Suppose we have a number n, we have to find the nth term of Connell sequence. The Connell
sequence is as follows: 1. Take first odd integer: 1 2. Take next two even integers 2, 4 3. Then
take the next three odd integers 5, 7, 9 4. After that take the next four even integers 10, 12, 14,
16 And so on.
So, if the input is like 12, then the output will be 21
To solve this, we will follow these steps −
i := 1
while quotient of (i *(i + 1) / 2) < n + 1, doi := i + 1
i := i + 1
idx := i *(i + 1) / 2, take only quotient
num := i^2
return num - 2 *(idx - n - 1)
Let us see the following implementation to get better understanding −
 Live Demo
class Solution:
   def solve(self, n):
      i = 1
      while (i * (i + 1) // 2) < n + 1:
         i += 1
      idx = i * (i + 1) // 2
      num = i**2
   return num - 2 * (idx - n - 1)
ob = Solution()
print(ob.solve(12))
12
21
When are Constructors Called in C++?

Here we will see, when constructors are called. Here constructors are of different types. Global, local, static local, dynamic.
For the global object, the constructors are called before entering into the main function.
#include <iostream>
using namespace std;
class MyClass {
   public:
      MyClass() {
         cout << "Calling Constructor" << endl;
      }
};
MyClass myObj; //Global object
int main() {
   cout << "Inside Main";
}
Calling Constructor
Inside Main
When the object is non-static, then, constructor is called when the execution reaches the point, where object is created.
#include <iostream>
using namespace std;
class MyClass {
   public:
      MyClass() {
         cout << "Calling Constructor" << endl;
      }
};
int main() {
   cout << "Inside Main\n";
   MyClass myObj; //Local object
   cout << "After creating object";
}
Inside Main
Calling Constructor
After creating object
When the object is local static, then only for the first time, its constructor will be called, if the same function is used again, it will not affect.
#include <iostream>
using namespace std;
class MyClass {
   public:
      MyClass() {
         cout << "Calling Constructor" << endl;
      }
};
void func() {
   static MyClass myObj; //Local static object
}
int main() {
   cout << "Inside Main\n";
   func();
   cout << "After creating object\n";
   func();
   cout << "After second time";
}
Inside Main
Calling Constructor
After creating object
After second time
Finally for the dynamic object, the constructor will be called, when object is created using new operator.
#include <iostream>
using namespace std;
class MyClass {
   public:
      MyClass() {
         cout << "Calling Constructor" << endl;
      }
};
int main() {
   cout << "Inside Main\n";
   MyClass *ptr;
   cout << "Declaring pointer\n";
   ptr = new MyClass;
   cout << "After creating dynamic object";
}
Inside Main
Declaring pointer
Calling Constructor
After creating dynamic object
First Bad Version in Python

Suppose in a company, one product manager is leading a team who develops a new product. Suppose latest version fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version will be bad. So we have an array A with n elements [1, 2, ... n] and we have to find the first bad version from this array.
Consider we have a function isBadVersion(version_id), this will return whether the version is bad or not. For an example, suppose n = 5, and version = 4 is first bad version. So if the isBadVersion(3) returns false isBadVersion(5) returns true, and isBadVersion(4) also returns true, then the first bad version is 4
To solve this, we will follow these steps −
When n < 2, then return n
Perform binary search approach to detect bad version using the given function.
Let us see the following implementation to get better understanding −
 Live Demo
first_bad = 0
def isBadVersion(version):
   if version >= first_bad:
      return True
   return False
class Solution:
   def firstBadVersion(self, n):
      if n <2:
         return n
      start = 1
      end = n
      while(start<=end):
         mid = (start+end)//2
         if isBadVersion(mid) and not isBadVersion(mid-1):
            return mid
         elif isBadVersion(mid-1):
            end = mid-1
         else:
            start = mid+1
ob1 = Solution()
first_bad = 4
op = ob1.firstBadVersion(5)
print(op)
5
4
4
How to Automate the Storage using Dropbox API in Python ?

21 Apr, 2021
In this Data Era Storing, Managing, and organizing the Data is an important factor considered by every business. Dropbox is one of the most popular cloud storage systems on the market, and it continues to improve its features.  In this article, we will be demonstrating how one can connect to dropbox API using Python and perform Storage Automation efficiently.
 Go to https://www.dropbox.com/developers/apps/create, You will see a Page like this. Select the “Scoped Access” option and in step 2 select “Full Dropbox”, Name your app with any significant name.
In the Oauth2 Section, Set Access Token Expiration to “No Expiration“, generate an Access Token.
Go to Permissions Tab, Select Appropriate Permissions that are required, and click Submit.
With The Token Key Generated from the Above steps, We can use this token to connect to dropbox and perform storage Automation. You can install the python library using the below command:
pip install dropbox 
Demonstration video to generate a token:
Use the token generated to connect to dropbox and create an object.
Python3
# importing necessary librariesimport dropbox  # Token Generated from dropboxTOKEN = "access_token"  # Establish connectiondef connect_to_dropbox():        try:        dbx = dropbox.Dropbox(TOKEN)        print('Connected to Dropbox successfully')          except Exception as e:        print(str(e))          return dbx  dbx = connect_to_dropbox()
Output:
Connected to Dropbox successfully
We have successfully connected to Dropbox. We can now list folders/files, read files, upload files, delete files, etc.  
First, call the above method to connect and create a dropbox object, then assign a path for the folder to be scanned, then iterate through the older using file_list_folder() method and for a loop.
Python3
# explicit function to list filesdef list_files_in_folder():        # here dbx is an object which is obtained    # by connecting to dropbox via token    dbx = connect_to_dropbox()          try:        folder_path = "/folder_path"          # dbx object contains all functions that         # are required to perform actions with dropbox        files = dbx.files_list_folder(folder_path).entries        print("------------Listing Files in Folder------------ ")                  for file in files:                          # listing            print(file.name)                  except Exception as e:        print(str(e))  list_files_in_folder()
Output:
Now we have successfully connected to dropbox using python, Listed the Folders present in it.
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Reverse String II in Python

Suppose we have a string and an integer k, we have to reverse the first k characters for every 2k characters counting from the start of the string. If there is no sufficient character left, then reverse all of them. If there are less than 2k characters but greater than or equal to k characters, then reverse the first k characters and left the other as original.
So, if the input is like "abcdefgh" and k = 3, then the output will be "cbadefhg"
To solve this, we will follow these steps −
l := make a list of characters of s
l := make a list of characters of s
i := k-1
i := k-1
while i < size of l + k −a := l[from index 0 to i-k+1]b := l[from index i-k+1 to i+1]c := l[from index i+1 to end]l := a concatenate b[from index 0 to end] concatenate ci := i + 2*k
while i < size of l + k −
a := l[from index 0 to i-k+1]
a := l[from index 0 to i-k+1]
b := l[from index i-k+1 to i+1]
b := l[from index i-k+1 to i+1]
c := l[from index i+1 to end]
c := l[from index i+1 to end]
l := a concatenate b[from index 0 to end] concatenate c
l := a concatenate b[from index 0 to end] concatenate c
i := i + 2*k
i := i + 2*k
return string by concatenating each character in l
return string by concatenating each character in l
Let us see the following implementation to get a better understanding −
 Live Demo
class Solution:
   def reverseStr(self, s, k):
      l = list(s)
      i = k-1
      while i < len(l)+k:
         a = l[:i-k+1]
         b = l[i-k+1:i+1]
         c = l[i+1:]
         l = a + b[::-1] + c
         i += 2*k
      return ''.join(l)

ob = Solution()
print(ob.reverseStr("abcdefg", 3))
"abcdefg", 3
cbadefg