code-rag-bench/online-tutorials huggingface dataset:
Elixir - Pattern Matching

Pattern matching is a technique which Elixir inherits form Erlang. It is a very powerful technique that allows us to extract simpler substructures from complicated data structures like lists, tuples, maps, etc.
A match has 2 main parts, a left and a right side. The right side is a data structure of any kind. The left side attempts to match the data structure on the right side and bind any variables on the left to the respective substructure on the right. If a match is not found, the operator raises an error.
The simplest match is a lone variable on the left and any data structure on the right. This variable will match anything. For example,
x = 12
x = "Hello"
IO.puts(x)
You can place variables inside a structure so that you can capture a substructure. For example, 
[var_1, _unused_var, var_2] = [{"First variable"}, 25, "Second variable" ]
IO.puts(var_1)
IO.puts(var_2)
This will store the values, {"First variable"} in var_1 and "Second variable" in var_2. There is also a special _ variable(or variables prefixed with '_') that works exactly like other variables but tells elixir, "Make sure something is here, but I don't care exactly what it is.". In the previous example, _unused_var was one such variable.
We can match more complicated patterns using this technique. For example if you want to unwrap and get a number in a tuple which is inside a list which itself is in a list, you can use the following command −
[_, [_, {a}]] = ["Random string", [:an_atom, {24}]]
IO.puts(a)
The above program generates the following result −
24

This will bind a to 24. Other values are ignored as we are using '_'.
In pattern matching, if we use a variable on the right, its value is used. If you want to use the value of a variable on the left, you'll need to use the pin operator.
For example, if you have a variable "a" having value 25 and you want to match it with another variable "b" having value 25, then you need to enter −
a = 25
b = 25
^a = b
The last line matches the current value of a, instead of assigning it, to the value of b. If we have a non-matching set of left and right hand side, the match operator raises an error. For example, if we try to match a tuple with a list or a list of size 2 with a list of size 3, an error will be displayed.

    35 Lectures 
     3 hours 

 Pranjal Srivastava

    54 Lectures 
     6 hours 

 Pranjal Srivastava, Harshit Srivastava

    80 Lectures 
     9.5 hours 

 Pranjal Srivastava

    43 Lectures 
     4 hours 

 Mohammad Nauman
 Print
 Add Notes
 Bookmark this page
Tensorflow.js tf.data.Dataset class .shuffle() Method - GeeksforGeeks

22 Apr, 2022
Tensorflow.js is an open-source library developed by Google for running machine learning models and deep learning neural networks in the browser or node environment.
The tf.data.Dataset.shuffle() method randomly shuffles a tensor along its first dimension.
Syntax:
tf.data.Dataset.shuffle(
    buffer_size, seed=None, 
    reshuffle_each_iteration=None
)
Parameters:
buffer_size: This is the number of elements from which the new dataset will be sampled.
seed[optional]: It is an optional parameter used to create a random seed for the distribution, to see the same results use same seed.
reshuffle_each_iteration: A Boolean, which is true indicates that the dataset should be pseudo randomly reshuffled each time it is iterated over. Default value is true. It is Optional parameter.
Return Value: A tensor with same shape and data type as value, but shuffled along its first dimension.
Example 1: In this example first we will create a tensor and then shuffle it, In this example reshuffle_each_iteration is True
Javascript
async function shuffle() {      // Creating a Tensor    const a = tf.data.array([1, 2, 3, 4, 5, 6]).shuffle(3);    await a.forEachAsync(e => console.log(e)); //print 1    await a.forEachAsync(e => console.log(e)); //print 2}  shuffle();
Output:
3 4 1 2 5 6
3 4 2 5 6 1
Example 2: In this example, seed is set to an Integer, whenever a specific integer is used it will generate that specific output
Javascript
async function shuffleseed() {    const a = tf.data.array([1, 2, 3]).shuffle(3, seed = 42);    await a.forEachAsync(e => console.log(e));      const b = tf.data.array([1, 2, 3]).shuffle(3, seed = 42);    await b.forEachAsync(e => console.log(e));}  shuffleseed();
Output:
2 1 3
2 1 3
Reference: https://js.tensorflow.org/api/3.6.0/#tf.data.Dataset.shuffle
rishikgoyal
Picked
Tensorflow.js
TensorFlow.js-Classes
TensorFlow.js-Data
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
How to filter object array based on attributes?
How to get selected value in dropdown list using JavaScript ?
How to remove duplicate elements from JavaScript Array ?
Installation of Node.js on Linux
Roadmap to Become a Web Developer in 2022
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to get Euler's constant value in JavaScript?

To get Euler’s constant value in JavaScript, use the Math E property. This is a Euler's constant and the base of natural logarithms, approximately 2.718.
You can try to run the following code to get Euler’s constant value in JavaScript −
Live Demo
<html>
   <head>
      <title>JavaScript Math E Property</title>
   </head>
   <body>
      <script>
         var property_value = Math.E
         document.write("Property Value is :" + property_value);
      </script>
   </body>
</html>
Property Value is :2.718281828459045
Tryit Editor v3.7

Tryit: HSL Lightness
Convert Integer to Hex String in Java

The Integer.toHexString() method in Java converts Integer to hex string.
Let’s say the following are our integer values.
int val1 = 5;
int val2 = 7;
int val3 = 13;
Convert the above int values to hex string.
Integer.toHexString(val1);
Integer.toHexString(val2);
Integer.toHexString(val3);
 Live Demo
public class Demo {
   public static void main(String[] args) {
      int val1 = 5;
      int val2 = 7;
      int val3 = 13;
      int val4 = 23;
      int val5 = 30;
      System.out.println("Converting integer "+val1+" to Hex String: "+Integer.toHexString(val1));
      System.out.println("Converting integer "+val2+" to Hex String: "+Integer.toHexString(val2));
      System.out.println("Converting integer "+val3+" to Hex String: "+Integer.toHexString(val3));
      System.out.println("Converting integer "+val4+" to Hex String: "+Integer.toHexString(val4));
      System.out.println("Converting integer "+val5+" to Hex String: "+Integer.toHexString(val5));
   }
}
Converting integer 5 to Hex String: 5
Converting integer 7 to Hex String: 7
Converting integer 13 to Hex String: d
Converting integer 23 to Hex String: 17
Converting integer 30 to Hex String: 1e
How to check the properties of the Windows PowerShell Console?

You can check the Powershell console properties in two ways. The first method is by right-clicking on the title bar and open the properties.
For Example,
You can find various properties there. Like Windows Size, Cursor size, Font Size, font colors, etc. But you can dynamically change the properties when the script runs using the RawUI properties in the $host UIconfiguration. You can view the properties of the console using the below command, which is the second method.
$host.UI.RawUI
ForegroundColor       : DarkYellow
BackgroundColor       : Black
CursorPosition        : 0,6
WindowPosition        : 0,0
CursorSize            : 25
BufferSize            : 120,3000
WindowSize            : 120,43
MaxWindowSize         : 120,44
MaxPhysicalWindowSize : 151,44
KeyAvailable          : False
WindowTitle           : Administrator: Windows PowerShell
Maximum Bitwise AND pair from given range in C++

Given a range [L, R], the task is to find a pair (X, Y) such that L ≤ X < Y ≤ R and X & Y is maximum among all the possible pairs then print the bitwise AND of the found pair.
If L = 1 and R = 10 then maximum bitwise AND value is 8 which can be formed as follows −
1000 # Binary representation of 8
Bitwise AND
1001 # Binary representation of 9
----
1000 # Final result
Iterate from L to R and check the bitwise AND for every possible pair and print the maximum value in the ends
Let us now see an example −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
int getMaxBitwiseAndValue(int L, int R) {
   int maxValue = L & R;
   for (int i = L; i < R; ++i) {
      for (int j = i + 1; j <= R; ++j) {
         maxValue = max(maxValue, (i & j));
      }
   }
   return maxValue;
}
int main() {
   int L = 1, R = 10;
   cout << "Maximum value = " << getMaxBitwiseAndValue(L, R) << endl;
   return 0;
}
Maximum value = 8
React-Bootstrap Image Component

26 Apr, 2021
React-Bootstrap is a front-end framework that was designed keeping react in mind. Image Component provides a way to put images in our application with the help of this Image Component. We can use the following approach in ReactJS to use the react-bootstrap Image Component.
Image Props:
fluid: It provides a way to set our image as fluid image.
rounded: It provides a way to set our image as a rounded shape.
roundedCircle: It provides a way to set our image as a circle shape.
thumbnail: It provides a way to set our image as a thumbnail shape.
bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:npx create-react-app foldername
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Step 3: After creating the ReactJS application, Install the required module using the following command:npm install react-bootstrap 
npm install bootstrap
Step 3: After creating the ReactJS application, Install the required module using the following command:
npm install react-bootstrap 
npm install bootstrap
Project Structure: It will look like the following.
Project Structure
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
App.js
import React from "react";import "bootstrap/dist/css/bootstrap.css";  import Image from "react-bootstrap/Image";  export default function App() {  return (    <div style={{ display: "block", width: 700, padding: 30 }}>      <h4>React-Bootstrap Image Component</h4>      <Image        src="https://media.geeksforgeeks.org/wp-content/uploads/20210425000233/test-300x297.png"        rounded      />      <Image        src="https://media.geeksforgeeks.org/wp-content/uploads/20210425000233/test-300x297.png"        roundedCircle      />    </div>  );}
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Reference: https://react-bootstrap.github.io/components/images/
React-Bootstrap
JavaScript
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
How to append HTML code to a div using JavaScript ?
How to fetch data from an API in ReactJS ?
How to redirect to another page in ReactJS ?
Axios in React: A Guide for Beginners
ReactJS Functional Components
Fetch fields from table or structure in ABAP SAP

If you need to identify the fields and number of fields in a structure, then you should use runtime type services. Using runtime type services makes more sense in this case as if we have some data in our environment, then it’s not ideal to call database for fetching the same.
DATA(structure) = VALUE <your structure>( )
DATA(Descriptor) = CAST cl_abap_structdescr( cl_abap_datadescr=>describe_by_data
                   (structure) )
DATA(Fields = LINES(Descriptor ->components ) 
This will give you the count of the components of the table or structure.
You can also try another option if you do not want to use runtime type services. Below query can get you’re the count
SELECT COUNT(*) INTO @data(count)
FROM DD03l (// this table stores the fields information of SAP tables)
WHERE tabname = <Structure name>
                AND AS4LOCAL = 'A'
TensorFlow – How to create a numpy ndarray from a tensor

01 Aug, 2020
TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning  neural networks.
To create a numpy array from Tensor, Tensor is converted to a proto tensor first.
Method Used:
make_ndarray: This method accepts a TensorProto as input and returns a numpy array with same content as TensorProto.
Example 1:
Python3
# importing the libraryimport tensorflow as tf  # Initializing Inputvalue = tf.constant([1, 15, 10], dtype = tf.float64)  # Printing the Inputprint("Value: ", value)  # Converting Tensor to TensorProtoproto = tf.make_tensor_proto(value)  # Generating numpy arrayres = tf.make_ndarray(proto)  # Printing the resulting numpy arrayprint("Result: ", res)
Output:
Value:  tf.Tensor([ 1. 15. 10.], shape=(3, ), dtype=float64)
Result:  [ 1. 15. 10.]


Example 2: This example uses a Tensor with shape (2, 2) so the shape of resulting array will be (2, 2).
Python3
# importing the libraryimport tensorflow as tf  # Initializing Inputvalue = tf.constant([[1, 2], [3, 4]], dtype = tf.float64)  # Printing the Inputprint("Value: ", value)  # Converting Tensor to TensorProtoproto = tf.make_tensor_proto(value)  # Generating numpy arrayres = tf.make_ndarray(proto)  # Printing the resulting numpy arrayprint("Result: ", res)
Output:
Value:  tf.Tensor(
[[1. 2.]
 [3. 4.]], shape=(2, 2), dtype=float64)
Result:  [[1. 2.]
 [3. 4.]]



Python-Tensorflow
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Pandas Series.div()

01 Oct, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Python Series.div() is used to divide series or list like objects with same length by the caller series.
Syntax: Series.div(other, level=None, fill_value=None, axis=0)
Parameters:other: other series or list type to be divided by the caller seriesfill_value: Value to be replaced by NaN in series/list before divisionlevel: integer value of level in case of multi index
Return type: Caller series with divided values
To download the data set used in following example, click here.In the following examples, the data frame used contains data of some NBA players. The image of data frame before any operations is attached below.
Example #1: Dividing Series by list
In this example, the top 5 rows are stored in new variable using .head() method. After that a list of same length is created and the age column is divided by the list column using .div() method
# importing pandas module import pandas as pd  # reading csv file from url data = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv")  # creating short data of 5 rowsshort_data = data.head()  # creating list with 5 valueslist =[1, 2, 3, 4, 5]  # Dividing by list data# creating new columnshort_data["Divided Age values"]= short_data["Age"].div(list)  # displayshort_data
Output:As shown in the output image, it can be compared that the Divided age value column is having the Divided values of (Age)/(list). Example #2: Dividing series by series having null values
In this example, the Salary column is divided by the Age column. Since the salary column contains null values too, by default it returns NaN no matter what is divided. In this example, 200000 is passed to replace null values with 200000.
# importing pandas module import pandas as pd  # reading csv file from url data = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv")  # passing age series to variableage = data["Age"]  # na replacementna = 200000  # Dividing values# storing to new columndata["Divided values"]= data["Salary"].div(other = age, fill_value = na)  # displaydata.head(10)
Output:As shown in the output image, the Divided values column has divided age column with 200000 in case of Null values.
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Relational Operators in Python

29 Aug, 2020
Relational operators are used for comparing the values. It either returns True or False according to the condition. These operators are also known as Comparison Operators.
Description
>
<
==
!=
>=
<=
Now Let’s see each Relational Operator one by one.
1) Greater than: This operator returns True if the left operand is greater than the right operand.
Syntax:
x > y

Example:
Python3
a = 9b = 5  # Outputprint(a > b)
Output:
True

2) Less than: This operator returns True if the left operand is less than the right operand.
Syntax:
x < y

Example:
Python3
a = 9b = 5  # Outputprint(a < b)
Output:
False

3) Equal to: This operator returns True if both the operands are equal i.e. if both the left and the right operand are equal to each other.
Example:
Python3
a = 9b = 5  # Outputprint(a == b)
Output:
False

4) Not equal to: This operator returns True if both the operands are not equal.
Syntax:
x != y

Example:
Python3
a = 9b = 5  # Outputprint(a != b)
Output:
True

5) Greater than or equal to: This operator returns True if the left operand is greater than or equal to the right operand.
Syntax:
x >= y

Example:
Python3
a = 9b = 5  # Outputprint(a >= b)
Output:
True

6) Less than or equal to: This operator returns True if the left operand is less than or equal to the right operand.
Syntax: 
x <= y

Example:
Python3
a = 9b = 5  # Outputprint(a <= b)
Output:
False

Python-Operators
Python
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()
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 dictionary with keys having multiple inputs

22 Sep, 2021
Prerequisite: Python-Dictionary. 
How to create a dictionary where a key is formed using inputs? Let us consider an example where have an equation for three input variables, x, y, and z. We want to store values of equation for different input triplets.
Example 1: 
Python3
# Python code to demonstrate a dictionary# with multiple inputs in a key.import random as rn # creating an empty dictionarydict = {} # Insert first triplet in dictionaryx, y, z = 10, 20, 30dict[x, y, z] = x + y - z; # Insert second triplet in dictionaryx, y, z = 5, 2, 4dict[x, y, z] = x + y - z; # print the dictionaryprint(dict)
Example 2: Let’s get access to the keys. Let us consider a dictionary where longitude and latitude are the keys and the place to which they belong to is the value.
Python3
# dictionary containing longitude and latitude of placesplaces = {("19.07'53.2", "72.54'51.0"):"Mumbai", \          ("28.33'34.1", "77.06'16.6"):"Delhi"} print(places)print('\n') # Traversing dictionary with multi-keys and creating# different lists from itlat = []long = []plc = []for i in places:    lat.append(i[0])    long.append(i[1])    plc.append(places[i[0], i[1]]) print(lat)print(long)print(plc)
Now that the keys(latitude, longitude) and values(place) are stored in a list, we can access it easily. 
gabaa406
Python dictionary-programs
python-dict
Python
python-dict
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
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Convert integer to string in Python
Select the maximum for each value in a MySQL table?

For this, use GROUP BY clause along with MAX(). Let us first create a table −
mysql> create table DemoTable
   -> (
   -> CountryName varchar(20),
   -> Population int
   -> );
Query OK, 0 rows affected (0.56 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('US',560);
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable values('UK',10090);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values('UK',8794);
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values('US',1090);
Query OK, 1 row affected (0.21 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-------------+------------+
| CountryName | Population |
+-------------+------------+
| US          |        560 |
| UK          |      10090 |
| UK          |       8794 |
| US          |       1090 |
+-------------+------------+
4 rows in set (0.00 sec)
Following is the query to select the maximum for each value in a MySQL table −
mysql> select CountryName,max(Population) from DemoTable group by CountryName;
This will produce the following output −
+-------------+-----------------+
| CountryName | max(Population) |
+-------------+-----------------+
| US          |            1090 |
| UK          |           10090 |
+-------------+-----------------+
2 rows in set (0.00 sec)
Mass Storage Management

Disks are the mainly used mass storage devices. They provide the bulk of secondary storage in operating systems today.
Each modern disk contains concentric tracks and each track is divided into multiple sectors. The disks are usually arranged as a one dimensional array of blocks, where blocks are the smallest storage unit.Blocks can also be called as sectors. For each surface of the disk, there is a read/write desk available. The same tracks on all the surfaces is known as a cylinder.
There are many disk scheduling algorithms that provide the total head movement for various requests to the disk. Here are the types of disk scheduling algorithms −
All these algorithms are explained using the following requests for the disk −
10,95,23,78,80
In first come first served scheduling, the requests are serviced in their coming order. This algorithm is fair as it allows all requests a chance but it does not provide the fastest possible service. An example of FCFS scheduling is given below −
In the above example, the requests are serviced in the order they appear i.e 10, 95, 23, 78, 80. The seek head is initially positioned at 50 and it starts from there.
The requests that are closest to the current head are served first before moving away in shortest seek time first scheduling algorithm. A problem with SSTF algorithm is that it may cause starvation for some requests. An example of Shortest Seek Time First Scheduling is given below −
In the above example, the requests are serviced in the order 23, 10, 78, 80, 95. The seek head is initially positioned at 50 and it starts from there. 23 is closest to 50 so it is services first. Then 10 is closer to 23 than 78 so it is services next. After this 78, 80 and 95 are serviced.
In this scheduling algorithm, the head moves towards one direction while servicing all the requests in that direction until it reaches the end of the disk. After that it starts moving towards the other direction. In this way, the head continuously scans back and forth across the disk. An example of SCAN scheduling is given below −
In the above example, the requests are serviced in the order 23, 10, 78, 80, 95. The head is initially at 50 and moves towards the left while servicing requests 23 and 10. When it reaches the end of the disk, it starts moving right and services 78, 80 and 95 as they occur.
LOOK scheduling algorithm is similar to SCAN scheduling but is its practical version. In this algorithm, the head moves towards one direction while servicing all the requests in that direction until it reaches the last request. After that it starts moving towards the other direction. An example of LOOK scheduling is given below −
In the above example, the requests are serviced in the order 23, 10, 78, 80, 95. The head is initially at 50 and moves towards the left while servicing requests 23 and 10. When it reaches the last request on the left i.e. 10, it starts moving right and services 78, 80 and 95 as they occur.
MATLAB - Basic Syntax

MATLAB environment behaves like a super-complex calculator. You can enter commands at the >> command prompt.
MATLAB is an interpreted environment. In other words, you give a command and MATLAB executes it right away.
Type a valid expression, for example,
5 + 5
And press ENTER
When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the result returned is −
ans = 10

Let us take up few more examples −
3 ^ 2	       % 3 raised to the power of 2
When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the result returned is −
ans = 9

Another example,
sin(pi /2)	  % sine of angle 90o

When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the result returned is −
ans = 1

Another example,
7/0		      % Divide by zero
When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the result returned is −
ans = Inf
warning: division by zero

Another example,
732 * 20.3	
When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the result returned is −
ans =  1.4860e+04

MATLAB provides some special expressions for some mathematical symbols, like pi for π, Inf for ∞, i (and j) for √-1 etc. Nan stands for 'not a number'.
Semicolon (;) indicates end of statement. However, if you want to suppress and hide the MATLAB output for an expression, add a semicolon after the expression.
For example,
x = 3;
y = x + 5
When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the result returned is −
y =  8

The percent symbol (%) is used for indicating a comment line. For example,
x = 9	     % assign the value 9 to x
You can also write a block of comments using the block comment operators % {  and % }.
The MATLAB editor includes tools and context menu items to help you add, remove, or change the format of comments.
MATLAB supports the following commonly used operators and special characters −
MATLAB supports the following special variables and constants −
Variable names consist of a letter followed by any number of letters, digits or underscore.
MATLAB is case-sensitive.
Variable names can be of any length, however, MATLAB uses only first N characters, where N is given by the function namelengthmax.
The save command is used for saving all the variables in the workspace, as a file with .mat extension, in the current directory.
For example,
save myfile

You can reload the file anytime later using the load command.
load myfile


    30 Lectures 
     4 hours 

 Nouman Azam

    127 Lectures 
     12 hours 

 Nouman Azam

    17 Lectures 
     3 hours 

 Sanjeev

    37 Lectures 
     5 hours 

 TELCOMA Global

    22 Lectures 
     4 hours 

 TELCOMA Global

    18 Lectures 
     3 hours 

 Phinite Academy
 Print
 Add Notes
 Bookmark this page
mailq Command in Linux with Examples - GeeksforGeeks

10 May, 2020
The name itself suggests, mailq i.e. “mail-queue”, this command in Linux prints the mail queue i.e the list of messages that are there in the mail queue. You should have a mail-server setup on your Linux machine, in order to use this command, there are ways i.e MTA’s(Mail Transfer agent) you can use like sendmail that uses the service smtp.
The output of mailq command is similar to the sendmail -bp command that also prints the mail queue.
Syntax:
mailq [options]
Examples:
1. maliq without any option: Simply prints the messages in the mail queue.
$ mailq

Output
 Mail Queue (1 request)
---QID---- --Size-- -----Q-Time----- ------Sender/Recipient-----
SS04506        5    Tue Nov 12 09:01            root
            (User unknown)

2. Prints along with priority specified: Simply prints the messages in the mail queue.
$ mailq -v

Output
 Mail Queue (1 request)
---QID---- --Size-- -Priority- -----Q-Time----- ------Sender/Recipient-----
SS04506        5      2005     Tue Nov 12 09:01            root
            (User unknown)

Here,
QID: Specific ID alloted to message.
Size: Number of bytes contained in body of message.
Q-Time Time at which message entered the queue.
Applications: In large applications at production env, email queuing is necessary as recipients are quite good in number, so sending the email to all at the same time becomes a risky thing, so mailq helps in looking out the sequence as per the priority.
linux-command
Picked
Linux-Unix
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
scp command in Linux with Examples
mv command in Linux with examples
chown command in Linux with Examples
Docker - COPY Instruction
nohup Command in Linux with Examples
Convert integer to string in Python
Convert string to integer in Python
How to set input type date in dd-mm-yyyy format using HTML ?
Python infinity
Matplotlib.pyplot.title() in Python
How to get parameter value from query string in ReactJS? - GeeksforGeeks

28 Dec, 2020
We can access query string via this.props.location.search then we can parse it using a library called query-string. This library has a parse() function that parses the query string and returns an object.
 For example, the query string is ?site=gfg&subject=react then after parsing object will be:
{
 Site:"gfg",
 Subject:"react"
}
Module Installation: Install the library using the following command:
npm install query-string 
Creating React Application:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. folder name, move to it using the following command:
cd foldername
Project Structure: It will look like the following.
Filename: App.js
Javascript
import React, { Component } from "react";// Importing Moduleimport queryString from 'query-string'  class App extends Component {    state = {    site: 'unknown',    subject: 'i dont know'  }    handleQueryString = () => {    // Parsing the query string     // Using parse method    let queries = queryString.parse(this.props.location.search)    console.log(queries)    this.setState(queries)  }    render() {    return (      <div style={{ margin: 200 }}>          <p> WebSite: {this.state.site} </p>            <p> Subject: {this.state.subject} </p>          <button          onClick={this.handleQueryString}          className='btn btn-primary'>          click me </button>      </div>    );  }}  export default App;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output:
You will see the following button and text on the screen:
You will see the following button and text on the screen:
After clicking on the button, the following will be the output:
After clicking on the button, the following will be the output:
Picked
react-js
JavaScript
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
How to get character array from string in JavaScript?
How to remove duplicate elements from JavaScript Array ?
How to get selected value in dropdown list using JavaScript ?
How to filter object array based on attributes?
Remove elements from a JavaScript Array
How to detect browser or tab closing in JavaScript ?
Lodash _.debounce() Method
Angular File Upload
What are Getters/Setters methods for Python Class?

Getters and setters are used in many object oriented programming languages to ensure the principle of data encapsulation. They are known as mutator methods as well. Data encapsulation is seen as the bundling of data with the methods that operate on these data. These methods are of course the getter for retrieving the data and the setter for changing the data. According to this principle, the attributes of a class are made private to hide and protect them from other code.
Unfortunately, it is widespread belief that a proper Python class should encapsulate private attributes by using getters and setters. Using getters and setters is not easy and elegant. The pythonic way to do this is to use properties or a class with property . A method which is used for getting a value is decorated with "@property". The method which has to function as the setter is decorated with "@x.setter". 
An example of using getters and setters is as follows
class P:
    def __init__(self,x):        
         self.__set_x(x)
    def __get_x(self):        
        return self.__x
    def __set_x(self, x):  
         if x < 0:            
           self.__x = 0  
        elif x > 1000:            
           self.__x = 1000        
        else:      
          self.__x = x
    x = property(__get_x, __set_x)
Python - Fill gaps in consecutive Records - GeeksforGeeks

02 Jun, 2020
Sometimes, while working with Python records, we can have a problem in which we have consecutive records, but a few missing and needs to be filled with any constant K. This kind of problem can have application in domains such as web development. Let’s discuss certain ways in which we need to perform this task.
Input :test_list = [(1, 4), (9, 11)]K = NoneOutput : [(1, 4), (2, None), (3, None), (4, None), (5, None), (6, None), (7, None), (8, None), (9, 11)]
Input :test_list = [(1, 4), (2, 11)]K = NoneOutput : [(1, 4), (2, 11)]
Method #1 : Using loopThis is one way in which this problem can be solved. In this, we check at each iteration if the element exists, if no, then it is filled with required value, if yes, the original value is retained.
# Python3 code to demonstrate working of # Fill gaps in consecutive Records# Using loop  # initializing listtest_list = [(1, 4), (3, 5), (4, 6), (7, 8), (9, 11)]  # printing original listprint("The original list is : " + str(test_list))  # initializing K valueK = "New"  # Fill gaps in consecutive Records# Using loopres = []cnt = 0for i, j in test_list:    if i - cnt > 1:        for k in range(cnt + 1, i):            res.append((k, K))    res.append((i, j))    cnt = i  # printing result print("The list after filling gaps : " + str(res)) 
The original list is : [(1, 4), (3, 5), (4, 6), (7, 8), (9, 11)]The list after filling gaps : [(1, 4), (2, ‘New’), (3, 5), (4, 6), (5, ‘New’), (6, ‘New’), (7, 8), (8, ‘New’), (9, 11)]
 
Method #2 : Using min() + max() + dict() + list comprehensionThis is yet another way in which this problem can be solved. In this, we check the range using min() and max() and use dictionary as a container of getting values that is required to fill in.
# Python3 code to demonstrate working of # Fill gaps in consecutive Records# Using min() + max() + dict() + list comprehension  # initializing listtest_list = [(1, 4), (3, 5), (4, 6), (7, 8), (9, 11)]  # printing original listprint("The original list is : " + str(test_list))  # initializing K valueK = "New"  # Fill gaps in consecutive Records# Using min() + max() + dict() + list comprehensiontest_list = dict(test_list)mini, maxi = min(test_list), max(test_list)res = [(idx, test_list.get(idx)) for idx in range(mini, maxi + 1)]  # printing result print("The list after filling gaps : " + str(res)) 
The original list is : [(1, 4), (3, 5), (4, 6), (7, 8), (9, 11)]The list after filling gaps : [(1, 4), (2, ‘New’), (3, 5), (4, 6), (5, ‘New’), (6, ‘New’), (7, 8), (8, ‘New’), (9, 11)]
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
Class forName() method in Java with Examples - GeeksforGeeks

01 Jun, 2021
The forName() method of java.lang.Class class is used to get the instance of this Class with the specified class name. This class name is specified as the string parameter.Syntax:  
public static Class<T> forName(String className) throws ClassNotFoundException
Parameter: This method accepts the parameter className which is the Class for which its instance is required.Return Value: This method returns the instance of this Class with the specified class name.Exception: This method throws following Exceptions:  
LinkageError: if the linkage fails
ExceptionInInitializerError: if the initialization provoked by this method fails
ClassNotFoundException: if the class cannot be located
Below programs demonstrate the forName() method.Example 1: 
Java
// Java program to demonstrate forName() method public class Test {    public static void main(String[] args)        throws ClassNotFoundException    {        // get the Class instance using forName method        Class c1 = Class.forName("java.lang.String");         System.out.print("Class represented by c1: "                         + c1.toString());    }}
Class represented by c1: class java.lang.String
 
Example 2: 
Java
// Java program to demonstrate forName() method public class Test {    public static void main(String[] args)        throws ClassNotFoundException    {        // get the Class instance using forName method        Class c1 = Class.forName("java.lang.Integer");         System.out.print("Class represented by c1: "                         + c1.toString());    }}
Class represented by c1: class java.lang.Integer
 
Reference: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#forName-java.lang.String- 
ruhelaa48
Java-Functions
Java-lang package
Java.lang.Class
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Interfaces in Java
Initialize an ArrayList in Java
ArrayList in Java
Stack Class in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java
Multithreading in Java
Collections in Java
How to set the style of the bottom border with JavaScript?

To set the style of the bottom border, use the JavaScript borderBottomStyle property. It allows you to add a bottom border.
You can try to run the following code to set the style of the bottom border −
<!DOCTYPE html>
<html>
   <body>
      <div id="box">Demo Text</div>
      <br>
      <button onclick="display()">Click to set style of bottom border</button>
      <script>
         function display() {
            document.getElementById("box").style.borderBottomStyle = "dashed";
         }
      </script>
   </body>
</html>
Saving images in Python at a very high quality

To save the images in Python with very high quality, you need to follow the steps given below −
Create fig and ax variables using subplots method, where default nrows and ncols are 1.
Create fig and ax variables using subplots method, where default nrows and ncols are 1.
Plot the lines using plot() method.
Plot the lines using plot() method.
We can add axes labels using ylabel() and xlabel().
We can add axes labels using ylabel() and xlabel().
To get a high-quality image, we can use .eps image format.
To get a high-quality image, we can use .eps image format.
You can increase the dot per inch value, i.e., dpi.
You can increase the dot per inch value, i.e., dpi.
Using savefig() method, we can save the image locally.
Using savefig() method, we can save the image locally.
To show the figure, use plt.show().
To show the figure, use plt.show().
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

plt.plot([0, 5], [0, 5])

plt.ylabel("Y-axis ")
plt.xlabel("X-axis ")

image_format = 'eps' # e.g .png, .svg, etc.
image_name = 'myimage.eps'

fig.savefig(image_name, format=image_format, dpi=1200)
Scala String indexOf() method with example

03 Oct, 2019
The indexOf() method is utilized to find the index of the first appearance of the character in the string and the character is present in the method as argument.
Method Definition: int indexOf(int ch)Return Type: It returns the index of the character stated in the argument.
Example #1:
// Scala program of int indexOf()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Applying indexOf method        val result = "Nidhi".indexOf('i')                  // Displays output        println(result)          }} 
1

So, here the first occurrence of ‘i’ is at index one So, 1 is returned as output.Example #2:
// Scala program of int indexOf()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Applying indexOf method        val result = "Nidhi".indexOf('h')                  // Displays output        println(result)          }} 
3

Scala
Scala-Method
Scala-Strings
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Pattern matcher() method in Java with examples

The java.util.regex package of java provides various classes to find particular patterns in character sequences.
The pattern class of this package is a compiled representation of a regular expression. The matcher() method of this class accepts an object of the CharSequence class representing the input string and, returns a Matcher object which matches the given string to the regular expression represented by the current (Pattern) object.
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MatcherExample {
   public static void main(String args[]) {
      //Reading string value
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter input string");
      String input = sc.nextLine();
      //Regular expression to find vowels
      String regex = "[aeiou]";
      //Compiling the regular expression
      Pattern pattern = Pattern.compile(regex);
      //Retrieving the matcher object
      Matcher matcher = pattern.matcher(input);
      if(matcher.find()) {
         System.out.println("Given string contains vowels");
      } else {
         System.out.println("Given string does not contain vowels");
      }
   }
}
Enter input string
RHYTHM
Given string does not contain vowels
SQL Tryit Editor v1.6

WHERE EXISTS (SELECT ProductName FROM Products WHERE Products.SupplierID = Suppliers.supplierID AND Price < 20);
​
Edit the SQL Statement, and click "Run SQL" to see the result.
This SQL-Statement is not supported in the WebSQL Database.
The example still works, because it uses a modified version of SQL.
Your browser does not support WebSQL.
Your are now using a light-version of the Try-SQL Editor, with a read-only Database.
If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time.
Our Try-SQL Editor uses WebSQL to demonstrate SQL.
A Database-object is created in your browser, for testing purposes.
You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button.
WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object.
WebSQL is supported in Chrome, Safari, Opera, and Edge(79).
If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
Remove a character from a Java StringBuffer object

In order to remove a character from a Java StringBuffer object, we use the deleteCharAt() method. The deleteCharAt() removes the character at the specified index. The length of resultant sequence of characters of the StringBuffer object is reduced by one.
Declaration − The java.lang.StringBuffer.deleteCharAt() method is declared as follows−
public StringBuffer deleteCharAt(int index)
Let us see a program to illustrate the use of the deleteCharAt()
 Live Demo
public class Example {
   public static void main(String[] args) {
      StringBuffer sb = new StringBuffer("Hello World");
      sb.deleteCharAt(7);
      System.out.println(sb);
   }
}
Hello Wrld
DAX Filter - ALLSELECTED function

ALLSELECTED function gets the context that represents all rows and columns in the query, while keeping explicit filters and contexts other than row and column filters.
This function can be used to obtain visual totals in queries.
ALLSELECTED ([<tableName> | <columnName>])

tableName
Optional.
The name of a table.
It cannot be an expression.
columnName
Optional.
The name of a column, usually fully qualified.
It cannot be an expression.
The context of the query without any column and row filters.
ALLSELECTED function takes one or no arguments.
ALLSELECTED function takes one or no arguments.
If there is one argument, the argument is either tableName or columnName.
If there is one argument, the argument is either tableName or columnName.
This function is different from the function ALL () because it retains all filters explicitly set within the query, and it retains all context filters other than row and column filters.
This function is different from the function ALL () because it retains all filters explicitly set within the query, and it retains all context filters other than row and column filters.
SumTotal:= CALCULATE (SUM (Sales[Sales Amount]),ALLSELECTED ()) 

    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
What is the difference between declaration and definition in C#?

Declaration means that variable is only declared and memory is allocated, but no value is set.
However, definition means the variables has been initialized.
The same works for variables, arrays, collections, etc.
Declaring a variable.
int x;
Let’s define and assign a value.
x = 10;

Declaring an array.
int [] n // declaring
int n= new int[10]; // initializing
Let’s assign a value.
n[0] = 100;
n[1] = 200
Represent Int64 as a Hexadecimal String in C#

To represent Int64 as a Binary string in C#, use the ToString() method and set the base as the ToString() method’s second parameter i.e.16 for Hexadecimal.
Int64 represents a 64-bit signed integer.
Firstly, set an Int64 variable.
long val = 947645;
Now, convert it to a hex string by including 16 as the second parameter.
Convert.ToString(val, 16)
Live Demo
using System;
class Demo {
   static void Main() {
      long val = 947645;
      Console.WriteLine("Long: "+val);
      Console.Write("Hex String: "+Convert.ToString(val, 16));
   }
}
Long: 947645
Hex String: e75bd