code-rag-bench/online-tutorials huggingface dataset:
How to make a div vertically scrollable without content using CSS ? - GeeksforGeeks

12 Aug, 2021
In this article, we will see how we can create a vertical scrollable section using CSS. HTML code is used to create the basic structure of the sections and CSS code is used to set the style,
HTML Code:
Create an HTML div element with the class container.
Created three more nested div with class box
Write some content inside each div with the class box.
CSS Code:
The “scroll” option is added in this case to always show the scrollbar for the overflow-y property.
The height is set to 100vh for 100% height of the viewport, which is set for the reason that if the contents exceed, it adds a scrollbar.
The scroll-snap-type is set to y, so that the direction of scroll snapping is in the y-axis for the container div. This property is added if the browser is needed to be stopped at a particular time. This forces scrolling to a snap point on the y-axis.
The scroll-snap-align property is used on elements with class “box” to set the position that scrolling will snap to. The scroll-snap-align is used to tell the point where the scrolling should stop.
Example:
HTML
<!DOCTYPE html><html>  <head>    <style type="text/css">        body {            margin: 0;        }          /* Adding scroll snap type mandatory         and scoll direction to y axis*/        .container {            scroll-snap-type: y mandatory;            overflow-y: scroll;              /* 100% height of the viewport */            height: 100vh;        }          /* Adding general css to box and         aligning snap to start */        .box {            height: 100vh;            color: #fff;            text-align: center;            line-height: 100vh;            font-size: 5rem;            scroll-snap-align: start;        }          /* Setting different colors to all boxes */        .box:nth-child(1) {            background: #5e38ff;        }                  .box:nth-child(2) {            background: #fe802b;        }                  .box:nth-child(3) {            background: #00bf71;        }    </style></head>  <body>    <div class="container">        <div class="box"></div>        <div class="box"></div>        <div class="box"></div>    </div></body>  </html>
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
CSS-Properties
CSS-Questions
HTML-Questions
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Design a web page using HTML and CSS
Form validation using jQuery
How to set space between the flexbox ?
Search Bar using HTML, CSS and JavaScript
How to style a checkbox using CSS?
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Hide or show elements in HTML using display property
How to Insert Form Data into Database using PHP ?
REST API (Introduction)
How to create button dynamically with click event in Angular ? - GeeksforGeeks

07 Nov, 2019
The task is to create a button dynamically with click event using angular. In these examples when someone clicks on the button then a new button gets created.
The easiest way to create a button in AngularJS is to use the ng-repeat directive. We can easily hook up a repeat logic inside a button click event.
Syntax:
<element ng-repeat="variable in expression"> Contents... </element>
Example: Here we have a counter variable that keeps the count of buttons currently present in the DOM. it gets increased by one each time the main button (GFG) is pressed. the increased count results in a new button generated by ng-repeat.
<!DOCTYPE html><html ng-app="myApp">  <head>    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.8/angular.min.js">    </script></head>  <body ng-controller="MyController">    <center>        <h1 style="color:green">          GeeksforGeeks      </h1>        <button type="button"                 ng-click="click(this)">          GFG      </button>        <br>        <!-- Dynamically created button using repeat -->        <button type="button"                 ng-repeat="i in range(0, counter)">          New button!      </button>    </center></body><script type="text/javascript">    var myApp = angular.module('myApp', []);      myApp.controller('MyController', ['$scope', function($scope) {        $scope.counter = 0;          $scope.click = function($scope) {            $scope.counter++;        }        $scope.range =            function(min, max, step) {                step = step || 1;                var input = [];                for (var i = min; i < max; i += step) {                    input.push(i);                }                return input;            };    }]);</script>  </html>
Output: As we keep on clicking the button, the number of buttons keep on increasing in the DOM:
AngularJS-Misc
Picked
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Angular File Upload
Angular | keyup event
Auth Guards in Angular 9/10/11
What is AOT and JIT Compiler in Angular ?
Angular PrimeNG Dropdown Component
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
How do I position the buttons on a Tkinter window?

To set the position of a button, we use the place method of button widget. The place method takes the x and y coordinates of the button.
Import the required libraries and create an instance of tkinter frame.
Import the required libraries and create an instance of tkinter frame.
Set the size of the frame using win.geometry method.
Set the size of the frame using win.geometry method.
Next, create multiple buttons and name them "Button-1", "Button-2", etc.
Next, create multiple buttons and name them "Button-1", "Button-2", etc.
Set the position of the buttons using the place method by supplying the x and y coordinate values.
Set the position of the buttons using the place method by supplying the x and y coordinate values.
Finally, run the mainloop of the application window.
Finally, run the mainloop of the application window.
# Import the Tkinter library
from tkinter import *
from tkinter import ttk

# Create an instance of Tkinter frame
win = Tk()

# Define the geometry
win.geometry("750x350")

# Create Buttons in the frame
button = ttk.Button(win, text="Button-1")
button.place(x=325, y=125)

button = ttk.Button(win, text="Button-2")
button.place(x=325, y=175)

button = ttk.Button(win, text="Button-3")
button.place(x=325, y=225)

#Create a Label
Label(win, text="Position the Buttons", font='Consolas 15').pack()

win.mainloop()
When you execute this code, it will show the following window −
Notice that we have fixed the x variable at 325 in all the three buttons which is why the buttons are aligned. You can alter the (x, y) values in the place method to change the position of the buttons.
What is the difference between a float, double and a decimal in C#?

Float , double and a decimal are all Value Types in C#. 
Value type variables can be assigned a value directly. They are derived from the class System.ValueType. The value types directly contain data.
Float is a 32-bit single-precision floating point type with range 3.4 x 1038 to + 3.4 x 1038
Memory Size is 4 bytes.
float a = 3.5f;

Double is a 64-bit double-precision floating point type with range (+/-)5.0 x 10-324 to (+/-)1.7 x 10308
Memory Size is 8 bytes.
double d = 5.78788

Decimal is a 128-bit precise decimal values with 28-29 significant digits with range (-7.9 x 1028 to 7.9 x 1028) / 100 to 28
Memory Size is 16 bytes.
decimal d = 1.0M;
How to find if a string is a palindrome using Java?

StringBuffer provides a method with name reverse() one way to check for a palindrome is
Create a StringBuffer object by passing the required string as a parameter to the constructor.Reverse the contents of the object using the reverse() method.Convert the StringBuffer object to Sting using the toString() method.Now, compare the String and the reversed one, if true, the given string is a palindrome.
Create a StringBuffer object by passing the required string as a parameter to the constructor.
Reverse the contents of the object using the reverse() method.
Convert the StringBuffer object to Sting using the toString() method.
Now, compare the String and the reversed one, if true, the given string is a palindrome.
Live Demo
public class StringPalindrome {
   public static void main(String args[]){

      String myString = "anna";
      StringBuffer buffer = new StringBuffer(myString);
      buffer.reverse();
      String data = buffer.toString();
      if(myString.equals(data)){
         System.out.println("Given String is palindrome");
      }else{
         System.out.println("Given String is not palindrome");
      }
   }
}
Given String is palindrome
C program for pipe in Linux

Here, we will create a C program for pipe in Linux. In this program, we will read some text from the input stream and then print it to the output screen.
First, let’s learn basics about pipe in Linux
Pipe is used to transfer data, it can be used for communication between process/ command/ program for transferring standard output between two in Linux or Unix based system.
One important thing to be noted is that pipes are unidirectional i.e. data can either flow from left to right or from right to left in the program.
Here, we will create a pipe that will read input from users and print it to the output screen. The implementation takes an array of size 2 which are used to take input arr[0] and returning output arr[1].
C program for pipe in Linux
 Live Demo
#include <errno.h>
#include<string.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
int main(){
   int Pipe[2];
   char string[100];
   if (pipe(Pipe) == -1){
      perror("Filed to create pipe");
      exit(1);
   }
   scanf("%s", string);
   write(Pipe[1], string, strlen(string)+1);
   printf("\n");
   read(Pipe[0], string, 5);
   printf("%s", string);
}
input: TutorialsPoint
TutorialsPoint
How to delete the Organizational Unit (OU) from the active directory using PowerShell?

To delete the OU from the Active Directory using PowerShell, we need to use the command Remove-ADOrganizationUnit
Remove-ADOrganizationalUnit -Identity "OU=LabUsers,DC=Labdomain,DC=Local"
If the OU is protected from the accidental delete, you will receive an Access is Denied error as shown below.
Remove-ADOrganizationalUnit : Access is denied At line:1 char:1 + Remove-ADOrganizationalUnit -Identity "OU=LabUsers,DC=Labdomain,DC=Lo ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : PermissionDenied: (OU=LabUsers,DC=Labdomain,DC=Local:ADOrganizationalUnit) [Remove-ADOrgan izationalUnit], UnauthorizedAccessException + FullyQualifiedErrorId : ActiveDirectoryCmdlet:System.UnauthorizedAccessException,Microsoft.ActiveDirectory.Managem
ent.Commands.RemoveADOrganizationalUnit
So for that, first you need to disable the protected mode using the Set-ADOrganizationalUnit command and then need to run the remove command as shown below.
$ou = "OU=LabUsers,DC=Labdomain,DC=Local" Set-ADOrganizationalUnit -Identity $ou -ProtectedFromAccidentalDeletion $false Remove-ADOrganizationalUnit -Identity $ou -Confirm:$false -Verbose
You need to make sure that there are no child objects that exist otherwise, OU won’t get deleted.
jQuery.getJSON() Method

The jQuery.getJSON( url, [data], [callback] ) method loads JSON data from the server using a GET HTTP request.
The method returns XMLHttpRequest object.
Here is the simple syntax to use this method −
$.getJSON( url, [data], [callback] )

Here is the description of all the parameters used by this method −
url − A string containing the URL to which the request is sent
url − A string containing the URL to which the request is sent
data − This optional parameter represents key/value pairs that will be sent to the server.
data − This optional parameter represents key/value pairs that will be sent to the server.
callback − This optional parameter represents a function to be executed whenever the data is loaded successfully.
callback − This optional parameter represents a function to be executed whenever the data is loaded successfully.
Assuming we have following JSON content in result.json file −
{
"name": "Zara Ali",
"age" : "67",
"sex": "female"
}
Following is a simple example a simple showing the usage of this method −
<html>
   <head>
      <title>The jQuery Example</title>
      <script type = "text/javascript" 
         src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
      </script>
		
      <script type = "text/javascript" language = "javascript">
         $(document).ready(function() {
			
            $("#driver").click(function(event){
               $.getJSON('result.json', function(jd) {
                  $('#stage').html('<p> Name: ' + jd.name + '</p>');
                  $('#stage').append('<p>Age : ' + jd.age+ '</p>');
                  $('#stage').append('<p> Sex: ' + jd.sex+ '</p>');
               });
            });
				
         });
      </script>
   </head>
	
   <body>
      <p>Click on the button to load result.html file:</p>
		
      <div id = "stage" style = "background-color:#cc0;">
         STAGE
      </div>
		
      <input type = "button" id = "driver" value = "Load Data" />
   </body>
</html>
This should produce following result −
Click on the button to load result.html file −

    27 Lectures 
     1 hours 

 Mahesh Kumar

    27 Lectures 
     1.5 hours 

 Pratik Singh

    72 Lectures 
     4.5 hours 

 Frahaan Hussain

    60 Lectures 
     9 hours 

 Eduonix Learning Solutions

    17 Lectures 
     2 hours 

 Sandip Bhattacharya

    12 Lectures 
     53 mins

 Laurence Svekis
 Print
 Add Notes
 Bookmark this page
React Native - Running Android

We can run the React Native app on Android platform by running the following code in the terminal.
react-native run-android

Before you can run your app on Android device, you need to enable USB Debugging inside the Developer Options.
When USB Debugging is enabled, you can plug in your device and run the code snippet given above.
The Native Android emulator is slow. We recommend downloading Genymotion for testing your app.
The developer menu can be accessed by pressing command + M.

    20 Lectures 
     1.5 hours 

 Anadi Sharma

    61 Lectures 
     6.5 hours 

 A To Z Mentor

    40 Lectures 
     4.5 hours 

 Eduonix Learning Solutions

    56 Lectures 
     12.5 hours 

 Eduonix Learning Solutions

    62 Lectures 
     4.5 hours 

 Senol Atac

    67 Lectures 
     4.5 hours 

 Senol Atac
 Print
 Add Notes
 Bookmark this page
Java program to find the factorial of a given number using recursion

Recursion is the process of repeating items in a self-similar way. In programming languages, if a program allows you to call a function inside the same function, then it is called a recursive call of the function.
Following is an example to find the factorial of a given number using a recursive function.
import java.util.Scanner;
public class ab21_FactorialUsingRecursion {
   public static long factorial(int i) {
      if(i <= 1) {
         return 1;
      }
      return i * factorial(i - 1);
   }
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the number to which you need to find the factorial");
      int i = sc.nextInt();
      System.out.println("Factorial of the given number is ::"+ factorial(i));
   }
}
Enter the number to which you need to find the factorial
12
Factorial of the given number is ::479001600
Can a method return multiple values in Java?

You can return only one value in Java. If needed you can return multiple values using array or an object.
In the example given below the calculate() method accepts two integer variables performs the addition subtraction, multiplication and, division operations on them stores the results in an array and returns the array.
public class ReturningMultipleValues {
   static int[] calculate(int a, int b){
      int[] result = new int[4];
      result[0] = a + b;
      result[1] = a - b;
      result[2] = a * b;
      result[3] = a / b;
      return result;
   }
   public static void main(String args[]){
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the value of a: ");
      int a = sc.nextInt();
      
      System.out.println("Enter the value of b: ");
      int b = sc.nextInt();
      int[] result = calculate(a, b);
      
      System.out.println("Result of addition: "+result[0]);
      System.out.println("Result of subtraction: "+result[1]);
      System.out.println("Result of multiplication: "+result[2]);
      System.out.println("Result of division: "+result[3]);
   }
}
Enter the value of a:
20
Enter the value of b:
10
Result of addition: 30
Result of subtraction: 10
Result of multiplication: 200
Result of division: 2
Java - The HashSet Class

HashSet extends AbstractSet and implements the Set interface. It creates a collection that uses a hash table for storage.
A hash table stores information by using a mechanism called hashing. In hashing, the informational content of a key is used to determine a unique value, called its hash code.
The hash code is then used as the index at which the data associated with the key is stored. The transformation of the key into its hash code is performed automatically.
Following is the list of constructors provided by the HashSet class.
HashSet( )
This constructor constructs a default HashSet.
HashSet(Collection c)
This constructor initializes the hash set by using the elements of the collection c.
HashSet(int capacity)
This constructor  initializes the capacity of the hash set to the given integer value capacity.
The capacity grows automatically as elements are added to the HashSet.

HashSet(int capacity, float fillRatio)
This constructor initializes both the capacity and the fill ratio (also called load capacity) of the hash set from its arguments.
Here the fill ratio must be between 0.0 and 1.0, and it determines how full the hash set can be before it is resized upward. Specifically, when the number of elements is greater than the capacity of the hash set multiplied by its fill ratio, the hash set is expanded.
Apart from the methods inherited from its parent classes, HashSet defines following methods −
boolean add(Object o)
Adds the specified element to this set if it is not already present.
void clear()
Removes all of the elements from this set.
Object clone()
Returns a shallow copy of this HashSet instance: the elements themselves are not cloned.
boolean contains(Object o)
Returns true if this set contains the specified element.
boolean isEmpty()
Returns true if this set contains no elements.
Iterator iterator()
Returns an iterator over the elements in this set.
boolean remove(Object o)
Removes the specified element from this set if it is present.
int size()
Returns the number of elements in this set (its cardinality).
The following program illustrates several of the methods supported by HashSet −
import java.util.*;
public class HashSetDemo {

   public static void main(String args[]) {
      // create a hash set
      HashSet hs = new HashSet();
      
      // add elements to the hash set
      hs.add("B");
      hs.add("A");
      hs.add("D");
      hs.add("E");
      hs.add("C");
      hs.add("F");
      System.out.println(hs);
   }
}
This will produce the following result −
[A, B, C, D, E, F]


    16 Lectures 
     2 hours 

 Malhar Lathkar

    19 Lectures 
     5 hours 

 Malhar Lathkar

    25 Lectures 
     2.5 hours 

 Anadi Sharma

    126 Lectures 
     7 hours 

  Tushar Kale

    119 Lectures 
     17.5 hours 

 Monica Mittal

    76 Lectures 
     7 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
Set the height and width of an image using percent with CSS

To set the height and width of an image using %, you can try to run the following code −
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <style>
         img {
            height: 50%;
            width: 50%;
         }
      </style>
   </head>
   <body>
      <p>Sized image in %</p>
      <img src = "https://www.tutorialspoint.com/videotutorials/assets/videos/courses/155/images/course_155_image.png" alt = "CSS" width = "200" height = "200">
   </body>
</html>
Go Comments

A comment is a text that is ignored upon execution.
Comments can be used to explain the code, and to make it more readable.
Comments can also be used to prevent code execution when testing an alternative code.
Go supports single-line or multi-line comments.
Single-line comments start with two forward slashes (//).
Any text between // and the end of the line is ignored by the compiler (will not be executed).
The following example uses a single-line comment at the end of a code line:
Multi-line comments start with /* and ends with */.
Any text between /* and */ will be ignored by the compiler:
Tip: It is up to you which you want to use. Normally, we use // for short comments, and /* */ for longer comments.
You can also use comments to prevent the code from being executed. 
The commented code can be saved for later reference and troubleshooting.
Comments in Go are written with a special character, which one?
package main   
import ("fmt") 
func main() {
   this is a comment  
  fmt.Println("Hello World!")
}

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.
How to create a chat message with CSS?

To create a chat message with CSS, the code is as follows −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
   body {
      margin: 0 auto;
      max-width: 800px;
      padding: 0 20px;
      font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
   }
   .message {
      font-size: 18px;
      font-weight:500;
      border: 2px solid #dedede;
      background-color: #55e4a8;
      color:rgb(0, 0, 0);
      border-radius: 12px;
      padding: 10px;
      margin: 10px 0;
   }
   .darker {
      border-color: #ccc;
      background-color: rgb(111, 25, 182);
      color:white;
   }
   .message::after {
      content: "";
      clear: both;
      display: table;
   }
   .profilePic{
      width: 100%;
   }
   .message img {
      float: left;
      max-width: 60px;
      width: 100%;
      margin-right: 20px;
      border-radius: 50%;
   }
   .message img.right {
      float: right;
      margin-left: 20px;
      margin-right:0;
   }
   .timeStampRight {
      float: right;
      color: rgb(0, 0, 0);
      font-weight: bold;
   }
   .timeStampLeft {
      float: left;
      color: rgb(255, 255, 255);
      font-weight: bold;
   }
</style>
</head>
<body>
<h1>Chat Messages Example</h1>
<div class="message">
<img class="profilePic" src="https://i.picsum.photos/id/295/200/200.jpg">
<p>Hello. How are your holidays going?</p>
<span class="timeStampRight">9:00</span>
</div>
<div class="message darker">
<img class="profilePic" src="https://i.picsum.photos/id/255/200/200.jpg">
<p>They are going pretty good.Thanks for asking!</p>
<span class="timeStampLeft">9:05</span>
</div>
<div class="message">
<img class="profilePic" src="https://i.picsum.photos/id/295/200/200.jpg">
<p>Are you visiting somewhere in holidays?</p>
<span class="timeStampRight">9:07</span>
</div>
<div class="message darker">
<img class="profilePic" src="https://i.picsum.photos/id/255/200/200.jpg">
<p>Yes! Thinking of going to Disneyland.</p>
<span class="timeStampLeft">9:10</span>
</div>
</body>
</html>
The above code will produce the following output −
PyQt5 – How to set minimum size of window | setMinimumSize method

26 Mar, 2020
We know that we can resize the window of PyQt5 application, but while shrinking the window size we can set minimum size so that it can’t be shrank any more. In this article, we will see how to do this.
In order to do this we will use setMinimumSize() method.
Syntax : self.setMinimumSize(width, height)
Argument : It takes two integer as argument.
Action performed : It sets the minimum size of window.
Code :
# importing the required libraries  from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * import sys    class Window(QMainWindow):    def __init__(self):        super().__init__()            # set the title        self.setWindowTitle("Python")          width = 200        height = 200          # setting the minimum size        self.setMinimumSize(width, height)                  # creating a label widget        self.label_1 = QLabel("Minimum size", self)          # moving position        self.label_1.move(0, 0)          # setting up the border        self.label_1.setStyleSheet("border :3px solid black;")          # resizing label        self.label_1.resize(120, 80)          # show all the widgets        self.show()    # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Pandas MultiIndex.from_tuples()

24 Dec, 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.
Pandas MultiIndex.from_tuples() function is used to convert list of tuples to MultiIndex. It is one of the several ways in which we construct a MultiIndex.
Syntax: MultiIndex.from_tuples(tuples, sortorder=None, names=None)
Parameters :tuples : Each tuple is the index of one row/column.sortorder : Level of sortedness (must be lexicographically sorted by that level)
Returns: index : MultiIndex
Example #1: Use MultiIndex.from_tuples() function to construct a MultiIndex using python tuples.
# importing pandas as pdimport pandas as pd  # Creating the Tupletuples =[(30, 'Larry'), (20, 'Mike'),         (18, 'David'), (25, 'Tim')]  # Print the Tupleprint(tuples)
Output :
Now let’s create the MultiIndex using the Tuples.
# Creating the MultiIndexmidx = pd.MultiIndex.from_tuples(tuples, names =('Age', 'Name'))  # Print the MultiIndexprint(midx)
Output :As we can see in the output, the function has created a MultiIndex object using the Tuples. Example #2: Use MultiIndex.from_tuples() function to construct a MultiIndex using python tuples.
# importing pandas as pdimport pandas as pd  # Creating the Tupletuples =[('Physics', 85), ('Chemistry', 88),           ('Maths', 95), ('Computers', 99)]  # Print the Tupleprint(tuples)
Output :
Now let’s create the MultiIndex using the Tuples.
# Creating the MultiIndexmidx = pd.MultiIndex.from_tuples(tuples, names =('Subject', 'Marks'))  # Print the MultiIndexprint(midx)
Output :
Python pandas-multiIndex
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JavaScript | Uint32Array from() Method

06 Oct, 2021
The Uint32Array array represents an array of 32-bit unsigned integers in the platform byte order. By default, the contents of Uint32Array are initialized to 0. from() function of Uint32Array used to creates a new Uint32Array from an array-like or iterable object. So when you want to convert an arrayLike or iterable object then you can be used this function by passing the object as a parameter to this function along with map function and value used for map function if needed.Syntax:  
Uint32Array.from(source[, mapFn[, thisArg]])
parameters: This method accepts three parameters that are specified below:  
source: This parameter is an array-like or iterable object which is used to convert to a Uint32Array object.mapFn: This parameter is Optional which is Map function to call on every element of the Uint32Array array.thisArg: This parameter is Optional which is value to use as this when executing mapFn.
source: This parameter is an array-like or iterable object which is used to convert to a Uint32Array object.
mapFn: This parameter is Optional which is Map function to call on every element of the Uint32Array array.
thisArg: This parameter is Optional which is value to use as this when executing mapFn.
Return Value: this method returns a new Uint32Array instance.JavaScript program to Illustrate the working of from() function: Program 1:  
javascript
<script>    //create a Uint32Array from a string like structure    var array = Uint32Array.from('987654321234567');     //print the result    document.write(array);</script>
Output:  
9, 8, 7, 6, 5, 4, 3, 2, 1, 2, 3, 4, 5, 6, 7
Program 2:  
javascript
<script>    //create a Uint32Array from a array by    //dividing by 32 to each number using function    var array = Uint32Array.from([543234, 432345, 5432123, 43234,        23432, 5432345, 432345, 23432    ], z => z / 32);     //print the result    document.write(array);</script>
Output:  
16976, 13510, 169753, 1351, 732, 169760, 13510, 732
References: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/from# 
gulshankumarar231
javascript-array
javascript-functions
JavaScript
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
Remove elements from a JavaScript Array
Roadmap to Learn JavaScript For Beginners
Difference Between PUT and PATCH Request
JavaScript | Promises
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Java string length without using length() method.

To calculate the length of the string convert the string to a character array and count the number of elements in the array.
Live Demo
public class StringLength {
   public static void main(String args[]) throws Exception {
      String str = "sampleString";
      int i = 0;
      for(char c: str.toCharArray()) {
         i++;
      }
      System.out.println("Length of the given string ::"+i);
   }
}
Length of the given string ::12
Python | Get unique tuples from list

27 Aug, 2019
Sometimes, while working with Python list, we can come across a problem in which we require to find the unique occurrences of list. Having elementary data types is easy to handle, but sometime, we might have complex data types and the problem becomes new in that cases. Let’s discuss certain ways in which tuples are handled for this problem.
Method #1 : Using list() + set()Alike integers, being immutable these can also be handled by set() for removal of the duplicates. It converts the list to set and removes duplicates and converted back to list by list()
# Python3 code to demonstrate working of# Get unique tuples from list# using set() + list()  # initializing listtest_list = [(4, 5), (6, 1), (4, 5), (6, 1)]  # printing original listprint("The original list is : " + str(test_list))  # Get unique tuples from list# using set() + list()res = list(set(test_list))  # printing result print("List after removal of duplicates " + str(res))
The original list is : [(4, 5), (6, 1), (4, 5), (6, 1)]
List after removal of duplicates [(4, 5), (6, 1)]

 
Method #2 : Using dict.fromkeys() + list()Since newer versions of Python dictionaries, remember their order of insertion, the list contents can be converted to dictionary element list, which remembers the order and removes the duplicates. It is converted back using list().
# Python3 code to demonstrate working of# Get unique tuples from list# using dict.fromkeys() + list()  # initializing listtest_list = [(4, 5), (6, 1), (4, 5), (6, 1)]  # printing original listprint("The original list is : " + str(test_list))  # Get unique tuples from list# using dict.fromkeys() + list()res = list(dict.fromkeys(test_list))  # printing result print("List after removal of duplicates " + str(res))
The original list is : [(4, 5), (6, 1), (4, 5), (6, 1)]
List after removal of duplicates [(4, 5), (6, 1)]

Python list-programs
Python
Python Programs
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
Python String | replace()
How to Install PIP on Windows ?
Python program to convert a list to string
Defaultdict in Python
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
Lex program to check whether a given number is even or odd

30 Apr, 2019
Given a number n, the task is to check whether the given n is even or odd using Lex program.
Examples:
Input : 10 
Output : Even

Input : 5
Output : Odd

Prerequisite: FLEX (Fast Lexical Analyzer Generator)
An even number is an integer which is “evenly divisible” by 2. This means that if the integer is divided by 2, it yields no remainder or 0 as remainder. Similarly, an Odd number is an integer which is not “evenly divisible” by 2 and will leaves 1 as remainder.
Below is the implementation of above approach:
/*Lex program to take check whetherthe given number is even or odd */   %{#include<stdio.h>int i;%}  %%  [0-9]+     {i=atoi(yytext);          if(i%2==0)                printf("Even");          else         printf("Odd");}%%   int yywrap(){}   /* Driver code */int main(){       yylex();    return 0;}
Output:
Lex program
Compiler Design
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Directed Acyclic graph in Compiler Design (with examples)
Type Checking in Compiler Design
Data flow analysis in Compiler
S - attributed and L - attributed SDTs in Syntax directed translation
Runtime Environments in Compiler Design
Compiler construction tools
Basic Blocks in Compiler Design
Token, Patterns, and Lexems
Compiler Design - Variants of Syntax Tree
Loop Optimization in Compiler Design
Decryption of Simple Substitution Cipher

In this chapter, you can learn about simple implementation of substitution cipher which displays the encrypted and decrypted message as per the logic used in simple substitution cipher technique. This can be considered as an alternative approach of coding.
You can use the following code to perform decryption using simple substitution cipher −
import random
chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + \
   'abcdefghijklmnopqrstuvwxyz' + \
   '0123456789' + \
   ':.;,?!@#$%&()+=-*/_<> []{}`~^"\'\\'

def generate_key():
   """Generate an key for our cipher"""
   shuffled = sorted(chars, key=lambda k: random.random())
   return dict(zip(chars, shuffled))

def encrypt(key, plaintext):
   """Encrypt the string and return the ciphertext"""
   return ''.join(key[l] for l in plaintext)

def decrypt(key, ciphertext):
   """Decrypt the string and return the plaintext"""
   flipped = {v: k for k, v in key.items()}
   return ''.join(flipped[l] for l in ciphertext)

def show_result(plaintext):
   """Generate a resulting cipher with elements shown"""
   key = generate_key()
   encrypted = encrypt(key, plaintext)
   decrypted = decrypt(key, encrypted)
   
   print 'Key: %s' % key
	print 'Plaintext: %s' % plaintext
   print 'Encrypted: %s' % encrypted
   print 'Decrypted: %s' % decrypted
show_result('Hello World. This is demo of substitution cipher')
The above code gives you the output as shown here −

    10 Lectures 
     2 hours 

 Total Seminars

    10 Lectures 
     2 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
Python Virtual Environments & Jupyter Notebook | by Anne Bode | Towards Data Science

conda create -n myenv python=3.8conda activate myenvconda install jupyterconda install -n base nb_conda_kernelsjupyter notebook
Note, I am running Python 3.8 (installed with Anaconda) on Windows
I recently decided to clean up my Python installation because mine had become a mess. I uninstalled/reinstalled Python with Anaconda, and chose to start creating virtual environments when beginning new projects, to keep my base installation of Python clean. Virtual environments will allow me to install whichever versions of whichever packages I need for a given project, without messing with my base installation. That way, I can have all of the versions of all of the packages I need, and no annoying incompatibility errors that I don’t.
To create a new virtual environment, open your Anaconda Prompt and run the following commands (substitute “myenv” with the virtual environment name of your choosing):
conda create -n myenv python=3.8conda activate myenv
Note that you have to specify the Python version, otherwise your virtual environment will be created as a completely empty folder, without Python and some basic packages like pip pre-installed. You can check to make sure you’ve installed it properly by running conda list to see which packages are already in there (hint: there should be >0).
At this point, you can use conda or pip to install whichever package(s) you need in your newly activated virtual environment.
When you run your project in Jupyter Notebook, you need a way to reference this new virtual environment instead of your base environment. In Anaconda Prompt (with your virtual environment still activated), run the following command. Keep in mind, you’ll have to run this in each virtual environment you create.
conda install jupyter
Then, in your base environment you need to install nb_conda_kernels (just one time), which automatically creates a new kernel for each virtual environment you create, provided you’ve installed jupyter in it.
conda install -n base nb_conda_kernels
Your Jupyter Notebooks can now run on either kernel (base or myenv), and therefore pull the correct packages/versions depending on the project at hand. You can launch Jupyter Notebook from within any activated environment with the command below, and it will open up your Notebooks location (mine are in C:/Users/myusername, which is where my Anaconda3 is also installed).
jupyter notebook
With a new Jupyter notebook open, you can click Kernel > Change kernel > and select the virtual environment you need.
I hope this was helpful!
Why use static_cast<int>(x) instead of (int)x in C++?

The (int)x is C style typecasting where static_cast<int>(x) is used in C++. This static_cast<>() gives compile time checking facility, but the C style casting does not support that. This static_cast<>() can be spotted anywhere inside a C++ code. And using this C++ cast the intensions are conveyed much better.
In C like cast sometimes we can cast some type pointer to point some other type data. Like one integer pointer can also point character type data, as they are quite similar, only difference is character has 1-byte, integer has 4-bytes. In C++ the static_cast<>() is more strict than C like casting. It only converts between compatible types.
char c = 65; //1-byte data. ASCII of ‘A’
int *ptr = (int*)&c; //4-byte
Since in a 4-byte pointer, it is pointing to 1-byte of allocated memory, it may generate runtime error or will overwrite some adjacent memory.
In C++ the static_cast<>() will allow the compiler to check whether the pointer and the data are of same type or not. If not it will raise incorrect pointer assignment exception during compilation.
char c = 65; //1-byte data. ASCII of ‘A’
int *ptr = static_cast<int>(&c);
This will generate compile time error.
Python – Remove all consonants from string

14 Feb, 2022
Sometimes, while working with Python, we can have a problem in which we wish to remove all the non vowels from strings. This is quite popular question and solution to it is useful in competitive programming and day-day programming. Lets discuss certain ways in which this task can be performed.Method #1 : Using loop This is one of the ways in which this task can be performed. In this, we iterate through the list and then check for non presence of vowels and filter. 
Python3
# Python3 code to demonstrate working of# Remove all consonants from string# Using loop # initializing stringtest_str = "Gfg is best for geeks" # printing original stringprint("The original string is : " + test_str) # Remove all consonants from string# Using loopres = []for chr in test_str:    if chr in "aeiouAEIOU":        res.extend(chr)res = "".join(res) # printing resultprint("String after consonants removal : " + str(res))
 Method #2 : Using list comprehension This is one of the ways in which this task can be performed. In this, we iterate through the list and then filter out vowels in similar manner but in one-liner. 
Python3
# Python3 code to demonstrate working of# Remove all consonants from string# Using list comprehension # initializing stringtest_str = "Gfg is best for geeks" # printing original stringprint("The original string is : " + test_str) # Remove all consonants from string# Using list comprehensionres = "".join([chr for chr in test_str if chr in "aeiouAEIOU"]) # printing resultprint("String after consonants removal : " + str(res))
rkbhola5
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to retrieve the contents of a text field in JavaFX?

The text field accepts and displays the text. In the latest versions of JavaFX, it accepts only a single line. In JavaFX the javafx.scene.control.TextField class represents the text field, this class inherits the javafx.scene.control.TextInputControl (base class of all the text controls) class. Using this you can accept input from the user and read it to your application.
To create a text field you need to instantiate this class, to the constructor of this class. It inherits a property named text from its superclass TextInputControl. This property holds the contents of the current text field. You can retrieve this data using the getText() method.
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.stage.Stage;
public class TextFieldGettingData extends Application {
   public void start(Stage stage) {
      //Creating nodes
      TextField textField1 = new TextField();
      TextField textField2 = new TextField();
      Button button = new Button("Submit");
      button.setTranslateX(250);
      button.setTranslateY(75);
      //Creating labels
      Label label1 = new Label("Name: ");
      Label label2 = new Label("Email: ");
      //Setting the message with read data
      Text text = new Text("");
      //Setting font to the label
      Font font = Font.font("verdana", FontWeight.BOLD, FontPosture.REGULAR, 10);
      text.setFont(font);
      text.setTranslateX(15);
      text.setTranslateY(125);
      text.setFill(Color.BROWN);
      text.maxWidth(580);
      text.setWrappingWidth(580);
      //Displaying the message
      button.setOnAction(e -> {
         //Retrieving data
         String name = textField1.getText();
         String email = textField2.getText();
         text.setText("Hello "+name+"Welcome to Tutorialspoint. From now, we will
         communicate with you at "+email);
      });
      //Adding labels for nodes
      HBox box = new HBox(5);
      box.setPadding(new Insets(25, 5 , 5, 50));
      box.getChildren().addAll(label1, textField1, label2, textField2);
      Group root = new Group(box, button, text);
      //Setting the stage
      Scene scene = new Scene(root, 595, 150, Color.BEIGE);
      stage.setTitle("Text Field Example");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}
Self Destructing Code in C

21 Nov, 2017
Using remove() function in C, we can write a program which can destroy itself after it is compiled and executed.
Explanation: This can be done using the remove function in C. Note that, this is done in Linux environment. So, the remove function is fed the first parameter in command line argument i.e. a.out file (executable file) created after compiling . Hence the program will be destroyed.
// CPP program of self destructing output file#include<stdio.h>#include<stdlib.h>  int main(int c, char *argv[]){    printf("By the time you run me "           "I will be destroyed \n");          // Array of pointers to command line arguments    remove(argv[0]);          // Note: argv[0] will contain the executable\    // file i.e. 'a.out'          return 0;}
Steps:
Open the terminal.Type the following command on the terminal : gcc self.c This will create the a.out file.Type the following command on the terminal : ./a.out 
Open the terminal.
Type the following command on the terminal : gcc self.c 
 gcc self.c 
This will create the a.out file.
Type the following command on the terminal : ./a.out 
 ./a.out 
Output:
By the time you run me, I will be destroyed

After the output shown above, the a.out file will be removed. And hence our work is done.
cpp-file-handling
C Language
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Unordered Sets in C++ Standard Template Library
Operators in C / C++
Exception Handling in C++
What is the purpose of a function prototype?
TCP Server-Client implementation in C
Smart Pointers in C++ and How to Use Them
'this' pointer in C++
Storage Classes in C
Ways to copy a vector in C++
Understanding "extern" keyword in C
What is a Dictionary Attack?

04 Jul, 2022
A Dictionary Attack is an attack vector used by the attacker to break in a system, which is password protected, by putting technically every word in a dictionary as a form of password for that system. This attack vector is a form of Brute Force Attack. 
The dictionary can contain words from an English dictionary and also some leaked list of commonly used passwords and when combined with common character replacing with numbers, can sometimes be very effective and fast. 
How is it done? 
Basically, it is trying every single word that is already prepared. It is done using automated tools that try all the possible words in the dictionary. 
Some Password Cracking Software:
John the Ripper
L0phtCrack
Aircrack-ng
Difference between Brute Force and Dictionary Attack: 
The difference with brute force attack is that, in brute force, a large number of possible key permutations are checked whereas, in the dictionary attack, only the words with most possibilities of success are checked and are less time consuming than brute force. 
How to be on the safer side? 
You can protect yourself from such kind of attacks by following ways:
Choose a mix of upper and lower case letters, numbers and specials (i.e. special characters).
Password must be a long string with more characters. The longer it is, the more time consuming it is to crack (sometimes, time to crack is in years).
Password reset should be done after a certain period of time.
abhishekpal97854368
Information-Security
Network-security
Technical Scripter 2019
Computer Networks
Technical Scripter
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Secure Socket Layer (SSL)
GSM in Wireless Communication
Wireless Application Protocol
Mobile Internet Protocol (or Mobile IP)
Introduction of Mobile Ad hoc Network (MANET)
Advanced Encryption Standard (AES)
Cryptography and its Types
Bluetooth
Intrusion Detection System (IDS)
Dynamic Host Configuration Protocol (DHCP)