code-rag-bench/online-tutorials huggingface dataset:
PyQt5 QListWidget - Setting Drag Drop Property - GeeksforGeeks

06 Aug, 2020
In this article we will see how we can set the drag drop property of the QListWidget. QListWidget is a convenience class that provides a list view with a classic item-based interface for adding and removing items. QListWidget uses an internal model to manage each QListWidgetItem in the list. Describes the various drag and drop events the view can act upon. By default the view does not support dragging or dropping (NoDragDrop). There are many options available like, drag only, drag drop, drop only, no drag drop.
In order to do this we will use setDragDropMode method with the list widget object.
Syntax : list_widget.setDragDropMode(dragdropmode)
Argument : It takes drag drop object as argument
Return : It returns None
Below is the implementation
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys    class Window(QMainWindow):      def __init__(self):        super().__init__()          # setting title        self.setWindowTitle("Python ")          # setting geometry        self.setGeometry(100, 100, 500, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()          # method for components    def UiComponents(self):          # creating a QListWidget        list_widget = QListWidget(self)          # setting geometry to it        list_widget.setGeometry(50, 70, 150, 60)          # list widget items        item1 = QListWidgetItem("A")        item2 = QListWidgetItem("B")        item3 = QListWidgetItem("C")          # adding items to the list widget        list_widget.addItem(item1)        list_widget.addItem(item2)        list_widget.addItem(item3)          # setting drag drop mode        list_widget.setDragDropMode(QAbstractItemView.DragDrop)          # creating a label        label = QLabel("GeesforGeeks", self)          # setting geometry to the label        label.setGeometry(230, 80, 280, 80)          # making label multi line        label.setWordWrap(True)    # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python PyQt-QListWidget
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Reading and Writing to text files in Python
Program to find a list of product of all elements except the current index in Python

Suppose we have a list of numbers called nums, we have to find a new list such that each element at index i of the newly generated list is the product of all the numbers in the original list except the one at index i. Here we have to solve it without using division.
So, if the input is like nums = [2, 3, 4, 5, 6], then the output will be [360, 240, 180, 144, 120]
To solve this, we will follow these steps −
if size of nums < 1, thenreturn nums
return nums
l := size of nums
left := a list of size l and initially all values are null
right := a list of size l and initially all values are null
temp := 1
for i in range 0 to size of nums, doif i is same as 0, thenleft[i] := tempotherwise,temp := temp * nums[i - 1]left[i] := temp
if i is same as 0, thenleft[i] := temp
left[i] := temp
otherwise,temp := temp * nums[i - 1]left[i] := temp
temp := temp * nums[i - 1]
left[i] := temp
temp := 1
for i in range size of nums - 1 to 0, decrease by 1, doif i is same as size of nums - 1, thenright[i] := tempotherwise,temp := temp * nums[i + 1]right[i] := temp
if i is same as size of nums - 1, thenright[i] := temp
right[i] := temp
otherwise,temp := temp * nums[i + 1]right[i] := temp
temp := temp * nums[i + 1]
right[i] := temp
for i in range 0 to size of nums, doleft[i] := left[i] * right[i]
left[i] := left[i] * right[i]
return left
Let us see the following implementation to get better understanding −
 Live Demo
class Solution:
   def solve(self, nums):
      if len(nums) < 1:
         return nums
      l = len(nums)
      left = [None] * l
      right = [None] * l
      temp = 1
      for i in range(len(nums)):
         if i == 0:
            left[i] = temp
         else:
            temp = temp * nums[i - 1]
            left[i] = temp
      temp = 1
      for i in range(len(nums) - 1, -1, -1):
         if i == len(nums) - 1:
            right[i] = temp
         else:
            temp = temp * nums[i + 1]
            right[i] = temp
      for i in range(len(nums)):
         left[i] = left[i] * right[i]
      return left
ob = Solution()
nums = [2, 3, 4, 5, 6]
print(ob.solve(nums))
[2, 3, 4, 5, 6]
[360, 240, 180, 144, 120]
Execute operations (plus, minus, multiply, divide) while updating a MySQL table?

Following is the syntax executing the plus (+) operator −
update yourTableName set yourColumnName3=(yourColumnName1+yourColumnName2)
The above syntax is only for plus operator. You need to change symbol like -,*,/ for other operations. Let us first create a table −
mysql> create table DemoTable
   -> (
   -> Number1 int,
   -> Number2 int,
   -> AddResult int,
   -> MinusResult int,
   -> MultiplyResult int,
   -> DivideResult int
   -> );
Query OK, 0 rows affected (0.89 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable(Number1,Number2) values(40,20);
Query OK, 1 row affected (0.16 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+---------+---------+-----------+-------------+----------------+--------------+
| Number1 | Number2 | AddResult | MinusResult | MultiplyResult | DivideResult |
+---------+---------+-----------+-------------+----------------+--------------+
|      40 |      20 |      NULL |        NULL |           NULL |         NULL |
+---------+---------+-----------+-------------+----------------+--------------+
1 row in set (0.00 sec)
Following is the query to execute operations like plus, minus, multiply and divide while using UPDATE in MySQL −
mysql> update DemoTable set AddResult=(Number1+Number2);
Query OK, 1 row affected (0.22 sec)
Rows matched: 1 Changed: 1 Warnings: 0

mysql> update DemoTable set MinusResult=(Number1-Number2);
Query OK, 1 row affected (0.08 sec)
Rows matched: 1 Changed: 1 Warnings: 0

mysql> update DemoTable set MultiplyResult=(Number1*Number2);
Query OK, 1 row affected (0.08 sec)
Rows matched: 1 Changed: 1 Warnings: 0

mysql> update DemoTable set DivideResult=(Number1/Number2);
Query OK, 1 row affected (0.07 sec)
Rows matched: 1 Changed: 1 Warnings: 0
Let us check the table records once again −
mysql> select *from DemoTable;
This will produce the following output −
+---------+---------+-----------+-------------+----------------+--------------+
| Number1 | Number2 | AddResult | MinusResult | MultiplyResult | DivideResult |
+---------+---------+-----------+-------------+----------------+--------------+
|      40 |      20 |        60 |          20 |            800 |            2 |
+---------+---------+-----------+-------------+----------------+--------------+
1 row in set (0.00 sec)
Send message to Telegram user using Python

16 Sep, 2021
Have you ever wondered how people do automation on Telegram? You may know that Telegram has a big user base and so it is one of the preferred social media to read people. What good thing about Telegram is that it provides a bunch of API’s methods, unlike Whatsapp which restricts such things. So in this post, we will be sharing how to send messages to a Telegram user using Python. 
First, create a bot using Telegram BotFather. To create a BotFather follow the below steps –  
Open the telegram app and search for @BotFather.
Click on the start button or send “/start”.
Then send “/newbot” message to set up a name and a username.
After setting name and username BotFather will give you an API token which is your bot token.  
Then create an app on the telegram. Follow the below steps –  
Log into the telegram core: https://my.telegram.org
Go to ‘API development tools’ and fill out the form.
You will get the api_id and api_hash parameters required for user authorization.  
 
You need several Python library imports for the script functioning.  
telebot: To install this module type the below command in the terminal.
pip install telebot
telethon: To install this module type the below command in the terminal.  
pip install telethon
Below is the implementation. 
Python3
# importing all required librariesimport telebotfrom telethon.sync import TelegramClientfrom telethon.tl.types import InputPeerUser, InputPeerChannelfrom telethon import TelegramClient, sync, events   # get your api_id, api_hash, token# from telegram as described aboveapi_id = 'API_id'api_hash = 'API_hash'token = 'bot token'message = "Working..." # your phone numberphone = 'YOUR_PHONE_NUMBER_WTH_COUNTRY_CODE'  # creating a telegram session and assigning# it to a variable clientclient = TelegramClient('session', api_id, api_hash)  # connecting and building the sessionclient.connect() # in case of script ran first time it will# ask either to input token or otp sent to# number or sent or your telegram idif not client.is_user_authorized():      client.send_code_request(phone)         # signing in the client    client.sign_in(phone, input('Enter the code: '))    try:    # receiver user_id and access_hash, use    # my user_id and access_hash for reference    receiver = InputPeerUser('user_id', 'user_hash')     # sending message using telegram client    client.send_message(receiver, message, parse_mode='html')except Exception as e:         # there may be many error coming in while like peer    # error, wrong access_hash, flood_error, etc    print(e); # disconnecting the telegram sessionclient.disconnect()
divz11
simmytarika5
Python-projects
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Order of operands for logical operators

28 May, 2017
The order of operands of logical operators &&, || are important in C/C++.
In mathematics, logical AND, OR, etc... operations are commutative. The result will not change even if we swap RHS and LHS of the operator.
In C/C++ (may be in other languages as well)  even though these operators are commutative, their order is critical. For example see the following code,
// Traverse every alternative nodewhile( pTemp && pTemp->Next ){   // Jump over to next node   pTemp = pTemp->Next->Next;}
The first part pTemp will be evaluated against NULL and followed by pTemp->Next. If pTemp->Next is placed first, the pointer pTemp will be dereferenced and there will be runtime error when pTemp is NULL.
It is mandatory to follow the order. Infact, it helps in generating efficient code. When the pointer pTemp is NULL, the second part will not be evaluated since the outcome of AND (&&) expression is guaranteed to be 0.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
C-Operators
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Function Pointer in C
Multidimensional Arrays in C / C++
Left Shift and Right Shift Operators in C/C++
Different Methods to Reverse a String in C++
Vector in C++ STL
Map in C++ Standard Template Library (STL)
Initialize a vector in C++ (7 different ways)
Set in C++ Standard Template Library (STL)
vector erase() and clear() in C++
Difference between readonly and const keyword in C#

12 May, 2021
In C#, a const keyword is used to declare constant fields and constant local. The value of the constant field is the same throughout the program or in other words, once the constant field is assigned the value of this field is not be changed. In C#, constant fields and locals are not variables, a constant is a number, string, null reference, boolean values.Example: 
CSharp
// C# program to illustrate the// use of const keywordusing System; class GFG {     // Constant fields    public const int myvar = 10;    public const string str = "GeeksforGeeks";     // Main method    static public void Main()    {         // Display the value of Constant fields        Console.WriteLine("The value of myvar: {0}", myvar);        Console.WriteLine("The value of str: {0}", str);    }}
Output:  
The value of myvar: 10
The value of str: GeeksforGeeks
In C#, you can use a readonly keyword to declare a readonly variable. This readonly keyword shows that you can assign the variable only when you declare a variable or in a constructor of the same class in which it is declared.Example: 
CSharp
// C# program to illustrate the use// of the readonly keywordusing System; class GFG {     // readonly variables    public readonly int myvar1;    public readonly int myvar2;     // Values of the readonly    // variables are assigned    // Using constructor    public GFG(int b, int c)    {         myvar1 = b;        myvar2 = c;        Console.WriteLine("Display value of myvar1 {0}, "+                        "and myvar2 {1}", myvar1, myvar2);    }     // Main method    static public void Main()    {        GFG obj1 = new GFG(100, 200);    }}
Output:  
Display value of myvar1 100, and myvar2 200
 
 
 
 
arorakashish0911
CSharp-keyword
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Sum of number digits in List

30 Jun, 2021
The problem of finding the summation of digits of numbers is quite common. This can sometimes come in form of a list and we need to perform that. This has application in many domains such as school programming and web development. Let’s discuss certain ways in which this problem can be solved. 
Method #1 : Using loop + str() This is brute force method to perform this particular task. In this, we run a loop for each element, convert each digit to string, and perform the count of the sum of each digit. 
Python3
# Python3 code to demonstrate# Sum of number digits in List# using loop + str() # Initializing listtest_list = [12, 67, 98, 34] # printing original listprint("The original list is : " + str(test_list)) # Sum of number digits in List# using loop + str()res = []for ele in test_list:    sum = 0    for digit in str(ele):        sum += int(digit)    res.append(sum)     # printing resultprint ("List Integer Summation : " + str(res))
The original list is : [12, 67, 98, 34]
List Integer Summation : [3, 13, 17, 7]
 
 Method #2 : Using sum() + list comprehension This task can also be performed using shorthand using above functionalities. The sum() is used to compute summation and list comprehension is used to compute iterations. 
Python3
# Python3 code to demonstrate# Sum of number digits in List# using sum() + list comprehension # Initializing listtest_list = [12, 67, 98, 34] # printing original listprint("The original list is : " + str(test_list)) # Sum of number digits in List# using sum() + list comprehensionres = list(map(lambda ele: sum(int(sub) for sub in str(ele)), test_list))     # printing resultprint ("List Integer Summation : " + str(res))
The original list is : [12, 67, 98, 34]
List Integer Summation : [3, 13, 17, 7]
 
Method #3 : Using sum() + reduce()This task can also be performed using shorthand using the above functionalities. The sum() is used to compute summation and reduce function from functools module.
Python3
# Python3 code to demonstrate# Sum of number digits in a List# using sum() + reduce()from functools import reduce # Initializing listtest_list = [12, 67, 98, 34] # printing original listprint("The original list is : " + str(test_list)) # Sum of number digits in List# using sum() + reduce()res = [reduce(lambda x, y: int(x) + int(y), list(str(i))) for i in test_list] # printing resultprint("List Integer Summation : " + str(res))
 Output:
The original list is : [12, 67, 98, 34]
List Integer Summation : [3, 13, 17, 7]
anjali pardeshi
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 ?
Python Classes and Objects
Python | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
JavaScript Error message Property

19 May, 2022
Below is the example of the Error message property.
Example: 
JavaScript
<script>    try {         alert("A computer science portal");        }     catch(err) {         document.write(err.message);        }</script>
Output:
allert is not defined
In JavaScript error message property is used to set or return the error message. 
Syntax:
errorObj.message
Return Value: It returns a string, representing the details of the error. More example codes for the above property are as follows: 
Example 1: This example does not contains any error so it does not display error message. 
html
<!DOCTYPE html><html>    <body style="text-align: center;">        <h1 style="color: green;">            GeeksforGeeks        </h1>         <h3>            JavaScript Error Message Property        </h3>         <p id="gfg"></p>         <script>            try {                alert("A computer science portal");            }            catch(err) {                document.getElementById("gfg").innerHTML                        = err.message;            }    </script>    </body></html>                   
Output:
  
Example 2: This example displays an error message when use misspelled ‘alert’ statement. 
html
<!DOCTYPE html><html>    <body style="text-align: center;">        <h1 style="color: green;">            GeeksforGeeks        </h1>         <h3>            JavaScript Error Message Property        </h3>         <p id="gfg"></p>         <script>            try {                popup("A computer science portal");            }            catch(err) {                document.getElementById("gfg").innerHTML                        = err.message;            }        </script>    </body></html>                        
Output:
  
Supported Browsers: The browser supported by JavaScript Error Message Property are listed below:
Google Chrome
Firefox
Internet Explorer
Opera
Safari
p741633
JavaScript-Properties
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js | fs.writeFileSync() Method
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
JavaScript | promise resolve() Method
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
REST API (Introduction)
How to fetch data from an API in ReactJS ?
WebAssembly - Working with C

In this chapter, we are going to compile a simple C program to javascript and execute the same in the browser.
For Example − C Program
#include<stdio.h> 
int square(int n) { 
   return n*n; 
}
We have done the installation of emsdk in folder wa/. In same folder, create another folder cprog/ and save above code as square.c.
We have already installed emsdk in the previous chapter. Here, we are going to make use of emsdk to compile the above c code.
Compile test.c in your command prompt as shown below −
emcc square.c -s STANDALONE_WASM –o findsquare.wasm

emcc command takes care of compiling the code as well as give you the .wasm code. We have used STANDALONE_WASM option that will give only the .wasm file.
Example − findsquare.html
<!doctype html> 
<html>
   <head>
      <meta charset="utf-8">
      <title>WebAssembly Square function</title>
      <style>
         div { 
            font-size : 30px; text-align : center; color:orange; 
         } 
      </style>
   </head> 
   <body>
      <div id="textcontent"></div>
      <script> 
      let square; fetch("findsquare.wasm").then(bytes => bytes.arrayBuffer()) 
      .then(mod => WebAssembly.compile(mod)) .then(module => {
         return new WebAssembly.Instance(module) 
      }) 
      .then(instance => {
         square = instance.exports.square(13); 
         console.log("The square of 13 = " +square);         
         document.getElementById("textcontent").innerHTML = "The square of 13 = " +square; 
      }); 
      </script>
   </body>
</html>
The output is as mentioned below −
Benefits of Double Division Operator over Single Division Operator in Python

24 Feb, 2020
The Double Division operator in Python returns the floor value for both integer and floating-point arguments after division.
# A Python program to demonstrate use of  # "//" for both integers and floating points  print(5//2)print(-5//2)print(5.0//2)
Output:
2
-3
2.0
The single division operator behaves abnormally generally for very large numbers. Consider the following example.
Examples 1:
# single divisionprint(1000000002/2)  # Gives wrong outputprint(int(((10 ** 17) + 2)/2))  # Gives Correct outputprint(((10 ** 17) + 2)//2)
Output:
500000001.0
50000000000000000
50000000000000001

Example 2:
x = 10000000000000000000006if int(x / 2) == x // 2:    print("Hello")else:    print("World")
Output:
World

The Output should have been Hello if the single division operator behaved normally because 2 properly divides x. But the output is World because The results after Single Division Operator and Double Division Operator ARE NOT THE SAME.
This fact can be used for programs such as finding the sum of first n numbers for a large n.
n = 10000000000  s1 = int(n * (n + 1) / 2)s2 = n * (n + 1) // 2  print("Sum using single division operator : ", s1)print("Sum using double division operator : ", s2)
Output:
Sum using single division operator :  50000000005000003584
Sum using double division operator :  50000000005000000000

Thus the result found by using the single division operator is Wrong, while the result found by using the double division operator is Correct. This is a huge benefit of Double Division Operator over Single Division Operator in Python.
python-basics
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Iterate over a list in Python
Python Classes and Objects
Convert integer to string in Python
Python OOPs Concepts
URL Encoding/Decoding using Base64 in Java

30 Jul, 2019
Base 64 is an encoding scheme that converts binary data into text format so that encoded textual data can be easily transported over network un-corrupted and without any data loss.(Base 64 format reference).
The URL encoding is the same as Basic encoding the only difference is that it encodes or decodes the URL and Filename safe Base64 alphabet and does not add any line separation.
URL encoding
String encodedURL = Base64.getUrlEncoder()
                       .encodeToString(actualURL_String.getBytes());

Explanation: In above code we called Base64.Encoder using getUrlEncoder() and then get the encoded URLstring by passing the byte value of actual URL in encodeToString() method as parameter.
URL decoding
byte[] decodedURLBytes = Base64.getUrlDecoder().decode(encodedURLString);

String actualURL= new String(decodedURLBytes);

Explanation: In above code we called Base64.Decoder using getUrlDecoder() and then decoded the URL string passed in decode() method as parameter then convert return value to actual URL.
Below programs illustrate the Encoding and Decoding URL in Java:
Program 1: URL encoding using Base64 class.
// Java program to demonstrate// URL encoding using Base64 class  import java.util.*;public class GFG {    public static void main(String[] args)    {        // create a sample url String to encode        String sampleURL = "https:// www.geeksforgeeks.org/";          // print actual URL String        System.out.println("Sample URL:\n"                           + sampleURL);          // Encode into Base64 URL format        String encodedURL = Base64.getUrlEncoder()                                .encodeToString(sampleURL.getBytes());          // print encoded URL        System.out.println("encoded URL:\n"                           + encodedURL);    }}
Sample URL:
https://www.geeksforgeeks.org/
encoded URL:
aHR0cHM6Ly93d3cuZ2Vla3Nmb3JnZWVrcy5vcmcv

Program 2: URL decoding using Base64 class.
// Java program to demonstrate// Decoding Basic Base 64 format to String  import java.util.*;public class GFG {    public static void main(String[] args)    {        // create a encoded URL to decode        String encoded = "aHR0cHM6Ly93d3cuZ2Vla3Nmb3JnZWVrcy5vcmcv";          // print encoded URL        System.out.println("encoded URL:\n"                           + encoded);          // decode into String URL from encoded format        byte[] actualByte = Base64.getUrlDecoder()                                .decode(encoded);          String actualURLString = new String(actualByte);          // print actual String        System.out.println("actual String:\n"                           + actualURLString);    }}
encoded URL:
aHR0cHM6Ly93d3cuZ2Vla3Nmb3JnZWVrcy5vcmcv
actual String:
https://www.geeksforgeeks.org/

References:
https://docs.oracle.com/javase/10/docs/api/java/util/Base64.html
https://www.geeksforgeeks.org/decode-encoded-base-64-string-ascii-string/
https://www.geeksforgeeks.org/encode-ascii-string-base-64-format/
Akanksha_Rai
Java 8
Java-Functions
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Move element to end of the list

12 Mar, 2019
The manipulation of lists is quite common in day-day programming. One can come across various issues where one wishes to perform using just one-liners. One such problem can be of moving a list element to the rear ( end of list ). Let’s discuss certain ways in which this can be done.
Method #1 : Using append() + pop() + index()This particular functionality can be performed in one line by combining these functions. The append function adds the element removed by pop function using the index provided by index function.
# Python3 code to demonstrate  # moving element to end # using append() + pop() + index()  # initializing listtest_list = ['3', '5', '7', '9', '11']  # printing original list print ("The original list is : " + str(test_list))  # using append() + pop() + index()# moving element to end test_list.append(test_list.pop(test_list.index(5)))  # printing resultprint ("The modified element moved list is : " + str(test_list))
The original list is : ['3', '5', '7', '9', '11']
The modified element moved list is : ['3', '7', '9', '11', '5']

 
Method #2 : Using sort() + key = (__eq__)The sort method can also be used to achieve this particular task in which we provide the key as equal to the string we wish to shift so that it is moved to the end.
# Python3 code to demonstrate  # moving element to end # using sort() + key = (__eq__)  # initializing listtest_list = ['3', '5', '7', '9', '11']  # printing original list print ("The original list is : " + str(test_list))  # using sort() + key = (__eq__)# moving element to end test_list.sort(key = '5'.__eq__)  # printing resultprint ("The modified element moved list is : " + str(test_list))
The original list is : ['3', '5', '7', '9', '11']
The modified element moved list is : ['3', '7', '9', '11', '5']

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
IntStream toArray() in Java with Examples - GeeksforGeeks

06 Dec, 2018
IntStream toArray() returns an array containing the elements of this stream. It is a terminal operation i.e, it may traverse the stream to produce a result or a side-effect. After the terminal operation is performed, the stream pipeline is considered consumed, and can no longer be used.
Syntax :
int[] toArray()

Return Value : The function returns an array containing the elements of this stream.
Example 1 :
// Java code for IntStream toArray()import java.util.*;import java.util.stream.IntStream;  class GFG {      // Driver code    public static void main(String[] args)    {        // Creating an IntStream        IntStream stream = IntStream.of(1, 3, 5, 7, 9);          // Using IntStream toArray()        int[] arr = stream.toArray();          // Displaying the elements in array arr        System.out.println(Arrays.toString(arr));    }}
Output :
[1, 3, 5, 7, 9]

Example 2 :
// Java code for IntStream toArray()import java.util.*;import java.util.stream.IntStream;  class GFG {      // Driver code    public static void main(String[] args)    {        // Creating an IntStream        IntStream stream = IntStream.range(-2, 10);          // Using IntStream toArray()        int[] arr = stream.toArray();          // Displaying the elements in array arr        System.out.println(Arrays.toString(arr));    }}
Output :
[-2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Java - util package
Java-Functions
java-intstream
java-stream
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Different ways of Reading a text file in Java
Constructors in Java
Stream In Java
Exceptions in Java
StringBuilder Class in Java with Examples
Comparator Interface in Java with Examples
Generics in Java
Functional Interfaces in Java
Java Programming Examples
HashMap get() Method in Java
fgetc() and fputc() in C

The function fgetc() is used to read the character from the file. It returns the character pointed by file pointer, if successful otherwise, returns EOF.
Here is the syntax of fgetc() in C language,
int fgetc(FILE *stream)
Here is an example of fgetc() in C language,
Let’s say we have “new.txt” file with the following content −
0,hell!o
1,hello!
2,gfdtrhtrhrt
3,demo
Now, let us see the example −
#include<stdio.h>
#include<conio.h>
void main() {
   FILE *f;
   char s;
   clrscr();
   f=fopen("new.txt","r");
   while((s=fgetc(f))!=EOF) {
      printf("%c",s);
   }
   fclose(f);
   getch();
}
Here is the output,
0,hell!o
1,hello!
2,gfdtrhtrhrt
3,demo
In the above program, we have a text file “new.txt”. A file pointer is used to open and read the file. It is displaying the content of file.
FILE *f;
char s;
clrscr();
f=fopen("new.txt","r");
The function fputc() is used to write the character to the file. It writes the character to the file, if successful otherwise, returns EOF.
Here is the syntax of fputc() in C language,
int fputc(int character, FILE *stream)
Here,
char − The character is to be written to the file.
stream − This is the pointer to the file where character is to be written.
Here is an example of fputc() in C language,
Let’s say we have “new.txt” file with the following content −
0,hell!o
1,hello!
2,gfdtrhtrhrt
3,demo
Now, let us see the example −
#include <stdio.h>
void main() {
   FILE *f;
   f = fopen("new.txt", "w");
   fputc('a',f);
   fclose(f);
}
The program will modify the “new.txt” file. It will not display any output to the screen but it will modify the file directly. You can check the modified file. The following text is the modified text of the file −
A
In the above program, the file pointer f is used to open the file “new.txt” and fputc() is used to write the character to the file.
FILE *f;
f = fopen("new.txt", "w");
fputc('a',f);
C Quiz - 101 | Question 5 - GeeksforGeeks

28 Jun, 2021
Consider the following variable declarations and definitions in C
i) int var_9 = 1;ii) int 9_var = 2;iii) int _ = 3;
Choose the correct statement w.r.t. above variables.(A) Both i) and iii) are valid.(B) Only i) is valid.(C) Both i) and ii) are valid.(D) All are valid.Answer: (A)Explanation: In C language, a variable name can consists of letters, digits and underscore i.e. _ . But a variable name has to start with either letter or underscore. It can’t start with a digit. So valid variables are var_9 and _ from the above question. Even two back to back underscore i.e. __ is also a valid variable name. Even _9 is a valid variable. But 9var and 9_ are invalid variables in C. This will be caught at the time of compilation itself. That’s why the correct answer is A).
 Quiz of this Question
C Quiz - 101
C-C Quiz - 101
C Language
C Quiz
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multidimensional Arrays in C / C++
Left Shift and Right Shift Operators in C/C++
fork() in C
Converting Strings to Numbers in C/C++
Core Dump (Segmentation fault) in C/C++
Operator Precedence and Associativity in C
C | File Handling | Question 1
C | Arrays | Question 7
C | Misc | Question 7
C | Pointer Basics | Question 14
Python | Check if a list exists in given list of lists - GeeksforGeeks

27 Mar, 2019
Given a list of lists, the task is to check if a list exists in given list of lists.
Input :
lst = [[1, 1, 1, 2], [2, 3, 4], [1, 2, 3], [4, 5, 6]]
list_search = [4, 5, 6]

Output:  True

Input :
lst = [[5, 6, 7], [12, 54, 9], [1, 2, 3]]
list_search = [4, 12, 54]

Output:  False

Let’s discuss certain ways in which this task is performed.
Method #1: Using CounterThe most concise and readable way to find whether a list exists in list of lists is using Counter.
# Python code find whether a list # exists in list of list.import collections  # Input List InitializationInput = [[1, 1, 1, 2], [2, 3, 4], [1, 2, 3], [4, 5, 6]]  # List to be searchedlist_search = [2, 3, 4]  # Flag initializationflag = 0   # Using Counterfor elem in Input:    if collections.Counter(elem) == collections.Counter(list_search) :        flag = 1      # Check whether list exists or not.    if flag == 0:    print("False")else:    print("True")
True

 Method #2: Using in
# Python code find whether a list # exists in list of list.  # Input List InitializationInput = [[1, 1, 1, 2], [2, 3, 4], [1, 2, 3], [4, 5, 6]]  # List to be searchedlist_search = [1, 1, 1, 2]  # Using in to find whether # list exists or notif list_search in Input:    print("True")else:    print("False")
True

 Method #3: Using any
# Python code find whether a list # exists in list of list.  # Input List InitializationInput = [[1, 1, 1, 2], [2, 3, 4], [1, 2, 3], [4, 5, 6]]  # List to be searchedlist_search = [4, 5, 6]  # Using any to find whether # list exists or notif any(list == list_search for list in Input):    print("True")else:    print("False")     
True

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python program to check whether a number is Prime or not
Learning to be precise | Practice | GeeksforGeeks

There are times when your answer is a floating point that contains undesired amount of digits after decimal. Here, we'll learn how to get a precise answer out of a floating number. You are given two floating numbers a and b. You need to output a/b and decimal precision of a/b upto 3 places after the decimal point.
Note: You may use setprecision and fixed.
Example:
Input:
a = 5.43
b = 2.653
Output:
2.04674 2.047
Explanation:
Value of a/b is printed with and 
without decimal precision.
 
User Task: 
Your task is to complete the provided function. 
Constraints:
1 <= a, b,<= 100
0
69406930ravi2 weeks ago
void precise(float a, float b)
{
  float r=a/b;
 
    cout<<r;
    cout<<" "<<setprecision(3)<<fixed<<r;
    
    cout<<endl;
}

0
manishv13 weeks ago
{   float c = a/b;   double d = a/b;   cout<< setprecision(6)<<c <<" " <<setprecision(4)<< d<<endl;      cout<<endl;}
0
tshreyastshreyas4 weeks ago
void precise(float a, float b){   float c;   c = a / b;//perform a/b      cout << setprecision(5)<<fixed<< c <<" "<< setprecision(3) << fixed<< c <<endl;      cout<<endl;}
0
shahabuddinbravo402 months ago
void precise(float a, float b){  cout<<setprecision(5)<<fixed<<a/b<<" "<<fixed<<setprecision(3)<<a/b<<endl;   cout<<endl;}https://www.geeksforgeeks.org/precision-of-floating-point-numbers-in-c-floor-ceil-trunc-round-and-setprecision/
0
mdsaif04052 months ago
void precise(float a, float b)
{
    cout<<a/b<<" "<<setprecision(3)<<fixed<<a/b<<endl;   
    cout<<endl;
}
-1
neerajjain071120023 months ago
void precise(float a, float b){   //perform a/b   float num=a/b;      cout<<fixed<<setprecision(5)<<num<<" "<<setprecision(3)<<num<<endl;      // cout<</*output the result of a/b here*/<<" "<</*use setprecision(3) here*/<</*use fixed here*/<</*Output c here*/<<endl;      cout<<endl;}
 
0
shivamsourav3 months ago
{      float c=a/b;   cout<<c<<" "<<setprecision(4)<<c<<endl;    cout<<endl;}
+1
bhabhilover26013 months ago
void precise(float a, float b)
{
    float c=a/b;
    
    cout<<a/b <<" "<< setprecision(3)<<fixed<<c<<endl;
    
   
}
0
gautambansal1283 months ago
float c=a/b;      cout<<c<<" "<< setprecision(3) <<fixed<<c <<endl;      cout<<endl;}
0
rushichoudhary994 months ago
why every code a giving wrong answer for multiple cases.
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 do I find the location of Python module sources?

For a pure python module you can find the location of the source files by looking at the module.__file__. For example,
 >>> import mymodule
>>> mymodule.__file__
C:/Users/Ayush/mymodule.py 
 Many built in modules, however,are written in C, and therefore module.__file__ points to a .so file (there is no module.__file__ on Windows), and therefore, you can't see the source. You can manually go and check the PYTHONPATH variable contents to find the directories from where these built in modules are being imported. 
 Running "python -v"from the command line tells you what is being imported and from where. This is useful if you want to know the location of built in modules.
How do we use a simple drop-down list of items in HTML forms?

With HTML, you can create a simple drop-down list of items to get user input in HTML forms. A select box also called drop-down box provides an option to list down various options in the form of drop-down list, from where a user can select one or more options. The <select> tag is used to create a drop-down list in HTML, with the <option> tag.
Here’s the list of attributes of <select> tag:
Here’s the list of attributes of <option> tag:
You can try to run the following to create a simple drop-down list of items to get user input in HTML forms:
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Select Box Control</title>
   </head>
   <body>
      <p>Here's the list of subjects. Select any one:</p>
      <form>
         <select name = "dropdown">
            <option value = "Computer Architecture" selected>Computer Architecture</option>
            <option value = "Java">Java</option>
            <option value = "Discrete Mathematics">Discrete Mathematics</option>
         </select>
      </form>
   </body>
</html>
Replace a letter with its alphabet position JavaScript

We are required to write a function that takes in a string, trims it off any whitespaces, converts it
to lowercase and returns an array of numbers describing corresponding characters positions in
the english alphabets, any whitespace or special character within the string should be ignored.
For example −
Input → ‘Hello world!’
Output → [8, 5, 12, 12, 15, 23, 15, 18, 12, 4]
The code for this will be −
const str = 'Hello world!';
const mapString = (str) => {
   const mappedArray = [];
   str
   .trim()
   .toLowerCase()
   .split("")
   .forEach(char => {
      const ascii = char.charCodeAt();
      if(ascii >= 97 && ascii <= 122){
         mappedArray.push(ascii - 96);
      };
   });
   return mappedArray;
};
console.log(mapString(str));
The output in the console will be −
[
   8, 5, 12, 12, 15,
   23, 15, 18, 12, 4
]
Which MySQL datatype to used to store an IP address?

We can store an IP address with the help of INT unsigned. While using INSERT, include INET_ATON() and with SELECT, include INET_NTOA(). IP address is in dotted format.
Let us see an example.
Creating a table.
mysql> create table IPV4AddressDemo
   -> (
   -> `IPV4Address` INT UNSIGNED
   -> );
Query OK, 0 rows affected (0.52 sec)
Inserting IP address into the table, with INET_ATON.
mysql> insert into IPV4AddressDemo values(INET_ATON("120.0.0.1"));
Query OK, 1 row affected (0.17 sec)
To display all records.
mysql> select *from IPV4AddressDemo;
The following is the output, but definitely we want it to be in IP address format.
+-------------+
| IPV4Address |
+-------------+
|  2013265921 |
+-------------+
1 row in set (0.00 sec)

As the above output is giving a sequence of integers, but we can convert them into the original IP address format. For that, use INET_NTOA
mysql> SELECT INET_NTOA(`IPV4Address`) FROM IPV4AddressDemo;
The following is the output that shows IP address in the actual format.
+--------------------------+
| INET_NTOA(`IPV4Address`) |
+--------------------------+
| 120.0.0.1                |
+--------------------------+
1 row in set (0.00 sec)
Python - find_element_by_id() method in Selenium - GeeksforGeeks

01 Jun, 2021
While performing any action on a web page using selenium, there is need of locators to perform specific tasks.Locators in web page are used to identify unique elements within a webpage. Web elements could be anything that the user sees on the page, such as title, table, links, buttons, toggle button, or any other HTML element.In order to find element by ID find_element_by_id() method is used. Id is basically unique attribute assigned to the elements of the web page such as buttons, image, heading etc.Syntax :  
driver.find_element_by_id(ID)
Argument :  
Takes ID in string format
Note :The first element with the ID attribute value matching the location will be returned. If no element has a matching ID attribute, a NoSuchElementException will be raised.Example 1 : – Consider the following page source :  
Below is the code for finding the element i.e “geek_id”  
Python3
#importing webdriver from seleniumfrom selenium import webdriver # Here Chrome  will be useddriver=webdriver.Chrome() # Opening the websitedriver.get(url) # finds button using its idform = driver.find_element_by_id('geek_id')
The form element can be located like this.Example : Source code of https://www.geeksforgeeks.org/ is given below.  
Below is the code for finding the scroll button with the help of its ID i.e scrollTopBtn.  
Python3
#importing webdriver from seleniumfrom selenium import webdriver # Here Chrome  will be useddriver=webdriver.Chrome() # URL of websiteurl = "https://www.geeksforgeeks.org/" # Opening the websitedriver.get(url) # finds button using its idbt = driver.find_element_by_id('scrollTopBtn')
With this code we can locate the scroll top button of this site. 
clintra
Python-selenium
selenium
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Read a file line by line in Python
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Reading and Writing to text files in Python
Python OOPs Concepts
Create a Pandas DataFrame from Lists
Th3Inspector - OSINT Tool for Reconnaissance - GeeksforGeeks

18 Jul, 2021
Th3 Inspector is an OSINT tool used for information gathering and reconnaissance which is available on Github. One can easily find a lot of information about the target, such as details about the server, whois info, target IP, mobile number, email, sub-domains, etc.
Open your terminal and type the following command to clone the tool.
git clone https://github.com/Moham3dRiahi/Th3inspector.git
To run this tool, we need to give the executable permissions to install.sh file, type the following command:
chmod +x install.sh && ./install.sh
Fig 1: Installation of Th3Inspector.
 Now, let’s run this tool by typing this in the terminal.
perl Th3Inspector.pl
Fig 2: Options provided by Th3Inspector.
Let us examine all the options available.
Target: www.google.com
Result:
Fig 3: Website information.
As we can see, this tool has provided us with the info regarding how many visitors per day visit Google.com, its hosting country, and address, its IP address, etc.
Target: +4158586273
Result:
Fig 4: Phone number Information:
Target: github.com
Result:
Fig 5:  Find IP address and Email Server.
Target: thehackernews.com
Result:
Fig 6: Domain Whois Lookup
Target: 104.215.148.63
Result:
Fig 7: IP address location.
Target: csfavorito.org
Result:
Fig 8: Bypass CLoudfare.
Target: youtube.com
Result:
Fig 9: Domain age checker.
Target: Mozilla/5.0 (x11; Ubuntu; Linux x86_64; rv:45.0)  Gecko/20100101 Firefox/45.0
Result:
Fig 10: User agent info.
Target: goair.in
Result:
Fig 11: Check Active Services on Resources.
Target: 474201
Result:
Fig 12: Credit card Bin Checker
Target: microsoft.com
Result:
Fig 13: Microsoft subdomains
Target: cyberpredator14@gmail.com
Result:
Fig 14: Valid E-Mail address.
Target: rentcarwithdriver.ro
Result:
Fig 15: Content Management System Checker.
We can see from the above examples that the Th3Inspector tool can prove to be very useful in finding information about the target. Tools like Th3Inspector are the complete package and offer a lot of options ranging from finding domain age or whether an email address is valid or not.So, it is a very powerful tool and should be used with the utmost care.
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
scp command in Linux with Examples
nohup Command in Linux with Examples
mv command in Linux with examples
Thread functions in C/C++
Docker - COPY Instruction
chown command in Linux with Examples
nslookup command in Linux with Examples
SED command in Linux | Set 2
Named Pipe or FIFO with example C program
uniq Command in LINUX with examples
Java How To Add Two Numbers

Learn how to add two numbers in Java:
int x = 5;
int y = 6;
int sum = x + y;
System.out.println(sum); // Print the sum of x + y
Learn how to add two numbers with user input:
import java.util.Scanner; // Import the Scanner class

class MyClass {
  public static void main(String[] args) {
    int x, y, sum;
    Scanner myObj = new Scanner(System.in); // Create a Scanner object
    System.out.println("Type a number:");
    x = myObj.nextInt(); // Read user input

    System.out.println("Type another number:");
    y = myObj.nextInt(); // Read user input

    sum = x + y;  // Calculate the sum of x + y
    System.out.println("Sum is: " + sum); // Print the sum
  }
} 
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.