code-rag-bench/online-tutorials huggingface dataset:
Filter Python list by Predicate in Python - GeeksforGeeks

19 Dec, 2021
In this article, we will discuss how to filter a python list by using predicate. Filter function is used to filter the elements in the given list of elements with the help of a predicate. A predicate is a function that always returns True or False by performing some condition operations in a filter method 
Syntax:
filter(predicate, list)
where,
list is an input list
predicate is the condition to be performed on the given list
Here lambda is used to evaluate an expression that acts as a predicate.
Syntax:
filter(lambda x: condition, list)
where
list is an input list
condition act as predicate
Example: Filter all even numbers and odd numbers  in a list
Python3
# create a list of 10 elementsdata = [10, 2, 3, 4, 56, 32, 56, 32, 21, 59]  # apply a filter that takes only even numbers with# lambda as predicatea = filter(lambda x: x % 2 == 0, data)  # displayfor i in a:    print(i)  print("------------")    # apply a filter that takes only odd  numbers with# lambda as predicatea = filter(lambda x: x % 2 != 0, data)  # displayfor i in a:    print(i)
Output:
10
2
4
56
32
56
32
------------
3
21
59
Here list comprehension act as a predicate.
Syntax:
[iterator for iterator  in list condition]
where,
list is the input list
iterator is used to iterate the input list of elements
condition act as predicate
Example: Python code to get odd and even numbers
Python3
# create a list of 10 elementsdata = [10, 2, 3, 4, 56, 32, 56, 32, 21, 59]  # filter data using comprehension# to get even numbersprint([x for x in data if x % 2 == 0])  # filter data using comprehension# to get odd numbersprint([x for x in data if x % 2 != 0])
Output:
[10, 2, 4, 56, 32, 56, 32]
[3, 21, 59]
Picked
python-list
Python
python-list
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 ?
How to drop one or multiple columns in Pandas Dataframe
Selecting rows in pandas DataFrame based on conditions
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
Merge two sorted linked lists using C++.

Given 2 sorted singly linked list. Write a function to merge given two sorted linked lists
List1: 10->15->17->20
List2: 5->9->13->19
Result: 5->9->10->13->15->17->19->20
1. Traverse both lists
   1.1. If list1->data < list2->data
      1.1.1 Add list1->data to new list and increment list1 pointer
   1.2 If list2->data < list1->data
      1.2.1 Add list2->data to new list and increment list2 pointer
2. Repeat procedure until both lists are exhausted
3. Return resultant list
#include <iostream>
#include <new>
#define SIZE(arr) (sizeof(arr) / sizeof(arr[0]))
using namespace std;
struct node {
   int data;
   struct node *next;
};
node *createList(int *arr, int n){
   node *head, *p;
   p = head = new node;
   head->data = arr[0];
   head->next = NULL;
   for (int i = 1; i < n; ++i) {
      p->next = new node;
      p = p->next;
      p->data = arr[i];
      p->next = NULL;
   }
return head;
}
void displayList(node *head){
   while (head != NULL) {
      cout << head->data << " ";
      head = head->next;
   }
   cout << endl;
}
node *mergeSortedLists(node *head1, node *head2){
   node *result = NULL;
   if (head1 == NULL) {
      return head2;
   }
   if (head2 == NULL) {
      return head1;
   }
   if (head1->data < head2->data) {
      result = head1;
      result->next = mergeSortedLists(head1->next, head2);
   } else {
      result = head2;
      result->next = mergeSortedLists(head1, head2->next);
   }
   return result;
}
int main(){
   int arr1[] = {10, 15, 17, 20};
   int arr2[] = {5, 9, 13, 19};
   node *head1, *head2, *result = NULL;
   head1 = createList(arr1, SIZE(arr1));
   head2 = createList(arr2, SIZE(arr1));
   cout << "First sorted list: " << endl;
   displayList(head1);
   cout << "Second sorted list: " << endl;
   displayList(head2);
   result = mergeSortedLists(head1, head2);
   cout << "Final sorted list: " << endl;
   displayList(result);
   return 0;
}
When you compile and execute the above program. It generates the following output −
First sorted list:
10 15 17 20
Second sorted list:
5 9 13 19
Final sorted list:
5 9 10 13 15 17 19 20
chvt command in Linux with examples - GeeksforGeeks

15 May, 2019
chvt command in Linux systems is used to switch between the different TTY (TeleTYpewriter) terminals available. These are essentially Virtual Terminals, which are toggled when the keys Ctrl + Alt + FunKey(1-6) are pressed. There are usually 6 TTY terminals, and the chvt command is used to switch between these terminals, without the use of function keys.
Note: This command needs Root Privilege to be executed.
Syntax:
chvt N
chvt with different N: This command takes an integer value for N, ranging from 1 to 6 (Since only 6 TTYs are present in the Linux OS). When an integer which is out of this range is specified, a blank screen pops up. To exit this screen, Alt + FunKey(7) needs to be pressed.
Note: The command fbcat which is used in the TTY terminals, serves to capture the screen of TTY terminals.
Example 1:
sudo chvt 1

Example 2:
sudo chvt 3

linux-command
Linux-misc-commands
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
Powershell - Start-Sleep Cmdlet

Start-Sleep cmdlet suspends the activity in a script or session for the particular period of time.
In these examples, we're see the Start-Sleep cmdlet in action.
In this example, we'll suspend the current process for 15 seconds.
Start-Sleep -s 15
You can see PowerShell console resumes after 15 seconds.
In this example, we'll suspend the current process for 500 milliseconds.
Start-Sleep -m 500

    15 Lectures 
     3.5 hours 

 Fabrice Chrzanowski

    35 Lectures 
     2.5 hours 

 Vijay Saini

    145 Lectures 
     12.5 hours 

 Fettah Ben
 Print
 Add Notes
 Bookmark this page
Convert DateTime Value into String in MySQL?

To convert the DateTime value into string in MySQL, you can use the DATE_FORMAT() function. The syntax is as follows −
select date_format(yourColumnName, ‘%d %m %y’) as anyVariableName from yourTableName;
To understand the above concept, let us create a table. The query to create a table is as follows −
mysql> create table DateAsStringDemo
   -> (
   -> YourDateTime datetime
   -> );
Query OK, 0 rows affected (0.57 sec)
Inserting the date with the help of curdate() method. The query to insert date is as follows −
mysql> insert into DateAsStringDemo values(curdate());
Query OK, 1 row affected (0.24 sec)
Let us display all records with the help of select statement. The query is as follows −
mysql> select *from DateAsStringDemo;
The following is the output −
+---------------------+
| YourDateTime        |
+---------------------+
| 2018-11-26 00:00:00 |
+---------------------+
1 row in set (0.00 sec)
The query to convert date to string is as follows −
mysql> select date_format(YourDateTime,'%d %m %y') as YourDateAsString from DateAsStringDemo;
The following is the output −
+------------------+
| YourDateAsString |
+------------------+
| 26 11 18         |
+------------------+
1 row in set (0.00 sec)
Python - First occurrence of one list in another - GeeksforGeeks

24 Feb, 2021
Given two lists, the task is to write a Python program to extract the first element that occurs in list 1 from list 2.
Examples:
Input : test_list1 = [1, 6, 3, 7, 8, 9, 2], test_list2 = [4, 10, 8, 2, 0, 11]
Output : 8
Explanation : 8 is first element from list 2, that occurs in list 1, in 5th index.
Input : test_list1 = [1, 6, 3, 7, 8, 9, 2], test_list2 = [4, 10, 18, 12, 0, 11]
Output : None
Explanation : No element of list 2 found in list 1.
Approach : Using set() + next()
In this, initially, the check container is converted to set, and each element is checked using next() and generator expression. The next() function returns the first element matching, else if no match element is found, None is returned.
Python3
# Python3 code to demonstrate working of# First occurrence of one list in another# Using next() + set()  # initializing liststest_list1 = [1, 6, 3, 7, 8, 9, 2]test_list2 = [4, 10, 8, 2, 0, 11]  # printing original listsprint("The original list 1 is : " + str(test_list1))print("The original list 2 is : " + str(test_list2))  # converting test list to setstest_list2 = set(test_list2)  # stops when 1st match element is foundres = next((ele for ele in test_list1 if ele in test_list2), None)  # printing resultprint("First element in list 1 from 2 : " + str(res))
Output:
The original list 1 is : [1, 6, 3, 7, 8, 9, 2]
The original list 2 is : [4, 10, 8, 2, 0, 11]
First element in list 1 from 2 : 8
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Selecting rows in pandas DataFrame based on conditions
Defaultdict in Python
Python | Split string into list of characters
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python program to check whether a number is Prime or not
Tk - Spinbox Widget

Spinbox widget allows users to choose numbers or arbitrary values.  The syntax for spinbox widget is shown below.
spinbox spinboxName options

The options available for the spinbox widget are listed below in table.
-background color
Used to set background color for widget.
-borderwidth width
Used to draw with border in 3D effects.
-font fontDescriptor
Used to set font for widget.
-foreground color
Used to set foreground color for widget.
-from number
Range start value for spinbox.
-increment number
Range increment value for spinbox.
-relief condition
Sets the 3D relief for this widget. The condition may be raised, sunken, flat, ridge, solid, or groove.
-textvariable varName
Variable associated with the widget. When the text of widget changes, the variable is set to text of widget.
-to number
Range end value for spinbox.
-values array
Arbitrary values for spinbox widget.
-width number
Sets the width for widget.
A simple example for spinbox widget is shown below −
#!/usr/bin/wish

set mylist [list C C++ Lua Tcl]
pack [spinbox .s1  -textvariable spinval1 -values $mylist -background yellow -borderwidth
   5 -font {Helvetica -18 bold} -foreground red -width 40  -relief ridge]
pack [spinbox .s2  -textvariable spinval2 -from 1.0 -to 100.0 -increment 5 -background
   yellow -borderwidth 5 -font {Helvetica -18 bold} -foreground red -width 40
   -relief ridge]
When we run the above program, we will get the following output −
 Print
 Add Notes
 Bookmark this page
Perl return Function

This function returns EXPR at the end of a subroutine, block, or do function. EXPR may be a scalar, array, or hash value; context will be selected at execution time. If no EXPR is given, returns an empty list in list context, undef in scalar context, or nothing in a void context.
Following is the simple syntax for this function −
return EXPR

return

This function returns in Scalar Context: List, which may be interpreted as scalar, list, or void context.
Following is the example code showing its basic usage −
#!/usr/bin/perl -w

$retval = Sum(5,10);
print ("Return value is $retval\n" );

@retval = Sum(5,10);
print ("Return value is @retval\n" );

sub Sum($$) {
   my($a, $b ) = @_; 

   my $c = $a + $b;
   
   return($a, $b, $c);
}
When above code is executed, it produces the following result −
Return value is 15
Return value is 5 10 15


    46 Lectures 
     4.5 hours 

 Devi Killada

    11 Lectures 
     1.5 hours 

 Harshit Srivastava

    30 Lectures 
     6 hours 

 TELCOMA Global

    24 Lectures 
     2 hours 

 Mohammad Nauman

    68 Lectures 
     7 hours 

 Stone River ELearning

    58 Lectures 
     6.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
Block-level Elements and Block Boxes in CSS

Block-level elements have their CSS display property set to either ‘block’, ‘list-item’, or ‘table’ and these elements force a line break above and below themselves. Block-level boxes are generated by each block-level element which is a part of the positioning scheme as well as contains child boxes.
Block container boxes contain either block-level boxes and follow block formatting context or contain inline-level boxes and follow inline formatting context. Block boxes is a term used if block-level boxes are also block containers.
Anonymous block boxes are those boxes over which developer has no control. If an inline box contains a block box and the inline content around the block box is enclosed in an anonymous block box.
Let’s see an example for Block-level Elements and Block Boxes −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<title>CSS Block-level Elements and Block Boxes</title>
<style>
form {
   width:70%;
   margin: 0 auto;
   text-align: center;
}
* {
   padding: 2px;
   box-sizing: border-box;
   /*margin:5px;*/
}
input[type="button"] {
   border-radius: 10px;
}
.child{
   height: 40px;
   width: 100%;
   color: white;
   border: 4px solid black;
}
.child:nth-of-type(1){
   background-color: #FF8A00;
}
.child:nth-of-type(2){
   background-color: #F44336;
}
.child:nth-of-type(3){
   background-color: #C303C3;
}
.child:nth-of-type(4){
   background-color: #4CAF50;
}
.child:nth-of-type(5){
   background-color: #03A9F4;
}
.child:nth-of-type(6){
   background-color: #FEDC11;
}
</style>
</head>
<body>
<form>
<fieldset>
<legend>CSS Block-level Elements and Block Boxes</legend>
<div id="container">Color Orange
<div class="child"></div>Color Red
<div class="child"></div>Color Violet
<div class="child"></div>
</div><br>
</body>
</html>
This will produce the following output −
How to get creation and modification date/time of a file using Python?

To get the creation time of a file, you can use the os.path.getctime(file_path) on windows. On UNIX systems, you cant use the same function as it returns the last time that the file's attributes or content were changed. To get the creation time on UNIX based systems, use the st_birthtime attribute of the stat tuple.
On Windows −
>>> import os
>>> print os.path.getctime('my_file')
1505928271.0689342
It gives the time in the number of seconds since the epoch. For UNIX systems,
import os
stat = os.stat(path_to_file)
try:
    print(stat.st_birthtime)
except AttributeError:
    # Probably on Linux. No easy way to get creation dates here,
    # so we'll settle for when its content was last modified.
    print(stat.st_mtime)
This will give the output −
1505928271.0689342
For getting the modification time for a file, you can use the os.path.getmtime(path). It is supported cross-platform.For example,
>>> import os
>>> print os.path.getmtime('my_file')
1505928275.3081832
What is the difference between ODBC and JDBC

Both ODBC and JDBC are the programming interface that is required by the applications at the client side to access the database at server side. Basically both are known as drivers to get connected with a database and are provided by the vendors of RDBMS.
The following are the important differences between ODBC and JDBC.
ODBC connection in c#
using System;
using System.Windows.Forms;
using System.Data.Odbc;
namespace WindowsApplication1{
   public partial class Form1 : Form{
      public Form1(){
         InitializeComponent();
      }
      private void button1_Click(object sender, EventArgs e){
         string connetionString = null;
         OdbcConnection cnn ;
         connetionString = "Driver={Microsoft Access Driver (*.mdb)};DBQ=yourdatabasename.mdb;";
         cnn = new OdbcConnection(connetionString);
         try{
            cnn.Open();
            MessageBox.Show ("Connection Open ! ");
            cnn.Close();
         }
         catch (Exception ex){
            MessageBox.Show("Can not open connection ! ");
         }
      }
   }
}
JDBC connection in java
import java.sql.*;
class JavaTester{
   public static void main(String args[]){
      try{
         Class.forName("com.mysql.jdbc.Driver");
         Connection con=DriverManager.getConnection(
         "jdbc:mysql://localhost:3306/'yourDBname'","username","userpassword");
         Statement stmt=con.createStatement();
         ResultSet rs=stmt.executeQuery("select * from emp");
         while(rs.next())
         System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
         con.close();
      }
      catch(Exception e){ System.out.println(e);}
   }
}
Circular Linked List Program in C

Circular Linked List is a variation of Linked list in which the first element points to the last element and the last element points to the first element. Both Singly Linked List and Doubly Linked List can be made into a circular linked list.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>

struct node {
   int data;
   int key;
	
   struct node *next;
};

struct node *head = NULL;
struct node *current = NULL;

bool isEmpty() {
   return head == NULL;
}

int length() {
   int length = 0;

   //if list is empty
   if(head == NULL) {
      return 0;
   }

   current = head->next;

   while(current != head) {
      length++;
      current = current->next;   
   }
	
   return length;
}

//insert link at the first location
void insertFirst(int key, int data) {

   //create a link
   struct node *link = (struct node*) malloc(sizeof(struct node));
   link->key = key;
   link->data = data;
	
   if (isEmpty()) {
      head = link;
      head->next = head;
   } else {
      //point it to old first node
      link->next = head;
		
      //point first to new first node
      head = link;
   }    
}

//delete first item
struct node * deleteFirst() {

   //save reference to first link
   struct node *tempLink = head;
	
   if(head->next == head) {  
      head = NULL;
      return tempLink;
   }     

   //mark next to first link as first 
   head = head->next;
	
   //return the deleted link
   return tempLink;
}

//display the list
void printList() {

   struct node *ptr = head;
   printf("\n[ ");
	
   //start from the beginning
   if(head != NULL) {
	
      while(ptr->next != ptr) {     
         printf("(%d,%d) ",ptr->key,ptr->data);
         ptr = ptr->next;
      }
   }
	
   printf(" ]");
}

void main() {
   insertFirst(1,10);
   insertFirst(2,20);
   insertFirst(3,30);
   insertFirst(4,1);
   insertFirst(5,40);
   insertFirst(6,56); 

   printf("Original List: "); 
	
   //print list
   printList();

   while(!isEmpty()) {            
      struct node *temp = deleteFirst();
      printf("\nDeleted value:");  
      printf("(%d,%d) ",temp->key,temp->data);
   }   
	
   printf("\nList after deleting all items: ");
   printList();   
}
If we compile and run the above program, it will produce the following result −
Original List: 
[ (6,56) (5,40) (4,1) (3,30) (2,20) ]
Deleted value:(6,56) 
Deleted value:(5,40) 
Deleted value:(4,1) 
Deleted value:(3,30) 
Deleted value:(2,20) 
Deleted value:(1,10) 
List after deleting all items: 
[ ]


    42 Lectures 
     1.5 hours 

 Ravi Kiran

    141 Lectures 
     13 hours 

 Arnab Chakraborty

    26 Lectures 
     8.5 hours 

 Parth Panjabi

    65 Lectures 
     6 hours 

 Arnab Chakraborty

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    64 Lectures 
     10.5 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page
Back-off Algorithm for CSMA/CD

Back Off Algorithm is an algorithm used for collision resolution. It works as,
When this collision occurs, both the devices wait for a random amount of time before retransmitting the signal again, they keep on trying until the data is transferred successfully. This is called back off, since the nodes ‘back-off’ for a certain amount of time, before they try to re-access it again. This random amount of time is directly proportional to the number of attempts it has made to transmit the signal.
Below is a simple flowchart to explain the Back Off Algorithm in brief.
As can be seen, that after each iteration value of N increases and so does the range [0,2^n-1], this way the probability of collisions decreases!
Moreover, it can be a drawback in some cases because continuous back-off can cause some nodes to discard packets. After all, maximum attempt limits have been reached.
So, after the collision, each node has to wait for a certain amount of time which is given by the formula,
Waiting time = K * Tslot
Tslot is the discrete-time slot of length equal to 2t, where t is the maximum propagation delay in the network.
K = [0, 2n -1]. n is the collision number.
How to get time difference between two timestamps in seconds?

To get the time difference between two timestamps, try to run the following code. Here, we are calculating the total number of hours, minutes and seconds between two timestamps −
Live Demo
<html>
   <head>
      <title>JavaScript Dates</title>
   </head>
   <body>
      <script>  
         var date1, date2;  

         date1 = new Date( "Jan 1, 2018 11:10:05" );
         document.write(""+date1);

         date2 = new Date( "Jan 1, 2018 08:15:10" );
         document.write("<br>"+date2);

         var res = Math.abs(date1 - date2) / 1000;
         
         // get total days between two dates
         var days = Math.floor(res / 86400);
         document.write("<br>Difference (Days): "+days);                        
         
         // get hours        
         var hours = Math.floor(res / 3600) % 24;        
         document.write("<br>Difference (Hours): "+hours);  
         
         // get minutes
         var minutes = Math.floor(res / 60) % 60;
         document.write("<br>Difference (Minutes): "+minutes);  
     
         // get seconds
         var seconds = res % 60;
         document.write("<br>Difference (Seconds): "+seconds);  
      </script>
   </body>
</html>
Mon Jan 01 2018 11:10:05 GMT+0530 (India Standard Time)
Mon Jan 01 2018 08:15:10 GMT+0530 (India Standard Time)
Difference (Days): 0
Difference (Hours): 2
Difference (Minutes): 54
Difference (Seconds): 55
How to combine multiple columns into one in R data frame without using column names?

To combine multiple columns into one in R data frame without using column names, we
can follow the below steps −
First of all, create a data frame.
Then, convert the data frame into a single column data frame.
Again, convert the data frame into a single column without column names
displayed in rows using row.names function.
Let's create a data frame as shown below −
 Live Demo
x<-sample(1:50,5)
y<-sample(1:50,5)
z<-sample(1:50,5)
a<-sample(1:50,5)
b<-sample(1:50,5)
c<-sample(1:50,5)
df<-data.frame(x,y,z,a,b,c)
df
On executing, the above script generates the below output(this output will vary on your system due to randomization) −
  x  y z  a  b  c
1 48 6 8 48 49 22
2 7 34 48 28 17 17
3 25 40 1 22 12 29
4 38 21 27 33 8 5
5 5 20 7 50 46 32
Using unlist function to convert df into a single data frame −
 Live Demo
x<-sample(1:50,5)
y<-sample(1:50,5)
z<-sample(1:50,5)
a<-sample(1:50,5)
b<-sample(1:50,5)
c<-sample(1:50,5)
df<-data.frame(x,y,z,a,b,c)
data.frame(unlist(df))
unlist.df.
x1 48
x2 7
x3 25
x4 38
x5 5
y1 6
y2 34
y3 40
y4 21
y5 20
z1 8
z2 48
z3 1
z4 27
z5 7
a1 48
a2 28
a3 22
a4 33
a5 50
b1 49
b2 17
b3 12
b4 8
b5 46
c1 22
c2 17
c3 29
c4 5
c5 32
Using unlist function to convert df into a single data frame without row numbers
represented by column names −
 Live Demo
x<-sample(1:50,5)
y<-sample(1:50,5)
z<-sample(1:50,5)
a<-sample(1:50,5)
b<-sample(1:50,5)
c<-sample(1:50,5)
df<-data.frame(x,y,z,a,b,c)
data.frame(One=unlist(df,use.names=FALSE))
 One
1 48
2 7
3 25
4 38
5 5
6 6
7 34
8 40
9 21
10 20
11 8
12 48
13 1
14 27
15 7
16 48
17 28
18 22
19 33
20 50
21 49
22 17
23 12
24 8
25 46
26 22
27 17
28 29
29 5
30 32
How to check if two data frames same or not in R?

Two data frames can be same if the column names, row names and all the values in the data frame are exactly same. We might to check this for data frames that we expect to be same, for example, if we have two data sets each one of have same number of rows, same number of columns, same data type for each of the columns, and the data view shows that values are same then it is worth checking whether the complete data sets are same or not. To do this checking in R, we can use identical function.
 Live Demo
df1<-data.frame(x1=rnorm(20),x2=letters[1:20])
df1
     x1 x2
1 -0.09240552 a
2 -0.86521420 b
3 -0.69926988 c
4 1.24016055 d
5 2.75433272 e
6 0.49542119 f
7 2.10237466 g
8 0.41385580 h
9 0.82198425 i
10 0.41587660 j
11 3.32618703 k
12 -0.56282543 l
13 -0.39042007 m
14 0.78080197 n
15 0.23957177 o
16 -1.92511201 p
17 0.57842631 q
18 -0.82922740 r
19 2.04836392 s
20 0.24616976 t
 Live Demo
df2<-data.frame(y1=rnorm(20),y2=letters[1:20])
df2
   y1    y2
1 0.02352228 a
2 -0.73437399 b
3 -0.64123651 c
4 0.09660536 d
5 -0.52194846 e
6 0.95606767 f
7 -0.37678881 g
8 0.26724937 h
9 -1.13132950 i
10 0.31408454 j
11 0.64873521 k
12 0.33610366 l
13 -1.82775097 m
14 -0.18508915 n
15 0.59403868 o
16 0.21510182 p
17 0.81497239 q
18 0.71799874 r
19 0.22732659 s
20 0.46474950 t
identical(df1,df2)
[1] FALSE
 Live Demo
df1<-data.frame(x1=rnorm(20),x2=letters[1:20])
df1
   x1    x2
1 0.34718972 a
2 -0.26756669 b
3 0.52007492 c
4 0.06377162 d
5 -0.11679032 e
6 -0.23173790 f
7 -0.53550405 g
8 1.07821494 h
9 -0.02160426 i
10 -0.12502472 j
11 0.27371128 k
12 -0.28931486 l
13 -0.36478099 m
14 0.79732361 n
15 1.24983019 o
16 1.15472390 p
17 0.30553105 q
18 -0.20471787 r
19 -2.28367371 s
20 1.30177853 t
df2<-data.frame(x1=rnorm(20),x2=letters[1:20])
identical(df1,df2)
[1] FALSE
df3<-data.frame(x1=LETTERS[1:20],x2=1:20)
df3
x1 x2
1 A 1
2 B 2
3 C 3
4 D 4
5 E 5
6 F 6
7 G 7
8 H 8
9 I 9
10 J 10
11 K 11
12 L 12
13 M 13
14 N 14
15 O 15
16 P 16
17 Q 17
18 R 18
19 S 19
20 T 20
df4<-data.frame(y1=LETTERS[1:20],y2=1:20)
identical(df3,df4)
[1] FALSE
df5<-data.frame(x1=LETTERS[1:20],x2=1:20)
identical(df3,df5)
[1] TRUE
String getBytes(String charsetName)

This method encodes this String into a sequence of bytes using the named charset, storing the result into a new byte array.
Here is the syntax of this method −
public byte[] getBytes(String charsetName) throws UnsupportedEncodingException

Here is the detail of parameters −
charsetName − the name of a supported charset.
charsetName − the name of a supported charset.
This method returns the resultant byte array.
import java.io.*;
public class Test {

   public static void main(String args[]) {
      String Str1 = new String("Welcome to Tutorialspoint.com");
      try {
         String Str2 = new String(Str1.getBytes( "UTF-8" ));
         System.out.println("Returned Value " + Str2 );
         Str2 = new String (Str1.getBytes( "ISO-8859-1" ));
         System.out.println("Returned Value " + Str2 );
      } catch ( UnsupportedEncodingException e) {
         System.out.println("Unsupported character set");
      }
   }
}
This will produce the following result −
Returned Value Welcome to Tutorialspoint.com
Returned Value Welcome to Tutorialspoint.com


    16 Lectures 
     2 hours 

 Malhar Lathkar

    19 Lectures 
     5 hours 

 Malhar Lathkar

    25 Lectures 
     2.5 hours 

 Anadi Sharma

    126 Lectures 
     7 hours 

  Tushar Kale

    119 Lectures 
     17.5 hours 

 Monica Mittal

    76 Lectures 
     7 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
Ruby on Rails - Session and Cookies

To save data across multiple requests, you can use either the session or the flash hashes. A flash stores a value (normally text) until the next request, while a session stores data during the complete session.
session[:user] = @user
flash[:message] = "Data was saved successfully"

<%= link_to "login", :action => 'login' unless session[:user] %>
<% if flash[:message] %>
<div><%= h flash[:message] %></div>
<% end %>
It's possible to turn off session management −
session :off                           # turn session management off
session :off, :only => :action      # only for this :action
session :off, :except => :action    # except for this action

session :only => :foo,              # only for :foo when doing HTTPS
        :session_secure => true 

session :off, :only=>:foo, # off for foo,if uses as Web Service
        :if => Proc.new { |req| req.parameters[:ws] }
Check out link for more detail on Session Management
Following is the syntax for setting cookies −
# Set a simple session cookie
cookies[:user_name] = "david" 

# Set a cookie that expires in 1 hour
cookies[:login] = { :value => "XJ12", :expires => Time.now + 3600}
Following is the syntax for reading cookies −
cookies[:user_name]  # => "david"
cookies.size         # => 2 
Following is the syntax for deleting cookies −
cookies.delete :user_name

All the option symbols for setting cookies are −
value − The cookie.s value or list of values (as an array).
value − The cookie.s value or list of values (as an array).
path − The path for which this cookie applies. Defaults to the root of the application.
path − The path for which this cookie applies. Defaults to the root of the application.
domain − The domain for which this cookie applies.
domain − The domain for which this cookie applies.
expires − The time at which this cookie expires, as a +Time+ object.
expires − The time at which this cookie expires, as a +Time+ object.
secure − Whether this cookie is a secure cookie or not (default to false). Secure cookies are only transmitted to HTTPS servers.
secure − Whether this cookie is a secure cookie or not (default to false). Secure cookies are only transmitted to HTTPS servers.
Check out the link on Cookies Management, for more detail.
 Print
 Add Notes
 Bookmark this page
How to add Matplotlib graph in Kivy ? - GeeksforGeeks

05 Apr, 2021

In this article, we will discuss how to add matplotlib graph in the kivy app.
Import matplotlib pyplot
Import numpy
Import FigureCanvas KivyAgg
Import kivy app
Import kivy builder
Create App class
Return builder string
Run an instance of the class
Below is the Implementation.
Python3
 

 
 










# importing pyplot for graph plotting 
from matplotlib import pyplot as plt 
  
# importing numpy 
import numpy as np 
from kivy.garden.matplotlib import FigureCanvasKivyAgg 
  
# importing kivyapp 
from kivy.app import App 
  
# importing kivy builder 
from kivy.lang import Builder 
  
  
# this is the main class which will  
# render the whole application 
class uiApp(App): 
  
    def build(self): 
        self.str = Builder.load_string("""  
  
BoxLayout: 
    layout:layout 
      
    BoxLayout: 
      
        id:layout 
      
                                """) 
  
        signal = [7, 89.6, 45.-56.34] 
  
        signal = np.array(signal) 
          
        # this will plot the signal on graph 
        plt.plot(signal) 
          
        # setting x label 
        plt.xlabel('Time(s)') 
          
        # setting y label 
        plt.ylabel('signal (norm)') 
        plt.grid(True, color='lightgray') 
          
        # adding plot to kivy boxlayout 
        self.str.layout.add_widget(FigureCanvasKivyAgg(plt.gcf())) 
        return self.str
  
  
# running the application 
uiApp().run() 






Output:
Note: When you run the below code this may throw the error given below
What you have to do is open the file given in the white box by clicking on file while holding ctrl key and comment line underlined by green color in that file and hit save now you will be able to run it!!

Python-kivy


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?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
GATE CS 2021 | Set 1 - GeeksforGeeks

17 Sep, 2021
(i) Everybody in the class is prepared for the exam.
(ii) Babu invited Danish to his home because he enjoys playing chess.
Pillar in Y-axis is longer than pillar in X-axis
Pillar in Y is horizontal and pillar in Y is vertical
Profit% = ((Selling price – Cost)/Cost)×100 
Statement 1: All bacteria are microorganisms.
Statement 2: All pathogens are microorganisms.
Conclusion I: Some pathogens are bacteria.
Conclusion II: All pathogens are not bacteria.
Case-1 is counter example of Conclusion II, because of all pathogens are bacteria in this diagram.
Conclusion I would be true in this case, because all so also some.
(So, Conclusion I is true and II is false.).
Case-2 is counter example of Conclusion I, because no pathogens are bacteria.
Conclusion II would be true in this case, because all so also some.
(So, Conclusion II is false and II is true.).
Case-3: Conclusion I is true, and Conclusion II is false as some pathogens are *already* bacteria.
Case-4: Conclusion I is true, and Conclusion II is false as some pathogens are *already* bacteria.
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Must Do Coding Questions for Product Based Companies
Find size of largest subset with bitwise AND greater than their bitwise XOR
How to Replace Values in Column Based on Condition in Pandas?
C Program to read contents of Whole File
Insert Image in a Jupyter Notebook
How to Replace Values in a List in Python?
How to Read Text Files with Pandas?
How to Compare Two Columns in Pandas?
Python Data Structures and Algorithms
Data Science With Python Tutorial
random.normalvariate() function in Python - GeeksforGeeks

26 May, 2020
random module is used to generate random numbers in Python. Not actually random, rather this is used to generate pseudo-random numbers. That implies that these randomly generated numbers can be determined.
normalvariate() is an inbuilt method of the random module. It is used to return a random floating point number with normal distribution.
Syntax : random.normalvariate(mu, sigma)
Parameters :mu : meansigma : standard deviation
Returns : a random normal distribution floating number
Example 1:
# import the random moduleimport random  # determining the values of the parametersmu = 100sigma = 50  # using the normalvariate() methodprint(random.normalvariate(mu, sigma))
Output :
110.86699628241412
Example 2: We can generate the number multiple times and plot a graph to observe the normal distribution.
# import the required libraries import random import matplotlib.pyplot as plt     # store the random numbers in a  # list nums = [] mu = 100sigma = 50    for i in range(100):     temp = random.normalvariate(mu, sigma)    nums.append(temp)         # plotting a graph plt.plot(nums) plt.show()
Output :
Example 3: We can create a histogram to observe the density of the normal distribution.
# import the required libraries import random import matplotlib.pyplot as plt     # store the random numbers in a list nums = [] mu = 100sigma = 50    for i in range(10000):     temp = random.normalvariate(mu, sigma)     nums.append(temp)         # plotting a graph plt.hist(nums, bins = 200) plt.show()
Output :
Python-random
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
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 Dictionary
Taking input in Python
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
C Program for Naive algorithm for Pattern Searching - GeeksforGeeks

11 Dec, 2018
Given a text txt[0..n-1] and a pattern pat[0..m-1], write a function search(char pat[], char txt[]) that prints all occurrences of pat[] in txt[]. You may assume that n > m.
Examples:
Input:  txt[] = "THIS IS A TEST TEXT"
        pat[] = "TEST"
Output: Pattern found at index 10

Input:  txt[] =  "AABAACAADAABAABA"
        pat[] =  "AABA"
Output: Pattern found at index 0
        Pattern found at index 9
        Pattern found at index 12


Pattern searching is an important problem in computer science. When we do search for a string in notepad/word file or browser or database, pattern searching algorithms are used to show the search results.
C
// C program for Naive Pattern Searching algorithm#include <stdio.h>#include <string.h>  void search(char* pat, char* txt){    int M = strlen(pat);    int N = strlen(txt);      /* A loop to slide pat[] one by one */    for (int i = 0; i <= N - M; i++) {        int j;          /* For current index i, check for pattern match */        for (j = 0; j < M; j++)            if (txt[i + j] != pat[j])                break;          if (j == M) // if pat[0...M-1] = txt[i, i+1, ...i+M-1]            printf("Pattern found at index %d \n", i);    }}  /* Driver program to test above function */int main(){    char txt[] = "AABAACAADAABAAABAA";    char pat[] = "AABA";    search(pat, txt);    return 0;}
Pattern found at index 0 
Pattern found at index 9 
Pattern found at index 13

Please refer complete article on Naive algorithm for Pattern Searching for more details!
C Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C Program to read contents of Whole File
Header files in C/C++ and its uses
Program to print ASCII Value of a character
How to return multiple values from a function in C or C++?
How to Append a Character to a String in C
C program to sort an array in ascending order
time() function in C
C Program to Swap two Numbers
Producer Consumer Problem in C
Program to find Prime Numbers Between given Interval
R - Check if a Directory Exists and Create if It does not - GeeksforGeeks

30 Apr, 2021
Directories and sub-directories are accessed by their corresponding paths in R Programming Language. It is easy to work with these in R and perform operations related to the creation, copy, and movement of folders and sub-folders within the system. In this article, we will see how to check if a directory exists and how to create a new directory if it does not exist using R Programming Language.
Directory in use:
The path corresponding to the main directory can be first stored in the working space. We can check if this directory exists, using the file.exists() method. This method returns a logical vector depicting whether the files specified by its argument exist in the space or not. If the file exists, it returns TRUE, otherwise FALSE is returned. 
Syntax: dir.exists(paths)
Parameter:
path – a character vector containing a single path name.
Example:
R
sub_dir<-"test1"  file.exists(sub_dir)
Output:
TRUE
If the file exists the working directory is set to the path formed by the concatenation of the main and subdirectories respectively. Otherwise, the directory is created using the dir.create() method.  This method returns a logical vector describing if the creation of the file succeeded for each of the files for which it was attempted. dir.create indicates failure if the directory already exists.
Syntax: dir.create(path, showWarnings = TRUE, recursive = FALSE, mode = “0777”)
Parameter : 
path – a character vector containing a single path name.
showWarnings – logical; should the warnings on failure be shown?
mode – the mode to be used on Unix-alikes.
Example:
R
# setting up the main directorymain_dir <- "C:\\Users\\Vanshi\\Desktop\\gfg\\test"  # setting up the sub directorysub_dir <- "abc"  # check if sub directory exists if (file.exists(sub_dir)){                  # specifying the working directory        setwd(file.path(main_dir, sub_dir))} else {                  # create a new sub directory inside        # the main path        dir.create(file.path(main_dir, sub_dir))                  # specifying the working directory        setwd(file.path(main_dir, sub_dir))}
Output:
Picked
R-FileHandling
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Replace specific values in column in R DataFrame ?
Filter data by multiple conditions in R using Dplyr
Loops in R (for, while, repeat)
How to change Row Names of DataFrame in R ?
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?
K-Means Clustering in R Programming
Creating a Data Frame from Vectors in R Programming
Matplotlib.axes.Axes.get_xscale() in Python - GeeksforGeeks

19 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.
The Axes.get_xscale() function in axes module of matplotlib library is used to return the x-axis scale as string.
Syntax: Axes.get_xscale(self)
Parameters: This method does not accepts any parameters.
Return: This function return the x-axis scale as a string.
Below examples illustrate the matplotlib.axes.Axes.set_yscale() function in matplotlib.axes:
Example 1:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np      fig, ax = plt.subplots()   ax.plot([1, 2, 3])   w = ax.get_xscale()   ax.set_title("xscale property : "+ str(w),              fontweight ="bold")fig.suptitle('matplotlib.axes.Axes.get_xscale()\ function Example\n', fontweight ="bold")  fig.canvas.draw()plt.show()
Output:
Example 2:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as npfrom matplotlib.ticker import EngFormatter   val = np.random.RandomState(19680801)xs = np.logspace(1, 9, 100)ys = (0.8 + 4 * val.uniform(size = 100)) * np.log10(xs)**2   fig, ax0 = plt.subplots()ax0.set_xscale('log')formatter0 = EngFormatter(unit ='Hz')ax0.xaxis.set_major_formatter(formatter0)ax0.plot(xs, ys)ax0.set_xlabel('Frequency')  w = ax0.get_xscale()   ax0.set_title("xscale property : "+ str(w),              fontweight ="bold")fig.suptitle('matplotlib.axes.Axes.get_xscale()\ function Example\n', fontweight ="bold")  fig.canvas.draw()plt.show()
Output:
Python-matplotlib
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?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
Python – Sympy Polygon.intersection() Method

01 Aug, 2020
In Sympy, the function Polygon.intersection() is used to get the intersection of a given polygon and the given geometry entity. The geometry entity can be a point, line, polygon, or other geometric figures. The intersection may be empty if the polygon and the given geometry entity are not intersected anywhere. But can contain individual Points or complete Line Segments if intersection exists.
Syntax: Polygon.intersection(o)

Parameters: Geometry Entity

Returns: The list of Segments or Points of intersection.

Example #1:
Python3
# import Point, Polygonfrom sympy import Point, Polygon  # creating points using Point()p1, p2, p3, p4 = map(Point, [(0, 0), (1, 0), (5, 1), (0, 1)])p5, p6, p7 = map(Point, [(3, 2), (1, -1), (0, 2)])  # creating polygons using Polygon()poly1 = Polygon(p1, p2, p3, p4)poly2 = Polygon(p5, p6, p7)  # using intersection()isIntersection = poly1.intersection(poly2)  print(isIntersection)
Output:
[Point2D(1/3, 1), Point2D(2/3, 0), Point2D(9/5, 1/5), Point2D(7/3, 1)]
Example #2:
Python3
# import Point, Polygonfrom sympy import Point, Polygon  # creating points using Point()p1, p2, p3, p4 = map(Point, [(0, 0), (1, 0), (5, 1), (0, 1)])  # creating polygon using Polygon()poly1 = Polygon(p1, p2, p3, p4)  # using intersection()isIntersection = poly1.intersection(Line(p1, Point(3, 2)))                                      print(isIntersection)
Output:
[Point2D(0, 0), Point2D(3/2, 1)]
Python SymPy-Geometry
SymPy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to reload the current page without losing any form data with HTML?

The easiest way to reload the current page without losing form data, use WebStorage where you have -persistent storage (localStorage) or session-based (sessionStorage) which remains in memory until your web browser is closed.
Try this when the page is about to reload,
window.onbeforeunload = function() {
   localStorage.setItem(name, $('#inputName').val());
   localStorage.setItem(phone, $('#inputPhone').val());
   localStorage.setItem(subject, $('#inputAddress').val());
}
Now check it like −
window.onload = function() {
   var name = localStorage.getItem(name);
   var phone = localStorage.getItem(phone);
   if (name !== null) $('#inputName').val(name); if (phone !== null) $('#inputPhone').val(phone);
   // ...
}
Python | Pandas Timestamp.to_julian_date

27 Jan, 2019
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas Timestamp.to_julian_date() function convert the given TimeStamp to a Julian Date. The value for 0 Julian date is noon January 1, 4713 BC.
Syntax :Timestamp.to_julian_date()
Parameters : None
Return : julian date
Example #1: Use Timestamp.to_julian_date() function to convert the given Timestamp to julian date.
# importing pandas as pdimport pandas as pd  # Create the Timestamp objectts = pd.Timestamp(year = 2011,  month = 11, day = 21,                   hour = 10, second = 49, tz = 'US/Central')   # Print the Timestamp objectprint(ts)
Output :
Now we will use the Timestamp.to_julian_date() function to convert the given Timestamp to julian date.
# convert to julian datets.to_julian_date()
Output :
As we can see in the output, the Timestamp.to_julian_date() function has converted the given Timestamp into the julian date. Example #2: Use Timestamp.to_julian_date() function to convert the given Timestamp to julian date.
# importing pandas as pdimport pandas as pd  # Create the Timestamp objectts = pd.Timestamp(year = 2009, month = 5, day = 31,                   hour = 4, second = 49, tz = 'Europe/Berlin')  # Print the Timestamp objectprint(ts)
Output :
Now we will use the Timestamp.to_julian_date() function to convert the given Timestamp to julian date.
# convert to julian datets.to_julian_date()
Output :
As we can see in the output, the Timestamp.to_julian_date() function has converted the given Timestamp into the julian date.
Python Pandas-Timestamp
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
Introduction To PYTHON
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list