code-rag-bench/online-tutorials huggingface dataset:
Logistic Regression in Python - Building Classifier

It is not required that you have to build the classifier from scratch. Building classifiers is complex and requires knowledge of several areas such as Statistics, probability theories, optimization techniques, and so on. There are several pre-built libraries available in the market which have a fully-tested and very efficient implementation of these classifiers. We will use one such pre-built model from the sklearn.
Creating the Logistic Regression classifier from sklearn toolkit is trivial and is done in a single program statement as shown here −
In [22]: classifier = LogisticRegression(solver='lbfgs',random_state=0)

Once the classifier is created, you will feed your training data into the classifier so that it can tune its internal parameters and be ready for the predictions on your future data. To tune the classifier, we run the following statement −
In [23]: classifier.fit(X_train, Y_train)

The classifier is now ready for testing. The following code is the output of execution of the above two statements −
Out[23]: LogisticRegression(C = 1.0, class_weight = None, dual = False, 
   fit_intercept=True, intercept_scaling=1, max_iter=100, 
   multi_class='warn', n_jobs=None, penalty='l2', random_state=0, 
   solver='lbfgs', tol=0.0001, verbose=0, warm_start=False))

Now, we are ready to test the created classifier. We will deal this in the next chapter.

    15 Lectures 
     1 hours 

 Ajay

    53 Lectures 
     6 hours 

 Abhishek And Pukhraj

    49 Lectures 
     5 hours 

 Abhishek And Pukhraj
 Print
 Add Notes
 Bookmark this page
Nested if in Java

07 Oct, 2021
Generally, if condition works like yes or no type. If the condition satisfies, it executes some block of code. Otherwise, it doesn’t execute the code. Let us see the syntax of the simple if condition.
Syntax : 
if( condition ){

       statements ;
       
}
Nested means within. Nested if condition means if-within-if. Nested if condition comes under decision-making statement in Java. There could be infinite if conditions inside an if condition. The below syntax represents the Nested if condition.
Syntax : 
if( condition ){

      if( condition ){
      
                if( condition ){
                
                         ......
                }
       }
}
Note – If the inner condition satisfies then only outer if will be executed. Along with if conditions we can write else conditions also.
Example 1 
Java
import java.util.*;import java.lang.*;import java.io.*;  class GFG{      public static void main(String args[])    {        int a=10;          int b=20;               if(a==10){            if(b==20){                System.out.println("GeeksforGeeks");            }        }    }}
GeeksforGeeks
Code explanation :
In the first step, we have imported the required packages.
In the next step, we have created a class names GFG
In the next step, we have written the main method.
Within the main method, we have assigned values to variables.
Using nested if conditions, we have printed a statement.
Here two statements are true. Hence statement was executed successfully.
Example 2 :
Java
import java.util.*;import java.lang.*;  class GFG{      public static void main(String args[])    {        int a=10;          int b=20;                if(a==10){              if(b!=20){                System.out.println("GeeksforGeeks");            }                        else{                System.out.println("GFG");            }        }    }}
GFG
Code explanation :
In the first step, we have imported the required packages.
In the next step, we have created a class names GFG
In the next step, we have written the main method.
Within the main method, we have assigned values to variables.
Using nested if conditions, we have printed a statement.
Here inner if the condition is not true. Hence else part is executed.
Nested if condition comes under decision-making statement in Java. It contains several branches with an if condition inside another if condition. The syntax, code examples, and explanations of Nested-if statements are covered in detail in the above article.
java-basics
Java-Control-Flow
Picked
Java
Java-Control-Flow
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java
PHP | isset() Function

27 Apr, 2020
The isset() function is an inbuilt function in PHP which is used to determine if the variable is declared and its value is not equal to NULL.
Syntax:
bool isset( mixed $var [, mixed $... ] )
Parameters: This function accept one or more parameter as mentioned above and described below:
$var: It contains the variable which need to check.
$...: It contains the list of other variables.
Return Value: It returns TRUE if var exists and its value not equal to NULL and FALSE otherwise.
Below examples illustrate the isset() function in PHP:
Example 1:
<?php  $str = "GeeksforGeeks";  // Check value of variable is set or notif(isset($str)) {    echo "Value of variable is set";}else {    echo "Value of variable is not set";}  $arr = array();  // Check value of variable is set or notif( !isset($arr[0]) ) {    echo "\nArray is Empty";}else {    echo "\nArray is not empty";}  ?>
Value of variable is set
Array is Empty

Output:
Example 2:
<?php  $num = 21;var_dump(isset($num));  $arr = array(        "a" => "Welcome",        "b" => "to",        "c" => "GeeksforGeeks"    );  var_dump(isset($arr["a"]));var_dump(isset($arr["b"]));var_dump(isset($arr["c"]));var_dump(isset($arr["Geeks"]));  ?>
bool(true)
bool(true)
bool(true)
bool(true)
bool(false)

Reference: https://www.php.net/manual/en/function.isset.php
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to convert array to string in PHP ?
PHP | Converting string to Date and DateTime
How to receive JSON POST with PHP ?
How to get parameters from a URL string in PHP?
Download file from URL using PHP
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Explain dynamic memory allocation in C with an example

Find the sum of n numbers entered by user using dynamically allocated memory using C programming.
The Dynamic memory allocation enables the C programmers to allocate memory at runtime.
The different functions that we used to allocate memory dynamically at run time are −
malloc () − allocates a block of memory in bytes at runtime.
calloc () − allocating continuous blocks of memory at run time.
realloc () − used for reduce (or) extend the allocated memory.
free () − deallocates previously allocated memory space.
Following C program is to display the elements and calculate sum of n numbers.
Using dynamic memory allocation functions, we are trying to reduce the wastage of memory.
 Live Demo
#include<stdio.h>
#include<stdlib.h>
void main(){
   //Declaring variables and pointers,sum//
   int numofe,i,sum=0;
   int *p;
   //Reading number of elements from user//
   printf("Enter the number of elements : ");
   scanf("%d",&numofe);
   //Calling malloc() function//
   p=(int *)malloc(numofe*sizeof(int));
   /*Printing O/p -
   We have to use if statement because we have to check if memory
   has been successfully allocated/reserved or not*/
   if (p==NULL){
      printf("Memory not available");
      exit(0);
   }
   //Printing elements//
   printf("Enter the elements : \n");
   for(i=0;i<numofe;i++){
      scanf("%d",p+i);
      sum=sum+*(p+i);
   }
   printf("\nThe sum of elements is %d",sum);
   free(p);//Erase first 2 memory locations//
   printf("\nDisplaying the cleared out memory location : \n");
   for(i=0;i<numofe;i++){
      printf("%d\n",p[i]);//Garbage values will be displayed//
   }
}
Enter the number of elements : 5
Enter the elements :
23
34
12
34
56
The sum of elements is 159
Displaying the cleared out memory location :
12522624
0
12517712
0
56
Print a 2D Array or Matrix in Java

In this post we will try to print an array or matrix of numbers at console in same manner as we generally write on paper.
For this the logic is to access each element of array one by one and make them print separated by a space and when row get to emd in matrix then we will also change the row.
 Live Demo
public class Print2DArray {
   public static void main(String[] args) {
      final int[][] matrix = {
         { 1, 2, 3 },
         { 4, 5, 6 },
         { 7, 8, 9 }
      };
      for (int i = 0; i < matrix.length; i++) { //this equals to the row in our matrix.
         for (int j = 0; j < matrix[i].length; j++) { //this equals to the column in each row.
            System.out.print(matrix[i][j] + " ");
         }
         System.out.println(); //change line on console as row comes to end in the matrix.
      }
   }
}
1 2 3
4 5 6
7 8 9
What does the 'tearoff' attribute do in a Tkinter Menu? - GeeksforGeeks

11 Dec, 2020
Prerequisite:
Python GUI – tkinter
Menus
Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with tkinter is the fastest and easiest way to create the GUI applications. Creating a GUI using tkinter is an easy task.
Menu is used to create various types of menus such as top level, pull down etc.. in Tkinter. The Top Level Menu, which is displayed under the title bar of main window.
Syntax:
To create menu
menubar = Menu(root)
To add text in Menu
file = Menu(menubar) 
menubar.add_cascade(label ='Your Text', menu = file)
A Tearoff permits you to detach menus for the most window making floating menus. If you produce a menu you may see dotted lines at the top after you click a top menu item. To fix this tearoff needs to set to 0 at the time of menu declaration.
file = Menu(menubar,tearoff=0)
edit = Menu(menubar,tearoff=0)
help_ = Menu(menubar,tearoff=0)
Cascade is used to create Sub-menus below the Main-menu.
A submenu is a menu plugged into another menu object. By adding the menu to the fileMenu and not to the menubar, we create a submenu.
Syntax:
Object_Name.add_command(label ='Write Text')
Import module
Create normal Tkinter window
Add Menus
Add SubMenus
Program:
Python3
# import Modulefrom tkinter import *  # creating tkinter windowroot = Tk()  # set geometryroot.geometry("400x400")  # Add titleroot.title('Menu Demonstration')  # Creating Menubarmenubar = Menu(root)  # Adding File Menu and SubMenusfile = Menu(menubar, tearoff=0)menubar.add_cascade(label='File', menu=file)file.add_command(label='New File')file.add_command(label='Open...')file.add_command(label='Save')  # Adding Edit Menu and SubMenusedit = Menu(menubar, tearoff=0)menubar.add_cascade(label='Edit', menu=edit)edit.add_command(label='Cut')edit.add_command(label='Copy')edit.add_command(label='Paste')edit.add_command(label='Select All')  # Adding Help Menu and SubMenushelp_ = Menu(menubar, tearoff=0)menubar.add_cascade(label='Help', menu=help_)help_.add_command(label='Tk Help')help_.add_command(label='Demo')  # display Menuroot.config(menu=menubar)  # Execute Tkinterroot.mainloop()
Output:
Without Using tearoff method
 
Output: 
 With tearoff method
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
*args and **kwargs in Python
sum() function in Python
How to Count Word Occurrences in a Text File using Shell Script?

Linux shell scripting has many powerful tools to process the data in files. One such feature is to find patterns and count the number of occurrences of matched patterns. One such example is to count the number of occurrences of a specific word in a given file. This is achieved by combination of commands for pattern search and counting. Below are the approaches which can be used for this need.
Lets use the below file for demonstrating the examples.
$ cat inspire.txt
Mastering anything needs practice.
It also needs patience.
And it needs time and other resources.
The grep command finds the pattern but it has some switches which can be used to print the pattern in new line every time it finds it. That is –o option. Also we can use the -i switch for ignoring the case of the word found. Finally, the result can be pipelined to wc to get the final count.In this example we count the number of occurrences of the word “needs”.
We grep for the word “needs” in the file. Use the –o switch to get each of the output as a new line. Use –i to ignore the case. Then pipeline it to wc in order to get the number of lines which is ultimately the number of occurrences of the word.
$ grep -o -i needs inspire.txt | wc -l
Running the above code gives us the following result −
3
The tr command translates one string to another. So we translate all the spaces into a new line and then grep for the pattern. Finally count the number of occurrences of the specific word by using the -c switch of grep for count and -i switch for ignoring the uppercase/lowercase word.
tr '[:space:]' '[\n*]' < inspire.txt | grep -i -c it
Running the above code gives us the following result −
2
Tcl - Nested If Statement

It is always legal in Tcl to nest if-else statements, which means you can use one if or else if statement inside another if or else if statement(s).
The syntax for a nested if statement is as follows −
if { boolean_expression 1 } {
   # Executes when the boolean expression 1 is true 
   if {boolean_expression 2} {
      # Executes when the boolean expression 2 is true
   }
}

You can nest else if...else in the similar way as you have nested if statement.
#!/usr/bin/tclsh

set a 100
set b 200
 
# check the boolean condition 
if { $a == 100 } {
   # if condition is true then check the following 
   if { $b == 200 } {
      #if condition is true then print the following 
      puts "Value of a is 100 and b is 200"
   }
}
puts "Exact value of a is : $a"
puts "Exact value of b is : $b"
When the above code is compiled and executed, it produces the following result −
Value of a is 100 and b is 200
Exact value of a is : 100
Exact value of b is : 200

 Print
 Add Notes
 Bookmark this page
Write a dictionary to a file in Python - GeeksforGeeks

29 Dec, 2020

Dictionary is used to store data values in the form of key:value pairs. In this article we will see how to write dictionary into a file. Actually we can only write a string to a file. If we want to write a dictionary object, we either need to convert it into string using json or serialize it.
Method:1 Storing Dictionary With Object Using Json
Approach:
Import Json
Create A Dictionary  in-order pass it into text file.
Open file in write mode.
Use json.dumps() for json string
Code:
Python3
 

 
 










import json 
  
details = {'Name': "Bob", 
          'Age' :28} 
  
with open('convert.txt', 'w') as convert_file: 
     convert_file.write(json.dumps(details))






Output:
Method 2: Using Loop
Approach:
Create a dictionary.
Open a file in write mode.
Here We Use For Loop With Key Value Pair Where “Name”  is Key And  “Alice” is Value So For loop Goes Through Each Key:Value Pair For Each Pairs 
Then f.write() Function Just Write’s The Output In Form Of String “%s” 
Code:
Python3
 

 
 










details={'Name' : "Alice", 
         'Age' : 21, 
         'Degree' : "Bachelor Cse", 
         'University' : "Northeastern Univ"} 
  
with open("myfile.txt", 'w') as f:  
    for key, value in details.items():  
        f.write('%s:%s\n' % (key, value))






Output:
Method:3 Without Using loads(),dumps().
Here The Steps Are Followed Above Methods But in Write We Use Str() Method Which Will Convert The Given Dictionary Into String
Python3
 

 
 










details = {'Name': "Bob", 'Age' :28}  
  
with open('file.txt','w') as data:  
      data.write(str(details))






Output:

Picked


Python file-handling-programs


python-file-handling


Python

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?
Selecting rows in pandas DataFrame based on conditions
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
Java Booleans

Very often, in programming, you will need a data type that can only have one of two values, like:
YES / NO
ON / OFF
TRUE / FALSE
For this, Java has a boolean data type, which can take the values true or false.
A boolean type is declared with the boolean keyword and can only take the values true or false:
boolean isJavaFun = true;
boolean isFishTasty = false;
System.out.println(isJavaFun);     // Outputs true
System.out.println(isFishTasty);   // Outputs false


Try it Yourself »

However, it is more common to return boolean values from boolean expressions, for conditional testing
(see below).
A Boolean expression is a Java expression that returns a Boolean value: true or false.
You can use a comparison operator, such as the greater than (>) operator to find out if an expression (or a variable) is true:
int x = 10;
int y = 9;
System.out.println(x > y); // returns true, because 10 is higher than 9


Try it Yourself »

Or even easier:
System.out.println(10 > 9); // returns true, because 10 is higher than 9


Try it Yourself »

In the examples below, we use the equal to (==) operator to evaluate an expression:
int x = 10;
System.out.println(x == 10); // returns true, because the value of x is equal to 10


Try it Yourself »

System.out.println(10 == 15); // returns false, because 10 is not equal to 15


Try it Yourself »

The Boolean value of an expression is the basis for all Java comparisons and conditions.
You will learn more about conditions in the next chapter.
Fill in the missing parts to print the values true and false:
 isJavaFun = true;
 isFishTasty = false;
System.out.println(isJavaFun);
System.out.println(isFishTasty);

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.
GREATEST() function in MySQL - GeeksforGeeks

01 Oct, 2020
GREATEST() function in MySQL is used to find greatest values from given arguments respectively. If any given value is NULL, it returns NULLs. Otherwise, it returns the greatest value.
Syntax :
GREATEST(X1, X2, X3, ...)
Parameter : This method accepts N parameters in the syntax, as mentioned above and described below :X1, X2, X3... : The list of values from which greatest to be evaluated.Returns : It returns the greatest value.
Example-1 :Finding Greatest number between given numbers using GREATEST() function.
SELECT GREATEST(10, 20, 30, 40, 50) AS Greatest_Value;
Output :
Example-2 :Finding Greatest value between given string using GREATEST() function.
SELECT GREATEST('MySQL', 'MS ACCESS', 'SQL') AS  GreatestValue_String;
Output :
Example-3 :Finding Greatest number between given numbers using GREATEST() function when there is a NULL Value.
SELECT GREATEST(10, 20, 30, 40, 50, NULL) AS Greatest_Value;
Output :
Example-4 :The GREATEST function can also be used to find the Greatest value between column data. To demonstrate create a table named Student.
CREATE TABLE Student(
    Student_id INT AUTO_INCREMENT,  
    Student_name VARCHAR(100) NOT NULL,
    Student_Class VARCHAR(20) NOT NULL,
    Subject1 INT  NOT NULL,
    Subject2 INT  NOT NULL,
    Subject3 INT  NOT NULL,
    Subject4 INT  NOT NULL,
    PRIMARY KEY(Student_id )
);
Now insert some data to the Student table –
INSERT INTO  
    Student(Student_name, Student_Class, Subject1, Subject2, Subject3, Subject4)
VALUES
    ('Sayan', 'X', 81, 90, 86, 92 ),
    ('Nitin', 'X', 90, 84, 88, 91 ),
    ('Aniket', 'X', 81, 80, 87, 95 ),
    ('Abdur', 'X', 85, 90, 80, 90  ),
    ('Sanjoy', 'X', 88, 82, 84, 90 );
Showing all data in Student Table –
Select * 
From Student ;
Now, we are going to find the greatest marks for every student in all subjects.
Select Student_id, Student_name, 
GREATEST(Subject1, Subject2, Subject3, Subject4) AS Greatest_Mark
FROM Student;
Output :
DBMS-SQL
mysql
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
SQL | DROP, TRUNCATE
Advanced SQL Interview Questions
How to Create a Table With Multiple Foreign Keys in SQL?
SQL | OFFSET-FETCH Clause
SQL | Sub queries in From Clause
Insert multiple values into multiple tables using a single statement in SQL Server
SQL vs NoSQL: Which one is better to use?
How to Select Data Between Two Dates and Times in SQL Server?
How to Update Multiple Columns in Single Update Statement in SQL?
SQL | CREATE
How to find percentile rank for groups in an R data frame?

The word percentile means the percentage that falls below or above the percentile value. For example, if we have a value that lies at 50th percentile then we would say 50 percent of the values lies below or above that value. The value 50 here is called the percentile rank. To find the percentile rank for groups in an R data frame, we can use mutate function of dplyr package.
Consider the below data frame −
 Live Demo
Group<-sample(LETTERS[1:4],20,replace=TRUE)
Response<-rpois(20,5)
df1<-data.frame(Group,Response)
df1
Group Response
1 D    5
2 B    7
3 D    5
4 C    4
5 D    5
6 C    5
7 A    10
8 D    3
9 B    2
10 D   0
11 B   4
12 D   5
13 A   3
14 A   6
15 D   2
16 A   7
17 A   6
18 C   2
19 A   9
20 C   3
Loading dplyr package −
library(dplyr)
Finding percentile rank of response for Groups −
df1%>%group_by(Group)%>%mutate(Percentile_Rank=rank(Response)/length(Response))
# A tibble: 20 x 3
# Groups: Group [4]
Group Response Percentile_Rank
<chr> <int> <dbl>
1 D    5    0.786
2 B    7    1
3 D    5    0.786
4 C    4    0.75
5 D    5    0.786
6 C    5    1
7 A    10    1
8 D    3    0.429
9 B    2    0.333
10 D   0    0.143
11 B   4    0.667
12 D   5    0.786
13 A   3    0.167
14 A   6    0.417
15 D   2    0.286
16 A   7    0.667
17 A   6    0.417
18 C   2    0.25
19 A   9    0.833
20 C   3    0.5
 Live Demo
Class<-sample(c("I","II","III"),20,replace=TRUE)
Y<-rnorm(20,25,3.27)
df2<-data.frame(Class,Y)
df2
   Class Y
1 III 32.88152
2 III 23.35048
3 III 19.78199
4 III 26.05137
5 I 26.16563
6 III 20.30466
7 I 22.93382
8 II 30.03620
9 I 16.89365
10 I 27.33329
11 I 27.46550
12 III 27.59028
13 II 27.40766
14 III 23.29442
15 II 28.69237
16 II 31.25723
17 II 22.58002
18 III 22.48583
19 I 26.08357
20 III 24.51681
Finding percentile rank of response for Class −
df2%>%group_by(Class)%>%mutate(Percentile_Rank=rank(Y)/length(Y))
# A tibble: 20 x 3
# Groups: Class [3]
Class Y Percentile_Rank
<chr> <dbl> <dbl>
1 III 32.9 1
2 III 23.4 0.556
3 III 19.8 0.111
4 III 26.1 0.778
5 I   26.2 0.667
6 III 20.3 0.222
7 I   22.9 0.333
8 II  30.0 0.8
9 I   16.9 0.167
10 I  27.3 0.833
11 I  27.5 1
12 III 27.6 0.889
13 II  27.4 0.4
14 III 23.3 0.444
15 II  28.7 0.6
16 II  31.3 1
17 II 22.6 0.2
18 III 22.5 0.333
19 I   26.1 0.5
20 III 24.5 0.667
Generate a Vector of specified length with each element as a unique color on RGB scale in R Language - topo.colors() Function - GeeksforGeeks

01 Jul, 2020
topo.colors() function in R Language is used to generate a Vector of specified length with each element as a unique color on RGB scale. This function also returns the hexadecimal code of the colours available. This hexadecimal code is of eight digits. This is because the last two digits specify the level of transparency (where FF is opaque and 00 is transparent).
Syntax: topo.colors(n)
Parameters:n: desired length of the returned color vector
Example 1:
# R program to illustrate# topo.colors function  # Calling topo.colors() functiontopo.colors(2)topo.colors(4)topo.colors(6)
Output:
[1] "#4C00FFFF" "#00E5FFFF"
[1] "#4C00FFFF" "#00E5FFFF" "#00FF4DFF" "#FFFF00FF"
[1] "#4C00FFFF" "#00E5FFFF" "#00FF4DFF" "#E6FF00FF" "#FFFF00FF" "#FFE0B3FF"

Example 2:
# R program to illustrate# topo.colors function  # Using topo.colors() function to# plot 6 different colorbarplot(1:6, col = topo.colors(6))
Output:
R Graphics-Functions
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Control Statements in R Programming
Change Color of Bars in Barchart using ggplot2 in R
Data Visualization in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
Logistic Regression in R Programming
Linear Discriminant Analysis in R Programming
How to filter R DataFrame by values in a column?
How to change Colors in ggplot2 Line Plot in R ?
How to import an Excel File into R ?
SQL Tryit Editor v1.6

SELECT CustomerName, ContactName, Address
FROM Customers
WHERE Address IS NOT NULL;
​
Edit the SQL Statement, and click "Run SQL" to see the result.
This SQL-Statement is not supported in the WebSQL Database.
The example still works, because it uses a modified version of SQL.
Your browser does not support WebSQL.
Your are now using a light-version of the Try-SQL Editor, with a read-only Database.
If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time.
Our Try-SQL Editor uses WebSQL to demonstrate SQL.
A Database-object is created in your browser, for testing purposes.
You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button.
WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object.
WebSQL is supported in Chrome, Safari, Opera, and Edge(79).
If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
How to convert C# DateTime to “YYYYMMDDHHMMSS” format?

Convert the dateTime to toString that results in converting the DateTime to “YYYYMMDDHHMMSS” format
There are also other formats that the dateTime can be converted
MM/dd/yyyy 08/22/2020
dddd, dd MMMM yyyy Tuesday, 22 August 2020
dddd, dd MMMM yyyy HH:mm Tuesday, 22 August 2020 06:30
dddd, dd MMMM yyyy hh:mm tt Tuesday, 22 August 2020 06:30 AM
dddd, dd MMMM yyyy H:mm Tuesday, 22 August 2020 6:30
dddd, dd MMMM yyyy h:mm tt Tuesday, 22 August 2020 6:30 AM
dddd, dd MMMM yyyy HH:mm:ss Tuesday, 22 August 2020 06:30:07
MM/dd/yyyy HH:mm 08/22/2020 06:30
MM/dd/yyyy hh:mm tt 08/22/2020 06:30 AM
MM/dd/yyyy H:mm 08/22/2020 6:30
MM/dd/yyyy h:mm tt 08/22/2020 6:30 AM
MM/dd/yyyy HH:mm:ss 08/22/2020 06:30:07
 Live Demo
class Program {
   static void Main() {
      DateTime d = DateTime.Now;
      string dateString = d.ToString("yyyyMMddHHmmss");
      System.Console.WriteLine(dateString);
      Console.ReadLine();
   }
}
20200727080325
How to bind a key to a button in Tkinter?

Tkinter provides a way to bind the widget to perform certain operations. These operations are defined in a function that can be called by a particular widget. The bind(<button>, function()) method is used to bind the keyboard key to handle such operations. We can also bind a particular key to handle certain events for the button widget.
#Import tkinter library
from tkinter import *
from tkinter import ttk

#Create an instance of Tkinter frame or window
win = Tk()

#Set the geometry of tkinter frame
win.geometry("750x250")
def callback():
   Label(win, text="Hello World!", font=('Georgia 20 bold')).pack(pady=4)

#Create a Label and a Button widget
btn = ttk.Button(win, text="Press Enter to Show a Message", command= callback)
btn.pack(ipadx=10)

win.bind('<Return>',lambda event:callback())

win.mainloop()
Executing the above code will display a window that consists of a button.
When we press the "Enter" key, it will show the message on the screen.
java.time.LocalDate.plusDays() Method Example

The java.time.LocalDate.plusDays(long daysToAdd) method returns a copy of this date with the specified days added.
Following is the declaration for java.time.LocalDate.plusDays(long daysToAdd) method.
public LocalDate plusDays(long daysToAdd)

daysToAdd − the days to add, may be negative.
a LocalDate based on this date with the days added, not null.
DateTimeException − if the result exceeds the supported date range.
The following example shows the usage of java.time.LocalDate.plusDays(long daysToAdd) method.
package com.tutorialspoint;

import java.time.LocalDate;

public class LocalDateDemo {
   public static void main(String[] args) {
	  
      LocalDate date = LocalDate.parse("2017-02-03");
      System.out.println(date.plusDays(2));  
   }
}
Let us compile and run the above program, this will produce the following result −
2017-02-05

 Print
 Add Notes
 Bookmark this page
Z-score for anomaly detection. Small-bites data science | by Mahbubul Alam | Towards Data Science

Most of the time I write longer articles on data science topics but recently I’ve been thinking about writing small, bite-sized pieces around specific concepts, algorithms and applications. This is my first attempt in that direction, hoping people will like these pieces.
In today’s “small-bite” I’m writing about Z-score in the context of anomaly detection.
Anomaly detection is a process for identifying unexpected data, event or behavior that require some examination. It is a well-established field within data science and there is a large number of algorithms to detect anomalies in a dataset depending on data type and business context. Z-score is probably the simplest algorithm that can rapidly screen candidates for further examination to determine whether they are suspicious or not.
What is Z-score
Simply speaking, Z-score is a statistical measure that tells you how far is a data point from the rest of the dataset. In a more technical term, Z-score tells how many standard deviations away a given observation is from the mean.
For example, a Z score of 2.5 means that the data point is 2.5 standard deviation far from the mean. And since it is far from the center, it’s flagged as an outlier/anomaly.
How it works?
Z-score is a parametric measure and it takes two parameters — mean and standard deviation.
Once you calculate these two parameters, finding the Z-score of a data point is easy.
Note that mean and standard deviation are calculated for the whole dataset, whereas x represents every single data point. That means, every data point will have its own z-score, whereas mean/standard deviation remains the same everywhere.
Example
Below is a python implementation of Z-score with a few sample data points. I’m adding notes in each line of code to explain what’s going on.
# import numpyimport numpy as np# random data points to calculate z-scoredata = [5, 5, 5, -99, 5, 5, 5, 5, 5, 5, 88, 5, 5, 5]# calculate meanmean = np.mean(data) # calculate standard deviationsd = np.std(data)# determine a threholdthreshold = 2# create empty list to store outliersoutliers = []# detect outlierfor i in data:     z = (i-mean)/sd # calculate z-score    if abs(z) > threshold:  # identify outliers        outliers.append(i) # add to the empty list# print outliers    print("The detected outliers are: ", outliers)
Caution and conclusion
If you play with these data you will notice a few things:
There are 14 data points and Z-score correctly detected 2 outliers [-99 and 88]. However, if you remove five data points from the list it detects only 1 outlier [-99]. That means you need to have a certain number of data size for Z-score to work.
In large production datasets, Z-score works best if data are normally distributed (aka. Gaussian distribution).
I used an arbitrary threshold of 2, beyond which all data points are flagged as outliers. The rule of thumb is to use 2, 2.5, 3 or 3.5 as threshold.
Finally, Z-score is sensitive to extreme values, because the mean itself is sensitive to extreme values.
Hope this was useful, feel free to get in touch via Twitter.
Maximum number of squares that can fit in a right angle isosceles triangle in C++

Given the task is to find the maximum number of squares having side ‘a’ that can fit inside a give
right angle isosceles triangle with base of ‘s’(An isosceles triangle has at least 2 equal sides).
Let’s now understand what we have to do using an example:
s=5, a=1
10
Explanation − The number of squares in the base can be calculated by dividing s by a and subtracting 1. So the number of squares in base = 5/1 – 1 = 4.
Similarly when the bottom 4 squares are placed then we get a new isosceles triangle with base
(s-a) and then we repeat the same procedure and get 3 squares and so on until a single square
is placed at the top.
s=7, a=2
3
To find the maximum number of squares we will have to start from the base of the
triangle and find out the number of squares.
To find the maximum number of squares we will have to start from the base of the
triangle and find out the number of squares.
To find the number of squares we will divide the base s by the side of the square
a and subtract 1 from it = s/a – 1.
To find the number of squares we will divide the base s by the side of the square
a and subtract 1 from it = s/a – 1.
Then it will leave us another isosceles triangle with base (s - a) which will
accommodate one less square than the previous row below it which we can
calculate in the following way −
Then it will leave us another isosceles triangle with base (s - a) which will
accommodate one less square than the previous row below it which we can
calculate in the following way −
Squares in next row = (s - a)/a – 1 = (s/a – a/a) – 1= s/a - 1 - 1 = s/a – 2 = one
square less than the previous row.
The number of squares keep decreasing until it reaches 1, therefore we have to
only find the number of squares in the base row and use the formula of adding
natural numbers to find the final sum which is −
The number of squares keep decreasing until it reaches 1, therefore we have to
only find the number of squares in the base row and use the formula of adding
natural numbers to find the final sum which is −
(n) * (n + 1) / 2
In this case the formula becomes − ((s / a) – 1) * (s / a) / 2
 Live Demo
#include<bits/stdc++.h>
using namespace std;
int Max(int s, int a){
   //formula for calculating maximum squares
   return ((s / a) - 1) * (s / a) / 2;
}
//Main function
int main(){
   int s = 5, a = 1;
   cout <<"Maximum squares possible are: "<<Max(s,a);
   return 0;
}
10
foreach Loop in C#

The foreach loop executes a statement or a block of statements for each element in an instance of the type that implements the System.Collections.IEnumerable or System.Collections.Generic.IEnumerable<T> interface.
Let us see an example of foreach loop −
 Live Demo
using System;
using System.Collections.Generic;
public class Demo {
   public static void Main(){
      LinkedList<int> linkedList = new LinkedList<int>();
      linkedList.AddLast(25);
      linkedList.AddLast(50);
      linkedList.AddLast(100);
      linkedList.AddLast(200);
      linkedList.AddLast(400);
      linkedList.AddLast(500);
      linkedList.AddLast(550);
      linkedList.AddLast(600);
      linkedList.AddLast(800);
      linkedList.AddLast(1200);
      Console.WriteLine("Count of nodes = " + linkedList.Count);
      foreach(int val in linkedList){
         Console.WriteLine(val);
      }
      Console.WriteLine("Does the LinkedList has node 800? "+linkedList.Contains(800));
   }
}
This will produce the following output −
Count of nodes = 10
25
50
100
200
400
500
550
600
800
1200
Does the LinkedList has node 800? True
How to instantiate Struct using new keyword in Golang? - GeeksforGeeks

17 May, 2020
A struct is mainly a holder for all other data types. By using a pointer to a struct we can easily manipulate/access the data assigned to a struct. We can instantiate Struct using the new keyword as well as using Pointer Address Operator in Golang as shown in the below example:
Example: Here, you can see we are instantiating a Struct using new keyword.
// Golang program to show how to instantiate// Struct using the new keywordpackage main  import "fmt"  type emp struct {    name   string    empid  int    salary int}  func main() {      // emp1 is a pointer to    // an instance of emp    // using new keyword    emp1 := new(emp)    emp1.name = "XYZ"    emp1.empid = 1555    emp1.salary = 25000    fmt.Println(emp1)      // emp2 is an instance of emp    var emp2 = new(emp)    emp2.name = "ABC"    emp2.salary = 35000    fmt.Println(emp2)}
Output:
&{XYZ 1555 25000}
&{ABC 0 35000}

Golang-Program
Picked
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Time Durations in Golang
How to Parse JSON in Golang?
Structures in Golang
Strings in Golang
Defer Keyword in Golang
How to iterate over an Array using for loop in Golang?
Loops in Go Language
Class and Object in Golang
Rune in Golang
time.Parse() Function in Golang With Examples
Design Pattern - Singleton Pattern

Singleton pattern is one of the simplest design patterns in Java. This type of design pattern comes under creational pattern as this pattern provides one of the best ways to create an object.
This pattern involves a single class which is responsible to create an object while making sure that only single object gets created. This class provides a way to access its only object which can be accessed directly without need to instantiate the object of the class.
We're going to create a SingleObject class. SingleObject class have its constructor as private and have a static instance of itself.
SingleObject class provides a static method to get its static instance to outside world. SingletonPatternDemo, our demo class will use SingleObject class to get a SingleObject object.
Create a Singleton Class.
SingleObject.java
public class SingleObject {

   //create an object of SingleObject
   private static SingleObject instance = new SingleObject();

   //make the constructor private so that this class cannot be
   //instantiated
   private SingleObject(){}

   //Get the only object available
   public static SingleObject getInstance(){
      return instance;
   }

   public void showMessage(){
      System.out.println("Hello World!");
   }
}
Get the only object from the singleton class.
SingletonPatternDemo.java
public class SingletonPatternDemo {
   public static void main(String[] args) {

      //illegal construct
      //Compile Time Error: The constructor SingleObject() is not visible
      //SingleObject object = new SingleObject();

      //Get the only object available
      SingleObject object = SingleObject.getInstance();

      //show the message
      object.showMessage();
   }
}
Verify the output.
Hello World!


    102 Lectures 
     10 hours 

 Arnab Chakraborty

    30 Lectures 
     3 hours 

 Arnab Chakraborty

    31 Lectures 
     4 hours 

 Arnab Chakraborty

    43 Lectures 
     1.5 hours 

 Manoj Kumar

    7 Lectures 
     1 hours 

 Zach Miller

    54 Lectures 
     4 hours 

 Sasha Miller
 Print
 Add Notes
 Bookmark this page
Assertions in Java

An assertion is a statement in Java which ensures the correctness of any assumptions which have been done in the program. When an assertion is executed, it is assumed to be true. If the assertion is false, the JVM will throw an Assertion error. It finds it application primarily in the testing purposes. Assertion statements are used along with boolean expressions.
Assertions in Java can be done with the help of the assert keyword. There are two ways in which an assert statement can be used.
First Way −
assert expression;
Second Way −
assert expression1 : expression2
By default, assertions are disabled in Java. In order to enable them we use the following command −
java -ea Example
(or)
java -enableassertions Example
where Example is the name of the Java file.
Let us see an example for generation of an assertion error by the JVM −
 Live Demo
public class Example {
   public static void main(String[] args) {
      int age = 14;
      assert age <= 18 : "Cannot Vote";
      System.out.println("The voter's age is " + age);
   }
}
The voter's age is 14
Convert time from 24 hour clock to 12 hour clock format in C++

In this tutorial, we will be discussing a program to convert time from 24 hour clock to 12 hour clock format.
For this we will be provided with certain time in 24 hour format. Our task is to convert it into 12 hour format with the extension of “AM” or “PM”.
 Live Demo
#include <bits/stdc++.h>
using namespace std;
//converting into 12 hour format
void convert_12hour(string str){
   int h1 = (int)str[0] - '0';
   int h2 = (int)str[1] - '0';
   int hh = h1 * 10 + h2;
   //finding the extension
   string Meridien;
   if (hh < 12) {
      Meridien = "AM";
   }
   else
      Meridien = "PM";
      hh %= 12;
   if (hh == 0) {
      cout << "12";
      for (int i = 2; i < 8; ++i) {
         cout << str[i];
      }
   } else {
      cout << hh;
      for (int i = 2; i < 8; ++i) {
         cout << str[i];
      }
   }
   cout << " " << Meridien << '\n';
}
int main(){
   string str = "17:35:20";
   convert_12hour(str);
   return 0;
}
5:35:20 PM
Hacking Monoalphabetic Cipher

In this chapter, you will learn about monoalphabetic cipher and its hacking using Python.
A Monoalphabetic cipher uses a fixed substitution for encrypting the entire message. A monoalphabetic cipher using a Python dictionary with JSON objects is shown here −
monoalpha_cipher = {
   'a': 'm',
   'b': 'n',
   'c': 'b',
   'd': 'v',
   'e': 'c',
   'f': 'x',
   'g': 'z',
   'h': 'a',
   'i': 's',
   'j': 'd',
   'k': 'f',
   'l': 'g',
   'm': 'h',
   'n': 'j',
   'o': 'k',
   'p': 'l',
   'q': 'p',
   'r': 'o',
   's': 'i',
   't': 'u',
   'u': 'y',
   'v': 't',
   'w': 'r',
   'x': 'e',
   'y': 'w',
   'z': 'q',
	' ': ' ',
}
With help of this dictionary, we can encrypt the letters with the associated letters as values in JSON object. The following program creates a monoalphabetic program as a class representation which includes all the functions of encryption and decryption.
from string import letters, digits
from random import shuffle

def random_monoalpha_cipher(pool = None):
   if pool is None:
      pool = letters + digits
   original_pool = list(pool)
   shuffled_pool = list(pool)
   shuffle(shuffled_pool)
   return dict(zip(original_pool, shuffled_pool))

def inverse_monoalpha_cipher(monoalpha_cipher):
   inverse_monoalpha = {}
   for key, value in monoalpha_cipher.iteritems():
      inverse_monoalpha[value] = key
   return inverse_monoalpha

def encrypt_with_monoalpha(message, monoalpha_cipher):
   encrypted_message = []
   for letter in message:
      encrypted_message.append(monoalpha_cipher.get(letter, letter))
   return ''.join(encrypted_message)

def decrypt_with_monoalpha(encrypted_message, monoalpha_cipher):
   return encrypt_with_monoalpha(
      encrypted_message,
      inverse_monoalpha_cipher(monoalpha_cipher)
   )
This file is called later to implement the encryption and decryption process of Monoalphabetic cipher which is mentioned as below −
import monoalphabeticCipher as mc

cipher = mc.random_monoalpha_cipher()
print(cipher)
encrypted = mc.encrypt_with_monoalpha('Hello all you hackers out there!', cipher)
decrypted = mc.decrypt_with_monoalpha('sXGGt SGG Nt0 HSrLXFC t0U UHXFX!', cipher)

print(encrypted)
print(decrypted)
You can observe the following output when you implement the code given above −
Thus, you can hack a monoalphabetic cipher with specified key value pair which cracks the cipher text to actual plain text.

    10 Lectures 
     2 hours 

 Total Seminars

    10 Lectures 
     2 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
How can we combine multiple print statements per line in Python?

You can combine multiple print statements per line using, in Python 2 and use the end argument to print function in Python 3.
Python2.x
print "Hello",
print " world"

Python3.x
print ("Hello", end='')
print (" world")
This will give the output −
Hello world
Another thing you could do is put all the things in an array and call ''.join(array). 
arr = ["Hello", "world"]
print(' '.join(arr))
This will give the output −
Hello world
PyQt5 QListWidget – Setting Uniform Item Sizes Property - GeeksforGeeks

06 Aug, 2020
In this article we will see how we can set uniform item sizes property of the QListWidget. QListWidget is a convenience class that provides a list view with a classic item-based interface for adding and removing items. QListWidget uses an internal model to manage each QListWidgetItem in the list. This property holds whether all items in the listview have the same size. This property should only be set to true if it is guaranteed that all items in the view have the same size. This enables the view to do some optimizations for performance purposes.
In order to do this we will use setUniformItemSizes method with the list widget object.
Syntax : list_widget.setUniformItemSizes(True)
Argument : It takes bool as argument
Return : It returns None
Below is the implementation
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys    class Window(QMainWindow):      def __init__(self):        super().__init__()          # setting title        self.setWindowTitle("Python ")          # setting geometry        self.setGeometry(100, 100, 500, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()          # method for components    def UiComponents(self):          # creating a QListWidget        list_widget = QListWidget(self)          # setting geometry to it        list_widget.setGeometry(50, 70, 150, 60)          # list widget items        item1 = QListWidgetItem("A")        item2 = QListWidgetItem("B")        item3 = QListWidgetItem("C")          # adding items to the list widget        list_widget.addItem(item1)        list_widget.addItem(item2)        list_widget.addItem(item3)          # setting uniform item size        list_widget.setUniformItemSizes(True)          # creating a label        label = QLabel("GeesforGeeks", self)          # setting geometry to the label        label.setGeometry(230, 80, 280, 80)          # making label multi line        label.setWordWrap(True)    # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python PyQt-QListWidget
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
Selecting rows in pandas DataFrame based on conditions
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Bar Plot in Matplotlib