code-rag-bench/online-tutorials huggingface dataset:
DirectX - Picking

The traditional method which is needed to perform the action of picking relies on the technique is called ray-casting. The user can shoot a ray from the camera position through the selected point which the aspect of near plane of the required frustum which intersects the resulting ray. The first object intersected by the way is considered as the ray of object which is picked.
We will be creating the Picking Demo project as mentioned in the figure below −
Here, you can see that only the required part is hand-picked or the picking process is created.
To pick the respective object, the user should convert the selected screen pixel into the mentioned camera’s view space. The screen-space coordinate is used to view the required space with the conversion of pixel position. Now let us focus on the process of picking the ray. The ray starts with the given point and extends the direction until it reaches the point of infinity. The specialized class called SlimDX provides the required position and the maintained direction properties which is referred to as intersection tests with bounding boxes, spheres, triangles and planes.
Normalized device coordinates map the screen with respect to x and y coordinates within the range of [-1,1].
The parameters which are used for transformation into the required world space by transforming the origin to the mentioned direction of vectors include ray with the inverse of camera’s view matrix. The code snippet which can be used is mentioned below −
public Ray GetPickingRay(Vector2 sp, Vector2 screenDims) {
   var p = Proj;
   // convert screen pixel to view space
   var vx = (2.0f * sp.X / screenDims.X - 1.0f) / p.M11;
   var vy = (-2.0f * sp.Y / screenDims.Y + 1.0f) / p.M22;
   var ray = new Ray(new Vector3(), new Vector3(vx, vy, 1.0f));
   var v = View;
   var invView = Matrix.Invert(v);
   var toWorld = invView;
   ray = new Ray(Vector3.TransformCoordinate(ray.Position, toWorld),    
      Vector3.TransformNormal(ray.Direction, toWorld));
   ray.Direction.Normalize();
   return ray;
}
Now we will focus on picking the object with respect to the 3D scene to select a triangle from our car mesh in this example. This changes our OnMouseDown override slightly, consider the code snippet which is mentioned below −
protected override void OnMouseDown(object sender, MouseEventArgs mouseEventArgs) {
   if (mouseEventArgs.Button == MouseButtons.Left) {
      _lastMousePos = mouseEventArgs.Location;
      Window.Capture = true;
   } 
   else if (mouseEventArgs.Button == MouseButtons.Right) {
      Pick(mouseEventArgs.X, mouseEventArgs.Y);
   }
}
 Print
 Add Notes
 Bookmark this page
Get data from sessionStorage in JavaScript?

The localStorage and sessionStorage properties allow to save key/value pairs in a web browser. The sessionStorage object stores data for only one session. The data will be deleted when the browser is closed. It works the same as local storage. Initially, we have to check whether the browser supports the session storage or not. Later on, we have to create the data and have to retrieve the data. 
sessionStorage.setItem();
Live Demo
<html>
<body>
<p> id = "storage"</p>
<script>
   if (typeof(Storage) !== "undefined") {
      sessionStorage.setItem("product", "Tutorix");
      document.getElementById("storage").innerHTML = sessionStorage.getItem("product");
   }
   else {
      document.getElementById("storage").innerHTML = "Sorry,no Web Storage compatibility...";
   }
</script>
</body>
</html>
Tutorix
How to Install Azure PowerShell Cmdlets?

Before Installing the Azure cmdlets for PowerShell, it is recommended to upgrade it to the PowerShell version 7.X to leverage the new features.
To install the PowerShell cmdlets for Azure, you need to download and install the AZ module.
Install-Module -Name Az -AllowClobber -Scope CurrentUser
To install it for all the users,
Install-Module -Name Az -AllowClobber -Scope AllUsers
If the AzureRM module is already installed, you first need to uninstall it because both modules AzureRM and AZ cannot reside in the same console and the AzureRm module is going to decommission soon. So anyway we need to upgrade it to the latest AZ Module.
To uninstall the AzureRM module use command,
Uninstall-Module AzureRm -Force -Verbose
fold command in Linux with examples - GeeksforGeeks

15 May, 2019
fold command in Linux wraps each line in an input file to fit a specified width and prints it to the standard output. By default, it wraps lines at a maximum width of 80 columns but this is configurable. To fold input using the fold command pass a file or standard input to the command.
Syntax:
$ fold [OPTION]... [FILE]...
Using fold command:
$ fold GfG.txt
In the above example we have passed a text file named GfG to fold command and as you can see in output it wraps the line up to 80 columns.
Different options of fold command :
-w :By using this option in fold command, we can limit the width by number of columns. By using this command we change the column width from default width of 80.Syntax:$ fold -w[n] GfG.txtIn the above example, we wrap the lines of GfG.txt to a width of 60 columns.
Syntax:
$ fold -w[n] GfG.txt
In the above example, we wrap the lines of GfG.txt to a width of 60 columns.
-b :this option of fold command is used to limit the width of the output by the number of bytes rather than the number of columns. By using this we can enforce the width of the output to the number of bytes.Syntax:$ fold -b[n] GfG.txtIn the above example, we have limited the output width of the file to 40 bytes and the command breaks the output at 40 bytes.
Syntax:
$ fold -b[n] GfG.txt
In the above example, we have limited the output width of the file to 40 bytes and the command breaks the output at 40 bytes.
-s : This option is used to break the lines on spaces so that words are not broken. If a segment of the line contains a blank character within the first width column positions, break the line after the last such blank character meeting the width constraints.Syntax:$ fold -w[n] -s GfG.txtIf you compare the above example with the previous one, you will see that the lines only break at spaces, whereas, in other examples, the output is displayed in such a way that some of the words are broken between the lines.
Syntax:
$ fold -w[n] -s GfG.txt
If you compare the above example with the previous one, you will see that the lines only break at spaces, whereas, in other examples, the output is displayed in such a way that some of the words are broken between the lines.
linux-command
Linux-text-processing-commands
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
tar command in Linux with examples
UDP Server-Client implementation in C
Conditional Statements | Shell Script
Cat command in Linux with examples
Tail command in Linux with examples
touch command in Linux with Examples
Mutex lock for Linux Thread Synchronization
echo command in Linux with Examples
tee command in Linux with examples
Compiling with g++
How to stop multiple services using PowerShell?

To stop multiple services can be stopped using Name or displayname by providing command (,) between them.
With name and DisplayName,
Stop-Service -Name Spooler, W32Time -Verbose
Stop-Service -DisplayName "Print Spooler","Windows Time" –Verbose
C# Abstraction

Data abstraction is the process of hiding certain details and showing only essential information to the user.
Abstraction can be achieved with either abstract classes or 
interfaces (which you will learn more about in the next chapter).
The abstract keyword is used for classes and methods:

Abstract class: is a restricted class that cannot be used to create objects (to access it, it must be inherited from another class).
Abstract method: can only be used in an abstract class, and it does not have a body. The body is provided by the 
derived class (inherited from).
An abstract class can have both abstract and regular methods:
abstract class Animal 
{
  public abstract void animalSound();
  public void sleep() 
  {
    Console.WriteLine("Zzz");
  }
}
 
 

From the example above, it is not possible to create an object of the Animal class:
Animal myObj = new Animal(); // Will generate an error (Cannot create an instance of the abstract class or interface 'Animal')

To access the abstract class, it must be inherited from another class. Let's convert the Animal class we used in the Polymorphism 
chapter to an abstract class.
Remember from the Inheritance chapter that we use the 
: symbol to inherit from a class, 
and that we use the override keyword to override the base class method.
// Abstract class
abstract class Animal
{
  // Abstract method (does not have a body)
  public abstract void animalSound();
  // Regular method
  public void sleep()
  {
    Console.WriteLine("Zzz");
  }
}

// Derived class (inherit from Animal)
class Pig : Animal
{
  public override void animalSound()
  {
    // The body of animalSound() is provided here
    Console.WriteLine("The pig says: wee wee");
  }
}

class Program
{
  static void Main(string[] args)
  {
    Pig myPig = new Pig(); // Create a Pig object
    myPig.animalSound();  // Call the abstract method
    myPig.sleep();  // Call the regular method
  }
} 
 
 
 
 
 


Try it Yourself »

To achieve security - hide certain details and only show the important 
details of an object.
Note: Abstraction can also be achieved with Interfaces, which you will learn more about in the next chapter.
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.
Drawing an image from a data URL to a HTML5 canvas

If you have a data url, you can create an image to a canvas. This can be done as shown in the following code snippet −
var myImg = new Image;
myImg.src = strDataURI;
The drawImage() method draws an image, canvas, or video onto the canvas. The drawImage() method can also draw parts of an image, and/or increase/reduce the image size.
The code given below is also appropriate with the sequence - create the image, set the onload to use the new image, and then set the src −
// load image from data url
Var Obj = new Image();
Obj.onload = function() {
   context.drawImage(myImg, 0, 0);
};
Obj.src = dataURL;
How to Align Text in HTML? - GeeksforGeeks

24 Jun, 2021
HTML stands for HyperText Markup Language. It is used to design web pages using a markup language. HTML is the combination of Hypertext and Markup language. Hypertext defines the link between the web pages. A markup language is used to define the text document within tag which defines the structure of web pages.
HTML is used by the browser to manipulate text, images, and other content to display it in the required format.
We can change the alignment of the text using the text-align property. We can align the text in the center, Left, Right.
The text alignment can be done with CSS(Cascading Style Sheets) and HTML Attribute tag.
Note: The left alignment of the text is default. If we do not write text align attribute then our text will automatically be aligned to the left.
CSS stands for Cascading Style Sheets, HTML allows the use of these CSS to perform changes in the style of the content on a Webpage. For example, here we will use CSS to align text in an HTML Code.
Method 1: Align text to the center
HTML
<html><head>    <title>Text alignment</title>    <style>        h1{text-align: center;}    </style></head><body>    <h1>GeeksforGeeks</h1></body></html>
Method 2: Align text to right
HTML
<html><head>    <title>Text alignment</title>    <style>        h1{text-align: right;}    </style></head><body>    <h1>GeeksforGeeks</h1></body></html>
Method 3: Align text to left
HTML
<html><head>    <title>Text alignment</title>    <style>        h1{text-align: left;}    </style></head><body>    <h1>GeeksforGeeks</h1></body></html>
Note: The text aligned to left is default.
Method 1: Align text to center
HTML
<html><head>    <title>Text alignment</title></head><body>    <h1 align="center">GeeksforGeeks</h1></body></html>
Method 2: Align text to right
HTML
<html><head>    <title>Text alignment</title></head><body>    <h1 align="right">GeeksforGeeks</h1></body></html>
Method 3: Align Text to Left
HTML
<html><head>    <title>Text alignment</title></head><body>    <h1 align="left">GeeksforGeeks</h1></body></html>
Note: The text aligned to left is default.
Picked
class 7
How To
School Learning
School Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
HTML Background Images
Understanding Layers in Photoshop
How to Use the Patch Tool in Photoshop?
Learn Photoshop Note and Count Tool
How to Use the Blur and Sharpen Tool in Photoshop?
How to Install PIP on Windows ?
How to Find the Wi-Fi Password Using CMD in Windows?
How to install Jupyter Notebook on Windows?
How to Install OpenCV for Python on Windows?
How to filter object array based on attributes?
How to get the FPS value in OpenCV using C++?

To get the FPS value, we used the 'get()' command of and 'CAP_PROP_FPS' as the argument of the 'get()'. This argument returns the FPS in integer form.
At the starting of the program, we have taken an integer variable named 'FPS'. Then we used FPS = cap.get(CAP_PROP_FPS); to store the FPS value in the variable.
The following program gets the FPS of a video and shows it in the console window.
#include<opencv2/opencv.hpp>//OpenCV header to use VideoCapture class//
#include<iostream>
using namespace std;
using namespace cv;
int main() {
   int FPS;//Declaring an integer variable to store the number of total frames//
   VideoCapture cap("video1.mp4");//Declaring an object to capture stream of frames from default camera//
   FPS = cap.get(CAP_PROP_FPS);//Getting the total number of frames//
   cout << "Total Number of frames are:" << FPS << endl;//Showing the number in console window//
   system("pause");//Pausing the system to see the result
   cap.release();//Releasing the buffer memory//
   return 0;
}
After launching this program, we will get the FPS value in the console window.
Check whether String is an interface or class in Java

The method java.lang.Class.isInterface() is used to find if String is an interface or class in Java. This method returns true if String is an interface, otherwise it returns false.
A program that demonstrates this is given as follows −
 Live Demo
package Test;
import java.lang.*;
public class Demo {
   public static void main(String[] args) {
      Class c = String.class;
      boolean interfaceFlag = c.isInterface();
      System.out.println("This is an Interface? " + interfaceFlag);
   }
}
This is an Interface? false
Now let us understand the above program.
The isInterface() method is used to find if String is an interface or not. The result is stored in interfaceFlag and then displayed. A code snippet which demonstrates this is as follows −
Class c = String.class;
boolean interfaceFlag = c.isInterface();
System.out.println("This is an Interface? " + interfaceFlag);
What permission do I need to access Internet from an Android application?

<uses-permission android:name="android.permission.INTERNET"/>
This example demonstrates how do I open google from android app using Internet permission.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical"
   android:padding="2dp"
   tools:context=".MainActivity">
   <WebView
      android:id="@+id/webView"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content">
   </WebView>
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;
public class MainActivity extends AppCompatActivity {
   WebView webView;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      webView = findViewById(R.id.webView);
      webView.loadUrl("http://www.google.com");
   }
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample">
   <uses-permission android:name="android.permission.INTERNET"/>
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
Click here to download the project code.
LESS - Mixins

Mixins are similar to functions in programming languages. Mixins are a group of CSS properties that allow you to use properties of one class for another class and includes class name as its properties. In LESS, you can declare a mixin in the same way as CSS style using class or id selector. It can store multiple values and can be reused in the code whenever necessary.
The following table demonstrates the use of LESS mixins in detail.
Mixins can be made to disappear in the output by simply placing the parentheses after it.
The mixins can contain not just properties, but they can contain selectors too.
Namespaces are used to group the mixins under a common name.
When guard is applied to namespace, mixins defined by it are used only when the guard condition returns true.
The !important keyword is used to override the particular property.
The following example demonstrates the use of mixins in the LESS file −
<html>
   <head>
      <link rel = "stylesheet" href = "style.css" type = "text/css" />
      <title>LESS Mixins</title>
   </head>

   <body>
      <h1>Welcome to Tutorialspoint</h1>
      <p class = "p1">LESS is a CSS pre-processor that enables customizable, 
      manageable and reusable style sheet for web site.</p>
      <p class = "p2">LESS is a dynamic style sheet language that extends the capability of CSS.</p>
      <p class = "p3">LESS is cross browser friendly.</p>
   </body>
</html>
Next, create the style.less file.
.p1 {
   color:red;
}

.p2 {
   background : #64d9c0;
   .p1();
}

.p3 {
   background : #LESS520;
  .p1;
}
You can compile the style.less to style.css by using the following command −
lessc style.less style.css

Execute the above command; it will create the style.css file automatically with the following code −
.p1 {
   color: red;
}

.p2 {
   background: #64d9c0;
   color: red;
}

.p3 {
   background: #LESS520;
   color: red;
}
Follow these steps to see how the above code works −
Save the above html code in the less_mixins.html file.
Save the above html code in the less_mixins.html file.
Open this HTML file in a browser, the following output will get displayed.
Open this HTML file in a browser, the following output will get displayed.
The parentheses are optional when calling mixins. In the above example, both statements .p1(); and .p1; do the same thing.

    20 Lectures 
     1 hours 

 Anadi Sharma

    44 Lectures 
     7.5 hours 

 Eduonix Learning Solutions

    17 Lectures 
     2 hours 

 Zach Miller

    23 Lectures 
     1.5 hours 

 Zach Miller

    34 Lectures 
     4 hours 

 Syed Raza

    31 Lectures 
     3 hours 

 Harshit Srivastava
 Print
 Add Notes
 Bookmark this page
How to use if clause in MySQL to display Students result as Pass or Fail in a new column?

Let us first create a table −
mysql> create table DemoTable
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> Name varchar(100),
   -> Subject varchar(100),
   -> Score int
   -> );
Query OK, 0 rows affected (0.94 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable(Name,Subject,Score) values('Chris','MySQL',80);
Query OK, 1 row affected (0.32 sec)

mysql> insert into DemoTable(Name,Subject,Score) values('Robert','MongoDB',45);
Query OK, 1 row affected (0.62 sec)

mysql> insert into DemoTable(Name,Subject,Score) values('Adam','Java',78);
Query OK, 1 row affected (0.52 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+----+--------+---------+-------+
| Id | Name   | Subject | Score |
+----+--------+---------+-------+
|  1 | Chris  | MySQL   |    80 |
|  2 | Robert | MongoDB |    45 |
|  3 | Adam   | Java    |    78 |
+----+--------+---------+-------+
3 rows in set (0.00 sec)
Here is the query to work with if clause in MySQL to display result in the form of Pass or Fail.
mysql> select Name,Subject,Score,if(Score > 75,"PASS","FAIL") AS Status  from DemoTable;
This will produce the following output −
+--------+---------+-------+--------+
| Name   | Subject | Score | Status |
+--------+---------+-------+--------+
| Chris  | MySQL   |    80 | PASS   |
| Robert | MongoDB |    45 | FAIL   |
| Adam   | Java    |    78 | PASS   |
+--------+---------+-------+--------+
3 rows in set (0.00 sec)
Python VLC MediaPlayer - Checking if it is playing or not - GeeksforGeeks

10 Feb, 2022
In this article we will see how we can check if the video is playing in MediaPlayer object in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. MediPlyer object is the basic object in vlc module for playing the video. We can create a MediaPlayer object with the help of MediaPlayer method. We uses play method to play the video.
In order to do this we will use is_playing method with the MediaPlayer object
Syntax : media_player.is_playing()
Argument : It takes no argument
Return : It returns 0 if not playing and 1 if playing
Below is the implementation
# importing vlc moduleimport vlc  # importing time moduleimport time    # creating vlc media player objectmedia_player = vlc.MediaPlayer()  # media objectmedia = vlc.Media("death_note.mkv")  # setting media to the media playermedia_player.set_media(media)    # start playing videomedia_player.play()  # wait so the video can be played for 5 seconds# irrespective of length of videotime.sleep(5)  # checking if it is playingvalue = media_player.is_playing()  # printing valueprint("Is playing : ")print(value)
Output :
Is playing : 
1

Another exampleBelow is the implementation
# importing vlc moduleimport vlc  # importing time moduleimport time  # creating vlc media player objectmedia_player = vlc.MediaPlayer()  # media objectmedia = vlc.Media("1mp4.mkv")  # setting media to the media playermedia_player.set_media(media)      # start playing video + commenting it # media_player.play()  # wait so the video can be played for 5 seconds# irrespective of length of videotime.sleep(5)  # checking if it is playingvalue = media_player.is_playing()  # printing valueprint("Is playing : ")print(value)
Output :
Is playing : 
0

kumaripunam984122
Python vlc-library
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Selecting rows in pandas DataFrame based on conditions
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | os.path.join() method
Python | Get unique values from a list
Defaultdict in Python
Create a directory in Python
Python | Pandas dataframe.groupby()
PHP 7 - Closure::call()

Closure::call() method is added as a shorthand way to temporarily bind an object scope to a closure and invoke it. It is much faster in performance as compared to bindTo of PHP 5.6.
<?php
   class A {
      private $x = 1;
   }

   // Define a closure Pre PHP 7 code
   $getValue = function() {
      return $this->x;
   };

   // Bind a clousure
   $value = $getValue->bindTo(new A, 'A'); 

   print($value());
?>
It produces the following browser output −
1

<?php
   class A {
      private $x = 1;
   }

   // PHP 7+ code, Define
   $value = function() {
      return $this->x;
   };

   print($value->call(new A));
?>
It produces the following browser output −
1


    45 Lectures 
     9 hours 

 Malhar Lathkar

    34 Lectures 
     4 hours 

 Syed Raza

    84 Lectures 
     5.5 hours 

 Frahaan Hussain

    17 Lectures 
     1 hours 

 Nivedita Jain

    100 Lectures 
     34 hours 

 Azaz Patel

    43 Lectures 
     5.5 hours 

 Vijay Kumar Parvatha Reddy
 Print
 Add Notes
 Bookmark this page
Write a Python program to export dataframe into an Excel file with multiple sheets

Assume, you have a dataframe and the result for export dataframe to multiple sheets as,
To solve this, we will follow the steps given below −
import xlsxwriter module to use excel conversion
import xlsxwriter module to use excel conversion
Define a dataframe and assign to df
Define a dataframe and assign to df
Apply pd.ExcelWriter function inside name excel name you want to create and set engine as xlsxwriter
Apply pd.ExcelWriter function inside name excel name you want to create and set engine as xlsxwriter
excel_writer = pd.ExcelWriter('pandas_df.xlsx', engine='xlsxwriter')
Convert the dataframe to multiple excel sheets using the below method,
Convert the dataframe to multiple excel sheets using the below method,
df.to_excel(excel_writer, sheet_name='first_sheet')
df.to_excel(excel_writer, sheet_name='second_sheet')
df.to_excel(excel_writer, sheet_name='third_sheet')
Finally save the excel_writer
Finally save the excel_writer
excel_writer.save()
Let’s understand the below code to get a better understanding −
import pandas as pd
import xlsxwriter
df = pd.DataFrame({'Fruits': ["Apple","Orange","Mango","Kiwi"],
                     'City' : ["Shimla","Sydney","Lucknow","Wellington"]
                  })
print(df)
excel_writer = pd.ExcelWriter('pandas_df.xlsx', engine='xlsxwriter')
df.to_excel(excel_writer, sheet_name='first_sheet')
df.to_excel(excel_writer, sheet_name='second_sheet')
df.to_excel(excel_writer, sheet_name='third_sheet')
excel_writer.save()
Apache Pig - TOP()

The TOP() function of Pig Latin is used to get the top N tuples of a bag. To this function, as inputs, we have to pass a relation, the number of tuples we want, and the column name whose values are being compared. This function will return a bag containing the required columns.
Given below is the syntax of the function TOP().
grunt> TOP(topN,column,relation)

Assume we have a file named employee_details.txt in the HDFS directory /pig_data/, with the following content.
employee_details.txt
001,Robin,22,newyork 
002,BOB,23,Kolkata 
003,Maya,23,Tokyo 
004,Sara,25,London 
005,David,23,Bhuwaneshwar 
006,Maggy,22,Chennai 
007,Robert,22,newyork 
008,Syam,23,Kolkata 
009,Mary,25,Tokyo 
010,Saran,25,London 
011,Stacy,25,Bhuwaneshwar 
012,Kelly,22,Chennai

We have loaded this file into Pig with the relation name emp_data as shown below.
grunt> emp_data = LOAD 'hdfs://localhost:9000/pig_data/ employee_details.txt' USING PigStorage(',')
   as (id:int, name:chararray, age:int, city:chararray);
Group the relation emp_data by age, and store it in the relation emp_group.
grunt> emp_group = Group emp_data BY age;
Verify the relation emp_group using the Dump operator as shown below.
grunt> Dump emp_group;
  
(22,{(12,Kelly,22,Chennai),(7,Robert,22,newyork),(6,Maggy,22,Chennai),(1,Robin, 22,newyork)}) 
(23,{(8,Syam,23,Kolkata),(5,David,23,Bhuwaneshwar),(3,Maya,23,Tokyo),(2,BOB,23, Kolkata)}) 
(25,{(11,Stacy,25,Bhuwaneshwar),(10,Saran,25,London),(9,Mary,25,Tokyo),(4,Sara, 25,London)})

Now, you can get the top two records of each group arranged in ascending order (based on id) as shown below.
grunt> data_top = FOREACH emp_group { 
   top = TOP(2, 0, emp_data); 
   GENERATE top; 
}
In this example we are retriving the top 2 tuples of a group having greater id. Since we are retriving top 2 tuples basing on the id, we are passing the index of the column name id as second parameter of TOP() function.
You can verify the contents of the data_top relation using the Dump operator as shown below.
grunt> Dump data_top;
  
({(7,Robert,22,newyork),(12,Kelly,22,Chennai)}) 
({(5,David,23,Bhuwaneshwar),(8,Syam,23,Kolkata)}) 
({(10,Saran,25,London),(11,Stacy,25,Bhuwaneshwar)})


    46 Lectures 
     3.5 hours 

 Arnab Chakraborty

    23 Lectures 
     1.5 hours 

 Mukund Kumar Mishra

    16 Lectures 
     1 hours 

 Nilay Mehta

    52 Lectures 
     1.5 hours 

 Bigdata Engineer

    14 Lectures 
     1 hours 

 Bigdata Engineer

    23 Lectures 
     1 hours 

 Bigdata Engineer
 Print
 Add Notes
 Bookmark this page
Install Visual Studio Code in Kali Linux - GeeksforGeeks

17 Jun, 2021
Visual Studio Code is an open-source, cross-platform source-code editor developed by Microsoft. It is used by developers for developing software and writing code using programming languages such as C, C++, Python, Go, Java, etc. Visual Studio Code employs the same editor used in Azure, DevOps 
Debugging
Syntax highlighting
Intelligent code completion
Code refactoring
In this article, we will show you the installation process of the Visual Studio Code on Kali Linux (or other Ubuntu/Debian-based Linux). 
To install Visual Code Studio on Debian-based systems, you have to enable the VS Code repository and install the Visual Studio Code package using the apt package manager.
The steps for installing Visual Code Studio is as follows:
Step 1: First, you have to update your system using the following command:
$ sudo apt update
Step 2: Now, after your system is updated, install the required dependencies for  Visual Code Studio by using the following command:-
$ sudo apt install software-properties-common apt-transport-https
Step 3: Next, download the repository using the wget command, import Microsoft’s GPG key, and add it to your kali source list by using the following commands:-
$ wget -qO- https://packages.microsoft.com/keys/microsoft.asc | gpg –dearmor > packages.microsoft.gpg
$ sudo install -o root -g root -m 644 packages.microsoft.gpg /etc/apt/trusted.gpg.d/
$ sudo sh -c ‘echo “deb [arch=amd64 signed-by=/etc/apt/trusted.gpg.d/packages.microsoft.gpg] https://packages.microsoft.com/repos/vscode stable main” > /etc/apt/sources.list.d/vscode.list’
Step 4: Once you’ve done with the above steps, next you have to update the system and install Visual Studio Code by running the following commands:-
$ sudo apt update
$ sudo apt install code
Step 5: Once the installation of  Visual Studio Code is completed,  go search for  Visual Code Studio from the application manager and you can see it over the screen like this:-
Kali-Linux
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
nohup Command in Linux with Examples
scp command in Linux with Examples
Thread functions in C/C++
mv command in Linux with examples
chown command in Linux with Examples
SED command in Linux | Set 2
Docker - COPY Instruction
Array Basics in Shell Scripting | Set 1
Basic Operators in Shell Scripting
nslookup command in Linux with Examples
What is Scanner class in Java? when was it introduced?

Until Java 1.5 to read data from the user programmers used to depend on the character stream classes and byte stream classes.
From Java 1.5 Scanner class was introduced. This class accepts a File, InputStream, Path and, String objects, reads all the primitive data types and Strings (from the given source) token by token using regular expressions.
By default, whitespace is considered as the delimiter (to break the data into tokens).
To read various datatypes from the source using the nextXXX() methods provided by this class namely, nextInt(), nextShort(), nextFloat(), nextLong(), nextBigDecimal(), nextBigInteger(), nextLong(), nextShort(), nextDouble(), nextByte(), nextFloat(), next().
Example − Reading data from keyboard
Following Java program reads name, date of birth, roll number and, percent from the user and prints back his age and grade. Here, we are using the methods of Scanner class to read the data.
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.Period;
import java.time.ZoneId;
import java.util.Date;
import java.util.Scanner;
public class ScannerExample {
   public static void main(String args[]) throws Exception {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter your name: ");
      String name = sc.next();
      System.out.println("Enter your date of birth (dd-MM-yyyy): ");
      String dob = sc.next();
      System.out.println("Enter your roll number: ");
      int rollNumber = sc.nextInt();
      System.out.println("Enter your percentage: ");
      float percent = sc.nextFloat();
      //Getting Date object from given String
      Date date = new SimpleDateFormat("dd-MM-yyyy").parse(dob);
      LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
      //Calculating age
      Period period = Period.between(localDate, LocalDate.now());
      System.out.print("Hello "+name+" your current age is: ");
      System.out.print(period.getYears()+" years "+period.getMonths()+" and "+period.getDays()+" days");
      System.out.println();
      if(percent>=80){
         System.out.println("Your grade is: A");
      } else if(percent>=60 && percent<80) {
         System.out.println("Your grade is: B");
      }
      else if(percent>=40 && percent<60){
         System.out.println("Your grade is: C");
      } else {
         System.out.println("Your grade is: D");
      }
   }
}
Enter your name:
Krishna
Enter your date of birth (dd-MM-yyyy):
26-09-1989
Enter your roll number:
1254
Enter your percentage:
83
Hello Krishna your current age is: 29 years 9 and 5 days
Your grade is: A
Program to equal two strings of same length by swapping characters in Python

Suppose we have two strings s and t of length n. We can take one character from s and another
from t and swap them. We can make unlimited number of swaps; we have to check whether it's
possible to make the two strings equal or not.
So, if the input is like s = "xy", t = "yx", then the output will be True
To solve this, we will follow these steps −
st:= sort the string after concatenating s and t
for i in range 0 to size of st - 1, increase by 2, doif st[i] is not same as st[i+1], thenreturn False
if st[i] is not same as st[i+1], thenreturn False
return False
return True
Let us see the following implementation to get better understanding −
 Live Demo
class Solution:
   def solve(self, s, t):
      st=sorted(s+t)
      for i in range(0,len(st),2):
         if st[i]!=st[i+1]:
            return False
      return True
ob = Solution()
print(ob.solve("xy", "yx"))
"xy", "yx"
True
PHP | current() Function

14 Feb, 2022
The current() function is an inbuilt function in PHP.
It is used to return the value of the element in an array which the internal pointer is currently pointing to.
The current() function does not increment or decrement the internal pointer after returning the value.
In PHP, all arrays have an internal pointer. This internal pointer points to some element in that array which is called as the current element of the array.
Usually, the current element is the first inserted element in the array.
Syntax: 
current($array)
Parameters: The current() function accepts a single parameter $array. It is the array of which we want to find the current element.
Return Values: It returns the value of the element in the array which the internal pointer is currently pointing to. If the array is empty then the current() function returns FALSE.
Examples:  
Input : current(array("John", "b", "c", "d"))
Output : John
Explanation : Here as we see that input array contains 
many elements and the output is "John" because first 
element is John and current() function returns 
the element to which internal pointer is currently
pointing.

Input: current(array("abc", "123", "7"))
Output: abc
Below programs illustrate the current() function in PHP:
Program 1: 
PHP
<?php // input array$arr = array("Ram", "Shita", "Geeta"); // Here current function returns the//  first element of the array.echo current($a); ?>
Output: 
Ram
Program 2: 
PHP
<?php $arr = array('Sham', 'Mac', 'Jhon', 'Adwin'); // Here current element is Sham.echo current($arr)."\n"; // increment internal pointer to point// to next element i.e, Macecho next($arr)."\n"; // printing the current element as// for now current element is Mac.echo current($arr)."\n"; // increment internal pointer to point// to next element i.e, Jhon.echo next($arr)."\n"; // increment internal pointer to point// to next element i.e, Adwin.echo next($arr)."\n"; // printing the current element as for// now current element is Adwin.echo current($arr)."\n"; ?>
Output: 
Sham
Mac
Mac
Jhon
Adwin
Adwin
Note: The current() function returns False when array is empty i.e, do not contain any elements, and also it returns false when internal pointer go out of the bound i.e beyond the end of the last element.
Reference: http://php.net/manual/en/function.current.php 
Akanksha_Rai
arorakashish0911
varshagumber28
PHP-array
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
killall Command in Linux with Examples

02 Nov, 2020
Have you ever confronted the circumstance where you executed a program or an application, and abruptly while you are utilizing the application, it gets halted and starts to crash? You attempt to begin the application again, yet nothing happens on the grounds that the first application measure never genuinely closes down totally. The arrangement is to end the application cycle. Fortunately, there are a few utilities in Linux that permits you to execute the kill process.
It is recommended to read kill Command before proceeding further.
The primary contrast between the kill and killall command is that the “kill” ends process cycles dependent on Process ID number (PID), while the killall orders end running cycles dependent on their names and different attributes. Normal users can end/kill their own cycles(processes), however not those that have a place with different users, while the root client can end all cycles.
The ionice device acknowledges the accompanying alternatives:
Tag
Description
To know the contrast among kill and killall orders we first need to ensure that we comprehend the nuts and bolts behind cycles on the Linux OS. The process is an occurrence of a running system. Each process cycle is allotted PID ( Process ID ) which is remarkable for each cycle and in this way, no two cycles can be allocated the same PID. When the cycle is ended the PID is accessible for reuse. 
General Syntax:
killall [ -Z CONTEXT ] [ -u USER ] [ -y TIME ] [ -o TIME ] [ -eIgiqrvw ] [ -s SIGNAL | -SIGNAL ] NAME...

1. The command below will begin the process yes and yield its standard output to/dev/null. What we are keen on here, is the second line which contains the accompanying data “[1]” ( work ID ) and “16017” the real PID. On your Linux OS, you can run numerous cycles at some random time and each cycle, contingent upon the client benefits can be ended utilizing either kill or killall orders.
$ yes > /dev/null &

$ jobs

3. The contrast between kill versus killall commands is that with kill order we can end just a solitary cycle at that point, though with killall order we can end numerous cycles dependent on given models, for example, process group, process age, or client privilege. Now, we will use “kill” command to terminate the process with PID “16022”:
$ sudo kill 16022

Now, from the above command, we have terminated the process with PID 16022, and it was processed no. [4]. We can also verify the command execution by giving the “jobs” command:
4. Ending each cycle individually can end up being hard and repetitive work. We should see whether we can get some assistance by utilizing killall order and process cycle name:
$ sudo killall yes

Now, we can easily observe that all processes running under the name “yes” have been terminated successfully.
linux-command
Linux-system-commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Program to Get Current Stack Trace Information Using Environment Class

21 Nov, 2021
In C#, Environment Class provides information about the current platform and manipulates, the current platform. It is useful for getting and setting various operating system-related information. We can use it in such a way that it retrieves command-line arguments information, exit codes information, environment variable settings information, contents of the call stack information, and time since the last system boot in milliseconds information. By just using some predefined methods we can get the information of the Operating System using the Environment class. Here in this article, we are using the StackTrace property to get the current stack trace information. This property is used to get the current stack trace information
Syntax:
string Environment.StackTrace
Return: string and gives the class name along with id 
Example 1:
C#
// C# program to find the current stack trace informationusing System; class GFG{ static public void Main(){         // Define the variable with string    string my_variable = "Hello Geeks";     // Get the current stack trace details    // Using StackTrace property    my_variable = Environment.StackTrace;    Console.WriteLine("Information of current stack trace: \n" +                      my_variable);}}
Output:
Current Stack Trace Details: 
  at System.Environment.get_StackTrace () [0x00000] in <a1ae6166591d4020b810288d19af38d4>:0 
  at GFG.Main () [0x00000] in <ec0c23afce674aedba9f00d218402cf6>:0
Example 2:
C#
// C# program to find the current stack trace informationusing System; class GFG{ static public void Main(){         // Define the variable with integer    string my_variable = "58";         // Get the current stack trace details    // Using StackTrace property    my_variable = Environment.StackTrace;    Console.WriteLine("Information of current stack trace: \n" +                      my_variable);}}
Output:
Current Stack Trace Details: 
  at System.Environment.get_StackTrace () [0x00000] in <a1ae6166591d4020b810288d19af38d4>:0 
  at GFG.Main () [0x00000] in <092e5ea1577d4af6be34040e9472afab>:0 
simmytarika5
CSharp-programs
Picked
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
matplotlib.axes.Axes.twiny() in Python

21 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.
The Axes.twiny() function in axes module of matplotlib library is used to create a twin Axes sharing the yaxis.
Syntax: Axes.twiny(self)
Return value: This method is used to returns the following.
ax_twin : This returns the newly created Axes instance.
Below examples illustrate the matplotlib.axes.Axes.twiny() function in matplotlib.axes:
Example 1:
# Implementation of matplotlib function# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np      def GFG1(temp):    return (5. / 9.) * (temp - 32)   def GFG2(ax1):    y1, y2 = ax1.get_ylim()    ax_twin .set_ylim(GFG1(y1), GFG1(y2))    ax_twin .figure.canvas.draw()   fig, ax1 = plt.subplots()ax_twin = ax1.twiny()   ax1.callbacks.connect("ylim_changed", GFG2)ax1.plot(np.linspace(-40, 120, 100))ax1.set_ylim(0, 100)   ax1.set_xlabel('Fahrenheit')ax_twin .set_xlabel('Celsius')  fig.suptitle('matplotlib.axes.Axes.twiny()\ function Example\n\n', fontweight ="bold")plt.show()
Output:
Example 2:
# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt  # Create some mock datat = np.arange(0.01, 10.0, 0.001)data1 = np.exp(t)data2 = np.sin(0.4 * np.pi * t)  fig, ax1 = plt.subplots()  color = 'tab:blue'ax1.set_ylabel('time (s)')ax1.set_xlabel('exp', color = color)ax1.plot(data1, t, color = color)ax1.tick_params(axis ='x', labelcolor = color)  ax2 = ax1.twiny()  color = 'tab:green'ax2.set_xlabel('sin', color = color)ax2.plot(data2, t, color = color)ax2.tick_params(axis ='x', labelcolor = color)  fig.suptitle('matplotlib.axes.Axes.twiny()\ function Example\n\n', fontweight ="bold")plt.show()
Output:
Python-matplotlib
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
Introduction To PYTHON
Python OOPs Concepts
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python - Pandas dataframe.append()
Create a directory in Python
Setting full screen iframe in JavaScript?

Following is the code for setting full screen iframe in JavaScript −
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result {
      font-weight: 500;
      font-size: 18px;
      color: blueviolet;
   }
   .fullScreen {
      width: 100vw;
      height: 100vh;
   }
</style>
</head>
<body>
<h1>Setting full screen iframe</h1>
<iframe class="frame" src="https://www.wikipedia.com" width="300px" height="200px"
></iframe>
<button class="Btn" style="margin: 15px;">Fullscreen</button>
<h3>Click on the above button to make the iframe go fullscreen</h3>
<script>
   let BtnEle = document.querySelector(".Btn");
   let frameEle = document.querySelector(".frame");
   BtnEle.addEventListener("click", () => {
      frameEle.className = "fullScreen";
   });
</script>
</body>
</html>
On clicking the ‘Fullscreen’ button −
Perl lock Function

This function places an advisory lock on a shared variable, or referenced object contained in THING until the lock goes out of scope.
lock() is a "weak keyword" : this means that if you've defined a function by this name before any calls to it, that function will be called instead.
Following is the simple syntax for this function −
lock THING

This function does not return any value.

    46 Lectures 
     4.5 hours 

 Devi Killada

    11 Lectures 
     1.5 hours 

 Harshit Srivastava

    30 Lectures 
     6 hours 

 TELCOMA Global

    24 Lectures 
     2 hours 

 Mohammad Nauman

    68 Lectures 
     7 hours 

 Stone River ELearning

    58 Lectures 
     6.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page