code-rag-bench/online-tutorials huggingface dataset:
Group with multiple fields and get the count of duplicate field values grouped together in
MongoDB

For this, use MongoDB aggregate and within that, use $cond. The $cond evaluates a boolean expression to return one of the two specified return expressions.
Let us first create a collection with documents −
> db.demo536.insertOne({"Name1":"Chris","Name2":"David"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e8c843eef4dcbee04fbbc01")
}
> db.demo536.insertOne({"Name1":"David","Name2":"Chris"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e8c843fef4dcbee04fbbc02")
}
> db.demo536.insertOne({"Name1":"Bob","Name2":"Sam"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e8c843fef4dcbee04fbbc03")
}
> db.demo536.insertOne({"Name1":"Chris","Name2":"David"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e8c843fef4dcbee04fbbc04")
}
Display all documents from a collection with the help of find() method −
> db.demo536.find();
This will produce the following output −
{ "_id" : ObjectId("5e8c843eef4dcbee04fbbc01"), "Name1" : "Chris", "Name2" : "David" }
{ "_id" : ObjectId("5e8c843fef4dcbee04fbbc02"), "Name1" : "David", "Name2" : "Chris" }
{ "_id" : ObjectId("5e8c843fef4dcbee04fbbc03"), "Name1" : "Bob", "Name2" : "Sam" }
{ "_id" : ObjectId("5e8c843fef4dcbee04fbbc04"), "Name1" : "Chris", "Name2" : "David" }
Following is the query to group with multiple fields −
> db.demo536.aggregate([
... {
...    $project:
...    {
...       FirstName1:
...       {
...          $cond: { if: { $gte: [ "$Name1", "$Name2" ] }, then: "$Name2", else: "$Name1" }
...       },
...       FirstName2:
...       {
...          $cond: { if: { $lt: [ "$Name1", "$Name2" ] }, then: "$Name2", else: "$Name1" }
...       }
...    }
... }
... ,{
...    $group:
...    {
...       _id:
...       {
...          Name1: "$FirstName1",
...          Name2: "$FirstName2"
...       }
...       ,count: { $sum: 1}
...    }
... }
... ])
This will produce the following output &imnus;
{ "_id" : { "Name1" : "Bob", "Name2" : "Sam" }, "count" : 1 }
{ "_id" : { "Name1" : "Chris", "Name2" : "David" }, "count" : 3 }
Elixir - Case Statement

Case statement can be considered as a replacement for the switch statement in imperative languages. Case takes a variable/literal and applies pattern matching to it with different cases. If any case matches, Elixir executes the code associated with that case and exits the case statement. If no match is found, it exits the statement with an CaseClauseError that displays no matching clauses were found. You should always have a case with _ which matches all values. This helps in prevention of the above mentioned error. Also this is comparable to the default case in switch-case statements.
The syntax of an if statement is as follows −
case value do
      matcher_1 -> #code to execute if value matches matcher_1
	matcher_2 -> #code to execute if value matches matcher_2
	matcher_3 -> #code to execute if value matches matcher_3
	...
	_ -> #code to execute if value does not match any of the above
end

case 3 do
   1 -> IO.puts("Hi, I'm one")
   2 -> IO.puts("Hi, I'm two")
   3 -> IO.puts("Hi, I'm three")
   _ -> IO.puts("Oops, you dont match!")
end
The above program generates the following result.
Hi, I'm three

Note that the case selection is done using pattern matching, so you can use the standard pattern matching techniques.

    35 Lectures 
     3 hours 

 Pranjal Srivastava

    54 Lectures 
     6 hours 

 Pranjal Srivastava, Harshit Srivastava

    80 Lectures 
     9.5 hours 

 Pranjal Srivastava

    43 Lectures 
     4 hours 

 Mohammad Nauman
 Print
 Add Notes
 Bookmark this page
How to change Tkinter label text on button press?

Most often, Tkinter Label widgets are used in the application to display the text or images. We can configure the label widget such as its text property, color, background or foreground color using the config(**options) method.
If you need to modify or change the label widget dynamically, then you can use a button and a function to change the text of the label widget.
# Import the required libraries
from tkinter import *

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

# Set the size of the tkinter window
win.geometry("700x350")

# Define a function update the label text
def on_click():
   label["text"] = "Python"
   b["state"] = "disabled"

# Create a label widget
label = Label(win, text="Click the Button to update this Text",
font=('Calibri 15 bold'))
label.pack(pady=20)

# Create a button to update the label widget
b = Button(win, text="Update Label", command=on_click)
b.pack(pady=20)

win.mainloop()
When you run the above code, it will show a label text and a button in the window.
When you click the button, it will just update the label text.
How to show a bar and line graph on the same plot in Matplotlib?

To show a bar and line graph on the same plot in matplotlib, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Set the figure size and adjust the padding between and around the subplots.
Make a two-dimensional, size-mutable, potentially heterogeneous tabular data.
Make a two-dimensional, size-mutable, potentially heterogeneous tabular data.
Create a figure and a set of subplots.
Create a figure and a set of subplots.
Plot the bar and line with the dataframe obtained from Step 2.
Plot the bar and line with the dataframe obtained from Step 2.
To display the figure, use show() method.
To display the figure, use show() method.
import pandas as pd
import matplotlib.pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

df = pd.DataFrame(dict(data=[2, 4, 1, 5, 9, 6, 0, 7]))
fig, ax = plt.subplots()

df['data'].plot(kind='bar', color='red')
df['data'].plot(kind='line', marker='*', color='black', ms=10)

plt.show()
Python - Text Translation

Text translation from one language to another is increasingly becoming common for various websites as they cater to an international audience. The python package which helps us do this is called translate.
This package can be installed by the following way. It provides translation for major languages.
pip install translate
Below is an example of translating a simple sentence from English to German. The default from language being English.
from translate import Translator
translator= Translator(to_lang="German")
translation = translator.translate("Good Morning!")
print translation
When we run the above program, we get the following output −
Guten Morgen!

If we have the need specify the from-language and the to-language, then we can specify it as in the below program.
from translate import Translator
translator= Translator(from_lang="german",to_lang="spanish")
translation = translator.translate("Guten Morgen")
print translation
When we run the above program, we get the following output −
Buenos días


    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
getpagesize() - Unix, Linux System Call

Unix - Home
Unix - Getting Started
Unix - File Management
Unix - Directories
Unix - File Permission
Unix - Environment
Unix - Basic Utilities
Unix - Pipes & Filters
Unix - Processes
Unix - Communication
Unix - The vi Editor
Unix - What is Shell?
Unix - Using Variables
Unix - Special Variables
Unix - Using Arrays
Unix - Basic Operators
Unix - Decision Making
Unix - Shell Loops
Unix - Loop Control
Unix - Shell Substitutions
Unix - Quoting Mechanisms
Unix - IO Redirections
Unix - Shell Functions
Unix - Manpage Help
Unix - Regular Expressions
Unix - File System Basics
Unix - User Administration
Unix - System Performance
Unix - System Logging
Unix - Signals and Traps
Unix - Useful Commands
Unix - Quick Guide
Unix - Builtin Functions
Unix - System Calls
Unix - Commands List
Unix Useful Resources
Computer Glossary
Who is Who
Copyright © 2014 by tutorialspoint

int getpagesize(void); 

The size of the kind of pages that
mmap() uses, is found using



#include <unistd.h>
long sz = sysconf(_SC_PAGESIZE);


(where some systems also allow the synonym _SC_PAGE_SIZE for _SC_PAGESIZE),
or



#include <unistd.h>
int sz = getpagesize();

mmap (2)
mmap (2)

Advertisements


    129 Lectures 
     23 hours 

 Eduonix Learning Solutions

    5 Lectures 
     4.5 hours 

 Frahaan Hussain

    35 Lectures 
     2 hours 

 Pradeep D

    41 Lectures 
     2.5 hours 

 Musab Zayadneh

    46 Lectures 
     4 hours 

 GUHARAJANM

    6 Lectures 
     4 hours 

 Uplatz
 Print
 Add Notes
 Bookmark this page
false command in Linux with examples - GeeksforGeeks

05 Mar, 2019
false command is used to return an exit status code (“1” by default) that indicates failure. It is useful when the user wants a conditional expression or an argument to always be unsuccessful. When no argument is passed to the false command, it fails with no output and exit status as 1.
Syntax:
false [argument]
Example:
We can see that no output is returned but we can check the exit status value by checking the value of the special shell variable i.e. ?, that contain the exit status of the false command. Since ? is a variable, we need to prefix it with $ for the reference.
Syntax:
"$?"
Example: To print the exit status of the previous command.
Options:
–help : It is used to show this help information and exit.
–version: It gives the version information and exit.
Implementing false command in an if statement: We can use the false command in if statement when we want to execute a statement/command if the condition becomes false.
Syntax:
if false; then [Executable statements]; else [Executable statement]; fi
Example:
if false; then echo "It's false"; else echo "It's True"; fi
linux-command
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Thread functions in C/C++
nohup Command in Linux with Examples
scp command in Linux with Examples
chown command in Linux with Examples
Array Basics in Shell Scripting | Set 1
mv command in Linux with examples
Basic Operators in Shell Scripting
SED command in Linux | Set 2
Docker - COPY Instruction
Named Pipe or FIFO with example C program
How to use OR condition in a JavaScript IF statement?

To use OR condition in JavaScript IF statement, use the || operator i.e Logical OR operator. If any of the two operands are non-zero, then the condition becomes true.
Here’s how you can use the operator || in JavaScript
Live Demo
<html>
   <body>
      <script>
         var a = true;
         var b = false;

         document.write("(a || b) => ");
         result = (a || b);
         document.write(result);
      </script>
   </body>
</html>
How to change the column names and row names of a data frame in R?

We can colnames function to change the column names and rownames function to
change the row names.
> df <- data.frame(ID=1:5,Salry=c(10000,30000,22000,27000,18000))
> df
ID Salry
1 1 10000
2 2 30000
3 3 22000
4 4 27000
5 5 18000
> colnames(df)<-c("EmployeeID","Salary")
> df
EmployeeID Salary
1 1 10000
2 2 30000
3 3 22000
4 4 27000
5 5 18000
> rownames(df)<-c("001","025","019","102","089")
df
EmployeeID Salary
001 1 10000
025 2 30000
019 3 22000
102 4 27000
089 5 18000
Cosine Similarity - GeeksforGeeks

06 Oct, 2020
Prerequisite – Measures of Distance in Data Mining
In Data Mining, similarity measure refers to distance with dimensions representing features of the data object, in a dataset. If this distance is less, there will be a high degree of similarity, but when the distance is large, there will be a low degree of similarity.
Some of the popular similarity measures are –
Euclidean Distance.Manhattan Distance.Jaccard Similarity.Minkowski Distance.Cosine Similarity.
Euclidean Distance.
Manhattan Distance.
Jaccard Similarity.
Minkowski Distance.
Cosine Similarity.
Cosine similarity is a metric, helpful in determining, how similar the data objects are irrespective of their size. We can measure the similarity between two sentences in Python using Cosine Similarity. In cosine similarity, data objects in a dataset are treated as a vector. The formula to find the cosine similarity between two vectors is –
Cos(x, y) = x . y / ||x|| * ||y||
where,
x . y = product (dot) of the vectors ‘x’ and ‘y’.
||x|| and ||y|| = length of the two vectors ‘x’ and ‘y’.
||x|| * ||y|| = cross product of the two vectors ‘x’ and ‘y’.
Example :Consider an example to find the similarity between two vectors – ‘x’ and ‘y’, using Cosine Similarity.
The ‘x’ vector has values, x = { 3, 2, 0, 5 }The ‘y’ vector has values, y = { 1, 0, 0, 0 }
The formula for calculating the cosine similarity is : Cos(x, y) = x . y / ||x|| * ||y||
x . y = 3*1 + 2*0 + 0*0 + 5*0 = 3

||x|| = √ (3)^2 + (2)^2 + (0)^2 + (5)^2 = 6.16

||y|| = √ (1)^2 + (0)^2 + (0)^2 + (0)^2 = 1

∴ Cos(x, y) = 3 / (6.16 * 1) = 0.49 
The dissimilarity between the two vectors ‘x’ and ‘y’ is given by –
∴ Dis(x, y) = 1 - Cos(x, y) = 1 - 0.49 = 0.51
The cosine similarity between two vectors is measured in ‘θ’.
If θ = 0°, the ‘x’ and ‘y’ vectors overlap, thus proving they are similar.
If θ = 90°, the ‘x’ and ‘y’ vectors are dissimilar.
Cosine Similarity between two vectors
Advantages :
The cosine similarity is beneficial because even if the two similar data objects are far apart by the Euclidean distance because of the size, they could still have a smaller angle between them. Smaller the angle, higher the similarity.
When plotted on a multi-dimensional space, the cosine similarity captures the orientation (the angle) of the data objects and not the magnitude.
data mining
DBMS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction of B-Tree
Difference between Clustered and Non-clustered index
CTE in SQL
SQL | Views
SQL Interview Questions
Third Normal Form (3NF)
SQL | GROUP BY
Difference between Primary Key and Foreign Key
Second Normal Form (2NF)
Difference between DELETE, DROP and TRUNCATE
JavaScript - The Function() Constructor

The function statement is not the only way to define a new function; you can define your function dynamically using Function() constructor along with the new operator.
Note − Constructor is a terminology from Object Oriented Programming. You may not feel comfortable for the first time, which is OK.
Following is the syntax to create a function using Function( ) constructor along with the new operator.
<script type = "text/javascript">
   <!--
      var variablename = new Function(Arg1, Arg2..., "Function Body");
   //-->
</script>

The Function() constructor expects any number of string arguments. The last argument is the body of the function – it can contain arbitrary JavaScript statements, separated from each other by semicolons.
Notice that the Function() constructor is not passed any argument that specifies a name for the function it creates. The unnamed functions created with the Function() constructor are called anonymous functions.
Try the following example.
<html>
   <head>
      <script type = "text/javascript">
         <!--
            var func = new Function("x", "y", "return x*y;");
            function secondFunction() {
               var result;
               result = func(10,20);
               document.write ( result );
            }
         //-->
      </script>
   </head>
   
   <body>
      <p>Click the following button to call the function</p>
      
      <form>
         <input type = "button" onclick = "secondFunction()" value = "Call Function">
      </form>
      
      <p>Use different parameters inside the function and then try...</p>
   </body>
</html>
Click the following button to call the function
Use different parameters inside the function and then try...

    25 Lectures 
     2.5 hours 

 Anadi Sharma

    74 Lectures 
     10 hours 

 Lets Kode It

    72 Lectures 
     4.5 hours 

 Frahaan Hussain

    70 Lectures 
     4.5 hours 

 Frahaan Hussain

    46 Lectures 
     6 hours 

 Eduonix Learning Solutions

    88 Lectures 
     14 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page
DAX Other - SUMMARIZECOLUMNS function

Returns a summary table over a set of groups.
DAX SUMMARIZECOLUMNS function is new in Excel 2016.
SUMMARIZECOLUMNS (<groupBy_columnName>, [< groupBy_columnName >] ..., 
   [<filterTable>] ..., [<name>, <expression>] ...) 

groupBy_columnName
A fully qualified column reference (Table[Column]) to a base table for which the distinct values are included in the returned table. Each groupBy_columnName column is
cross-joined (different tables), or
auto-existed (same table)
with the subsequent specified columns.
filterTable
A table expression which is added to the filter context of all columns specified as groupBy_columnName arguments.
The values present in the filter table are used to filter before cross-join/auto-exist is performed.
name
A string representing the column name to use for the subsequent expression specified.
expression
Any DAX expression that returns a single value (not a table).
A table which includes the combinations of values from the supplied columns, based on the grouping specified.
Only rows for which at least one of the supplied expressions return a non-blank value are included in the table returned.
Only rows for which at least one of the supplied expressions return a non-blank value are included in the table returned.
If all expressions evaluate to BLANK/NULL for a row, that row is not included in the table returned.
If all expressions evaluate to BLANK/NULL for a row, that row is not included in the table returned.
SUMMARIZECOLUMNS does not guarantee any sort order for the results.
A column cannot be specified more than once in the groupBy_columnName parameter.
= SUMX ( 
   SUMMARIZECOLUMNS (Salesperson[Salesperson],  
   FILTER (Sales, Sales[Region]="South"), 
   "Sales Amount", SUMX (Sales, Sales[Sales Amount])), 
   [Sales Amount]
) 

    53 Lectures 
     5.5 hours 

 Abhay Gadiya

    24 Lectures 
     2 hours 

 Randy Minder

    26 Lectures 
     4.5 hours 

 Randy Minder
 Print
 Add Notes
 Bookmark this page
Groovy - ceil()

The method ceil gives the smallest integer that is greater than or equal to the argument.
double ceil(double d) 
double ceil(float f)

Parameters − A double or float primitive data type.
Return Value − This method Returns the smallest integer that is greater than or equal to the argument. Returned as a double.
Following is an example of the usage of this method −
class Example { 
   static void main(String[] args) { 
      double a = -100.675; 
      float b = -90;
		
      System.out.println(Math.ceil(a)); 
      System.out.println(Math.ceil(b)); 
   } 
}
When we run the above program, we will get the following result −
-100.0 
-90.


    52 Lectures 
     8 hours 

 Krishna Sakinala

    49 Lectures 
     2.5 hours 

 Packt Publishing
 Print
 Add Notes
 Bookmark this page
Bitwise Operators in C

The following table lists the Bitwise operators supported by C. Assume variable 'A' holds 60 and variable 'B' holds 13, then −
Try the following example to understand all the bitwise operators available in C −
#include <stdio.h>

main() {

   unsigned int a = 60;	/* 60 = 0011 1100 */  
   unsigned int b = 13;	/* 13 = 0000 1101 */
   int c = 0;           

   c = a & b;       /* 12 = 0000 1100 */ 
   printf("Line 1 - Value of c is %d\n", c );

   c = a | b;       /* 61 = 0011 1101 */
   printf("Line 2 - Value of c is %d\n", c );

   c = a ^ b;       /* 49 = 0011 0001 */
   printf("Line 3 - Value of c is %d\n", c );

   c = ~a;          /*-61 = 1100 0011 */
   printf("Line 4 - Value of c is %d\n", c );

   c = a << 2;     /* 240 = 1111 0000 */
   printf("Line 5 - Value of c is %d\n", c );

   c = a >> 2;     /* 15 = 0000 1111 */
   printf("Line 6 - Value of c is %d\n", c );
}
When you compile and execute the above program, it produces the following result −
Line 1 - Value of c is 12
Line 2 - Value of c is 61
Line 3 - Value of c is 49
Line 4 - Value of c is -61
Line 5 - Value of c is 240
Line 6 - Value of c is 15

 Print
 Add Notes
 Bookmark this page
Boundary Value Test Cases, Robust Cases and Worst Case Test Cases - GeeksforGeeks

29 May, 2020
Generate boundary Value analysis, robust and worst-case test case for the program to find the median of three numbers. Its input is a triple of positive integers (say x, y, and z) and the minimum value can be 100 and maximum can be 500.
Median of three numbers is the middle number when all three numbers are sorted.
Example –
10, 40, 20
In this case, the median is 20 (10, 20, 40).
1. Boundary Value Test Cases are –
for x, y, z :
min value = 100
close to min = 101
nominal = 300
close to max = 499
max = 500 
Test cases are,
4*3 + 1 = 13 
2. Robust Test Cases –Here, we go outside the legitimate boundary, it is an extension of boundary value analysis.
for x, y, z :
min value : 100  
close to min : 101  
nominal : 300 
close to max : 499 
max : 500 
lesser than min value : 99 
larger than max value : 501  
Total test cases,
= 6*n+1 = 6*3+1 = 19 
So there will be extra 6 cases apart from the above 13 cases –
3. Worst Test Cases –If we reject “single” fault assumption theory of reliability, and consider cases where more than 1 variable has extreme values, then it is known as worst case analysis.
Total no. of test cases,
5^n = 5^3 = 125 cases 
Mathematically, the test cases will be a cross product of 3 sets –
  {100, 101, 300, 499, 500} 
x {100, 101, 300, 499, 500} 
x {100, 101, 300, 499, 500}
Let set A,
= {100, 101, 300, 499, 500}
So, the set of worst cases will be represented by,
= A x A x A 
Software Testing
Software Engineering
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Software Requirement Specification (SRS) Format
Software Engineering | Requirements Engineering Process
Software Engineering | SDLC V-Model
Levels in Data Flow Diagrams (DFD)
Software Testing Life Cycle (STLC)
Class Diagram for Library Management System
Software Engineering | Iterative Waterfall Model
Software Engineering | Requirements Elicitation
Software Engineering | Quality Characteristics of a good SRS
Difference between Spring and Spring Boot
How to Count Unique Values in Excel? - GeeksforGeeks

17 Dec, 2021
We often need to report the Unique number of customers purchased, the number of products in our stock, List of regions our business covered.  
In this article, we explain how to count unique values in an excel column.
Sample Data:
We have given sample data with two fields Customer and Products purchased.  Need to create a summary report to show how many customers are in our database.
Syntax:
COUNTIF (range, criteria)

Range – List of data

Criteria – A number or text.  Apply on input range

Return an integer value that match the criteria  
Step 1: Type “Number of Customers” in cell D5
Step 2: Write the below formula in cell E5, to count the Number of unique customers.  We use the Array formula to compute unique count, So make sure you have to Press Ctrl+Shift+Enter as shown in Image 1 below:
=SUM(1/COUNTIF(B2:B30,B2:B30))
Your formula in cell E5 should be covered with “{}“ Curly braces  as shown in Image 2 below:
Image 1
Image 2
IF you are using MS office 365, you can use the below formula to compute unique count.
=COUNTA(UNIQUE(B2:B30))
Syntax
COUNTA(Value1, Value2,...)

Value1 – a cell, excel range, array of text

Return count of non-empty cells
UNIQUE(array, by_col, exactly_once)

Array - list of data value to return unique

By_col – Boolean value [True - return unique columns / False – return unique rows]

Exactly_once – Boolean value [return only distinct values]
Excel-functions
Picked
Excel
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Use Solver in Excel?
How to Find the Last Used Row and Column in Excel VBA?
How to Get Length of Array in Excel VBA?
Using CHOOSE Function along with VLOOKUP in Excel
Macros in Excel
How to Extract the Last Word From a Cell in Excel?
Introduction to Excel Spreadsheet
How to Show Percentages in Stacked Column Chart in Excel?
How to Remove Duplicates From Array Using VBA in Excel?
How to Sum Values Based on Criteria in Another Column in Excel?
bokeh.plotting.figure.diamond() function in Python - GeeksforGeeks

28 Jul, 2020
Bokeh is a data visualization library in Python that provides high-performance interactive charts and plots and the output can be obtained in various mediums like notebook, HTML and server. Figure Class create a new Figure for plotting. It is a subclass of Plot that simplifies plot creation with default axes, grids, tools, etc.  
The diamond() function in the plotting module of the bokeh library is used to Configure and add Diamond glyphs to this Figure.  
Syntax: diamond(x, y, size=4, angle=0.0, *, angle_units=’rad’, fill_alpha=1.0, fill_color=’gray’, line_alpha=1.0, line_cap=’butt’, line_color=’black’, line_dash=[], line_dash_offset=0, line_join=’bevel’, line_width=1, name=None, tags=[], **kwargs)
Parameters: This method accept the following parameters that are described below:  
x: This parameter is the x-coordinates for the center of the markers.
y: This parameter is the y-coordinates for the center of the markers.
size: This parameter is the size (diameter) values for the markers in screen space units.
angle: This parameter is the angles to rotate the markers.
fill_color: This parameter is the fill color values for the markers.
line_color: This parameter is the line color values for the markers with default value of black.1.
name: This parameter is the user-supplied name for this model.
tags: This parameter is the user-supplied values for this model.
Return: This method return the GlyphRenderer value.  
Below examples illustrate the bokeh.plotting.figure.diamond() function in bokeh.plotting: Example 1:  
Python3
# Implementation of bokeh function      import numpy as np  from bokeh.plotting import figure, output_file, show      plot = figure(plot_width = 300, plot_height = 300) plot.diamond(x = [1, 2, 3], y = [3, 7, 5],              size = 20, color ="red", alpha = 0.9)      show(plot) 
Output:  
Example 2:  
Python3
# Implementation of bokeh function      import numpy as np  from bokeh.plotting import figure, output_file, show      x = [1, 2, 3, 4, 5] y = [6, 7, 8, 7, 3]     output_file("geeksforgeeks.html")     p = figure(plot_width = 300, plot_height = 300)   p.line(x, y, line_width = 2) p.diamond(x, y, fill_color ="red",           line_color ="green", size = 18)     show(p) 
Output:  
 
Python Bokeh-plotting-figure-class
Python-Bokeh
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | Get unique values from a list
Python | os.path.join() method
Defaultdict in Python
Create a directory in Python
Python | Pandas dataframe.groupby()
How to get the structure of a given DataFrame in R? - GeeksforGeeks

26 Mar, 2021
In this article, we will see how to get the structure of a DataFrame in R programming.
Steps for Getting Structure of DataFrame:
Create dataframe.
The size of each vector should be the same.
Follow the syntax while creating data frames.
Function Used:
To get the structure of a data frame we use a built-in function called srt().
Syntax: srt( Dataframe_name )
We have to pass the data frame which is already created.
If we don’t pass an already created data frame we are not getting anything.
Example 1: Creating a data frame with 2 columns:
R
df1 = data.frame(id = c(1  ,2 , 3), name = c("karhik" ,                                            "nikhil" ,                                           "sravan"))print(df1)
Output:
Example 2: Creating dataframe with 3 columns.
R
df2 = data.frame(sid = c(1, 2, 3),                 sname = c("karthik" , "nikhil" , "sravan"),                 Branch = c("IT" , "CSE" , "IT"))print(df2)
Output:
Example 3: Creating dataframe with 4 columns.
R
df3 = data.frame(eid = c(1, 2, 3) ,                 ename = c("krishna" , "nikhil" , "manoj"),                 salary = c(50,000 , 60,000 , 70,000),                  Designation = c("senior manager" , "HR" , "Manager"))print(df3)
Output:
Example 1: Structure of df1
R
df1 = data.frame(id = c(1  , 2, 3),                 name = c("karhik" , "nikhil" , "sravan"))srt(df1)
Output:
Example 2: Structure of df2
R
df2 = data.frame(sid = c(1, 2, 3),                 sname = c("karthik" , "nikhil" , "sravan"),                 Branch = c("IT" , "CSE" , "IT"))str(df2)
Output:
Example 3: Structure of df3
R
df3 = data.frame(eid = c(1, 2, 3) ,                  ename = c("krishna" , "nikhil" , "manoj"),                 salary = c(50000 , 60000 , 70000),                 Designation = c("senior manager" , "HR" , "Manager"))str(df3)
Output:
Picked
R DataFrame-Programs
R-DataFrame
R Language
R Programs
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
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
How to filter R dataframe by multiple conditions?
Convert Matrix to Dataframe in R
Implementation of Perceptron Algorithm for NAND Logic Gate with 2-bit Binary Input - GeeksforGeeks

08 Jul, 2020
In the field of Machine Learning, the Perceptron is a Supervised Learning Algorithm for binary classifiers. The Perceptron Model implements the following function:
    
For a particular choice of the weight vector  and bias parameter , the model predicts output  for the corresponding input vector .
NAND logical function truth table for 2-bit binary variables, i.e, the input vector  and the corresponding output  –
We can observe that, Now for the corresponding weight vector  of the input vector  to the AND node, the associated Perceptron Function can be defined as:
    
Later on, the output of AND node  is the input to the NOT node with weight . Then the corresponding output  is the final output of the NAND logic function and the associated Perceptron Function can be defined as:
    
For the implementation, considered weight parameters are  and the bias parameters are .
Python Implementation:
# importing Python libraryimport numpy as np  # define Unit Step Functiondef unitStep(v):    if v >= 0:        return 1    else:        return 0  # design Perceptron Modeldef perceptronModel(x, w, b):    v = np.dot(w, x) + b    y = unitStep(v)    return y  # NOT Logic Function# wNOT = -1, bNOT = 0.5def NOT_logicFunction(x):    wNOT = -1    bNOT = 0.5    return perceptronModel(x, wNOT, bNOT)  # AND Logic Function# w1 = 1, w2 = 1, bAND = -1.5def AND_logicFunction(x):    w = np.array([1, 1])    bAND = -1.5    return perceptronModel(x, w, bAND)  # NAND Logic Function# with AND and NOT  # function calls in sequencedef NAND_logicFunction(x):    output_AND = AND_logicFunction(x)    output_NOT = NOT_logicFunction(output_AND)    return output_NOT  # testing the Perceptron Modeltest1 = np.array([0, 1])test2 = np.array([1, 1])test3 = np.array([0, 0])test4 = np.array([1, 0])  print("NAND({}, {}) = {}".format(0, 1, NAND_logicFunction(test1)))print("NAND({}, {}) = {}".format(1, 1, NAND_logicFunction(test2)))print("NAND({}, {}) = {}".format(0, 0, NAND_logicFunction(test3)))print("NAND({}, {}) = {}".format(1, 0, NAND_logicFunction(test4)))
NAND(0, 1) = 1
NAND(1, 1) = 0
NAND(0, 0) = 1
NAND(1, 0) = 1

Here, the model predicted output () for each of the test inputs are exactly matched with the NAND logic gate conventional output () according to the truth table for 2-bit binary input.Hence, it is verified that the perceptron algorithm for NAND logic gate is correctly implemented.
Akanksha_Rai
Neural Network
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Linear Regression
Reinforcement learning
Decision Tree
Decision Tree Introduction with example
Support Vector Machine Algorithm
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python | Alternate range slicing in list - GeeksforGeeks

29 Mar, 2019
List slicing is quite common utility in Python, one can easily slice certain elements from a list, but sometimes, we need to perform that task in non-contiguous manner and slice alternate ranges. Let’s discuss how this particular problem can be solved.
Method #1 : Using list comprehensionList comprehension can be used to perform this particular task with ease as it can be used to run a loop and only filter the elements that leave a remainder more than half of target slice size multiplied by 2. By this way we can extract the sliced numbers in range alternatively.
# Python3 code to demonstrate# alternate range slicing # using list comprehension  # initializing list test_list = [2, 4, 6, 8, 9, 10, 12, 16, 18, 20, 7, 30]  # printing original listprint("The original list : " + str(test_list))  # Select range size N = 3  # using list comprehension# alternate range slicingres = [test_list[i] for i in range(len(test_list))                               if i % (N * 2) >= N]  # print resultprint("The alternate range sliced list : " + str(res))
The original list : [2, 4, 6, 8, 9, 10, 12, 16, 18, 20, 7, 30]
The alternate range sliced list : [8, 9, 10, 20, 7, 30]

 
Method #2 : Using enumerate() + list comprehensionThe list comprehension can also be combined with the enumerate function to perform this task. The advantage of using enumerate is that we can track of index along with the value and it’s more efficient and has lesser run-time than the above function.
# Python3 code to demonstrate# alternate range slicing # using list comprehension + enumerate()  # initializing list test_list = [2, 4, 6, 8, 9, 10, 12, 16, 18, 20, 7, 30]  # printing original listprint("The original list : " + str(test_list))  # Select range size N = 3  # using list comprehension + enumerate()# alternate range slicingres = [val for i, val in enumerate(test_list)                         if i % (N * 2) >= N]  # print resultprint("The alternate range sliced list : " + str(res))
The original list : [2, 4, 6, 8, 9, 10, 12, 16, 18, 20, 7, 30]
The alternate range sliced list : [8, 9, 10, 20, 7, 30]

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
numpy.argpartition() in Python - GeeksforGeeks

28 Dec, 2018
numpy.argpartition() function is used to create a indirect partitioned copy of input array with its elements rearranged in such a way that the value of the element in k-th position is in the position it would be in a sorted array. All elements smaller than the k-th element are moved before this element and all equal or greater are moved behind it. The ordering of the elements in the two partitions is undefined.It returns an array of indices of the same shape as arr, i.e arr[index_array] yields a partition of arr.
Syntax : numpy.argpartition(arr, kth, axis=-1, kind=’introselect’, order=None)
Parameters :arr : [array_like] Input array.kth : [int or sequence of ints ] Element index to partition by.axis : [int or None] Axis along which to sort. If None, the array is flattened before sorting. The default is -1, which sorts along the last axis.kind : Selection algorithm. Default is ‘introselect’.order : [str or list of str] When arr is an array with fields defined, this argument specifies which fields to compare first, second, etc.
Return : [index_array, ndarray] Array of indices that partition arr along the specified axis.
Code #1 :
# Python program explaining# argpartition() function   import numpy as geek  # input arrayin_arr = geek.array([[ 2, 0,  1], [ 5, 4, 9] ])print ("Input array : \n", in_arr)   out_arr = geek.argpartition(in_arr, 1, axis = 1)print ("Output partitioned array indices :\n ", out_arr)
Input array : 
 [[2 0 1]
 [5 4 9]]
Output partitioned array indices :
  [[1 2 0]
 [1 0 2]]

 Code #2 :
# Python program explaining# argpartition() function   import numpy as geek  # input arrayin_arr = geek.array([ 2, 0,  1, 5, 4, 3])print ("Input array : ", in_arr)   out_arr = geek.argpartition(in_arr, (0, 2))print ("Output partitioned array indices: ", out_arr)
Input array :  [2 0 1 5 4 3]
Output partitioned array indices:  [1 2 0 3 4 5]

Python numpy-Sorting Searching
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Reorder Facets in ggplot2 Plot in R - GeeksforGeeks

31 Aug, 2021
In this article, we will be looking at an approach to reorder the facets in the ggplot2 plot in R programming language.
To reorder the facets accordingly of the given ggplot2 plot, the user needs to reorder the levels of our grouping variable accordingly with the help of the levels function and required parameter passed into it, further it will lead to the reordering of the facets accordingly in the R programming language.
Level function provides access to the levels attribute of a variable. The first form returns the value of the levels of its argument and the second sets the attribute.
Syntax:
levels(x)
Parameters:
x: an object, for example, a factor.
Let us first look at the initial plot. so that the difference after reordering can be observed prominently.
Example: initial plot
R
library(ggplot2)  gfg < - data.frame(x=c(4, 9, 5, 6, 10, 2, 3, 7, 8, 1),                   y=c(9, 4, 3, 1, 5, 2, 8, 10, 7, 6),                   group=c('A', 'B', 'C', 'D', 'E'))  gfg_plot < - ggplot(gfg, aes(x, y)) +geom_point() + facet_grid(.~group)  gfg_plot
Output:
Now let’s reorder facets using the levels function.
Example: Plot after reordering of facets
R
library(ggplot2)  gfg < - data.frame(x=c(4, 9, 5, 6, 10, 2, 3, 7, 8, 1),                   y=c(9, 4, 3, 1, 5, 2, 8, 10, 7, 6),                   group=c('A', 'B', 'C', 'D', 'E'))  gfg$group < - factor(gfg$group, levels=c("E", "B", "A", "C", "D"))  gfg_plot < - ggplot(gfg, aes(x, y)) + geom_point() +facet_grid(.~group)  gfg_plot
Output:
Example: In this example, we will be using a set of 10 data points for the ggplot2 bar plot and will be reordering the facets of this bar plot accordingly with the help of the level function.
R
library(ggplot2)  gfg < - data.frame(x=c(4, 9, 5, 6, 10, 2, 3, 7, 8, 1),                   y=c(9, 4, 3, 1, 5, 2, 8, 10, 7, 6),                   group=c('A', 'B', 'C', 'D', 'E'))  gfg$group < - factor(gfg$group, levels=c("C", "E", "B", "A", "D"))  gfg_plot < - ggplot(gfg, aes(x, y)) + geom_bar(stat="identity") +facet_grid(.~group)  gfg_plot
Output:
Picked
R-ggplot
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
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to import an Excel File into R ?
How to filter R DataFrame by values in a column?
Time Series Analysis in R
R - if statement
Logistic Regression in R Programming
Set the innerHTML with JavaScript

The correct syntax to set the innerHTML is as follows −
document.getElementById(“yourIdName”).innerHTML=”yourValue”;
Let’s now see how to set the innerHTML −
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<title>Document</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fontawesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
<label>
Username:<input type="text" />
</label>
<p id="test"></p>
<script>
   document.getElementById('test').innerHTML = 'Enter Some value into the text box';
</script>
</body>
</html>
To run the above program, save the file name “anyName.html(index.html)” and right click on the
file. Select the option “Open with Live Server” in VS Code editor.
This will produce the following output −
Fortran - Cycle Statement

The cycle statement causes the loop to skip the remainder of its body, and immediately retest its condition prior to reiterating.
program cycle_example     
implicit none      

   integer :: i     
   
   do i = 1, 20          
   
      if (i == 5) then 
         cycle          
      end if         
      
   print*, i      
   end do  
   
end program cycle_example
When the above code is compiled and executed, it produces the following result −
1
2
3
4
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

 Print
 Add Notes
 Bookmark this page
Swap two numbers in C#

To swap two numbers, work with the following logic.
Set two variables for swapping −
val1 = 100;
val2 = 200;
Now perform the following operation for swap −
val1 = val1 + val2;
val2 = val1 - val2;
val1 = val1 - val2;
The following is the code −
using System;
namespace Demo {
   class Program {
      static void Main(string[] args) {

         int val1,val2;
         val1 = 100;
         val2 = 200;

         Console.WriteLine("Values before swap...");
         Console.WriteLine(val1.ToString());
         Console.WriteLine(val2.ToString());

         val1 = val1 + val2;
         val2 = val1 - val2;
         val1 = val1 - val2;
   
         Console.WriteLine("Values after swap...");
         Console.WriteLine(val1.ToString());
         Console.WriteLine(val2.ToString());
         Console.ReadLine();
      }
   }
}
Removing Horizontal Lines in image (OpenCV, Python, Matplotlib)

To remove horizontal lines in an image, we can take the following steps −
Read a local image.
Convert the image from one color space to another.
Apply a fixed-level threshold to each array element.
Get a structuring element of the specified size and shape for morphological operations.
Perform advanced morphological transformations.
Find contours in a binary image.
Repeat step 4 with different kernel size.
Repeat step 5 with a new kernel from step 7.
Show the resultant image.
import cv2

image = cv2.imread('input_image.png')
cv2.imshow('source_image', image)

gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

horizontal_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (25, 1))
detected_lines = cv2.morphologyEx(thresh, cv2.MORPH_OPEN,
horizontal_kernel, iterations=2)

cnts = cv2.findContours(detected_lines, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]

for c in cnts:
   cv2.drawContours(image, [c], -1, (255, 255, 255), 2)

repair_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1, 6))

result = 255 - cv2.morphologyEx(255 - image, cv2.MORPH_CLOSE, repair_kernel,
iterations=1)

cv2.imshow('resultant image', result)
cv2.waitKey()
cv2.destroyAllWindows()
Observe that the horizontal lines in our source_image are no longer visible in the resultant_image.
How to check if a character is upper-case in Python?

To check if a character is upper-case, we can simply use isupper() function call on the said character. 
print( 'Z'.isupper())
print( 'u'.isupper())
True
False
We can also check it using range based if conditions. 
def check_upper(c):
    if c >= 'A' and c <= 'Z':
        return True
    else:
        return False
print check_upper('A')
print check_upper('a')
This will give us the output:
True
False
Difference between HashTable and ConcurrentHashMap in Java

Concurrent Hashmap is a class that was introduced in jdk1.5.  Concurrent hash map applies locks only at bucket level called fragment while adding or updating the map. So, a concurrent hash map allows concurrent read and write operations to the map. 
HashTable is a thread-safe legacy class introduced in the Jdk1.1. It is a base implementation of Map interface. It doesn't allow null keys and values. It is synchronized in nature so two different threads can’t access simultaneously. Hashtable does not maintain any order.
1
Basic 
 ConcurrentHashmap is a class that was introduced in jdk1.5
2
Locking
It applies lock on the entire collection 
ConcurrentHashMap apply locks only at bucket level called fragment  while adding or updating the map
3
Performance 
It is better than HashTable
4.
Null
It doesn't allow null key and value
It allows null key and value
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
public class HashtableExample {
   public static void main(String[] args) {
      // create Hashtable
      Hashtable map = new Hashtable();
      map.put("HCL", "100");
      map.put("DELL", "200");
      map.put("IBM", "300");
      // print the map
      for (Map.Entry m : map.entrySet()) {
         System.out.println(m.getKey() + " " + m.getValue());
      }
   }
}
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class ConcurrentHashMapExample {
   public static void main(String[] args) {
      // ConcurrentHashMap
      Map myMap = new ConcurrentHashMap();
      myMap.put("HCL", "1");
      myMap.put("DELL", "1");
      // print the map
      for (Map.Entry m : map.entrySet()) {
         System.out.println(m.getKey() + " " + m.getValue());
      }
   }
}
Get the List of Arguments of a Function in R Programming – args() Function

12 Jun, 2020
args() function in R Language is used to get the required arguments by a function. It takes function name as arguments and returns the arguments that are required by that function.
Syntax: args(name)
Parameters:name: Function name
Returns:
For a closure: Formal Argument list but with NULL body
For a Primitive Function: A closure with usage and a NULL body
For a non-function: NULL in case of not a function.
Example 1:
# R program to get arguments of a function  # Calling args() Functionargs(append)args(sin)args(paste)
Output:
function (x, values, after = length(x)) 
NULL
function (x) 
NULL
function (..., sep = " ", collapse = NULL) 
NULL

Example 2:
# R program to get arguments of a function  # Calling args() Functionargs(1)args(10)
Output:
NULL
NULL

The above code returns NULL because the names passed to args() function are not actual functions.
R-Functions
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Filter data by multiple conditions in R using Dplyr
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Loops in R (for, while, repeat)
Group by function in R using Dplyr
How to change Row Names of DataFrame in R ?
How to Change Axis Scales in R Plots?
How to filter R DataFrame by values in a column?
R - if statement
Remove rows with NA in one column of R DataFrame