code-rag-bench/online-tutorials huggingface dataset:
Python program to add two numbers

04 Jun, 2022
Given two numbers num1 and num2. The task is to write a Python program to find the addition of these two numbers. Examples:
Input: num1 = 5, num2 = 3
Output: 8

Input: num1 = 13, num2 = 6
Output: 19
In the below program to add two numbers, the user is first asked to enter two numbers and the input is scanned using the input() function and stored in the variables number1 and number2. Then, the variables number1 and number2 are added using the arithmetic operator + and the result is stored in the variable sum. Below is the Python program to add two numbers: 
Example 1: 
Python3
# Python3 program to add two numbers num1 = 15num2 = 12 # Adding two nossum = num1 + num2 # printing valuesprint("Sum of {0} and {1} is {2}" .format(num1, num2, sum))
Output:
Sum of 15 and 12 is 27
Example 2: Adding two number provided by user input 
Python3
# Python3 program to add two numbers number1 = input("First number: ")number2 = input("\nSecond number: ") # Adding two numbers# User might also enter float numberssum = float(number1) + float(number2) # Display the sum# will print value in floatprint("The sum of {0} and {1} is {2}" .format(number1, number2, sum))
Output:
First number: 13.5 Second number: 1.54
The sum of 13.5 and 1.54 is 15.04
Example 3:
Python3
# Python3 program to add two numbers # Driver Codeif __name__ == "__main__" :     num1 = 15  num2 = 12     # Adding two numbers  sum_twoNum = lambda num1, num2 : num1 + num2     # printing values  print("Sum of {0} and {1} is {2};" .format(num1, num2, sum_twoNum(num1, num2)))
Output:
Sum of 15 and 12 is 27;
ankthon
Python
Python Programs
School Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Difference between Private and Public IP addresses

07 Jun, 2022
Private IP address of a system is the IP address that is used to communicate within the same network. Using private IP data or information can be sent or received within the same network. 
Public IP address of a system is the IP address that is used to communicate outside the network. A public IP address is basically assigned by the ISP (Internet Service Provider). 
Range:
10.0.0.0 – 10.255.255.255, 
172.16.0.0 – 172.31.255.255, 
192.168.0.0 – 192.168.255.255 
guptavivek0503
IP Addressing
Computer Networks
Difference Between
GATE CS
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Differences between TCP and UDP
Types of Network Topology
TCP Server-Client implementation in C
Socket Programming in Python
GSM in Wireless Communication
Class method vs Static method in Python
Difference between BFS and DFS
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Differences between JDK, JRE and JVM
How to use Boto3 library in Python to upload an object in S3 using AWS Resource?

Problem Statement − Use Boto3 library in Python to upload an object into S3. For example, how to upload test.zip into Bucket_1 of S3.
Step 1 − Import boto3 and botocore exceptions to handle exceptions.
Step 2 − From pathlib, import PurePosixPath to retrive filename from path
Step 3 − s3_path and filepath are the two parameters in function upload_object_into_s3
Step 4 − Validate the s3_path is passed in AWS format as s3://bucket_name/key and filepath as local path C://users/filename
Step 5 − Create an AWS session using boto3 library.
Step 6 − Create an AWS resource for S3.
Step 7 − Split the S3 path and perform operations to separate the root bucket name and key path
Step 8 − Get the file name for complete filepath and add into S3 key path.
Step 9 − Now use the function upload_fileobj to upload the local file into S3.
Step 10 − Use the function wait_until_exists to wait until operation is finished.
Step 11 − Handle the exception based on response code to validate whether file is uploaded or not.
Step 12 − Handle the generic exception if something went wrong while uploading the file
Use the following code to upload a file into AWS S3 −
import boto3
from botocore.exceptions import ClientError
from pathlib import PurePosixPath

def upload_object_into_s3(s3_path, filepath):

   if 's3://' in filepath:
      print('SourcePath is not a valid path.' + filepath)
      raise Exception('SourcePath is not a valid path.')
   elif s3_path.find('s3://') == -1:
      print('DestinationPath is not a s3 path.' + s3_path)
      raise Exception('DestinationPath is not a valid path.')
   session = boto3.session.Session()
   s3_resource = session.resource('s3')
   tokens = s3_path.split('/')
   target_key = ""
   if len(tokens) > 3:
      for tokn in range(3, len(tokens)):
         if tokn == 3:
            target_key += tokens[tokn]
         else:
            target_key += "/" + tokens[tokn]
   target_bucket_name = tokens[2]

   file_name = PurePosixPath(filepath).name
   if target_key != '':
      target_key.strip()
      key_path = target_key + "/" + file_name
   else:
      key_path = file_name
   print(("key_path: " + key_path, 'target_bucket: ' + target_bucket_name))

   try:
      # uploading Entity from local path
      with open(filepath, "rb") as file:
      s3_resource.meta.client.upload_fileobj(file, target_bucket_name, key_path)
      try:
         s3_resource.Object(target_bucket_name, key_path).wait_until_exists()
         file.close()
      except ClientError as error:
         error_code = int(error.response['Error']['Code'])
         if error_code == 412 or error_code == 304:
            print("Object didn't Upload Successfully ", target_bucket_name)
            raise error
      return "Object Uploaded Successfully"
   except Exception as error:
      print("Error in upload object function of s3 helper: " + error.__str__())
      raise error
print(upload_object_into_s3('s3://Bucket_1/testfolder', 'c://test.zip'))
key_path:/testfolder/test.zip, target_bucket: Bucket_1
Object Uploaded Successfully
Boolean.TryParse() Method in C#

The Boolean.TryParse() method in C# is used to convert the specified string representation of a logical value to its Boolean equivalent.
Following is the syntax −
public static bool TryParse (string val out bool result);
Let us now see an example to implement the Boolean.TryParse() method −
using System;
public class Demo {
   public static void Main(){
      bool val;
      bool flag;
      val = Boolean.TryParse("true", out flag);
      Console.WriteLine("Result = "+val);
   }
}
This will produce the following output −
Result = True
Let us now see another example to implement the Boolean.TryParse() method −
using System;
public class Demo {
   public static void Main(){
      bool val;
      bool flag;
      val = Boolean.TryParse("$", out flag);
      Console.WriteLine("Result = "+val);
   }
}
This will produce the following output −
Result = False
openat() - 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
#include <fcntl.h> 

int openat(int dirfd, const char *pathname, int flags); 
int openat(int dirfd, const char *pathname, int flags 
", mode_t " mode );


int openat(int dirfd, const char *pathname, int flags); 
int openat(int dirfd, const char *pathname, int flags 
", mode_t " mode );


If the pathname given in
pathname is relative, then it is interpreted relative to the directory
referred to by the file descriptor
dirfd (rather than relative to the current working directory of
the calling process, as is done by
open(2)
for a relative pathname).


If the pathname given in
pathname is relative and
dirfd is the special value
AT_FDCWD, then
pathname is interpreted relative to the current working
directory of the calling process (like
open(2)).


If the pathname given in
pathname is absolute, then
dirfd is ignored.


First,
openat() allows an application to avoid race conditions that could
occur when using
open(2)
to open files in directories other than the current working directory.
These race conditions result from the fact that some component
of the directory prefix given to
open() could be changed in parallel with the call to
open(). Such races can be avoided by
opening a file descriptor for the target directory,
and then specifying that file descriptor as the
dirfd argument of
openat(). 

Second,
openat() allows the implementation of a per-thread "current working
directory", via file descriptor(s) maintained by the application.
(This functionality can also be obtained by tricks based
on the use of
/proc/self/fd/dirfd, but less efficiently.)

faccessat (2)
faccessat (2)
fchmodat (2)
fchmodat (2)
fchownat (2)
fchownat (2)
fstatat (2)
fstatat (2)
futimesat (2)
futimesat (2)
linkat (2)
linkat (2)
mkdirat (2)
mkdirat (2)
mknodat (2)
mknodat (2)
open (2)
open (2)
path_resolution (2)
path_resolution (2)
readlinkat (2)
readlinkat (2)
renameat (2)
renameat (2)
symlinkat (2)
symlinkat (2)
unlinkat (2)
unlinkat (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
Double Pointer (Pointer to Pointer) in C

A pointer is used to store the address of variables. So, when we define a pointer to pointer, the first pointer is used to store the address of the second pointer. Thus it is known as double pointers.
Begin
   Declare v of the integer datatype.
      Initialize v = 76.
   Declare a pointer p1 of the integer datatype.
   Declare another double pointer p2 of the integer datatype.
   Initialize p1 as the pointer to variable v.
   Initialize p2 as the pointer to variable p1.
   Print “Value of v”.
      Print the value of variable v.
   Print “Value of v using single pointer”.
      Print the value of pointer p1.
   Print “Value of v using double pointer”.
      Print the value of double pointer p2.
End.
A simple program to understand double pointer:
int main() {
   int v = 76;
   int *p1;
   int **p2;
   p1 = &v;
   p2 = &p1;
   printf("Value of v = %d\n", v);
   printf("Value of v using single pointer = %d\n", *p1 );
   printf("Value of v using double pointer = %d\n", **p2);
   return 0;
}
Value of v = 76
Value of v using single pointer = 76
Value of v using double pointer = 76
MySQL query to replace backslash from a varchar column with preceding backslash string values

Let us first create a table −
mysql> create table DemoTable
(
   Title varchar(100)
);
Query OK, 0 rows affected (0.57 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('\\"MySQL');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('MongoDB\\"');
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable values('\\"Java\\"');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values('\\"C\"');
Query OK, 1 row affected (0.14 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-----------+
| Title     |
+-----------+
| \"MySQL   |
| MongoDB\" |
| \"Java\"  |
| \"C"      |
+-----------+
4 rows in set (0.00 sec)
Following is the query to replace backslash from a varchar column with preceding backslash string values −
mysql> update DemoTable set Title=replace(Title,'\\"','"');
Query OK, 4 rows affected (0.14 sec)
Rows matched: 4 Changed: 4 Warnings: 0
Let us check table records once again −
mysql> select *from DemoTable;
This will produce the following output −
+----------+
| Title    |
+----------+
| "MySQL   |
| MongoDB" |
| "Java"   |
| "C"      |
+----------+
4 rows in set (0.00 sec)
Go - Basic Syntax

We discussed the basic structure of a Go program in the previous chapter. Now it will be easy to understand the other basic building blocks of the Go programming language.
A Go program consists of various tokens. A token is either a keyword, an identifier, a constant, a string literal, or a symbol. For example, the following Go statement consists of six tokens −
fmt.Println("Hello, World!")

The individual tokens are −
fmt
.
Println
(
   "Hello, World!"
)
In a Go program, the line separator key is a statement terminator. That is, individual statements don't need a special separator like “;” in C. The Go compiler internally places “;” as the statement terminator to indicate the end of one logical entity.
For example, take a look at the following statements −
fmt.Println("Hello, World!")
fmt.Println("I am in Go Programming World!")

Comments are like helping texts in your Go program and they are ignored by the compiler. They start with /* and terminates with the characters */ as shown below −
/* my first program in Go */

You cannot have comments within comments and they do not occur within a string or character literals.
A Go identifier is a name used to identify a variable, function, or any other user-defined item. An identifier starts with a letter A to Z or a to z or an underscore _ followed by zero or more letters, underscores, and digits (0 to 9).
identifier = letter { letter | unicode_digit }.
Go does not allow punctuation characters such as @, $, and % within identifiers. Go is a case-sensitive programming language. Thus, Manpower and manpower are two different identifiers in Go. Here are some examples of acceptable identifiers −
mahesh      kumar   abc   move_name   a_123
myname50   _temp    j      a23b9      retVal

The following list shows the reserved words in Go. These reserved words may not be used as constant or variable or any other identifier names.
Whitespace is the term used in Go to describe blanks, tabs, newline characters, and comments. A line containing only whitespace, possibly with a comment, is known as a blank line, and a Go compiler totally ignores it.
Whitespaces separate one part of a statement from another and enables the compiler to identify where one element in a statement, such as int, ends and the next element begins. Therefore, in the following statement −
var age int;

There must be at least one whitespace character (usually a space) between int and age for the compiler to be able to distinguish them. On the other hand, in the following statement −
fruit = apples + oranges;   // get the total fruit

No whitespace characters are necessary between fruit and =, or between = and apples, although you are free to include some if you wish for readability purpose.

    64 Lectures 
     6.5 hours 

 Ridhi Arora

    20 Lectures 
     2.5 hours 

 Asif Hussain

    22 Lectures 
     4 hours 

 Dilip Padmanabhan

    48 Lectures 
     6 hours 

 Arnab Chakraborty

    7 Lectures 
     1 hours 

 Aditya Kulkarni

    44 Lectures 
     3 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
How do I create a random alpha-numeric string using C++?

In this section we will see how to generate a random alphanumeric string using C++. Here we are providing lowercase letters, uppercase letters and numbers (0-9). This program takes the characters randomly, then creates the random string.
Input: Here we are giving the string length
Output: A random string of that length. Example “XSme6VAsvJ”
Step 1:Define array to hold all uppercase, lowercase letters and numbers
Step 2: Take length n from user
Step 3: Randomly choose characters’ n times and create a string of length n
Step 4: End
 Live Demo
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
static const char alphanum[] = "0123456789" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz";
int len = sizeof(alphanum) - 1;
char genRandom() { // Random string generator function.
   return alphanum[rand() % len];
}
int main() {
   srand(time(0));
   int n;
   cout << "Enter string length: ";
   cin >> n;
   for(int z = 0; z < n; z++) {    //generate string of length n
      cout << genRandom(); //get random character from the given list
   }
   return 0;
}
Enter string length: 10
XSme6VAsvJ
C++ Queue Library - back() Function

The C++ function std::queue::back() returns a reference to the last element of queue. This is the most recently enqueued element.
Following is the declaration for std::queue::back() function form std::queue header.
value_type& back();
const value_type& back() const;

reference& back();
const_reference& back() const;

None
Returns reference to the last element of the queue.
No-throw guarantee for standard non-empty containers.
Constant i.e. O(1)
The following example shows the usage of std::queue::back() function.
#include <iostream>
#include <queue>

using namespace std;

int main(void) {
   queue<int> q;

   for (int i = 0; i < 5; ++i)
      q.push(i + 1);

   cout << "Last element of queue q is = " << q.back() << endl;

   return 0;
}
Let us compile and run the above program, this will produce the following result −
Last element of queue q is = 5

 Print
 Add Notes
 Bookmark this page
Start Coding - Java | Practice | GeeksforGeeks

When learning a new language, we first learn to output some message. Here, we'll start with the famous Hello World message. Now, here you are given a function to complete. Don't worry about the ins and outs of functions, just add the command (System.out.print("Hello World")) to print Hello World.
Example:
Input:
No input

Output:
Hello World

Explanation:
Hello World is printed.
User Task:
Your task is to complete the function below to print hello world.
0
nivruttidahake304 days ago
// { Driver Code Starts//Initial Template for Java
// } Driver Code Ends//User function Template for Java
class Geeks{      // Function to print hello   static void printHello(){              // Your code here       System.out.println("Hello World");   }   }
// { Driver Code Starts.
class GfG{      public static void main(String args[]){            //Creating an Object of Class Geeks       Geeks g = new Geeks();              //Calling printHello() function of the Class Geeks       g.printHello();   }   }  // } Driver Code Ends
0
maquickstop1 week ago
class hello{
public void m1(){
System.out.println("Hello World");
}
}
0
vadaliyaravi21 week ago
class Geeks{      // Function to print hello   static void printHello(){             System.out.println("Hello World")          }   }
0
roxsonu92 weeks ago
class Geeks{      // Function to print hello   static void printHello(){              System.out.print("Hello World");          }   }
0
priyanshukumar235652 weeks ago
class Geeks{      // Function to print hello   static void printHello(){       System.out.println("Hello World");              // Your code here          }   }
0
shubhamkumar0285s2 weeks ago
class Geeks{      // Function to print hello   static void printHello(){              // Your code here       System.out.println("Hello World");   }   }
0
arpandutta5033 weeks ago
System.out.println(hello world)
0
arpandutta5033 weeks ago
System.out.println(Hello world);
0
ddarshu7713 weeks ago
Darshan K R
System.out.println("Hello World);
0
ashishreddy0333 weeks ago
System.out.println("Hello World");
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
How to draw triangle shape in android?

This example demonstrate about How to draw triangle shape in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical"
   android:gravity="center"
   android:layout_marginTop="30dp"
   tools:context=".MainActivity">
   <ImageView
      android:layout_width="100dp"
      android:layout_height="100dp"
      android:background="@drawable/background"/>
</LinearLayout>
In the above code, we have taken imageview and added background as background.xml.
Step 3 − Add the following code to drawable/ background.xml
<vector xmlns:android="http://schemas.android.com/apk/res/android"
   android:height="100dp"
   android:width="100dp"
   android:viewportWidth="24"
   android:viewportHeight="24">
   <path android:fillColor="#000" android:pathData="M1,21H23L12,2" />
</vector>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
Click here to download the project code
Angular 2 - Data Binding

Two-way binding was a functionality in Angular JS, but has been removed from Angular 2.x onwards. But now, since the event of classes in Angular 2, we can bind to properties in AngularJS class.
Suppose if you had a class with a class name, a property which had a type and value.
export class className {
   property: propertytype = value;
}
You could then bind the property of an html tag to the property of the class.
<html tag htmlproperty = 'property'>

The value of the property would then be assigned to the htmlproperty of the html.
Let’s look at an example of how we can achieve data binding. In our example, we will look at displaying images wherein the images source will come from the properties in our class. Following are the steps to achieve this.
Step 1 − Download any 2 images. For this example, we will download some simple images shown below.
Step 2 − Store these images in a folder called Images in the app directory. If the images folder is not present, please create it.
Step 3 − Add the following content in app.component.ts as shown below.
import { Component } from '@angular/core';

@Component ({
   selector: 'my-app',
   templateUrl: 'app/app.component.html'
})

export class AppComponent {
   appTitle: string = 'Welcome';
   appList: any[] = [ {
      "ID": "1",
      "url": 'app/Images/One.jpg'
   },

   {
      "ID": "2",
      "url": 'app/Images/Two.jpg'
   } ];
}
Step 4 − Add the following content in app.component.html as shown below.
<div *ngFor = 'let lst of appList'>
   <ul>
      <li>{{lst.ID}}</li>
      <img [src] = 'lst.url'>
   </ul>
</div>
In the above app.component.html file, we are accessing the images from the properties in our class.
The output of the above program should be like this −

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    28 Lectures 
     2.5 hours 

 Anadi Sharma

    11 Lectures 
     7.5 hours 

 SHIVPRASAD KOIRALA

    16 Lectures 
     2.5 hours 

 Frahaan Hussain

    69 Lectures 
     5 hours 

 Senol Atac

    53 Lectures 
     3.5 hours 

 Senol Atac
 Print
 Add Notes
 Bookmark this page
DAX Time Intelligence - DATESYTD function

Returns a table that contains a column of the dates for the year to date, in the current context.
DATESYTD (<dates>, [<year_end_date>]) 

dates
A column that contains dates.
year_end_date
Optional.
A literal string with a date that defines the year-end date.
If omitted, the default is December 31.
A table containing a single column of date values.
The dates parameter can be any of the following −
A reference to a date/time column.
A table expression that returns a single column of date/time values.
A Boolean expression that defines a single-column table of date/time values.
Constraints on Boolean expressions −
The expression cannot reference a calculated field.
The expression cannot reference a calculated field.
The expression cannot use CALCULATE function.
The expression cannot use CALCULATE function.
The expression cannot use any function that scans a table or returns a table, including aggregation functions.
The expression cannot use any function that scans a table or returns a table, including aggregation functions.
However, a Boolean expression can use any function that looks up a single value, or that calculates a scalar value.
= CALCULATE ( 
   SUM (Sales [Sales Amount]), DATESYTD (Sales [Date])
) 

    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
bounce - Unix, Linux Command

bounce [generic Postfix daemon options]


The bounce(8) daemon processes two types of service requests:


Optionally, a bounce (defer, trace) client can request that the
per-message log file be deleted when the requested operation fails.
This is used by clients that cannot retry transactions by
themselves, and that depend on retry logic in their own client.

RFC 822 (ARPA Internet Text Messages)
RFC 2045 (Format of Internet Message Bodies)
RFC 2822 (ARPA Internet Text Messages)
RFC 3462 (Delivery Status Notifications)
RFC 3464 (Delivery Status Notifications)
RFC 3834 (Auto-Submitted: message header)




The text below provides only a parameter summary. See
postconf(5) for more details including examples.

/var/spool/postfix/bounce/* non-delivery records
/var/spool/postfix/defer/* non-delivery records
/var/spool/postfix/trace/* delivery status records

bounce(5), bounce message template format
qmgr(8), queue manager
postconf(5), configuration parameters
master(5), generic daemon options
master(8), process manager
syslogd(8), system logging



Wietse Venema
IBM T.J. Watson Research
P.O. Box 704
Yorktown Heights, NY 10598, USA


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
Binary to BCD conversion in 8051

In this problem, we will see how to convert an 8-bit binary number to its BCD equivalent. The binary number is stored at location 20H. After converting, the results will be stored at 30H and 31H. The 30H will hold the MS portion, and 31H will hold the LS portion. 
So let us assume the data is D5H. The program converts the binary value of D5H to BCD value 213D.
MOVR1,#20H;Takethe address 20H into R1
MOVA,@R1;Takethe data into Acc
MOVB,#0AH;LoadB with AH = 10D
DIVAB ;DivideA with B
MOVR5,B;Storethe remainder
MOVB,#0AH;LoadB with AH = 10D
DIVAB ;DivideA with B
MOVR1,#30H;Loaddestination address
MOV@R1,A;Storethe MS portion
MOVA,B;LoadB content to A
SWAPA;Swapthe nibbles
ADDA,R5;Addstored remainder with A
INCR1;Increasethe address
MOV@R1,A
HALT:   SJMPHALT
Here we are just taking the binary number into the accumulator. And then divide the content of accumulator by 0AH (10D). So the remainder partis stored into a separate register. This will be added later. Then again divide the quotient by 0AH, and generate the MS bits. After storing the MS bits, get the number from register B to the accumulator. Swap the nibbles of the accumulator to generate four zeros at the LSbits. Then add the previously stored remainder to generate the result.
Can we use “IF NOT IN” in a MySQL procedure?

Let us first see the syntax of IF NOT IN in MySQL −
if(yourVariableName  NOT IN (yourValue1,yourValue2,........N) ) then
   statement1
else
   statement2
endif    
Let us implement the above syntax to use IF NOT IN −
mysql> DELIMITER //
mysql> CREATE PROCEDURE IF_NOT_INDemo(IN value int)
   ->    BEGIN
   ->       if(value NOT IN  (10,20,30) ) then
   ->          select "Value Not Found";
   ->       else
   ->          select "Value Found";
   ->       end if;
   ->    END
   -> //
Query OK, 0 rows affected (0.25 sec)
mysql> DELIMITER ;
Now call the stored procedure using CALL command.
Case 1 − When a value is found −
mysql> call IF_NOT_INDemo(10);
+-------------+
| Value Found |
+-------------+
| Value Found |
+-------------+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.01 sec)
Case 2 - When a value isn’t found -
mysql> call IF_NOT_INDemo(100);
 +-----------------+
 | Value Not Found |
 +-----------------+
 | Value Not Found |
 +-----------------+
1 row in set (0.05 sec)

Query OK, 0 rows affected (0.07 sec)
How to set the maximum width of an element with JavaScript?

Use the maxWidth property in JavaScript to set the maximum width.
You can try to run the following code to set the maximum width of an element with JavaScript −
Live Demo
<!DOCTYPE html>
<html>
   <body>
      <p>Click below to set Maximum width.</p>
      <button type="button" onclick="display()">Max Width</button>
      <div id="box">
         <p>This is a div. This is a div. This is a div.</p>
         <p>This is a div. This is a div. This is a div.</p>
         <p>This is a div. This is a div. This is a div.</p>
         <p>This is a div. This is a div. This is a div.</p>
         <p>This is a div. This is a div. This is a div.</p>
      </div>
      <br>
      <script>
         function display() {
            document.getElementById("box").style.maxWidth = "80px";
         }
      </script>
   </body>
</html>
java.lang.reflect - Method Class

The java.lang.reflect.Method class  provides information about, and access to, a single method on a class or interface. The reflected method may be a class method or an instance method (including an abstract method). A Method permits widening conversions to occur when matching the actual parameters to invoke with the underlying method's formal parameters, but it throws an IllegalArgumentException if a narrowing conversion would occur.
Following is the declaration for java.lang.reflect.Method class −
public final class Method<T>
   extends AccessibleObject
      implements GenericDeclaration, Member

Compares this Method against the specified object.
Returns this element's annotation for the specified type if such an annotation is present, else null.
Returns all annotations that are directly present on this element.
Returns the Class object representing the class that declares the method represented by this Method object.
Returns the default value for the annotation member represented by this Method instance.
Returns an array of Class objects that represent the types of exceptions declared to be thrown by the underlying constructor represented by this Constructor object.
Returns an array of Type objects that represent the exceptions declared to be thrown by this Constructor object.
Returns an array of Type objects that represent the formal parameter types, in declaration order, of the method represented by this Constructor object.
Returns a Type object that represents the formal return type of the method represented by this Method object.
Returns the Java language modifiers for the method represented by this Method object, as an integer.
Returns the name of this method, as a string.
Returns an array of arrays that represent the annotations on the formal parameters, in declaration order, of the method represented by this Method object.
Returns an array of Class objects that represent the formal parameter types, in declaration order, of the constructor represented by this Method object.
Returns a Class object that represents the formal return type of the method represented by this Method object.
Returns a hashcode for this Constructor.
Invokes the underlying method represented by this Method object, on the specified object with the specified parameters.
Returns true if this method is a bridge method; returns false otherwise.
Returns true if this method is a synthetic method; returns false otherwise.
Returns true if this method was declared to take a variable number of arguments; returns false otherwise.
Returns a string describing this Method, including type parameters.
Returns a string describing this Method.
This class inherits methods from the following classes −
java.lang.reflect.AccessibleObject
java.lang.Object
 Print
 Add Notes
 Bookmark this page
Remove the first entry of the TreeMap in Java

To remove the first entry of the TreeMap, use the pollFirstEntry() method.
Let us first create a TreeMap and add elements −
TreeMap<Integer,String> m = new TreeMap<Integer,String>();
m.put(1,"India");
m.put(2,"US");
m.put(3,"Australia");
m.put(4,"Netherlands");
m.put(5,"Canada");
Remove the first entry now −
m.pollFirstEntry()
The following is an example to remove the first entry of the TreeMap.
 Live Demo
import java.util.*;
public class Demo {
   public static void main(String args[]) {
      TreeMap<Integer,String> m = new TreeMap<Integer,String>();
      m.put(1,"India");
      m.put(2,"US");
      m.put(3,"Australia");
      m.put(4,"Netherlands");
      m.put(5,"Canada");
      System.out.println("TreeMap Elements = "+m);
      System.out.println("Removing First Entry : "+m.pollFirstEntry());
      System.out.println("Updated TreeMap Elements = "+m);
   }
}
TreeMap Elements = {1=India, 2=US, 3=Australia, 4=Netherlands, 5=Canada}
Removing First Entry = 1=India
Updated TreeMap Elements = {2=US, 3=Australia, 4=Netherlands, 5=Canada}
How to create instance Objects using __init__ in Python?

The instantiation or calling-a-class-object operation creates an empty object. Many classes like to create objects with instances with a specific initial state. Therefore a class may define a special method named __init__(), as follows −
def __init__(self) −
    self.data = [ ]
When a class defines an __init__() method, class instantiation automatically invokes the newly-created class instance which is obtained by −
x = MyClass()
The __init__() method may have arguments. In such a case, arguments given to the class instantiation operator are passed on to __init__(). For example,
>>> class Complex:
...     def __init__(self, realpart, imagpart):
...         self.r = realpart
...         self.i = imagpart
...
>>> x = Complex(4.0, -6.5)
>>> x.r, x.i
(4.0, -6.5)
numpy.dot() in Python - GeeksforGeeks

18 Nov, 2021
numpy.dot(vector_a, vector_b, out = None) returns the dot product of vectors a and b. It can handle 2D arrays but considers them as matrix and will perform matrix multiplication. For N dimensions it is a sum-product over the last axis of a and the second-to-last of b :
dot(a, b)[i,j,k,m] = sum(a[i,j,:] * b[k,:,m]) 
 
Parameters
vector_a : [array_like] if a is complex its complex conjugate is used for the calculation of the dot product. vector_b : [array_like] if b is complex its complex conjugate is used for the calculation of the dot product. out : [array, optional] output argument must be C-contiguous, and its dtype must be the dtype that would be returned for dot(a,b). 
vector_a : [array_like] if a is complex its complex conjugate is used for the calculation of the dot product. 
vector_b : [array_like] if b is complex its complex conjugate is used for the calculation of the dot product. 
out : [array, optional] output argument must be C-contiguous, and its dtype must be the dtype that would be returned for dot(a,b). 
Return:
Dot Product of vectors a and b. if vector_a and vector_b are 1D, then scalar is returned
Code 1:
Python
# Python Program illustrating# numpy.dot() method import numpy as geek # Scalarsproduct = geek.dot(5, 4)print("Dot Product of scalar values  : ", product) # 1D arrayvector_a = 2 + 3jvector_b = 4 + 5j product = geek.dot(vector_a, vector_b)print("Dot Product  : ", product)
Output:
Dot Product of scalar values  :  20
Dot Product  :  (-7+22j)
How Code1 works ? 
vector_a = 2 + 3j 
vector_b = 4 + 5j
now dot product 
= 2(4 + 5j) + 3j(4 – 5j) 
= 8 + 10j + 12j – 15 
= -7 + 22j
Code 2:
Python
# Python Program illustrating# numpy.dot() method import numpy as geek # 1D arrayvector_a = geek.array([[1, 4], [5, 6]])vector_b = geek.array([[2, 4], [5, 2]]) product = geek.dot(vector_a, vector_b)print("Dot Product  : \n", product) product = geek.dot(vector_b, vector_a)print("\nDot Product  : \n", product) """Code 2 : as normal matrix multiplication"""
Output:
Dot Product  : 
 [[22 12]
 [40 32]]

Dot Product  : 
 [[22 32]
 [15 32]]
References: https://numpy.org/doc/stable/reference/generated/numpy.dot.html
This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
codeachalesh
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
Defaultdict in Python
Python Classes and Objects
Create a directory in Python
Python | os.path.join() method
Python | Pandas dataframe.groupby()
Python | Get unique values from a list
What is the difference between 'except Exception as e' and 'except Exception, e' in Python?

The difference between using ',' and 'as' in except statements, is as follows:
Both ',' and 'as' are same functionality wise; but their use depends on the python versions as follows.In Python 2.5 and earlier versions, use of the 'comma' is recommended since 'as' isn't supported.In Python 2.6+ versions, both 'comma' and 'as' can be used. But from Python 3.x, 'as' is required to assign an exception to a variable.As of Python 2.6 using 'as' allows us an elegant way to catch multiple exceptions in a single except block as shown below
except (Exception1, Exception2) as err
is any day better than
except (Exception1, Exception2), err
Tryit Editor v3.7

Tryit: Template 2 - using float
How will you show memory representation of C variables? - GeeksforGeeks

18 Feb, 2022
Write a C program to show memory representation of C variables like int, float, pointer, etc. Algorithm: Get the address and size of the variable. Typecast the address to char pointer. Now loop for size of the variable and print the value at the typecasted pointer.
Program: 
c
#include <stdio.h>typedef unsigned char *byte_pointer; /*show bytes takes byte pointer as an argument  and prints memory contents from byte_pointer  to byte_pointer + len */void show_bytes(byte_pointer start, int len){     int i;     for (i = 0; i < len; i++)           printf(" %.2x", start[i]);     printf("\n");} void show_int(int x){     show_bytes((byte_pointer) &x, sizeof(int));} void show_float(float x){     show_bytes((byte_pointer) &x, sizeof(float));} void show_pointer(void *x){     show_bytes((byte_pointer) &x, sizeof(void *));} /* Driver program to test above functions */int main(){    int i = 1;    float f = 1.0;    int *p = &i;    show_float(f);    show_int(i);    show_pointer(p);    show_int(i);    getchar();    return 0;}
simmytarika5
c-puzzle
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Structures in C
TCP Server-Client implementation in C
Data Types in C
Multithreading in C
Pointer to an Array | Array Pointer
Memory Layout of C Programs
Power Function in C/C++
Taking String input with space in C (4 Different Methods)
Exception Handling in C++
INT_MAX and INT_MIN in C/C++ and Applications
C++ Program for ShellSort - GeeksforGeeks

09 May, 2019
In shellSort, we make the array h-sorted for a large value of h. We keep reducing the value of h until it becomes 1. An array is said to be h-sorted if all sublists of every h’th element is sorted.
// C++ implementation of Shell Sort#include <iostream>  /* function to sort arr using shellSort */void shellSort(int arr[], int n){    // Start with a big gap, then reduce the gap    for (int gap = n / 2; gap > 0; gap /= 2) {        // Do a gapped insertion sort for this gap size.        // The first gap elements arr[0..gap-1] are already in gapped order        // keep adding one more element until the entire array is        // gap sorted        for (int i = gap; i < n; i += 1) {            // add arr[i] to the elements that have been gap sorted            // save arr[i] in temp and make a hole at position i            int temp = arr[i];              // shift earlier gap-sorted elements up until the correct            // location for arr[i] is found            int j;            for (j = i; j >= gap && arr[j - gap] > temp; j -= gap)                arr[j] = arr[j - gap];              // put temp (the original arr[i]) in its correct location            arr[j] = temp;        }    }}  void printArray(int arr[], int n){    for (int i = 0; i < n; i++)        std::cout << arr[i] << " ";    std::cout << "\n";}  int main(){    int arr[] = { 12, 34, 54, 2, 3 };    int n = sizeof(arr) / sizeof(arr[0]);      std::cout << "Array before sorting: \n";    printArray(arr, n);      shellSort(arr, n);      std::cout << "Array after sorting: \n";    printArray(arr, n);}
Array before sorting: 
12 34 54 2 3 
Array after sorting: 
2 3 12 34 54

Please refer complete article on ShellSort for more details!
ted1
C++ Programs
Sorting
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Passing a function as a parameter in C++
Program to implement Singly Linked List in C++ using class
cout in C++
Pi(π) in C++ with Examples
Const keyword in C++
How to merge two strings alternatively in JavaScript

We are required to write a JavaScript function that takes in two. Our function should then return a new array that contains characters alternatively from both the strings.
For example: If the two strings are −
const str1 = 'abc';
const str2 = 'def';
Then the output should be −
const output = 'adbecf';
The code for this will be −
const str1 = 'abc';
const str2 = 'def';
const mergeAlternatively = (str1, str2) => {
   const a = str1.split("").filter(el => !!el);
   const b = str2.split("");
   let mergedString = '';
   for(var i = 0; i < a.length || i < b.length; i++){
      if(i < a.length){
         mergedString += a[i];
      };
      if(i < b.length){
         mergedString += b[i];
      };
   };
   return mergedString;
};
console.log(mergeAlternatively(str1, str2));
The output in the console −
adbecf
Map get() method in Java with Examples - GeeksforGeeks

31 Dec, 2018
The get() method of Map interface in Java is used to retrieve or fetch the value mapped by a particular key mentioned in the parameter. It returns NULL when the map contains no such mapping for the key.
Syntax:
thisMap.get(Object key_element)
Parameter: The method takes one parameter key_element of object type and refers to the key whose associated value is supposed to be fetched.
Return Value: The method returns the value associated with the key_element in this Map collection.
Below programs illustrates the working of java.util.Map.get() method:
Program 1: Mapping String Values to Integer Keys.
// Java code to illustrate the get() methodimport java.util.*;  public class Map_Demo {    public static void main(String[] args)    {        // Creating an empty Map        Map<Integer, String> map = new HashMap<Integer, String>();          // Mapping string values to int keys        map.put(10, "Geeks");        map.put(15, "4");        map.put(20, "Geeks");        map.put(25, "Welcomes");        map.put(30, "You");          // Displaying the Map        System.out.println("Initial Mappings are: " + map);          // Getting the value of 25        System.out.println("The Value is: " + map.get(25));          // Getting the value of 10        System.out.println("The Value is: " + map.get(10));    }}
Initial Mappings are: {20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=4}
The Value is: Welcomes
The Value is: Geeks

Program 2: Mapping Integer Values to String Keys.
// Java code to illustrate the get() method  import java.util.*;  public class Map_Demo {    public static void main(String[] args)    {        // Creating an empty Map        Map<String, Integer> map = new HashMap<String, Integer>();          // Mapping int values to string keys        map.put("Geeks", 10);        map.put("4", 15);        map.put("Geeks", 20);        map.put("Welcomes", 25);        map.put("You", 30);          // Displaying the Map        System.out.println("Initial Mappings are: " + map);          // Getting the value of "Geeks"        System.out.println("The Value is: " + map.get("Geeks"));          // Getting the value of "You"        System.out.println("The Value is: " + map.get("You"));    }}
Initial Mappings are: {4=15, Geeks=20, You=30, Welcomes=25}
The Value is: 20
The Value is: 30

Note: The same operation can be performed with any type of Mappings with variation and combination of different data types.
Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Map.html#get(java.lang.Object)
Java-Collections
Java-Functions
java-map
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Initialize an ArrayList in Java
Object Oriented Programming (OOPs) Concept in Java
Interfaces in Java
ArrayList in Java
Multidimensional Arrays in Java
Singleton Class in Java
Stack Class in Java
Multithreading in Java
LinkedList in Java
Collections in Java
Correlation and Regression in Python

Correlation refers to some statistical relationships involving dependence between two data sets. While linear regression is a linear approach to establish the relationship between a dependent variable and one or more independent variables. A single independent variable is called linear regression whereas multiple independent variables is called multiple regression.
Simple examples of dependent phenomena include the correlation between the physical appearance of parents and their offspring, and the correlation between the price for a product and its supplied quantity.We take example of the iris data set available in seaborn python library. In it we try to establish the correlation between the length and the width of the sepals and petals of three species of iris flower. Based on the correlation found, a strong model could be created which easily distinguishes one species from another.
import matplotlib.pyplot as plt
import seaborn as sns
df = sns.load_dataset('iris')
#without regression
sns.pairplot(df, kind="scatter")
plt.show()
Running the above code gives us the following result −
Mathematically a linear relationship represents a straight line when plotted as a graph. A non-linear relationship where the exponent of any variable is not equal to 1 creates a curve.
The functions in Seaborn to find the linear regression relationship is regplot. The below example shows its use.
import seaborn as sb
from matplotlib import pyplot as plt
df = sb.load_dataset('tips')
sb.regplot(x = "total_bill", y = "tip", data = df)
plt.show()
Running the above code gives us the following result −