code-rag-bench/online-tutorials huggingface dataset:
When to use StringJoiner over StringBuilder?

11 Aug, 2021
Prerequisite: StringJoinerStringJoiner is very useful, when you need to join Strings in a Stream. Task : Suppose we want the string “[George:Sally:Fred]”, where we have given a string array that contains “George”, “Sally” and “Fred”.StringJoiner provide add(String str) method to concatenate the strings based on supplied delimiter,prefix and suffix in the constructor, but if we use StringBuilder to perform our task then first we have to append prefix and then iterate through string array and append the required delimiter after each element and finally append the prefix. Below is the java program to demonstrate both ways. 
Java
// Java program to demonstrate use of// StringJoiner class over StringBuilder class import java.util.StringJoiner; public class Test{    public static void main(String[] args)    {        // given string array        String str[] = {"George","Sally","Fred"};                     // By using StringJoiner class                     // initializing StringJoiner instance with        // required delimiter, prefix and suffix        StringJoiner sj = new StringJoiner(":", "[", "]");                     // concatenating strings        sj.add("George").add("Sally").add("Fred");                     // converting StringJoiner to String        String desiredString = sj.toString();                     System.out.println(desiredString);                     // By using StringBuilder class                     // declaring empty stringbuilder        StringBuilder sb = new StringBuilder();                     // appending prefix        sb.append("[");                     // checking for empty string array        if(str.length>0)        {            // appending first element            sb.append(str[0]);                             // iterating through string array            // and appending required delimiter            for (int i = 1; i < str.length; i++)            {                sb.append(":").append(str[i]);            }        }                     // finally appending suffix        sb.append("]");                     // converting StringBuilder to String        String desiredString1 = sb.toString();                     System.out.println(desiredString1);    }}
Output:  
[George:Sally:Fred]
[George:Sally:Fred]
This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
simmytarika5
surindertarika1234
Java-Library
Java-String-Programs
Java-Strings
Java
Java-Strings
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python JSON

09 Dec, 2020
JSON JavaScript Object Notation is a format for structuring data. It is mainly used for storing and transferring data between the browser and the server. Python too supports JSON with a built-in package called json. This package provides all the necessary tools for working with JSON Objects including parsing, serializing, deserializing, and many more. Let’s see a simple example where we convert the JSON objects to Python objects and vice-versa.
Example:
Python3
import json  # JSON stringemployee = '{"id":"09", "name": "Nitin", "department":"Finance"}'  # Convert string to Python dictemployee_dict = json.loads(employee)print(employee_dict)print(type(employee_dict))print("\n")  # Convert Python dict to JSONjson_object = json.dumps(employee_dict, indent=4)print(json_object)print(type(json_object))
Output:
 {'id': '09', 'name': 'Nitin', 'department': 'Finance'}
<class 'dict'>


{
    "id": "09",
    "name": "Nitin",
    "department": "Finance"
}
<class 'str'>
This JSON Tutorial will help you learn the working of JSON with Python from basics to advance, like parsing JSON, reading and writing to JSON file, serializing and deserializing JSON using a huge set of JSON programs.
What is JSON?
Data types in JSON
Working With JSON Data in Python
Read, Write and Parse JSON using Python
Reading and Writing JSON to a File in Python
Read JSON file using Python
Append to JSON file using Python
How to Parse Data From JSON into Python?
How To Convert Python Dictionary To JSON?
Python – Convert JSON to string
Ways to convert string to json object
Convert JSON data Into a Custom Python Object
Serializing JSON in Python
json.dump() in Python
json.dumps() in Python
Python – Difference between json.dump() and json.dumps()
Deserialize JSON to Object in Python
json.load() in Python
json.loads() in Python
Difference Between json.load() and json.loads()
Encoding and Decoding Custom Objects in Python-JSON
Serialize and Deserialize complex JSON in Python
Python – JSON to XML
Python – XML to JSON
Convert CSV to JSON using Python
Convert multiple JSON files to CSV Python
Convert Text file to JSON in Python
Saving Text, JSON, and CSV to a File in Python
JSON Formatting in Python
Pretty Print JSON in Python
Flattening JSON objects in Python
Check whether a string is valid json or not
Sort JSON by value
JSON
Python-json
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Python map() function
Adding new column to existing DataFrame in Pandas
How to get column names in Pandas dataframe
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
How to Install PIP on Windows ?
Python String | replace()
Python OOPs Concepts
MoviePy – Getting Duration of Video File Clip

01 Aug, 2020
In this article we will see how we can get the duration of the video file clip in MoviePy. MoviePy is a Python module for video editing, which can be used for basic operations on videos and GIF’s. Duration is basically length of the video i.e how long the video is, it is in seconds.
In order to do this we will use duration method with the VideoFileClip object
Syntax : clip.duration
Argument : It takes no argument
Return : It returns float
Below is the implementation
# Import everything needed to edit video clipsfrom moviepy.editor import *     # loading video dsa gfg intro videoclip = VideoFileClip("dsa_geek.webm")   # getting only first 5 secondsclip = clip.subclip(0, 5)  # getting duration of the videoduration = clip.duration  # printing durationprint("Duration : " + str(duration))  # showing final clipclip.ipython_display()
Output :
Duration : 5
Moviepy - Building video __temp__.mp4.
Moviepy - Writing video __temp__.mp4

                                                                                                                       
Moviepy - Done !
Moviepy - video ready __temp__.mp4
Another example
# Import everything needed to edit video clipsfrom moviepy.editor import *  # loading video gfgclip = VideoFileClip("geeks.mp4")    # getting duration of the videoduration = clip.duration  # printing durationprint("Duration : " + str(duration))  # showing final clipclip.ipython_display()
Output :
Duration : 10.98
Moviepy - Building video __temp__.mp4.
MoviePy - Writing audio in __temp__TEMP_MPY_wvf_snd.mp3
                                                                                                                       
MoviePy - Done.
Moviepy - Writing video __temp__.mp4

                                                                                                                       
Moviepy - Done !
Moviepy - video ready __temp__.mp4
Python-MoviePy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Convert integer to string in Python
Access Token Error Response and Codes

Access token is a type of token that is assigned by the authorization server. The authorization server issues the access token, if the access token request is valid and authorized. If the token access request is invalid or unauthorized, then the authorization server returns an error response.
For information on access token response, click this link
The application can handle error response by sending them to redirect_uri.
For instance −
GET http://www.site.com/?error=access_denied&error_description=the+user+canceled+authentication

The above URI contains the following parameters −
error − It specifies the error code if there is an invalid request, invalid client, invalid grant, or unauthorized client.
error − It specifies the error code if there is an invalid request, invalid client, invalid grant, or unauthorized client.
error_description − It defines the detail description of the error.
error_description − It defines the detail description of the error.
Following are the various error codes, which can occur when there are errors at the authorization endpoint.
invalid_request
This error occurs when there is a missing parameter that includes multiple credentials, unsupported parameter value.
unauthorized_client
The unauthorized client is not allowed to access the authorization grant type.
access_denied
It specifies the user will have no access permission to files or subfolders.
unsupported_response_type
It specifies the response type is not supported by the authorization server.
server_error
This error code is mainly used when 500 internal server cannot be returned to the client by using HTTP redirect.
temporarily_unavailable
It specifies that the server is unable to handle the request during overloading of server or during server maintenance.
Introduction to TELNET

19 Jul, 2021
TELNET stands for TErminaL NETwork. It is a type of protocol that enables one computer to connect to local computer. It is a used as a standard TCP/IP protocol for virtual terminal service which is given by ISO. Computer which starts connection known as the local computer. Computer which is being connected to i.e. which accepts the connection known as remote computer. When the connection is established between local and remote computer. During telnet operation whatever that is being performed on the remote computer will be displayed by local computer. Telnet operates on client/server principle. Local computer uses telnet client program and the remote computers uses telnet server program. 
TELNET Commands : Commands of the telnet are identified by a prefix character, Interpret As Command (IAC) which is having code 255. IAC is followed by command and option codes. Basic format of the command is as shown in the following figure : 
 
Figure – Telnet command format 
Following are some of the important TELNET commands : 
 
Following are some common options used with the telnet :  
Modes of Operation : Most telnet implementation operates in one of the following three modes : 
Default mode
Character mode
Line mode
Default Mode : 
If there is no other modes are invoked then this mode is used.
Echoing is performed in this mode by client.
In this mode, user types a character and client echoes the character on the screen but it does not send it until whole line is completed.
Character Mode : 
Each character typed in this mode is sent by client to server.
Server in this type of mode is normally echoes character back to be displayed on the client’s screen.
Line Mode :  
Line editing like echoing, character erasing etc. is done from the client side.
Client will send the whole line to the server.
ratnadeepbh1999
Computer Networks
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Types of Network Topology
Socket Programming in Python
Differences between IPv4 and IPv6
Wireless Application Protocol
GSM in Wireless Communication
Secure Socket Layer (SSL)
Mobile Internet Protocol (or Mobile IP)
Data encryption standard (DES) | Set 1
TCP 3-Way Handshake Process
Types of Transmission Media
Python Program to create an OTP by squaring and concatenating the odd digits of a number

19 Feb, 2020
Given a number n. The task is to create an OTP by squaring and concatenating the odd digits of the number.
Examples:
Input: 4365188
Output: 9256

Input: 123456
Output: 4163

Explanation: In the First example, the integers at odd places are 3, 5, and 8. So we have to return a 4 digit OTP by squaring the digits. The square of the above digits are 9, 25, 65 so the OTP to be returned is the first four digits 9256.
Approach: Iterate through the length of the string (number) with the starting index as 1 and taking the step as 2. Initialize an empty string and then concatenate the squares of the odd digit to that string. Finally, return the first four characters of the string as an OTP.
Below is the implementation.
# python program to generate# an OTP from the squares of the# odd digits    def OTP(number):          # Finding the length     # of the string    length = len(number)          # Declaring an empty string     # for storing otp    otp = ''          # Iterating from index 1     # with step as 2    for odd in range(1, length, 2):                  # Concatenating the output        # to the string         otp+= str(int(number[odd])**2)              print(otp[0:4])  # Driver codenumber = '4365188'OTP(number)
Output:
9256

Python string-programs
Technical Scripter 2019
Python
Python Programs
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
Python for Matlab Users. One common issue I have noticed people... | by Syed Sadat Nazrul | Towards Data Science

One common issue I have noticed people are facing (especially in the Engineering world) is the transition from academia to industry. Most schools prefer having us use Matlab. Whether you are an electrical engineer, chemical engineer or even a nanoengineer, most likely you have had to use Matlab throughout your college career (other than a tiny bit of C/C++). A recent trend in industry had been the transition from Matlab to Python. This could be due to the $1000+ licensing fees, inefficiencies of memory allocation, lack of open source libraries or even the fact that most software developers hate the Matlab syntax. Lucky for us, the syntax in Matlab and Python are very similar (if you ignore the fact that Matlab indices start from 1 instead of 0). On this tutorial, I have covered the basics of Python for Matlab users, in the realm of data analytics and visualization.
While the code is available on this blog, I have also posted the same material on youtube:
One of the first things things Matlab users will be interested in will be linear algebra and matrix manipulation. Python’s math library, numpy, comes with various tools for performing simple math operations.
import numpy as np
Let’s assume we wish to first derive the following matrix, A:
For those of you used to the simple matlab syntax, the following can be used:
A = np.matrix('1,1,1 ; 2,4,5 ; 5,7,6')
However, Python logic works in terms of vectors. Hence, it is important to eventually get used to the following syntax:
A = np.matrix([[1,1,1],[2,4,6],[5,7,6]])
Now that we have defined our matrix, we can first get the (0,0) value:
A[0,0]
Output: 1
Next, we can only get the first column:
A[:,0]
Output:[[1] [2] [5]]
Finally, just the first row:
A[0,:]
Output:[[1 1 1]]
Now that we have managed to replicate the matrix manipulations, let’s try to perform some basic math operations. We can use the same Numpy library with the matrix A from the previous section.
Adding the values of the first row:
np.sum(A[0,:])
Output:3
Dot product of A with itself:
np.dot(A,A)
Output:[[ 8, 12, 13], [40, 60, 62], [49, 75, 83]]
Cross product of A with itself:
np.cross(A,A)
Output:[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
Finally, plotting is really important when visualizing data. Python’s Matplotlib function provides an extensive set of functions to perform plotting operations.
import matplotlib.pyplot as pltplt.figure()plt.plot(A[:,0])plt.plot(A[:,1])plt.title('Sample Matlab type Plot')plt.xlabel('X Axis')plt.ylabel('Y Axis')plt.show()
jQuery | event.namespace Property - GeeksforGeeks

20 Feb, 2019
The event.namespace property in jQuery is used to return the custom namespace whenever the event is triggered. It is used to handle tasks differently depending on the namespace used.
Syntax:
event.namespace
Parameters: This property contains single parameter event which is required. It returns the custom namespace and it comes from the event binding function.
Example 1: This example uses event.namespace property to return and remove namespace.
<!DOCTYPE html><html>      <head>    <title>        jQuery event.namespace Property    </title>          <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">    </script>          <!-- Script to use event.namespace property -->    <script>        $(document).ready(function() {            $("h3").on("custom.someNamespace", function(event) {                alert(event.namespace);            });                          $("h3").click(function(event) {                $(this).trigger("custom.someNamespace");            });                      $("button").click(function() {                $("h3").off("custom.someNamespace");            });    });      </script></head>  <body>    <center>           <h1>Welcome to GeeksforGeeks!.</h1>                   <div style="background-color:green">            <h3> Click here Geeks for Geeks.</h3>            <button>Remove namespace</button>        </div>          </center> </body>  </html>
Output:Before Click on element h3:After Click on element h3:
Example 2: This example uses click.mySomething namespace to slideToggle the content.
<!DOCTYPE html><html>      <head>    <title>        jQuery event.namespace Property    </title>          <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">    </script>          <!-- Script to use event.namespace to         slideToggle content -->    <script>        $(document).ready(function() {            $("h3").on("click.mySomething", function() {                $(this).slideToggle();            });                         $("button").click(function() {                $("h3").off("click.mySomething");            });        });    </script></head>  <body>    <center>        <h1>Welcome to GeeksforGeeks!.</h1>                   <div style="background-color:green">            <h3>1st statement : Geeks for Geeks.</h3>            <h3>2nd statement : Mathematics</h3>            <button>Click to remove namespace</button>        </div>    </center> </body>  </html>
Output:Before Click on the first statement:After Click on the first statement:
jQuery-Events
Picked
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Form validation using jQuery
How to Dynamically Add/Remove Table Rows using jQuery ?
How to Show and Hide div elements using radio buttons?
Scroll to the top of the page using JavaScript/jQuery
jQuery | children() with Examples
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
C++ New Library - operator new[]

It allocates storage space for array.
Following is the declaration for operator new[].
	
void* operator new[] (std::size_t size) throw (std::bad_alloc);   (throwing allocation)
void* operator new[] (std::size_t size, const std::nothrow_t& nothrow_value) throw();   (nothrow allocation)
void* operator new[] (std::size_t size, void* ptr) throw();   (placement)
	
void* operator new[] (std::size_t size);    (throwing allocation)
void* operator new[] (std::size_t size, const std::nothrow_t& nothrow_value) noexcept;	(nothrow allocation)
void* operator new[] (std::size_t size, void* ptr) noexcept;    (placement)
size − It contain size in bytes of the requested memory block.
size − It contain size in bytes of the requested memory block.
nothrow_value − It contains the constant nothrow.
nothrow_value − It contains the constant nothrow.
ptr − It is a pointer to an already-allocated memory block of the proper size.
ptr − It is a pointer to an already-allocated memory block of the proper size.
It returns a pointer to the newly allocated storage space.
If it fails to allocate storage then it throws bad_alloc.
It modifies the storage referenced by the returned value.
In below example explains about new operator.
#include <iostream>
#include <new>

struct MyClass {
   int data;
   MyClass() {std::cout << '@';}
};

int main () {
   std::cout << "constructions (1): ";
   MyClass * p1 = new MyClass[10];
   std::cout << '\n';

   std::cout << "constructions (2): ";
   MyClass * p2 = new (std::nothrow) MyClass[5];
   std::cout << '\n';

   delete[] p2;
   delete[] p1;

   return 0;
}
Let us compile and run the above program, this will produce the following result −
constructions (1): @@@@@@@@@@
constructions (2): @@@@@

 Print
 Add Notes
 Bookmark this page
AngularJS | currency Filter - GeeksforGeeks

17 Nov, 2021
AngularJS currency filter is used to convert a number into a currency format. If no currency format is specified currency filter uses the local currency format.Syntax: 
{{ currency_expression | currency : symbol : fractionSize}}
Parameters: It contains two parameters as mentioned above and described below:  
symbol: It is optional parameter. It is used to specify the currency symbol. The currency symbol can be any character or text.
fractionsize: It is optional parameter. It is used to specify the number of decimals.
Example 1: This example displays the number in Indian currency format.  
html
<!DOCTYPE html><html>    <head>        <title>Currency Filter</title>                 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">        </script>    </head>         <body>          <div ng-app="gfgApp" ng-controller="currencyCntrl">                         <h3>                Currency filter with currency                symbol and fraction size.            </h3>                           <p>Amount : {{ amount | currency : "Rs" : 2}}</p>          </div>          <script>            var app = angular.module('gfgApp', []);                         app.controller('currencyCntrl', function($scope) {                $scope.amount = 75;            });        </script>    </body>     </html>
Output:  
Example 2: This example display the number in currency format.  
html
<!DOCTYPE html><html>    <head>        <title>Currency Filter</title>                 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">        </script>    </head>         <body>          <div ng-app="gfgApp" ng-controller="currencyCntrl">                         <h3>                Currency filter without currency                symbol and fraction size.            </h3>                           <p>Amount : {{ amount | currency}}</p>          </div>          <script>            var app = angular.module('gfgApp', []);                         app.controller('currencyCntrl', function($scope) {                $scope.amount = 38;            });        </script>      </body></html>
Output:  
simmytarika5
surindertarika1234
Picked
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 10 Angular Libraries For Web Developers
How to use <mat-chip-list> and <mat-chip> in Angular Material ?
Angular File Upload
How to use Mat-Dialog in Angular ?
<mat-label> in Angular Material
Express.js express.Router() Function
Installation of Node.js on Linux
How to create footer to stay at the bottom of a Web page?
Convert a string to an integer in JavaScript
How to set input type date in dd-mm-yyyy format using HTML ?
Alternative to iFrames in HTML5 - GeeksforGeeks

31 Oct, 2019
Unlike iframe before it was a non standard tag, which is standardized in HTML 5. Which admittedly was implemented by all major browsers. The embed element provides an integration purpose for an external (typically non-HTML) application or interactive content. The HTML tag is used for embedding an external application or interactive content into an HTML document.
The basic tag is written like this with the URL of the embedded resource added to the src attribute (i.e. between the double quotes).The type attribute accepts the MIME type of the embedded resource.
Adjusting Height and Width
<!DOCTYPE html><html>  <body>    <center>        <h1 style="color:green">GeeksforGeeks</h1>          <p>Using "embed" as an alternative to iframes</p>        <embed src="https://ide.geeksforgeeks.org"               width="400"                height="400" />    </center></body>  </html>
Output: Using The Height and Width With Embed
Using Embed Without Borders.By default, embed don’t have a border around it. But we can also remove the border by using the style attribute and use the CSS border property.
<!DOCTYPE html><html>  <body>    <center>        <h1 style="color:green">          GeeksforGeeks      </h1>        <p>Using "embed" as an alternative to iframes</p>        <embed src="https://ide.geeksforgeeks.org/"                width="400"                height="400"               style="border:none;" />    </center></body>  </html>
Output: using embed without any borders
In embed tag we can also apply borders with different colors.
<!DOCTYPE html><html>  <body>    <center>        <h1 style="color:green">GeeksforGeeks</h1>        <p>Using embedas an alternative to iframes</p>        <embed src="https://ide.geeksforgeeks.org"                style="border:4px solid orange;" />    </center></body>  </html>
Output: Using Embed With Borders Of Colour Solid Orange
Supported Browsers: The browsers supported by Embed are listed below:
Google Chrome
Internet Explorer
Firefox
Apple Safari
Opera
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
HTML5
Picked
HTML
Technical Scripter
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Types of CSS (Cascading Style Sheet)
HTML | <img> align Attribute
Form validation using HTML and JavaScript
HTML Introduction
How to Upload Image into Database and Display it using PHP ?
Express.js express.Router() Function
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
Top 10 Angular Libraries For Web Developers
How to create footer to stay at the bottom of a Web page?
How to split at NEWLINEs in Python?

We can use the method splitlines() in string class to achieve this. For example:
>>> """some
multi line
string""".splitlines()
['some', 'multi line', 'string']
We can also specify the delimiter '\n' in the split() method as follows:
>>> """some
multi line
string""".split('\n')
 ['some', 'multi line', 'string']
Get the number of rows of an Object in R Programming - nrow() Function - GeeksforGeeks

09 Mar, 2021
nrow() function in R Language is used to return the number of rows of the specified matrix. 
Syntax: nrow(x)Parameters: x: matrix, vector, array or data frame  
Example 1:  
Python3
# R program to illustrate# nrow function # Getting R Biochemical Oxygen Demand DatasetBOD # Calling nrow() function to# get the number of rowsnrow(BOD)
Output:  
  Time demand
1    1    8.3
2    2   10.3
3    3   19.0
4    4   16.0
5    5   15.6
6    7   19.8

[1] 6
Example 2:  
Python3
# R program to illustrate# nrow function # Specifying a matrixx <- matrix(c(1, 2, 3, 4), 1, 4) # Calling the nrow() functionnrow(x)
Output:  
[1] 1
 
arorakashish0911
R DataFrame-Function
R Matrix-Function
R Object-Function
R Vector-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Replace specific values in column in R DataFrame ?
Loops in R (for, while, repeat)
Filter data by multiple conditions in R using Dplyr
How to change Row Names of DataFrame in R ?
Change Color of Bars in Barchart using ggplot2 in R
Printing Output of an R Program
Remove rows with NA in one column of R DataFrame
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
Python String decode() Method

Python string  method decode() decodes the string using the codec registered for encoding. It defaults to the default string encoding.
Str.decode(encoding='UTF-8',errors='strict')

encoding − This is the encodings to be used. For a list of all encoding schemes please visit: Standard Encodings.
encoding − This is the encodings to be used. For a list of all encoding schemes please visit: Standard Encodings.
errors − This may be given to set a different error handling scheme. The default for errors is 'strict', meaning that encoding errors raise a UnicodeError. Other possible values are 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' and any other name registered via codecs.register_error().
errors − This may be given to set a different error handling scheme. The default for errors is 'strict', meaning that encoding errors raise a UnicodeError. Other possible values are 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' and any other name registered via codecs.register_error().
Decoded string.
#!/usr/bin/python

Str = "this is string example....wow!!!";
Str = Str.encode('base64','strict');

print "Encoded String: " + Str
print "Decoded String: " + Str.decode('base64','strict')
Encoded String: dGhpcyBpcyBzdHJpbmcgZXhhbXBsZS4uLi53b3chISE=
Decoded String: this is string example....wow!!!


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
JavaScript - Array map() Method

Javascript array map() method creates a new array with the results of calling a provided function on every element in this array.
Its syntax is as follows −
array.map(callback[, thisObject]);

callback − Function that produces an element of the new Array from an element of the current one.
callback − Function that produces an element of the new Array from an element of the current one.
thisObject − Object to use as this when executing callback.
thisObject − Object to use as this when executing callback.
Returns the created array.
This method is a JavaScript extension to the ECMA-262 standard; as such it may not be present in other implementations of the standard. To make it work, you need to add the following code at the top of your script.
if (!Array.prototype.map) {
   Array.prototype.map = function(fun /*, thisp*/) {
      var len = this.length;
      
      if (typeof fun != "function")
      throw new TypeError();
      
      var res = new Array(len);
      var thisp = arguments[1];
      
      for (var i = 0; i < len; i++) {
         if (i in this)
         res[i] = fun.call(thisp, this[i], i, this);
      }
      return res;
   };
}
Try the following example.
<html>
   <head>
      <title>JavaScript Array map Method</title>
   </head>
   
   <body>
      <script type = "text/javascript">
         if (!Array.prototype.map) {
            Array.prototype.map = function(fun /*, thisp*/) {
               var len = this.length;
               
               if (typeof fun != "function")
               throw new TypeError();
               
               var res = new Array(len);
               var thisp = arguments[1];
               
               for (var i = 0; i < len; i++) {
                  if (i in this)
                  res[i] = fun.call(thisp, this[i], i, this);
               }
               return res;
            };
         }
         var numbers = [1, 4, 9];
         var roots = numbers.map(Math.sqrt);
         document.write("roots is : " + roots ); 
      </script>      
   </body>
</html>
roots is : 1,2,3  


    25 Lectures 
     2.5 hours 

 Anadi Sharma

    74 Lectures 
     10 hours 

 Lets Kode It

    72 Lectures 
     4.5 hours 

 Frahaan Hussain

    70 Lectures 
     4.5 hours 

 Frahaan Hussain

    46 Lectures 
     6 hours 

 Eduonix Learning Solutions

    88 Lectures 
     14 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page
Adjacent Sibling Selectors in CSS

The CSS adjacent sibling selector is used to select the adjacent sibling of an element. It is used to select only those elements which immediately follow the first selector.
The syntax for CSS adjacent sibling selector is as follows −
element + element {
   /*declarations*/
}
The following examples illustrate CSS adjacent sibling selector −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
div {
   margin: 8px;
   height: 50px;
   width: 60px;
   display: flex;
   float: left;
   border-radius: 5%;
   border: 2px solid brown;
   box-shadow: inset 0 2px 12px olivedrab;
}
div + div {
   border-radius: 50%;
   background-color: orchid;
}
</style>
</head>
<body>
<div></div>
<hr>
<div></div>
<div></div>
</body>
</html>
This gives the following output −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
p {
   font-size: 1.5em;
}
span {
   background-color: lavender;
}
span + span {
   background-color: darkseagreen;
}
</style>
</head>
<body>
<p>
<span>Demo text</span>   <span>goes here</span>
</p>
</body>
</html>
This gives the following output −
Python - Measuring Central Tendency

Mathematically central tendency means measuring the center or distribution of location of values of a data set. It gives an idea of the average value of the data in the data set and also 
an indication of how widely the values are spread in the data set. That in turn helps in evaluating the chances of a new input fitting into the existing data set and hence probability 
of success.
There are three main measures of central tendency which can be calculated using the methods in pandas python library.
Mean -  It is the Average value of the data which is a division of sum of the values with the number of values.
Mean -  It is the Average value of the data which is a division of sum of the values with the number of values.
Median - It is the middle value in distribution when the values are arranged in ascending or descending order.
Median - It is the middle value in distribution when the values are arranged in ascending or descending order.
Mode - It is the most commonly occurring value in a distribution.
Mode - It is the most commonly occurring value in a distribution.
The pandas functions can be directly used to calculate these values. 
import pandas as pd

#Create a Dictionary of series
d = {'Name':pd.Series(['Tom','James','Ricky','Vin','Steve','Smith','Jack',
   'Lee','Chanchal','Gasper','Naviya','Andres']),
   'Age':pd.Series([25,26,25,23,30,29,23,34,40,30,51,46]),
   'Rating':pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8,3.78,2.98,4.80,4.10,3.65])}

#Create a DataFrame
df = pd.DataFrame(d)
print "Mean Values in the Distribution"
print df.mean()
print "*******************************"
print "Median Values in the Distribution"
print df.median()
Its output is as follows −
Mean Values in the Distribution
Age       31.833333
Rating     3.743333
dtype: float64
*******************************
Median Values in the Distribution
Age       29.50
Rating     3.79
dtype: float64
Mode may or may not be available in a distribution depending on whether the data is continous or whether there are values which has maximum frquency. We take a simple distribution below
to find out the mode. Here we have a value which has maximum frequency in the distribution.
import pandas as pd

#Create a Dictionary of series
d = {'Name':pd.Series(['Tom','James','Ricky','Vin','Steve','Smith','Jack',
   'Lee','Chanchal','Gasper','Naviya','Andres']),
   'Age':pd.Series([25,26,25,23,30,25,23,34,40,30,25,46])}
#Create a DataFrame
df = pd.DataFrame(d)

print df.mode()
Its output is as follows −
     Age      Name
0   25.0    Andres
1    NaN  Chanchal
2    NaN    Gasper
3    NaN      Jack
4    NaN     James
5    NaN       Lee
6    NaN    Naviya
7    NaN     Ricky
8    NaN     Smith
9    NaN     Steve
10   NaN       Tom
11   NaN       Vin

    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
Bokeh - Jupyter Notebook

Displaying Bokeh figure in Jupyter notebook is very similar to the above. The only change you need to make is to import output_notebook instead of output_file from bokeh.plotting module.
from bokeh.plotting import figure, output_notebook, show

Call to output_notebook() function sets Jupyter notebook’s output cell as the destination for show() function as shown below −
output_notebook()
show(p)

Enter the code in a notebook cell and run it. The sine wave will be displayed inside the notebook.
 Print
 Add Notes
 Bookmark this page
Anomaly detection in time series with Prophet library | by Insaf Ashrapov | Towards Data Science

First of all, let’s define what is an anomaly in time series. Anomaly detection problem for time series can be formulated as finding outlier data points relative to some standard or usual signal. While there are plenty of anomaly types, we’ll focus only on the most important ones from a business perspective, such as unexpected spikes, drops, trend changes, and level shifts. You can solve this problem in two ways: supervised and unsupervised. While the first approach needs some labeled data, second does not, you need the just raw data. In that article, we will focus on the second approach.
Check out my Machine & Deep Learning blog https://diyago.github.io/
Generally, unsupervised anomaly detection method works this way: you build some generalized simplified version of your data — everything which is outside some boundary by the threshold of this model is called outlier or anomaly. So first all of we will need to fit our data into some model, which hopefully will well describe our data. Here comes prophet library. For sure you can try more or less powerful/complicated models such arima, regression trees, rnn/lstm or even moving averages and etc — but almost all of them need to be tuned, unlikely that will work out of the box. Prophet is not like that, it is like auto arima but much, much better. It is really powerful and easy to start using the library which is focused on forecasting time series. It developed by Facebook’s Core Data Science team. You can read more about the library here.
To install Prophet library can be installed through the pypi:
pip install fbprophet
We will be working with some sample data, which has some interesting outliers. You download data here and it looks this way:
To train the model we will define basic hyperparameters some interval_width and changepoint_range. They can be used to adjust the width of the boundary:
Then we set as outliers everything higher than the top and lowers the bottom of the model boundary. In addition, the set the importance of outlier as based on how far the dot from the boundary:
Then you are ready to get the plot. I recommend to try altair library, you can easily get an interactive plot just by setting adding .interactive to your code.
Finally, we get the result. They seem to be very reasonable:
Github repository with code and data
Kaggle code with data by Vinay Jaju
How to implement the Runnable interface using lambda expression in Java?

The Runnable interface is a functional interface defined in java.lang package. This interface contains a single abstract method, run() with no arguments. When an object of a class implementing this interface used to create a thread, then run() method has invoked in a thread that executes separately.
@FunctionalInterface
public interface Runnable {
 void run();
}
In the below example, we can implement a Runnable interface by using an anonymous class and lambda expression.
public class RunnableLambdaTest {
   public static void main(String[] args) {
      Runnable r1 = new Runnable() {
         @Override
         public void run() { // anonymous class
            System.out.println("Runnable with Anonymous Class");
         }
      };
      Runnable r2 = () -> {   // lambda expression
         System.out.println("Runnable with Lambda Expression");
      };
      new Thread(r1).start();
      new Thread(r2).start();
   }
}
Runnable with Anonymous Class
Runnable with Lambda Expression
LinkedList getFirst() Method in Java

08 Apr, 2022
Linked List is a part of the Collection framework present in java.util package. This class is an implementation of the LinkedList data structure which is a linear data structure where the elements are not stored in contiguous locations and every element is a separate object with a data part and address part. The Java.util.LinkedList.getFirst() method is used to fetch or retrieve the first element from a LinkedList or the element present at the head of the List.
Illustration:
Input : 4 --> 1 --> 5 --> 6 --> 1 --> 3
Output: 4
As we all know that getFirst() is one of the methods been there up present inside LinkedList class. It retrieves the first element from the object inside which elements of LinkedList are present. As we know LinkedList is a class been present inside java.util package so and if we do operate the following methods the syntax will look like as shown below as follows:
import java.util.LinkedList;
LinkedList ll = new LinkedList<T>();  
ll.getFirst();
In simpler words, if we want to know the first element then do perform the below check as listed below. It will, later on, be illustrated as an example while implementing.
Syntax: 
LinkedList.getFirst();
Return Value: The first element or the element at the head of the list.
Example:
Java
// Java Program to Illustrate getFirst() Method// of LinkedList class // Importing required classesimport java.io.*;import java.util.LinkedList; // Main classpublic class GFG {     // Main driver method    public static void main(String args[])    {         // Creating an empty LinkedList by creating its        // object Declaring object of type strings        LinkedList<String> list = new LinkedList<String>();         // Adding custom input elements to the List        // Using add() method        list.add("Geeks");        list.add("for");        list.add("Geeks");        list.add("10");        list.add("20");         // Displaying the list(all elements inside object)        System.out.println("LinkedList:" + list);         // Fetching first element from the list        // using getFirst() method        System.out.println("The first element is: "                           + list.getFirst());    }}
LinkedList:[Geeks, for, Geeks, 10, 20]
The first element is: Geeks
 
solankimayank
singghakshay
surinderdawra388
Java-Collections
java-LinkedList
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL SERVER | IN Condition

23 May, 2018
IN condition is an alternative to multiple OR conditions in SELECT, INSERT, UPDATE, or DELETE statement. The IN operator allows multiple values to be tested against the expression and thus reduces the use of multiple OR conditions with each test value.
Syntax:
expression IN (value1, value2, .... value_n);

Where1. expression : value/attribute to be tested.2. value1, value2, .. value_n : The values to be tested against expression.
Selecting multiple values using ‘OR’. Multiple OR’s have to be used for checking the expression.
The same query can be answered using ‘IN’ which reduces the number of times conditions have to be written and all test values are present at a single place.IN Query:
Explanation:The inner query will be executed first and all the values in the ‘name’ column of Table Geeks_7 will be selected. Then the outer query will start executing and it will use the inner query values to filter out matching values.
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
SQL | Sub queries in From Clause
Window functions in SQL
What is Temporary Table in SQL?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL using Python
SQL Query to Convert VARCHAR to INT
RANK() Function in SQL Server
How to Import JSON Data into SQL Server?
SQL Query to Compare Two Dates
How to Check if a Column Exists in a SQL Server Table?

13 Sep, 2021
In this article, we will look at how to check if a particular column exists in a database table or not. For checking the existence of a column we need to create the table first. So, let us create a table with some columns and data.
Creating table:
Syntax:
CREATE TABLE table_name (
    column1 datatype,
    column2 datatype,
    column3 datatype,
   ....);
Using the above syntax we will be creating a Student table. The student table will have three fields Name, Department, and Roll Number of a student. To create the table use the below query.
Query:
CREATE TABLE Student(Name varchar(40),
Department varchar(30),Roll_No int, );
Output:
This query will show the output as Commands completed successfully. It means that a student table is created in our database. To insert values in the table we have to use the INSERT query.
INSERT INTO table_name
VALUES (value1, value2, value3, ...);
Using the above syntax we will be adding student data to our table. We have to insert the values according to the columns created. Use the below query to insert the data.
Query:
INSERT INTO Student
VALUES ('Rahul Sharma','Electronics',15),
       ('Soha Shaikh','Computer Science',24),
       ('Vivek Rao','Arts',31),
       ('Sonali Rane','Electronics',20);
Output:
We have added the data to our table. We can verify or print the data in the table using the SELECT query as below.
Query:
SELECT * FROM Student
Output:
For checking the existence we need to use the COL_LENGTH() function.
Syntax:
COL_LENGTH ( 'table' , 'column' )
COL_LENGTH() function returns the defined length of a column in bytes.
We have to pass two parameters – table name and column name
This function can be used with the IF ELSE condition to check if the column exists or not.
Now we use the below query to check the existence of a column.
Query:
IF COL_LENGTH('table_name','column_name') IS NOT NULL
    PRINT 'Column Exists';
ELSE
    PRINT 'Column does not Exists';
The above Student table has three columns Name, Department, and Roll Number. The below examples show how to check if a column exists in a database table.
Output 1:
Output 2:
Using COL_LENGTH() function we can find out if a column exists in our database table or not.
Blogathon-2021
Picked
SQL-Query
SQL-Server
Blogathon
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.