code-rag-bench/online-tutorials huggingface dataset:
SQL | ENCRYPT Function

31 Oct, 2019
The SQL Encrypt function is used to encrypt a string using UNIX crypt(). The function is based on Unix crypt() system call, hence it returns NULL on Windows systems. The Encrypt function accepts two parameters which are the string and the salt to be encrypted.The Encrypt function returns a binary string.
Syntax:
ENCRYPT(string, salt)
Parameters Used:
string – It is used to specify the plain text string that is to be encrypted using UNIX crypt().
salt – It is used to specify a string that is at least 2 characters long and cab be used in the encryption process. If salt is not provided, the ENCRYPT function uses a random value.
Return Value:The Encrypt function in SQL returns a binary string.
The Encrypt function returns null in the following cases:
If salt is less than 2 characters in length, then the Encrypt function returns NULL.
If the string is NULL, then the Encrypt function returns NULL.
If UNIX crypt() is not available on the system, then the Encrypt function returns NULL.
Supported Versions of MySQL:
MySQL 5.7
MySQL 5.6
MySQL 5.5
MySQL 5.1
MySQL 5.0
MySQL 4.1
Example-1: Implementing Encrypt function on a string.
SELECT 
ENCRYPT('xyz'); 
Output:
sf3Le/pz2ApNY 
Example-2: Implementing Encrypt function on a bigger string.
SELECT 
ENCRYPT('geeksforgeeks'); 
Output:
.mblNS3yOZxb2 
Example-3: Implementing Encrypt function on a string by passing both the arguments.
SELECT 
ENCRYPT('geeksforgeeks', '123'); 
Output:
12SrVMQf0pwFU 
Example-4: Implementing Encrypt function on a string by passing less than 2 characters in the salt argument.
SELECT 
ENCRYPT('geeksforgeeks', '2'); 
Output:
NULL 
Since the salt argument is less than 2 characters in length, the Encrypt function returns NULL.
Example-5: Implementing Encrypt function on a NULL string.
SELECT 
ENCRYPT(NULL); 
Output:
NULL 
SQL-Functions
SQLmysql
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
Window functions in SQL
SQL | Sub queries in From Clause
What is Temporary Table in SQL?
SQL using Python
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL Query to Convert VARCHAR to INT
RANK() Function in SQL Server
SQL Query to Compare Two Dates
SQL Query to Insert Multiple Rows
Restoring Division Algorithm For Unsigned Integer

22 Apr, 2020
A division algorithm provides a quotient and a remainder when we divide two number. They are generally of two type slow algorithm and fast algorithm. Slow division algorithm are restoring, non-restoring, non-performing restoring, SRT algorithm and under fast comes Newton–Raphson and Goldschmidt.
In this article, will be performing restoring algorithm for unsigned integer. Restoring term is due to fact that value of register A is restored after each iteration.
Here, register Q contain quotient and register A contain remainder. Here, n-bit dividend is loaded in Q and divisor is loaded in M. Value of Register is initially kept 0 and this is the register whose value is restored during iteration due to which it is named Restoring.
Let’s pick the step involved:
Step-1: First the registers are initialized with corresponding values (Q = Dividend, M = Divisor, A = 0, n = number of bits in dividend)
Step-2: Then the content of register A and Q is shifted left as if they are a single unit
Step-3: Then content of register M is subtracted from A and result is stored in A
Step-4: Then the most significant bit of the A is checked if it is 0 the least significant bit of Q is set to 1 otherwise if it is 1 the least significant bit of Q is set to 0 and value of register A is restored i.e the value of A before the subtraction with M
Step-5: The value of counter n is decremented
Step-6: If the value of n becomes zero we get of the loop otherwise we repeat from step 2
Step-7: Finally, the register Q contain the quotient and A contain remainder
Examples:
Perform Division Restoring Algorithm 
Dividend = 11
Divisor  = 3
Remember to restore the value of A most significant bit of A is 1. As that register Q contain the quotient, i.e. 3 and register A contain remainder 2.
ShubhamMaurya3
subhendu17620
Computer Organization & Architecture
Digital Electronics & Logic Design
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CSS scroll-margin-top property

07 Sep, 2020
The scroll-margin-top property is used to set all the scroll margins to the top of an element at once. The value specified for the scroll-margin-top determines how much of the page that is primarily outside the support should remain visible.
Hence, the scroll-margin-top values represent outsets that define the scroll snap area that is used for snapping this box to the support.
Syntax:
scroll-margin-top: length
/* Or */
scroll-margin-top: Global_Values

Property values: This property accepts two-properties mentioned above and described below:
length: This property refers to the values defined with length units: px, em, rem, vh, etc.
Global_Values: This property refers to the global values like initial, inherit, unset, etc.
Note: scroll-margin-top doesn’t accept percentage value as the length.
Example: In this example, you can see the effect of scroll-margin-top by scrolling to a point partway between two of the “interfaces” of the example’s content.
<!DOCTYPE html><html>      <head>    <style>          .page {                width:278px;                height:296px;                color: white;                font-size: 50px;                display: flex;                box-sizing: border-box;                align-items: center;                justify-content: center;                scroll-snap-align: end none;          }          .Container {                width: 300px;                height:300px;                overflow-x: hidden;                overflow-y: auto;                white-space: nowrap;                scroll-snap-type:y mandatory;          }    </style>        </head>  <body>          <div class="Container">                  <div class="page" style=               "background-color: rgb(20, 240, 38);                 scroll-margin-top: 0px;">                   Geeks            </div>                  <div class="page" style=               "background-color: green;                 scroll-margin-top: 20px;">                for          </div>                  <div class="page"                style="color: black;                scroll-margin-top: 40px;">                 Geeks            </div>                  <div class="page"                style=     "background-color: rgb(10, 207, 43);                scroll-margin-top: 30px;">                  for            </div>    </div>    </body></html>
Output:
Supported Browsers:
Chrome
Firefox
Opera
Edge
Internet Explorer (Not Supported)
Safari(partially supported)
CSS-Properties
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
jQuery | keyup() with Examples

13 Feb, 2019
The keyup() is an inbuilt method in jQuery which is used to trigger the keyup event whenever User releases a key from the keyboard. So, Using keyup() method we can detect if any key is released from the keyboard.
Syntax:
$(selector).keyup(function) 

Here selector is the selected element.
Parameters: It accepts an optional parameter as a function which gives the idea whether any key is pressed or not.
Return values: It returns whether any key is pressed or not and accordingly change the background color.
<html>  <head>    <title>Jquery | Keyup() </title>    <scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js">    </script></head><script>    $(document).keyup(function(event) {          alert('You released a key');    });</script>  <body>    <br>    <br>    <center>        <h1>Press and release a key from the keyboard </h1>    </center></body>  </html>
Output:After running the code:
After pressing any key from the keyboard-
Code: #2Below code is used to change background color of the page whenever a key is released from the keyboard
<html>  <head>    <title>Jquery | Keyup() </title>    <scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js">    </script></head><script>    var colors = ['red', 'blue', 'green', 'grey',                 'black', 'white', 'teal', 'yellow'];    var i = 0;    $(document).keyup(function(event) {          $('body').css('background-color', colors[i]);        i++;        i = i % 9;      });</script>  <body>    <br>    <br>    <center>        <h3>     Press any key from the keyboard and then release it <br>     to change the background color of the page</h3>    </center></body>  </html>                                       
Output:Before pressing a key:Every time When any key is pressed and released from the keyboard, The background colour of the page changes to a new colour-
After pressing and releasing any key:
jQuery-Events
JavaScript
JQuery
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
Remove elements from a JavaScript Array
Roadmap to Learn JavaScript For Beginners
Difference Between PUT and PATCH Request
JavaScript | Promises
JQuery | Set the value of an input text field
How to change selected value of a drop-down list using jQuery?
Form validation using jQuery
How to add options to a select element using jQuery?
jQuery | children() with Examples
Python | Corner detection with Harris Corner Detection method using OpenCV

08 Feb, 2022
Harris Corner detection algorithm was developed to identify the internal corners of an image. The corners of an image are basically identified as the regions in which there are variations in large intensity of the gradient in all possible dimensions and directions. Corners extracted can be a part of the image features, which can be matched with features of other images, and can be used to extract accurate information. Harris Corner Detection is a method to extract the corners from the input image and to extract features from the input image. About the function used:  
Syntax: cv2.cornerHarris(src, dest, blockSize, kSize, freeParameter, borderType)Parameters: src – Input Image (Single-channel, 8-bit or floating-point) dest – Image to store the Harris detector responses. Size is same as source image blockSize – Neighborhood size ( for each pixel value blockSize * blockSize neighbourhood is considered ) ksize – Aperture parameter for the Sobel() operator freeParameter – Harris detector free parameter borderType – Pixel extrapolation method ( the extrapolation mode used returns the coordinate of the pixel corresponding to the specified extrapolated pixel )
Below is the Python implementation :  
Python3
# Python program to illustrate# corner detection with# Harris Corner Detection Method # organizing importsimport cv2import numpy as np # path to input image specified and# image is loaded with imread commandimage = cv2.imread('GeekforGeeks.jpg') # convert the input image into# grayscale color spaceoperatedImage = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # modify the data type# setting to 32-bit floating pointoperatedImage = np.float32(operatedImage) # apply the cv2.cornerHarris method# to detect the corners with appropriate# values as input parametersdest = cv2.cornerHarris(operatedImage, 2, 5, 0.07) # Results are marked through the dilated cornersdest = cv2.dilate(dest, None) # Reverting back to the original image,# with optimal threshold valueimage[dest > 0.01 * dest.max()]=[0, 0, 255] # the window showing output image with cornerscv2.imshow('Image with Borders', image) # De-allocate any associated memory usageif cv2.waitKey(0) & 0xff == 27:    cv2.destroyAllWindows()
Input:  
Output:  
 
sweetyty
Image-Processing
OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Tryit Editor v3.7

CSS Math Functions
Tryit: Using the max() function
The netrc file processing using Python

The netrc class in python is used to read the data from the .netrc file presnt in unix systems in user’s home firectory. These are hidden files containing user’s login credential details. This is helpful for tool slike ftp, curl etc to successfully read the ,netrc file and use it for their actions.
The below program shows how we can read the .netrc file using python’s netrc module.
import netrc
netrc = netrc.netrc()
remoteHostName = "hostname"
authTokens = netrc.authenticators(remoteHostName)
# Print the access tokens
print("Remote Host Name:%s" % (remoteHostName))
print("User Name at remote host:%s" % (authTokens[0]))
print("Account Password:%s" % (authTokens[1]))
print("Password for the user name at remote host:%s" % (authTokens[2]))
# print the macros
macroDictionary = netrc.macros
print(macroDictionary)
Running the above code gives us the following result −
Remote Host Name:hostname
User Name at remote host:xxx
Account Password: XXX
Password for the user name at remote host:XXXXXX
Git Ignore and .gitignore

When sharing your code with others, there are often files or parts of your project, you do not want to share.
Examples
log files
temporary files
hidden files
personal files
etc.
Git can specify which files or parts of your project should be 
ignored by Git using a .gitignore file.
Git will not track files and folders specified in .gitignore. However, the .gitignore 
file itself IS tracked by Git.
To create a .gitignore file, go to the root of your local Git, and create it:
touch .gitignore
Now open the file using a text editor.
We are just going to add two simple rules:
Ignore any files with the .log extension
Ignore everything in any directory named temp
Now all .log files and anything in 
temp folders will be ignored by Git.
Note: In this case, we use a single .gitignore which applies to the entire repository.
 It is also possible to have additional .gitignore files in subdirectories. These only apply to files or folders within that directory.
Here are the general rules for matching patterns in .gitignore 
files: 
It is also possible to ignore files or folders but not show it in the 
distubuted .gitignore file.
These kinds of ignores are specified in the 
.git/info/exclude file. It works the same way as
.gitignore but are not shown to anyone else.
In .gitignore add a line to ignore all .temp files:



Start the Exercise
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.
Set file attributes in Java

One of the file attribute that can be set is to make the file read-only. This can be done by using the method java.io.File.setReadOnly(). This method requires no parameters and it returns true if the file is set to read-only and false otherwise.
The java.io.File.canRead() and java.io.File.canWrite() methods are used to check whether the file can be read or written to respectively.
A program that demonstrates this is given as follows −
 Live Demo
import java.io.File;
public class Demo {
   public static void main(String[] args) {
      try {
         File file = new File("demo1.txt");
         file.createNewFile();
         if (file.canRead())
            System.out.println("Readable");
         else
            System.out.println("Not Readable");
         if (file.canWrite())
            System.out.println("Writable");
         else
            System.out.println("Not Writable");
            file.setReadOnly();
         if (file.canRead())
            System.out.println("\nReadable");
         else
            System.out.println("\nNot Readable");
         if (file.canWrite())
            System.out.println("Writable");
         else
            System.out.println("Not Writable");
      } catch(Exception e) {
         e.printStackTrace();
      }
   }
}
The output of the above program is as follows −
Readable
Writable
Readable
Not Writable
endDrawer Widget in Flutter - GeeksforGeeks

13 Nov, 2020
The endDrawer is the panel displayed to the side of the body (Scaffold Widget). It is generally hidden in mobile devices. We can open it by swiping in from right to left, or we can customise it to open on-press of an icon or a button. This widget is similar to the already present Drawer widget in flutter except for the fact the Drawer by default open from left-to-right and the endDrawer by default opens from right-to-left. However, this direction can be changed by using textDirection property. 
Constructor of Drawer class:
Drawer({Key key,
double elevation, 
Widget child, 
String semanticLabel})





child: This property takes in a widget as a parameter to show below endDrawer widget in the tree.
hashCode: This property takes an int as the parameter. The hash code represents the state of the object that effects operator== comparison.
elevation: This property takes in a double value as a parameter to control the z-coordinate at which to place this drawer relative to its parent.
semanticLabel: This property takes in a string value a the parameter to create the semantic label of the dialog used by accessibility frameworks to announce screen transitions when the drawer is opened and closed.
main.dart
Dart
import 'package:flutter/material.dart'; void main() {  runApp(MyApp());}class MyApp extends StatelessWidget {     // This widget is the  // root of your application.  @override  Widget build(BuildContext context) {    return MaterialApp(      title: 'Flutter Demo',      theme: ThemeData(        primarySwatch: Colors.blue,      ),      home: MyHomePage(),      debugShowCheckedModeBanner: false,    );  }} class MyHomePage extends StatefulWidget {  @override  _MyHomePageState createState() => _MyHomePageState();}class _MyHomePageState extends State<MyHomePage> {  @override  Widget build(BuildContext context) {    return Scaffold(      appBar: AppBar(        title:Text("GeeksforGeeks"),        backgroundColor: Colors.green,      ),      endDrawer: Drawer(        child: ListView.builder(          itemBuilder: (            BuildContext context,int index){          return ListTile(            leading:Icon(Icons.list),            title: Text("GFG item $index"),            trailing: Icon(Icons.done),          );        }),        //elevation: 20.0,        //semanticLabel: 'endDrawer',      ),    );  }}
  
We create a Scaffold that contains an AppBar and Drawer.
Let’s add the endDrawer in our app. Child of Drawer is ListView.builder to build the list of items.
Create a List of items as shown above in the code.
Run the app and see the output.
 
Output:
 
 
ankit_kumar_
Flutter
Dart
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Flutter - DropDownButton Widget
Flutter - Custom Bottom Navigation Bar
Flutter - Checkbox Widget
Flutter - BoxShadow Widget
ListView Class in Flutter
Flutter - Flexible Widget
Operators in Dart
Flutter - Stack Widget
What is widgets in Flutter?
Android Studio Setup for Flutter Development
Is there any alternative for CONCAT() in MySQL?

Yes, an alternative is CONCAT_WS(). Let us first create a table −
mysql> create table DemoTable
   (
   StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   StudentName varchar(100)
   );
Query OK, 0 rows affected (0.74 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable(StudentName) values('Chris');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(StudentName) values('Robert');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable(StudentName) values('Bob');
Query OK, 1 row affected (0.12 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
| 1         | Chris       |
| 2         | Robert      |
| 3         | Bob         |
+-----------+-------------+
3 rows in set (0.00 sec)
Let us see how to work with an alternative of CONCAT() in MySQL −
mysql> select concat_ws(SPACE(2), 'Student Name is:',StudentName) from DemoTable;
+-----------------------------------------------------+
| concat_ws(SPACE(2), 'Student Name is:',StudentName) |
+-----------------------------------------------------+
| Student Name is: Chris                              |
| Student Name is: Robert                             |
| Student Name is: Bob                                |
+-----------------------------------------------------+
3 rows in set (0.04 sec)
scipy stats.mode() function | Python

11 Feb, 2019
scipy.stats.mode(array, axis=0) function calculates the mode of the array elements along the specified axis of the array (list in python).
Its formula –
where,
l : Lower Boundary of modal class
h : Size of modal class
fm : Frequency corresponding to modal class
f1 : Frequency preceding  to modal class
f2 : Frequency proceeding to modal class
Parameters :array : Input array or object having the elements to calculate the mode.axis : Axis along which the mode is to be computed. By default axis = 0
Returns : Modal values of the array elements based on the set parameters.
Code #1:
# Arithmetic mode  from scipy import statsimport numpy as np   arr1 = np.array([[1, 3, 27, 13, 21, 9],                [8, 12, 8, 4, 7, 10]])      print("Arithmetic mode is : \n", stats.mode(arr1)) 
Output :
Arithmetic mode is : 
 ModeResult(mode=array([[1, 3, 8, 4, 7, 9]]), count=array([[1, 1, 1, 1, 1, 1]]))
 Code #2: With multi-dimensional data
# Arithmetic mode from scipy import statsimport numpy as np   arr1 = [[1, 3, 27],         [3, 4, 6],         [7, 6, 3],         [3, 6, 8]]     print("Arithmetic mode is : \n", stats.mode(arr1))   print("\nArithmetic mode is : \n", stats.mode(arr1, axis = None))   print("\nArithmetic mode is : \n", stats.mode(arr1, axis = 0))   print("\nArithmetic mode is : \n", stats.mode(arr1, axis = 1)) 
Output :
Arithmetic mode is : 
 ModeResult(mode=array([[3, 6, 3]]), count=array([[2, 2, 1]]))

Arithmetic mode is : 
 ModeResult(mode=array([3]), count=array([4]))

Arithmetic mode is : 
 ModeResult(mode=array([[3, 6, 3]]), count=array([[2, 2, 1]]))

Arithmetic mode is : 
 ModeResult(mode=array([[1],
       [3],
       [3],
       [3]]), count=array([[1],
       [1],
       [1],
       [1]]))
Python scipy-stats-functions
Python-scipy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function
Java - valueOf() Method

The valueOf method returns the relevant Number Object holding the value of the argument passed. The argument can be a primitive data type, String, etc.
This method is a static method. The method can take two arguments, where one is a String and the other is a radix.
Following are all the variants of this method −
static Integer valueOf(int i)
static Integer valueOf(String s)
static Integer valueOf(String s, int radix)

Here is the detail of parameters −
i − An int for which Integer representation would be returned.
i − An int for which Integer representation would be returned.
s − A String for which Integer representation would be returned.
s − A String for which Integer representation would be returned.
radix − This would be used to decide the value of returned Integer based on the passed String.
radix − This would be used to decide the value of returned Integer based on the passed String.
valueOf(int i) − This returns an Integer object holding the value of the specified primitive.
valueOf(int i) − This returns an Integer object holding the value of the specified primitive.
valueOf(String s) − This returns an Integer object holding the value of the specified string representation.
valueOf(String s) − This returns an Integer object holding the value of the specified string representation.
valueOf(String s, int radix) − This returns  an Integer object holding the integer value of the specified string representation, parsed with the value of radix.
valueOf(String s, int radix) − This returns  an Integer object holding the integer value of the specified string representation, parsed with the value of radix.
public class Test { 

   public static void main(String args[]) {
      Integer x =Integer.valueOf(9);
      Double c = Double.valueOf(5);
      Float a = Float.valueOf("80");               
      Integer b = Integer.valueOf("444",16);

      System.out.println(x); 
      System.out.println(c);
      System.out.println(a);
      System.out.println(b);
   }
}
This will produce the following result −
Calling Python from C | Set 1

27 Mar, 2019
In this article, we will mainly focus on safe execution of a Python callable from C, returning a result back to C and writing C code that needs to access a Python function as a callback.
The code below focuses on the tricky parts that are involved in calling Python from C.
Code #1 : [Step 1 and 2] Own the GIL and Verify that function is a proper callable
#include <Python.h>  /* Execute func(x, y) in the Python interpreter. Thearguments and return result of the function mustbe Python floats */  double call_func(PyObject *func, double x, double y){    PyObject *args;    PyObject *kwargs;    PyObject *result = 0;    double retval;          // Make sure we own the GIL    PyGILState_STATE state = PyGILState_Ensure();                // Verify that func is a proper callable    if (!PyCallable_Check(func))    {        fprintf(stderr, "call_func: expected a callable\n");        goto fail;    }
 Code #2 : Building Arguments, calling function, Check for Python exceptions
Create the return value, Restore previous GIL state and return.
    // Step3    args = Py_BuildValue("(dd)", x, y);    kwargs = NULL;          // Step 4    result = PyObject_Call(func, args, kwargs);    Py_DECREF(args);    Py_XDECREF(kwargs);          // Step 5    if (PyErr_Occurred())    {        PyErr_Print();        goto fail;    }          // Verify the result is a float object     if (!PyFloat_Check(result))    {        fprintf(stderr, "call_func: callable didn't return a float\n");        goto fail;    }          // Step 6    retval = PyFloat_AsDouble(result);    Py_DECREF(result);          // Step 7    PyGILState_Release(state);    return retval;    fail:        Py_XDECREF(result);        PyGILState_Release(state);        abort(); }
A reference to an existing Python callable needs to be passed in, to use this function. To do that there are many ways like – simply writing C code to extract a symbol from an existing module or having a callable object passed into an extension module. The code given below shows calling a function from an embedded Python interpreter.
Code #3 : Loading a symbol from a module
#include <Python.h>/* Definition of call_func() same as above */  /* Load a symbol from a module */PyObject *import_name(const char *modname, const char *symbol){    PyObject *u_name, *module;    u_name = PyUnicode_FromString(modname);    module = PyImport_Import(u_name);    Py_DECREF(u_name);          return PyObject_GetAttrString(module, symbol);}
Python-ctype
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 ?
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Introduction To PYTHON
void pointer in C

The void pointer in C is a pointer which is not associated with any data types. It points to some data location in the storage means points to the address of variables. It is also called general purpose pointer. In C, malloc() and calloc() functions return void * or generic pointers.
It has some limitations −
1) Pointer arithmetic is not possible with void pointer due to its concrete size.
2) It can’t be used as dereferenced.
Begin
   Declare a of the integer datatype.
      Initialize a = 7.
   Declare b of the float datatype.
      Initialize b = 7.6.
   Declare a pointer p as void.
   Initialize p pointer to a.
   Print “Integer variable is”.
      Print the value of a using pointer p.
   Initialize p pointer to b.
   Print “Float variable is”.
      Print the value of b using pointer p
End.
Here is a simple example −
 Live Demo
#include<stdlib.h>
int main() {
   int a = 7;
   float b = 7.6;
   void *p;
   p = &a;
   printf("Integer variable is = %d", *( (int*) p) );
   p = &b;
   printf("\nFloat variable is = %f", *( (float*) p) );
   return 0;
}
Integer variable is = 7
Float variable is = 7.600000
PostgreSQL – ROW_NUMBER Function

10 Feb, 2021
In PostgreSQL, the ROW_NUMBER() function is used to assign a unique integer to every row that is returned by a query.
Syntax:
ROW_NUMBER() OVER(
    [PARTITION BY column_1, column_2, ...]
    [ORDER BY column_3, column_4, ...]
)
Let’s analyze the above syntax:
The set of rows on which the ROW_NUMBER() function operates is called a window.
The PARTITION BY clause is used to divide the query set results. 
The ORDER BY clause inside the OVER clause is used to set the order in which the query result will be displayed.
Example 1:
First, create two tables named mammals and Animal_groups:
CREATE TABLE Animal_groups (
    animal_id serial PRIMARY KEY,
    animal_name VARCHAR (255) NOT NULL
);

CREATE TABLE Mammals (
    mammal_id serial PRIMARY KEY,
    mammal_name VARCHAR (255) NOT NULL,
    lifespan DECIMAL (11, 2),
    animal_id INT NOT NULL,
    FOREIGN KEY (animal_id) REFERENCES Animal_groups (animal_id)
);

Now add some data to it:
INSERT INTO Animal_groups (animal_name)
VALUES
    ('Terrestrial'),
    ('Aquatic'),
    ('Winged');

INSERT INTO Mammals(mammal_name, animal_id, lifespan)
VALUES
    ('Cow', 1, 10),
    ('Dog', 1, 7),
    ('Ox', 1, 13),
    ('Wolf', 1, 11),
    ('Blue Whale', 2, 80),
    ('Dolphin', 2, 5),
    ('Sea Horse', 2, 3),
    ('Octopus', 2, 8),
    ('Bat', 3, 4),
    ('Flying Squirrels', 3, 1),
    ('Petaurus', 3, 2);
In the following query, we change the column in the ORDER BY clause to product_name, the ROW_NUMBER() function assigns the integer values to each row based on the product name order
SELECT
    mammal_id,
    mammal_name,
    animal_id,
    ROW_NUMBER () OVER (
           ORDER BY mammal_name
        )
FROM
    Mammals;
Output:
Example 2:
The following query uses the ROW_NUMBER() function to assign integers to the distinct prices from the products table:
SELECT DISTINCT
    lifespan,
    ROW_NUMBER () OVER (ORDER BY lifespan)
FROM
    Mammals
ORDER BY
    lifespan;
Output:
PostgreSQL-function
PostgreSQL-Window-function
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Check for Descending Sorted List

11 May, 2020
The sorted operation of list is essential operation in many application. But it takes best of O(nlogn) time complexity, hence one hopes to avoid this. So, to check if this is required or not, knowing if list is by default reverse sorted or not, one can check if list is sorted or not. Lets discuss various ways this can be achieved.
Method #1 : Naive methodThe simplest way to check this is run a loop for first element and check if we could find any larger element than it after that element, if yes, the list is not reverse sorted.
# Python3 code to demonstrate # Check for Descending Sorted List# using naive method   # initializing listtest_list = [10, 8, 4, 3, 1]  # printing original list print ("Original list : " + str(test_list))  # using naive method to # Check for Descending Sorted Listflag = 0i = 1while i < len(test_list):    if(test_list[i] > test_list[i - 1]):        flag = 1    i += 1      # printing resultif (not flag) :    print ("Yes, List is reverse sorted.")else :    print ("No, List is not reverse sorted.")
Original list : [10, 8, 4, 3, 1]
Yes, List is reverse sorted.

 
Method #2 : Using sort() + reverseThe new list can be made as a copy of the original list, sorting the new list and comparing with the old list will give us the result if sorting was required to get reverse sorted list or not.
# Python3 code to demonstrate # Check for Descending Sorted List# using sort() + reverse  # initializing listtest_list = [10, 5, 4, 3, 1]  # printing original list print ("Original list : " + str(test_list))  # using sort() + reverse to # Check for Descending Sorted Listflag = 0test_list1 = test_list[:]test_list1.sort(reverse = True)if (test_list1 == test_list):    flag = 1      # printing resultif (flag) :    print ("Yes, List is reverse sorted.")else :    print ("No, List is not reverse sorted.")
Original list : [10, 8, 4, 3, 1]
Yes, List is reverse sorted.

Python list-programs
Python-Sorted
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 OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
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
How to write to an HTML file in Python ?

26 Mar, 2021
Python language has great uses today in almost every field, it can be used along with other technologies to make our lives easier. One such use of python is getting the data output in an HTML file.
We can save any amount of our input data into an HTML file in python using the following examples in two ways.
Example 1: Creating an HTML file and saving the input data into it.
Approach:
Creating an HTML file.
Function_Name = open("Complete_File_Name","File_operation")
Adding input data in HTML format into the file.
Function_Name.write("Adding_Input_data_using_HTML_Synatx_separted_by_/n")
Saving the HTML file.
Function_Name.close()
Opening the HTML file from the saved location.
Below is the implementation:
Python3
# Creating an HTML fileFunc = open("GFG-1.html","w")   # Adding input data to the HTML fileFunc.write("<html>\n<head>\n<title> \nOutput Data in an HTML file \           </title>\n</head> <body><h1>Welcome to <u>GeeksforGeeks</u></h1>\           \n<h2>A <u>CS</u> Portal for Everyone</h2> \n</body></html>")              # Saving the data into the HTML fileFunc.close()
Output:
GFG-1.html file is created in the folder
Checking the Output data of the GFG-1.html file
Example 2: Creating and Saving an HTML file and then adding input data to it.
Approach:
Creating an HTML file and saving it.
Function_Name = open("Complete_File_Name","File_operation")
Function_Name.close()
Opening the HTML file from the saved location.
Now adding input data into the created HTML file.
Function_Name = open(File_Location,"File_operation")
Function_Name.write("Adding_Input_data_using_HTML_Synatx_separted_by_/n")
Saving the HTML file.
Function_Name.close()
Opening the HTML file from the saved location again to check the output data.
Below is the implementation:
Python3
# Opening the existing HTML fileFunc = open("GFG-2.html","w")  # Adding input data to the HTML fileFunc.write("<html>\n<head>\n<title> \nOutput Data in an HTML file\n \           </title>\n</head> <body> <h1>Welcome to \           <font color = #00b300>GeeksforGeeks</font></h1>\n \           <h2>A CS Portal for Everyone</h2>\n</body></html>")  # Saving the data into the HTML fileFunc.close()
Output:
Input data is saved into the GFG-2.html file
Checking the Output data of the GFG-2.html file
We’ve successfully saved and output data into an HTML file using a simple function in python. Any one of the above methods can be used to get the desired result.
Picked
python-file-handling
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js Buffer.writeUInt8() Method

13 Oct, 2021
The Buffer.writeUInt8() method is an inbuilt application programming interface of class Buffer within Buffer module which is used to write values to buffer at the specified offset. The value should be a valid unsigned 8-bit integer otherwise behavior is undefined.
Syntax:
Buffer.writeUInt8( value, offset )
Parameters: This method accepts two parameters as mentioned above and described below:
value: The unsigned integer value that to be written into buffer.
offset: It denotes the number of bytes to skipped before starting to write to buffer. The offset can be in range 0 <= offset <= buf.length – 1. The default value of offset is 0.
Return value: It returns the buffer with the value inserted at the specified offset.
Below examples illustrate the use of Buffer.writeUInt8() Method in Node.js:
Example 1:
// Node.js program to demonstrate the // Buffer.writeUInt8() method       // Creating a buffer const buf = Buffer.allocUnsafe(5);  // Using Buffer.writeUInt8() methodbuf.writeUInt8(0x14, 0);  // Display the bufferconsole.log(buf);   // Using Buffer.writeUInt8() methodbuf.writeUInt8(0x15, 1);  // Display the bufferconsole.log(buf);   // Using Buffer.writeUInt8() methodbuf.writeUInt8(0x16, 4);  // Display the bufferconsole.log(buf);   // Using Buffer.writeUInt8() methodbuf.writeUInt8(0x17, 3);  // Display the bufferconsole.log(buf);   // Using Buffer.writeUInt8() methodbuf.writeUInt8(0x18, 2);      // Display the result console.log(buf); 
Output:
<Buffer 14 00 00 00 d6>
<Buffer 14 15 00 00 d6>
<Buffer 14 15 00 00 16>
<Buffer 14 15 00 17 16>
<Buffer 14 15 18 17 16>

Example 2:
// Node.js program to demonstrate the // Buffer.writeUInt8() method       // Creating a buffer const buf = Buffer.allocUnsafe(3);  // Using Buffer.writeUInt8() methodbuf.writeUInt8(0x11, 0);  // Display the bufferconsole.log(buf);   // Using Buffer.writeUInt8() methodbuf.writeUInt8(0x22, 1);  // Display the bufferconsole.log(buf);   // Using Buffer.writeUInt8() methodbuf.writeUInt8(0x33, 2);  // Display the bufferconsole.log(buf); 
Output:
<Buffer 11 e7 31>
<Buffer 11 22 31>
<Buffer 11 22 33>

Note: The above program will compile and run by using the node index.js command.
Reference: https://nodejs.org/dist/latest-v13.x/docs/api/buffer.html#buffer_buf_writeuint8_value_offset
Node.js-Buffer-module
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Moving a file from one directory to another using Java

We can use Files.move() API to move file from one directory to another. Following is the syntax of the move method.
public static Path move(Path source,Path target,CopyOption... options) throws IOException
Where
source − Source path of file to be moved
source − Source path of file to be moved
target − Target path of file to be moved
target − Target path of file to be moved
options − options like REPLACE_EXISTING, ATOMIC_MOVE
options − options like REPLACE_EXISTING, ATOMIC_MOVE
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Tester {
   public static void main(String[] args) {
      //move file from D:/temp/test.txt to D:/temp1/test.txt
      //make sure that temp1 folder exists
      moveFile("D:/temp/test.txt", "D:/temp1/test.txt");
   }
   private static void moveFile(String src, String dest ) {
      Path result = null;
      try {
         result = Files.move(Paths.get(src), Paths.get(dest));
      } catch (IOException e) {
         System.out.println("Exception while moving file: " + e.getMessage());
      }
      if(result != null) {
         System.out.println("File moved successfully.");
      }else{
         System.out.println("File movement failed.");
      }
   }
}
File moved successfully.
How to change each column width of a JTable in Java?

A JTable is a subclass of JComponent for displaying complex data structures.
A JTable can follow the Model View Controller (MVC) design pattern for displaying the data in rows and columns.
The DefaultTableModel class can extend AbstractTableModel and it can be used to add the rows and columns to a JTable dynamically.
The DefaultTableCellRenderer class can extend JLabel class and it can be used to add images, colored text and etc. inside the JTable cell.
A JTable can generate TableModelListener, TableColumnModelListener, ListSelectionListener, CellEditorListener, RowSorterListener interfaces.
By default the width of a JTable is fixed, we can also change the width of each column by using table.getColumnModel().getColumn().setPreferredWidth() method of JTable class.
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
public class JTableTest extends JFrame {
   private JTable table;
   private JScrollPane scrollPane;
   private DefaultTableModel model;
   private DefaultTableCellRenderer cellRenderer;
   public JTableTest() {
      setTitle("JTable Test");
      setLayout(new FlowLayout());
      scrollPane = new JScrollPane();
      JTable table = new JTable();
      scrollPane.setViewportView(table);
      model = (DefaultTableModel)table.getModel();
      model.addColumn("S.No");
      model.addColumn("First Name");
      model.addColumn("Last Name");
      model.addColumn("Email");
      model.addColumn("Contact");
      for(int i = 0;i < 4; i++) {
         model.addRow(new Object[0]);
         model.setValueAt(i+1, i, 0);
         model.setValueAt("Tutorials", i, 1);
         model.setValueAt("Point", i, 2);
         model.setValueAt("@tutorialspoint.com", i, 3);
         model.setValueAt("123456789", i, 4);
      }
      // set the column width for each column
      table.getColumnModel().getColumn(0).setPreferredWidth(5);
      table.getColumnModel().getColumn(3).setPreferredWidth(100);
      cellRenderer = new DefaultTableCellRenderer();
      cellRenderer.setHorizontalAlignment(JLabel.CENTER);
      table.getColumnModel().getColumn(0).setCellRenderer(cellRenderer);
      add(scrollPane);
      setSize(475, 250);
      setResizable(false);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setLocationRelativeTo(null);
      setVisible(true);
   }
   public static void main(String[] args) {
      new JTableTest();
   }
}
How to get the number of seconds between two Dates in JavaScript?

To get the number of seconds between two dates, use the Maths.abs() method.
You can try to run the following code to get seconds between two dates −
Live Demo
<html>
   <head>
      <title>JavaScript Get Seconds</title>
   </head>
   <body>
      <script>
         var date1, date2;
         date1 = new Date();
         document.write(""+date1);
         date2 = new Date( "Dec 10, 2015 20:15:10" );
         document.write("<br>"+date2);
         // get total seconds between two dates
         var seconds = Math.abs(date1 - date2) / 1000;
         document.write("<br>Difference between 2 dates: "+seconds);
      </script>
   </body>
</html>
Mon May 28 2018 09:35:25 GMT+0530 (India Standard Time)
Thu Dec 10 2015 20:15:10 GMT+0530 (India Standard Time)
Difference between 2 dates: 77721615.573
Setting the Image Brightness using CSS3

To set image brightness in CSS, use filter brightness(%). Remember, the value 0 makes the image black, 100% is for original image and default. Rest, you can set any value of your choice, but values above 100% would make the image brighter.
Let us now see an example −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
img.demo {
   filter: brightness(120%);
}
</style>
</head>
<body>
<h1>Learn MySQL</h1>
<img src="https://www.tutorialspoint.com/mysql/images/mysql-mini-logo.jpg" alt="MySQL" width="160" height="150">
<h1>Learn MySQL</h1>
<p>Below image is brighter than the original image above.</p>
<img class="demo" src="https://www.tutorialspoint.com/mysql/images/mysql-mini-logo.jpg" alt="MySQL" width="160" height="150">
</body>
</html>
How to count number of columns in a table with jQuery

To count number of columns in a table with jQuery, use the each() function with attr(). You can try to run the following code to learn how to count column in a table:
Live Demo
<html>
  <head>
    <title>jQuery Example</title>
    <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script>
    $(document).ready(function(){
      var num = 0;
      $('tr:nth-child(1) td').each(function () {
        if ($(this).attr('colspan')) {
          num += +$(this).attr('colspan');
        } else {
        num++;
      }
    });
   alert("Total Columns= "+num);
});
</script>
</head>
<body>
  <table>
  <tr>
    <td>-1st column-</td>
    <td colspan="1">-2nd column-</td>
    <td colspan="1">-3rd column-</td>
  <tr>
  </table>
</body>
</html
Laravel - Redirections

Named route is used to give specific name to a route. The name can be assigned using the “as” array key.
Route::get('user/profile', ['as' => 'profile', function () {
   //
}]);

Note − Here, we have given the name profile to a route user/profile.
Observe the following example to understand more about Redirecting to named routes −
Step 1 − Create a view called test.php and save it at
resources/views/test.php.
<html>
   <body>
      <h1>Example of Redirecting to Named Routes</h1>
   </body>
</html>
Step 2 − In routes.php, we have set up the route for test.php file. We have renamed it to testing. We have also set up another route redirect which will redirect the request to the named route testing.
app/Http/routes.php
Route::get('/test', ['as'=>'testing',function() {
   return view('test2');
}]);

Route::get('redirect',function() {
   return redirect()->route('testing');
});

Step 3 − Visit the following URL to test the named route example.
http://localhost:8000/redirect

Step 4 − After execution of the above URL, you will be redirected to http://localhost:8000/test as we are redirecting to the named route testing.
Step 5 − After successful execution of the URL, you will receive the following output −
Not only named route but we can also redirect to controller actions. We need to simply pass the controller and name of the action to the action method as shown in the following example. If you want to pass a parameter, you can pass it as the second argument of the action method.
return redirect()->action(‘NameOfController@methodName’,[parameters]);

Step 1 − Execute the following command to create a controller called RedirectController.
php artisan make:controller RedirectController --plain

Step 2 − After successful execution, you will receive the following output −
Step 3 − Copy the following code to file
app/Http/Controllers/RedirectController.php.
app/Http/Controllers/RedirectController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class RedirectController extends Controller {
   public function index() {
      echo "Redirecting to controller's action.";
   }
}

Step 4 − Add the following lines in app/Http/routes.php.
app/Http/routes.php
Route::get('rr','RedirectController@index');
Route::get('/redirectcontroller',function() {
   return redirect()->action('RedirectController@index');
});

Step 5 − Visit the following URL to test the example.
http://localhost:8000/redirectcontroller

Step 6 − The output will appear as shown in the following image.

    13 Lectures 
     3 hours 

 Sebastian Sulinski

    35 Lectures 
     3.5 hours 

 Antonio Papa

    7 Lectures 
     1.5 hours 

 Sebastian Sulinski

    42 Lectures 
     1 hours 

 Skillbakerystudios

    165 Lectures 
     13 hours 

 Paul Carlo Tordecilla

    116 Lectures 
     13 hours 

 Hafizullah Masoudi
 Print
 Add Notes
 Bookmark this page