code-rag-bench/online-tutorials huggingface dataset:
Python Program to Print all Integers that Aren't Divisible by Either 2 or 3 - GeeksforGeeks

26 Nov, 2020
We can input a set of integer, and check which integers in this range, beginning with 1 are not divisible by 2 or 3, by checking the remainder of the integer with 2 and 3. 
Example:
Input: 10
Output: Numbers not divisible by 2 and 3
1
5
7

Method 1: We check if the number is not divisible by 2 and 3 using the and clause, then outputs the number. 
Python3
# input the maximum number to# which you want to sendmax_num = 20  # starting numbers from 0n = 1  # run until it reaches maximum numberprint("Numbers not divisible by 2 and 3")while n <= max_num:          # check if number is divisible by 2 and 3    if n % 2 != 0 and n % 3 != 0:        print(n)          # incrementing the counter    n = n+1
Output:
Numbers not divisible by 2 and 3
1
5
7
11
13
17
19
Method 2: We traverse the odd numbers starting with 1 since even numbers are divisible by 2. So, we increment the for a loop by 2, traversing only odd numbers and check, which one of them is not divisible by 3. This approach is better than the previous one since it only iterates through half the number of elements in the specified range.
The following Python code illustrates this : 
Python3
# input the maximum number to# which you want to sendmax_num = 40print("Numbers not divisible by 2 or 3 : ")  # run until it reaches maximum number# we increment the loop by +2 each time,# since odd numbers are not divisible by 2for i in range(1, max_num, 2):          # check if number is not divisible by  3    if i % 3 != 0:        print(i)
Output:
Numbers not divisible by 2 or 3 : 
1
5
7
11
13
17
19
23
25
29
31
35
37

Number Divisibility
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Box Plot in Python using Matplotlib
Python | Get dictionary keys as a list
Bar Plot in Matplotlib
Multithreading in Python | Set 2 (Synchronization)
Python Dictionary keys() method
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python program to check whether a number is Prime or not
Python | Convert a list to dictionary
How to Force User to Change Password at Next Login in Linux?

Because of security concerns, the users in a system are required to update their passwords regularly. In this article we will see how we can force an user to change their password when they login to the system next time.
First lets have a look at the users available in the system.
$ cut -d: -f1 /etc/passwd
Running the above code gives us the following result −
mail
news
uucp
proxy
www-data
backup
list
...
Ubuntu
uname1
Next we check the settings for users current password system configuration.
$ sudo chage -l uname1
[sudo] password for ubuntu:
Running the above code gives us the following result −
Last password change: Dec 30, 2019
Password expires: never
Password inactive: never
Account expires: never
Minimum number of days between password change: 0
Maximum number of days between password change: 99999
Number of days of warning before password expires: 7
Now we sue the expire option to set the timeline for password expiry and then query it with the chage to find the expiry implemented.
$ sudo passwd --expire uname1
passwd: password expiry information changed.
$ sudo chage -l uname1
Running the above code gives us the following result −
Last password change: password must be changed
Password expires: password must be changed
Password inactive: password must be changed
Account expires: never
Minimum number of days between password change: 0
Maximum number of days between password change: 99999
Number of days of warning before password expires: 7
Drink Water notification system in Python - GeeksforGeeks

13 Jan, 2021
The idea behind this article is to create a notification system that reminds the user to drink water after a fixed interval of time. The program coded below first asks its user to input time interval for notification. Then until user ends script, it sends repeated notifications to user to drink water. After each interval it creates a text file which contains a log of when user drank water.
time: To manage the interval time.
win10Toast : To send quick notification.
datetime : To keep record of time and date in log.
Import module
Get time interval from the user, it asks user to input hour, minutes and seconds
Convert them to seconds and return time to main function.
Add loop to start timer and generate a toast message when timer reaches the set time
After sending notification program will call to function to write log file. This function will get current time and date  
Create a .txt file and append drink water log to it.
Program:
Python3
import timefrom win10toast import ToastNotifierimport datetime    def getTimeInput():    hour = int(input("hours of interval :"))    minutes = int(input("Mins of interval :"))    seconds = int(input("Secs of interval :"))    time_interval = seconds+(minutes*60)+(hour*3600)    return time_interval    def log():    now = datetime.datetime.now()    start_time = now.strftime("%H:%M:%S")    with open("log.txt", 'a') as f:        f.write(f"You drank water {now} \n")    return 0    def notify():    notification = ToastNotifier()    notification.show_toast("Time to drink water")    log()    return 0    def starttime(time_interval):    while True:        time.sleep(time_interval)        notify()    if __name__ == '__main__':    time_interval = getTimeInput()    starttime(time_interval)
Output:
python-utility
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Defaultdict in Python
Selecting rows in pandas DataFrame based on conditions
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Python | Pandas dataframe.groupby()
How to create responsive "Meet The Team" page with CSS?

Following is the code to produce a responsive “meet the team” page using HTML and CSS −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
html {
   box-sizing: border-box;
}
body{
   font-family: monospace,serif,sans-serif;
}
img{
   height: 300px;
   width: 100%;
}
*, *:before, *:after {
   box-sizing: inherit;
}
.teamColumn {
   float: left;
   width: 33.3%;
   margin-bottom: 16px;
   padding: 0 8px;
}
@media screen and (max-width: 650px) {
.teamColumn {
   width: 100%;
   display: block;
}
}
.teamCard {
   background-color: rgb(162, 162, 255);
   text-align: center;
   font-size: 20px;
}
.personContainer {
   padding: 0 16px;
}
.personContainer::after, .teamContainer::after {
   content: "";
   clear: both;
   display: table;
}
.Designation {
   color: rgb(15, 0, 100);
   font-weight: bolder;
   font-size: 40px;
}
.contact {
   border: none;
   outline: 0;
   display: inline-block;
   padding: 12px;
   color: white;
   font-weight: bolder;
   background-color: rgb(78, 0, 102);
   text-align: center;
   cursor: pointer;
   width: 100%;
}
.contact:hover {
   background-color: #555;
}
</style>
</head>
<body>
<h1 style="text-align: center;">Responsive Meet the team example </h1>
<div class="teamContainer">
<div class="teamColumn">
<div class="teamCard">
<img src="https://images.pexels.com/photos/839011/pexels-photo-839011.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" >
<div class="personContainer">
<h2>Jane Doe</h2>
<p class="Designation">CTO</p>
<p><button class="contact">Contact</button></p>
</div>
</div>
</div>
<div class="teamColumn">
<div class="teamCard">
<img src="https://images.pexels.com/photos/614810/pexels-photo-614810.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500">
<div class="personContainer">
<h2>Mike Ross</h2>
<p class="Designation">Front End Developer</p>
<p><button class="contact">Contact</button></p>
</div>
</div>
</div>
<div class="teamColumn">
<div class="teamCard">
<img src="https://images.pexels.com/photos/736716/pexels-photo-736716.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500">
<div class="personContainer">
<h2>John Doe</h2>
<p class="Designation">FullStack Developer</p>
<p><button class="contact">Contact</button></p>
</div>
</div>
</div>
</div>
</body>
</html>
The above code will produce the following output −
React Native - Modal

In this chapter, we will show you how to use the modal component in React Native.
Let us now create a new file: ModalExample.js
We will put logic inside ModalExample. We can update the initial state by running the toggleModal.
After updating the initial state by running the toggleModal, we will set the visible property to our modal. This prop will be updated when the state changes.
The onRequestClose is required for Android devices.
import React, { Component } from 'react'
import WebViewExample from './modal_example.js'

const Home = () => {
   return (
      <WebViewExample/>
   )
}
export default Home;
import React, { Component } from 'react';
import { Modal, Text, TouchableHighlight, View, StyleSheet}

from 'react-native'
class ModalExample extends Component {
   state = {
      modalVisible: false,
   }
   toggleModal(visible) {
      this.setState({ modalVisible: visible });
   }
   render() {
      return (
         <View style = {styles.container}>
            <Modal animationType = {"slide"} transparent = {false}
               visible = {this.state.modalVisible}
               onRequestClose = {() => { console.log("Modal has been closed.") } }>
               
               <View style = {styles.modal}>
                  <Text style = {styles.text}>Modal is open!</Text>
                  
                  <TouchableHighlight onPress = {() => {
                     this.toggleModal(!this.state.modalVisible)}}>
                     
                     <Text style = {styles.text}>Close Modal</Text>
                  </TouchableHighlight>
               </View>
            </Modal>
            
            <TouchableHighlight onPress = {() => {this.toggleModal(true)}}>
               <Text style = {styles.text}>Open Modal</Text>
            </TouchableHighlight>
         </View>
      )
   }
}
export default ModalExample

const styles = StyleSheet.create ({
   container: {
      alignItems: 'center',
      backgroundColor: '#ede3f2',
      padding: 100
   },
   modal: {
      flex: 1,
      alignItems: 'center',
      backgroundColor: '#f7021a',
      padding: 100
   },
   text: {
      color: '#3f2949',
      marginTop: 10
   }
})
Our starting screen will look like this −
If we click the button, the modal will open.

    20 Lectures 
     1.5 hours 

 Anadi Sharma

    61 Lectures 
     6.5 hours 

 A To Z Mentor

    40 Lectures 
     4.5 hours 

 Eduonix Learning Solutions

    56 Lectures 
     12.5 hours 

 Eduonix Learning Solutions

    62 Lectures 
     4.5 hours 

 Senol Atac

    67 Lectures 
     4.5 hours 

 Senol Atac
 Print
 Add Notes
 Bookmark this page
C++ List Library - resize() Function

The C++ function std::list::resize() changes the size of list. If n is smaller than current size then extra elements are destroyed. If n is greater than current container size then new elements are inserted at the end of list.
Following is the declaration for std::list::resize() function form std::list header.
void resize (size_type n);

n − Number of element to be inserted.
None
If reallocation fails then bad_alloc exception is thrown.
Linear i.e. O(n)
The following example shows the usage of std::list::resize() function.
#include <iostream>
#include <list>

using namespace std;

int main(void) {
   list<int> l;

   cout << "Initial size of list = " << l.size() << endl;

   l.resize(5);

   cout << "Size of list after resize operation = " << l.size() << endl;

   cout << "List contains following elements" << endl;

   for (auto it = l.begin(); it != l.end(); ++it)
      cout << *it << endl;

   return 0;
}
Let us compile and run the above program, this will produce the following result −
Initial size of list = 0
Size of list after resize operation = 5
List contains following elements
0
0
0
0
0

 Print
 Add Notes
 Bookmark this page
Convert a string to an integer in JavaScript - GeeksforGeeks

26 Jul, 2021
In JavaScript parseInt() function is used to convert the string to an integer. This function returns an integer of base which is specified in second argument of parseInt() function.parseInt() function returns Nan( not a number) when the string doesn’t contain number.
Syntax:
parseInt(Value, radix)
It accepts string as a value and converts it to specified radix system and returns an integer.
Program to convert string to integer:Example-1:
<script>      function convertStoI() {        var a = "100";        var b = parseInt(a);        document.write("Integer value is" + b);        var d = parseInt("3 11 43");        document.write("</br>");          document.write('Integer value is ' + d);      }convertStoI(); </script>    
Output:
Integer value is100
Integer value is 3
ParseInt() function converts number which is present in any base to base 10. It parses string and converts until it faces a string literal and stops parsing.
Example-2:
<script>      function convertStoI() {        var r = parseInt("1011", 2);        var k = parseInt("234", 8);          document.write('Integer value is ' + r);        document.write("<br>");        document.write("integer value is " + k);        document.write("<br>");        document.write(parseInt("528GeeksforGeeks"));      }convertStoI();</script>                    
Output:
Integer value is 11
integer value is 156
528
JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.
javascript-functions
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Difference Between PUT and PATCH Request
Set the value of an input field in JavaScript
How to read a local text file using JavaScript?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
Program to find sum of given sequence in C++

In this problem, we are given two numbers n and k for a series. Our task is to
create a program to find sum of given sequence in C++.
The sequence is −
(1*2*3*...*k) + (2*3*...k*(k+1)) + (3*4*...*k*k+1*k+2) + ((n-k+1)*(nk+
2)*... *(n-k+k).
Problem description − Here, we will find the sum of the given series till nth term based on the given value of k.
Let’s take an example to understand the problem
n = 4, k = 3
30
Series: (1*2*3) + (2*3*4) = 30
A simple solution is to find the sum using iteration. We will use two loops,
one for each term and second for finding the value of the term. Then adding
the value of each term to get the result.
Program to illustrate the working of our solution
 Live Demo
#include <iostream>
using namespace std;
int findSeriesSum(int n, int k){
   int sumVal = 0, term = 1;
   for(int i = 1; i <= (n-k + 1); i++){
      term = 1;
      for(int j = i; j< (k+i); j++){
         term *= j;
      }
      sumVal += term;
   }
   return sumVal;
}
int main(){
   int n = 4, k = 3;
   cout<<"The sum of series is "<<findSeriesSum(n, k);
   return 0;
}
The sum of series is 30
This solution is not efficient as it needs a nested loop that makes the time
complexity of the order O(n2).
An efficient solution could be using the general formula for the series. The formula is,
(◻+1)∗◻∗(◻−1)∗(◻−2)∗....∗(◻−◻+1)◻+1
Program to illustrate the working of our solution
 Live Demo
#include <iostream>
using namespace std;
int findSeriesSum(int n, int k){
   int sumVal = 1;
   for(int i = n+1; i > n-k; i--)
   sumVal *= i;
   sumVal /= (k + 1);
   return sumVal;
}
int main(){
   int n = 4, k = 3;
   cout<<"The sum of series is "<<findSeriesSum(n, k);
   return 0;
}
The sum of series is 30
Set.forEach() function in JavaScript

The forEach() function of the Set object accepts the name of a particular function and runs that function for every value in the current set. For Example, if you have written a function to print a value, if you use forEach() function it prints the value of every element in the set.
Its Syntax is as follows
setObj.forEach()
 Live Demo
<html>
<head>
   <title>JavaScript Example</title>
</head>
<body>
   <script type="text/javascript">
      function sampleFunction(value){
         document.writeln(value+",");
      }
      const setObj1 = new Set();
      setObj1.add('Java');
      setObj1.add('JavaFX');
      setObj1.add('JavaScript');
      setObj1.add('HBase');
      setObj1.forEach(sampleFunction);
      document.write("<br>");
      var sum = 0;
      function mathExample(value) {
         sum = value+sum;
         //document.write(value);
      }
      const setObj2 = new Set();
      setObj2.add(172);
      setObj2.add(364);
      setObj2.add(885);
      setObj2.add(746);
      setObj2.forEach(mathExample);
      document.write("Sum of all elements in the set: "+sum);
   </script>
</body>
</html>
Java, JavaFX, JavaScript, HBase,
Sum of all elements in the set: 2167
What is Kestrel and how does it differ from IIS? (ASP.NET)

Kestrel is a lightweight, cross-platform, and open-source web server for ASP.NET Core. It is included and enabled by default in ASP.NET Core. Kestrel is supported on all platforms and versions supported by .NET Core.
In the Program class, the ConfigureWebHostDefaults() method configures Kestrel as the web server for the ASP.NET Core application.
public class Program{
   public static void Main(string[] args){
      CreateHostBuilder(args).Build().Run();
   }

   public static IHostBuilder CreateHostBuilder(string[] args) =>
      Host.CreateDefaultBuilder(args)
         .ConfigureWebHostDefaults(webBuilder =>{
            webBuilder.UseStartup<Startup>();
         });
}
Though Kestrel can serve an ASP.NET Core application on its own, Microsoft recommends using it along with a reverse proxy such as Apache, IIS, or Nginx for better performance, security, and reliability.
The main difference between IIS and Kestrel is that Kestrel is a cross-platform server. It runs on Linux, Windows, and Mac, whereas IIS is Windows-specific.
Another essential difference between the two is that Kestrel is fully open-source, whereas IIS is closed-source and developed and maintained only by Microsoft.
IIS is an old, albeit powerful software. With Kestrel, Microsoft started with cross-platform and high performance as explicit design goals. Since the Kestrel codebase started from scratch, it allowed developers to ignore the legacy/compatibility issues and focus on speed and efficiency.
However, Kestrel doesn’t provide all the rich functionality of a full-fledged web server such as IIS, Nginx, or Apache. Hence, we typically use it as an application server, with one of the above servers acting as a reverse proxy.
Get or Set Dimensions of a Matrix in R Programming - dim() Function - GeeksforGeeks

04 Jun, 2020
dim() function in R Language is used to get or set the dimension of the specified matrix, array or data frame.
Syntax: dim(x)
Parameters:x: array, matrix or data frame.
Example 1:
# R program to illustrate# dim function  # Getting R Biochemical Oxygen Demand DatasetBOD   # Getting dimension of the above datasetdim(BOD) 
Output:
  Time demand
1    1    8.3
2    2   10.3
3    3   19.0
4    4   16.0
5    5   15.6
6    7   19.8

[1] 6 2

Example 2:
# R program to illustrate# dim function  # Getting the number from 1 to 9x <- rep(1:9)x  # Calling the dim() function to# Set dimension of 3 * 3dim(x) <- c(3, 3)  # Getting the numbers# in 3 * 3 representationx
Output:
[1] 1 2 3 4 5 6 7 8 9

     [, 1] [, 2] [, 3]
[1, ]    1    4    7
[2, ]    2    5    8
[3, ]    3    6    9

R Matrix-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
How to import an Excel File into R ?
How to filter R dataframe by multiple conditions?
Replace Specific Characters in String in R
R - if statement
Time Series Analysis in R
How to get the applied azure resource tags using PowerShell?

To get all the applied tags to the Azure resources we need to use the Get-AZTag command and need to provide ResourceID to it. For example,
We need to retrieve the Azure VM tags and we will use its resource ID.
PS C:\> $vm = Get-AzVM -Name Testmachine2k16
PS C:\> Get-AzTag -ResourceId $vm.Id
You can see the output in the properties window. Another simple method is to use the Tags property for that particular cmdlet. For example, Get-AzVM, Get-AZResourceGroup, etc use the tag property for displaying the applied tags.
PS C:\> Get-AzVM -VMName TestMachine2k16 | Select -ExpandProperty Tags
Key             Value
---             -----
Owner           Chirag
For             Ansible
Patching_Day    Sunday
Application     SecretTag
Similarly, to get the resource group tags, you can use either the Get-AZTag command with the ResourceID property of the resource group or the Get-AZResourceGroup command with the Tag property.
PS C:\> $rg = Get-AzResourceGroup -ResourceGroupName TestRG
PS C:\> Get-AzTag -ResourceId $rg.ResourceId
Or,
PS C:\> Get-AzResourceGroup -Name TestRG | Select -ExpandProperty Tags
To search for the specific tags. We need to use -Name property of the Get-AZTag command. For example, we need to search the tag called Patching_Day then we can use the below command. It shows the Patching_Day tag from the entire subscription because we haven’t provided any specific resource or resource group.
The count property shows the number of times the tag is applied to the resources and ValuesTable and values property shows the values associated with that tag key.
PS C:\> Get-AzTag -Name Patching_Day | fl

Name        : Patching_Day
ValuesTable :
  Name    Count
  ======  =====
  Sunday  2

Count       : 2
Values      : {Sunday}
C program to print characters without using format specifiers - GeeksforGeeks

29 Oct, 2017
As we know that there are various format specifiers in C like %d, %f, %c etc, to help us print characters or other data types. We normally use these specifiers along with the printf() function to print any variables. But there is also a way to print characters specifically without the use of %c format specifier. This can be obtained by using the below-shown method to get the character value of any ASCII codes of any particular character.Example:
// Prints characters without format specifiers#include <stdio.h>  int main(){    printf("\x47 \n");    printf("\x45 \n");    printf("\x45 \n");    printf("\x4b \n");    printf("\x53");    return 0;}
Output:
G 
E 
E 
K 
S

This article is contributed by Chinmoy Lenka. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
c-puzzle
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
TCP Server-Client implementation in C
Exception Handling in C++
Multithreading in C
'this' pointer in C++
UDP Server-Client implementation in C
Arrow operator -> in C/C++ with Examples
Understanding "extern" keyword in C
Storage Classes in C
Smart Pointers in C++ and How to Use Them
Switch Statement in C/C++
MySQL GROUP BY Statement

The GROUP BY statement groups rows that have the same values into summary 
rows, like "find the number of customers in each country".
The GROUP BY statement is often used with aggregate functions (COUNT(), 
MAX(), 
MIN(), SUM(), 
AVG()) to group the result-set by one or more columns.
Below is a selection from the "Customers" table in the Northwind sample 
database:
The following SQL statement lists the number of customers in each country:
The following SQL statement lists the number of customers in each country, 
sorted high to low:
Below is a selection from the "Orders" table in the Northwind sample database:
And a selection from the "Shippers" table:
The following SQL statement lists the number of orders sent by each shipper:
List the number of customers in each country.
SELECT (CustomerID),
Country
FROM Customers
;

Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
Python 3 - time time() Method

The method time() returns the time as a floating point number expressed in seconds since the epoch, in UTC.
Note − Even though the time is always returned as a floating point number, not all systems provide time with a better precision than 1 second. While this function normally returns non-decreasing values, it can return a lower value than a previous call if the system clock has been set back between the two calls.
Following is the syntax for time() method −
time.time()
NA
This method returns the time as a floating point number expressed in seconds since the epoch, in UTC.
The following example shows the usage of time() method.
#!/usr/bin/python3
import time

print ("time.time(): %f " %  time.time())
print (time.localtime( time.time() ))
print (time.asctime( time.localtime(time.time()) ))
When we run the above program, it produces the following result −
time.time(): 1455519806.011433 
time.struct_time(tm_year = 2016, tm_mon = 2, tm_mday = 15, tm_hour = 12, tm_min = 33, 
   tm_sec = 26, tm_wday = 0, tm_yday = 46, tm_isdst = 0)
Mon Feb 15 12:33:26 2016


    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
C# Program to Convert Binary to Decimal

Firstly, set the binary value −
int num = 101;
Now assign the binary to a new variable −
binVal = num;
Till the value is greater than 0, loop through the binary number and base value like this,
while (num > 0) {
   rem = num % 10;
   decVal = decVal + rem * baseVal;
   num = num / 10;
   baseVal = baseVal * 2;
}
The following is the code to convert binary to decimal.
Live Demo
using System;
using System.Collections.Generic;
using System.Text;
namespace Demo {
   class MyApplication {
      static void Main(string[] args) {
         int num, binVal, decVal = 0, baseVal = 1, rem;
         num = 101;
         binVal = num;
         while (num > 0) {
            rem = num % 10;
            decVal = decVal + rem * baseVal;
            num = num / 10 ;
            baseVal = baseVal * 2;
         }
         Console.Write("Binary Number: "+binVal);
         Console.Write("\nDecimal: "+decVal);
         Console.ReadLine();
      }
   }
}
Binary Number: 101
Decimal: 5
Program to check if the given list has Pythagorean Triplets or not in Python

Suppose we have a list of numbers called nums, we have to check whether there exist three
numbers a, b, and c such that a^2 + b^2 = c^2.
So, if the input is like [10, 2, 8, 5, 6], then the output will be True, as 8^2 + 6^2 = 64+36 = 100 =
10^2.
To solve this, we will follow these steps −
tmp := list of square of all numbers in nums in descending order
for each index i and corresponding number n in tmp, dobase := nleft := i+1, right := size of tmp -1while left <= right, dot := join two lists tmp[left] and tmp[right]if t is same as base, thenreturn Trueotherwise when t > base, thenleft := left + 1otherwise,right := right - 1
base := n
left := i+1, right := size of tmp -1
while left <= right, dot := join two lists tmp[left] and tmp[right]if t is same as base, thenreturn Trueotherwise when t > base, thenleft := left + 1otherwise,right := right - 1
t := join two lists tmp[left] and tmp[right]
if t is same as base, thenreturn True
return True
otherwise when t > base, thenleft := left + 1
left := left + 1
otherwise,right := right - 1
right := right - 1
return False
Let us see the following implementation to get better understanding −
 Live Demo
class Solution:
   def solve(self, nums):
      tmp = sorted([n*n for n in nums], reverse = True)
      for i, n in enumerate(tmp):
         base = n
         left = i+1; right = len(tmp)-1
         while left <= right:
            t = tmp[left]+tmp[right]
            if t == base:
               return True
            elif t > base:
               left += 1
            else:
               right -= 1
      return False
ob = Solution()
print(ob.solve([10, 2, 8, 5, 6]))
[10, 2, 8, 5, 6]
True
Check for balanced parentheses in Python

Many times we are required to find if an expression is balanced with respect to the brackets present in it. By balanced we mean for each left bracket there is a corresponding right bracket and the sequence of brackets is properly ordered. This has importance in writing a program or a mathematical expression where brackets are heavily used. In this topic, we will see how we can programmatically find out if an expression containing brackets is balanced or not.
In this method, we find out the innermost pair of brackets and replace them with null values. We keep doing this till all the pairs of brackets are replaced. If still some bracket is left then the expression is not balanced otherwise the expression is found to be balanced.
def brackets(expression):
   all_br = ['()', '{}', '[]']
   while any(x in expression for x in all_br):
      for br in all_br:
         expression = expression.replace(br, '')
   return not expression

# calling the function
input_string = "([]{}()"
if brackets(input_string):
   print(input_string,"balanced")
else:
   print(input_string,"Not balanced")
Running the above code gives us the following result −
([]{}() Not balanced
How to extract the residuals and predicted values from linear model in R?

The residuals are the difference between actual values and the predicted values and the predicted values are the values predicted for the actual values by the linear model. To extract the residuals and predicted values from linear model, we need to use resid and predict function with the model object.
Consider the below data frame −
 Live Demo
x1<-rnorm(20,14,3.25)
y1<-rnorm(20,6,0.35)
df1<-data.frame(x1,y1)
df1
       x1       y1
1  14.565652  6.506233
2  13.350634  6.481486
3  8.636661   5.806754
4  11.495087  6.164963
5  12.159347  6.749101
6  16.642371  6.061237
7  9.137345   6.121711
8  12.616223  5.911341
9  10.109950  5.819494
10 15.953629  6.067601
11 13.579602  6.438686
12 14.708544  5.175576
13 19.234206  6.926994
14 13.539790  5.669169
15 15.101462  6.253202
16 13.812982  6.042699
17 12.680245  6.019822
18 15.292250  6.174533
19 12.759720  5.648624
20 11.371360  5.879896
Creating linear model between x1 and y1 −
Model1<-lm(y1~x1,data=df1)
Finding the residuals and predicted values from Model1 −
resid(Model1)
     1         2            3         4             5       6
0.34576809 0.38483276 -0.04232628 0.16576122 0.71501218 -0.20829562
    7             8          9           10        11        12
0.24633525 -0.14674241 -0.10696233 -0.16575896 0.33000726 -0.99239332
    13         14         15           16           17         18
0.52134132 -0.43741908 0.06459654 -0.07823690 -0.04162379 -0.02409178
   19          20
-0.41699579 -0.11280836
> predict(Model1)
   1       2           3       4        5         6       7       8
6.160465 6.096654 5.849080 5.999202 6.034088 6.269532 5.875376 6.058083
   9         10        11      12       13      14       15       16
5.926456 6.233360 6.108679 6.167970 6.405653 6.106588 6.188605 6.120936
   17       18         19       20
6.061445 6.198625 6.065619 5.992704
 Live Demo
x2<-rpois(20,5)
y2<-rpois(20,2)
df2<-data.frame(x2,y2)
df2
  x2 y2
1 7  0
2 5  1
3 3  1
4 3  2
5 6  3
6 2  8
7 4  2
8 6  0
9 9  1
10 3 0
11 4 3
12 7 1
13 6 2
14 6 0
15 5 2
16 9 1
17 5 3
18 5 2
19 6 5
20 7 0
Creating linear model between x2 and y2 −
Model2<-lm(y2~x2,data=df2)
Finding the residuals and predicted values from Model2 −
resid(Model2)
      1           2           3           4          5        6
-1.15697674 -1.02325581 -1.88953488 -0.88953488 1.40988372 4.67732558
       7          8           9           10        11         12
-0.45639535 -1.59011628 0.70930233 -2.88953488 0.54360465 -0.15697674
      13        14           15        16        17         18
0.40988372 -1.59011628 -0.02325581 0.70930233 0.97674419 -0.02325581
      19        20
3.40988372 -1.15697674
predict(Model2)
    1         2           3       4       5           6       7         8
1.1569767 2.0232558 2.8895349 2.8895349 1.5901163 3.3226744 2.4563953 1.5901163
    9        10          11        12     13        14         15         16
0.2906977 2.8895349 2.4563953 1.1569767 1.5901163 1.5901163 2.0232558 0.2906977
   17          18       19       20
2.0232558 2.0232558 1.5901163 1.1569767
Python - Queue

We are familiar with queue in our day to day life as we wait for a service. The queue data structure aslo means the same where the data elements are arranged in a queue. The uniqueness of queue lies in the way items are added and removed. The items are allowed at on end but removed form the other end. So it is a First-in-First out method.
A queue can be implemented using python list where we can use the insert() and pop() methods to add and remove elements. Their is no insertion as data elements are always added at the end of the queue.
In the below example we create a queue class where we implement the First-in-First-Out method. We use the in-built insert method for adding data elements.
class Queue:
   def __init__(self):
      self.queue = list()

   def addtoq(self,dataval):
# Insert method to add element
   if dataval not in self.queue:
      self.queue.insert(0,dataval)
      return True
   return False

   def size(self):
      return len(self.queue)

TheQueue = Queue()
TheQueue.addtoq("Mon")
TheQueue.addtoq("Tue")
TheQueue.addtoq("Wed")
print(TheQueue.size())
When the above code is executed, it produces the following result −
3

In the below example we create a queue class where we insert the data and then remove the data using the in-built pop method.
class Queue:
   def __init__(self):
      self.queue = list()

   def addtoq(self,dataval):
# Insert method to add element
   if dataval not in self.queue:
      self.queue.insert(0,dataval)
      return True
   return False
# Pop method to remove element
   def removefromq(self):
      if len(self.queue)>0:
         return self.queue.pop()
      return ("No elements in Queue!")

TheQueue = Queue()
TheQueue.addtoq("Mon")
TheQueue.addtoq("Tue")
TheQueue.addtoq("Wed")
print(TheQueue.removefromq())
print(TheQueue.removefromq())
When the above code is executed, it produces the following result −
Mon
Tue


    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 create a border pane using JavaFX?

Once you create all the required nodes for your application you can arrange them using a layout. Where a layout is a process of calculating the position of objects in the given space. JavaFX provides various layouts in the javafx.scene.layout package.
In this layout, the nodes are arranged in the top, center, bottom, left, and, right positions. You can create a border pane in your application by instantiating the javafx.scene.layout.BorderPane class.
There are five properties of this class (Node type) specifying the positions in the pane, namely, top, bottom, right, left, center. You can set nodes as values to these properties using the setTop(), setBottom(), setRight(), setleft() and, setCenter().
You can set the size of the border pane using the setPrefSize() method. To add nodes to this pane you can either pass them as arguments of the constructor or, add them to the observable list of the pane as −
getChildren().addAll();
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class BorderPaneExample extends Application {
   public void start(Stage stage) {
      //Creating buttons
      Button left = new Button("Left");
      left.setPrefSize(200, 100);
      Button right = new Button("Right");
      right.setPrefSize(200, 100);
      Button top = new Button("Top");
      top.setPrefSize(595, 100);
      Button bottom = new Button("Buttom");
      bottom.setPrefSize(595, 100);
      Button center = new Button("Center");
      center.setPrefSize(200, 100);
      //Creating the border pane
      BorderPane pane = new BorderPane();
      //Setting the top, bottom, center, right and left nodes to the pane
      pane.setTop(top);
      pane.setBottom(bottom);
      pane.setLeft(left);
      pane.setRight(right);
      pane.setCenter(center);
      //Setting the Scene
      Scene scene = new Scene(pane, 595, 300);
      stage.setTitle("Border Pane");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}
How to create a stacked bar chart for my DataFrame using Seaborn in Matplotlib?

To create a stacked bar chart, we can use Seaborn's barplot() method, i.e., show point estimates and confidence intervals with bars.
Create df using Pandas Data Frame.
Create df using Pandas Data Frame.
Using barplot() method, create bar_plot1 and bar_plot2 with color as red and green, and label as count and select.
Using barplot() method, create bar_plot1 and bar_plot2 with color as red and green, and label as count and select.
To enable legend, use legend() method, at the upper-right location.
To enable legend, use legend() method, at the upper-right location.
To display the figuree, use show() method.
To display the figuree, use show() method.
import pandas
import matplotlib.pylab as plt
import seaborn as sns
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
df = pandas.DataFrame(dict(
   number=[2, 5, 1, 6, 3],
   count=[56, 21, 34, 36, 12],
   select=[29, 13, 17, 21, 8]
))
bar_plot1 = sns.barplot(x='number', y='count', data=df, label="count", color="red")
bar_plot2 = sns.barplot(x='number', y='select', data=df, label="select", color="green")
plt.legend(ncol=2, loc="upper right", frameon=True)
plt.show()
C# - Arithmatic Operators

Following table shows all the arithmetic operators supported by C#. Assume variable A holds 10 and variable B holds 20, then −
The following example demonstrates all the arithmetic operators available in C# −
using System;

namespace OperatorsAppl {
   class Program { 
      static void Main(string[] args) { 
         int a = 21;
         int b = 10;
         int c;

         c = a + b;
         Console.WriteLine("Line 1 - Value of c is {0}", c);
         
         c = a - b;
         Console.WriteLine("Line 2 - Value of c is {0}", c);
         
         c = a * b;
         Console.WriteLine("Line 3 - Value of c is {0}", c);
         
         c = a / b;
         Console.WriteLine("Line 4 - Value of c is {0}", c);
         
         c = a % b;
         Console.WriteLine("Line 5 - Value of c is {0}", c);
         
         c = a++;
         Console.WriteLine("Line 6 - Value of c is {0}", c);
         
         c = a--;
         Console.WriteLine("Line 7 - Value of c is {0}", c);
         Console.ReadLine();
      }
   }
}
When the above code is compiled and executed, it produces the following result −
Line 1 - Value of c is 31
Line 2 - Value of c is 11
Line 3 - Value of c is 210
Line 4 - Value of c is 2
Line 5 - Value of c is 1
Line 6 - Value of c is 21
Line 7 - Value of c is 22


    119 Lectures 
     23.5 hours 

 Raja Biswas

    37 Lectures 
     13 hours 

 Trevoir Williams

    16 Lectures 
     1 hours 

 Peter Jepson

    159 Lectures 
     21.5 hours 

 Ebenezer Ogbu

    193 Lectures 
     17 hours 

 Arnold Higuit

    24 Lectures 
     2.5 hours 

 Eric Frick
 Print
 Add Notes
 Bookmark this page
Count Primes in Ranges in C++

We are given range variables START and END. The goal is to find the count of prime numbers in the range [START,END].
We will check if number i in range is prime by checking if any number other than 1 fully divides it and is between 1 and i/2. If it is prime. Increment count.
Let’s understand with examples.
Input 
Start=1 End=20
Output 
Primes in Ranges : 8
Explanation 
Primes between 1 and 20 are: 2,3,5,7,11,13,17,19.
Input 
Start=100 End=200
Output 
Primes in Ranges : 21
Explanation 
Primes between 100 and 200 are: 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199
We take range variables as START and END.
We take range variables as START and END.
Function countPrimes(int strt,int end) returns the count of primes in range.
Function countPrimes(int strt,int end) returns the count of primes in range.
Take the initial variable count as 0.
Take the initial variable count as 0.
Traverse using for loop from i=strt to i <=end
Traverse using for loop from i=strt to i <=end
Take each number i and check if it is prime using isprime(i).
Take each number i and check if it is prime using isprime(i).
Function isprime(int num) returns 0 if the number is non prime and 1 if it is prime.
Function isprime(int num) returns 0 if the number is non prime and 1 if it is prime.
After the end of loop, return count as result.
After the end of loop, return count as result.
 Live Demo
#include <bits/stdc++.h>
using namespace std;
int isprime(int num){
   if (num <= 1)
      return 0;
   for (int i = 2; i <= num/2; i++){
      if (num % i == 0)
         { return 0; }
   }
   return 1; //if both failed then num is prime
}
int countPrimes(int strt,int end){
   int count=0;
   for(int i=strt;i<=end;i++){
      if(isprime(i)==1)
         { count++; }
   }
   return count;
}
int main(){
   int START=10, END=20;
   cout <<endl<<"Primes in Ranges : "<<countPrimes(START,END);
   return 0;
}
If we run the above code it will generate the following output −
Primes in Ranges : 4
Prolog - Linked Lists

Following chapters describe how to generate/create linked lists using recursive structures.
Linked list has two components, the integer part and the link part. The link part will hold another node. End of list will have nil into the link part.
In prolog, we can express this using node(2, node(5, node(6, nil))).
Note − The smallest possible list is nil, and every other list will contain nil as the "next" of the end node. In list terminology, the first element is usually called the head of the list, and the rest of the list is called the tail part. Thus the head of the above list is 2, and its tail is the list node(5, node(6, nil)).
We can also insert elements into front and back side −
add_front(L,E,NList) :- NList = node(E,L).

add_back(nil, E, NList) :-
   NList = node(E,nil).
   
add_back(node(Head,Tail), E, NList) :-
   add_back(Tail, E, NewTail),
   NList = node(Head,NewTail).
| ?- [linked_list].
compiling D:/TP Prolog/Sample_Codes/linked_list.pl for byte code...
D:/TP Prolog/Sample_Codes/linked_list.pl compiled, 7 lines read - 966 bytes written, 14 ms

(15 ms) yes
| ?- add_front(nil, 6, L1), add_front(L1, 5, L2), add_front(L2, 2, L3).

L1 = node(6,nil)
L2 = node(5,node(6,nil))
L3 = node(2,node(5,node(6,nil)))

yes
| ?- add_back(nil, 6, L1), add_back(L1, 5, L2), add_back(L2, 2, L3).

L1 = node(6,nil)
L2 = node(6,node(5,nil))
L3 = node(6,node(5,node(2,nil)))

yes
| ?- add_front(nil, 6, L1), add_front(L1, 5, L2), add_back(L2, 2, L3).

L1 = node(6,nil)
L2 = node(5,node(6,nil))
L3 = node(5,node(6,node(2,nil)))

yes
| ?-


    65 Lectures 
     5 hours 

 Arnab Chakraborty

    78 Lectures 
     7 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
How can we create a MySQL temporary table by using PHP script?

As we know that PHP provides us the function named mysql_query() to create a MySQL table. Similarly, we can use mysql_query() function to create MySQL temporary table. To illustrate this, we are using the following example −
In this example, we are creating a temporary table named ‘SalesSummary’ with the help of PHP script in the following example −
<html>
   <head>
      <title>Creating MySQL Temporary Tables</title>
   </head>
   <body>
      <?php
         $dbhost = 'localhost:3036';
         $dbuser = 'root';
         $dbpass = 'rootpassword';
         $conn = mysql_connect($dbhost, $dbuser, $dbpass);

         if(! $conn ) {
            die('Could not connect: ' . mysql_error());
         }
         echo 'Connected successfully<br />';
         $sql = "CREATE TEMPORARY TABLE SalesSummary( ".
            "Product_Name VARCHAR(50) NOT NULL, ".
            "total_sales DECIMAL(12,2) NOT NULL DEFAULT 0.00, ".
            "avg_unit_price DECIMAL(7,2) NOT NULL DEFAULT 0.00, ".
            "total_units_sold INT UNSIGNED NOT NULL DEFAULT 0, ".); ";
         
         mysql_select_db( 'TUTORIALS' );
         $retval = mysql_query( $sql, $conn );

         if(! $retval ) {
            die('Could not create table: ' . mysql_error());
         }
         echo "Table created successfully\n";
         mysql_close($conn);
      ?>
   </body>
</html>
Convert varchar to date in MySQL?

You can use date_format() to convert varchar to date. The syntax is as follows −
SELECT DATE_FORMAT(STR_TO_DATE(yourColumnName, 'yourFormatSpecifier'), 'yourDateFormatSpecifier') as anyVariableName from yourTableName;
To understand the above syntax, let us create a table. The query to create a table is as follows −
mysql> create table VarcharToDate
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> Created_Time varchar(100),
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (1.10 sec)
Insert some records in the table using insert command. The query is as follows −
mysql> insert into VarcharToDate(Created_Time) values('12/1/2016');
Query OK, 1 row affected (0.14 sec)

mysql> insert into VarcharToDate(Created_Time) values('14/3/2017');
Query OK, 1 row affected (0.18 sec)

mysql> insert into VarcharToDate(Created_Time) values('15/3/2018');
Query OK, 1 row affected (0.21 sec)

mysql> insert into VarcharToDate(Created_Time) values('19/5/2011');
Query OK, 1 row affected (0.18 sec)

mysql> insert into
VarcharToDate(Created_Time) values('19/8/2019');
Query OK, 1 row affected (0.15 sec)

mysql> insert into VarcharToDate(Created_Time) values('21/11/2020');
Query OK, 1 row affected (0.23 sec)
Display all records from the table using select statement. The query is as follows −
mysql> select *from VarcharToDate;
+----+--------------+
| Id | Created_Time |
+----+--------------+
|  1 | 12/1/2016    |
|  2 | 14/3/2017    |
|  3 | 15/3/2018    |
|  4 | 19/5/2011    |
|  5 | 19/8/2019    |
|  6 | 21/11/2020   |
+----+--------------+
6 rows in set (0.00 sec)
Here is the query to convert varchar to date. First, you need to use str_to_date() function to convert into date. After that use date_format() to give the actual date −
mysql> select date_format(str_to_date(Created_Time, '%d/%m/%Y'), '%Y-%m-%d') as Date from VarcharToDate;
The following is the output −
+------------+
| Date       |
+------------+
| 2016-01-12 |
| 2017-03-14 |
| 2018-03-15 |
| 2011-05-19 |
| 2019-08-19 |
| 2020-11-21 |
+------------+
6 rows in set (0.00 sec)