code-rag-bench/online-tutorials huggingface dataset:
How to Copy Struct Type Using Value and Pointer Reference in Golang?

22 Jun, 2020
A structure or struct in Golang is a user-defined data type that allows to combine data types of different kinds and act as a record.A struct variable in Golang can be copied to another variable easily using the assignment statement(=). Any changes made to the second struct will not be reflected back to the first struct.
Example 1:
// Golang program to illustrate copying// a structure to another variable  package main  import (    "fmt")  // declaring a structuretype Student struct{      // declaring variables    name string    marks int64    stdid int64}  // main functionfunc main() {                    // creating the instance of the     // Student struct type     std1 := Student{"Vani", 98, 20024}              // prints the student struct    fmt.Println(std1)              // copying the struct student    // to another variable by     // using the assignment operator    std2 := std1              // printing copied struct    // this will have same values     // as struct std1    fmt.Println(std2)              // changing values of struct    // std2 after copying    std2.name = "Abc"    std2.stdid = 20025              // printing updated struct    fmt.Println(std2)      }
Output:
{Vani 98 20024}
{Vani 98 20024}
{Abc 98 20025}

In the case of pointer reference to the struct, the underlying memory location of the original struct and the pointer to the struct will be the same. Any changes made to the second struct will be reflected in the first struct also. Pointer to a struct is achieved by using the ampersand operator(&). It is allocated on the heap and its address is shared.
Example 2:
// Golang program to illustrate the// concept of a pointer to a struct  package main  import (    "fmt")  // declaring a structuretype Person struct{      // declaring variables    name string    address string    id int64}  // main functionfunc main() {                    // creating the instance of the         // Person struct type     p1 := Person{"Vani", "Delhi", 20024}              // prints the student struct    fmt.Println(p1)              // referencing the struct person    // to another variable by     // using the ampersand operator    // Here, it is the pointer to the struct     p2 := &p1              // printing pointer to the struct    fmt.Println(p2)              // changing values of struct p2    p2.name = "Abc"    p2.address = "Hyderabad"              // printing updated struct    fmt.Println(p2)          // struct p1 values will     // also change since values    // of p2 were also changed    fmt.Println(p1)      }
Output:
{Vani Delhi 20024}
&{Vani Delhi 20024}
&{Abc Hyderabad 20024}
{Abc Hyderabad 20024}

Golang-Pointers
Golang-Program
Picked
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PyQt5 – How to clear the content of label | clear and setText method

26 Mar, 2020
In this article, we will see how we can easily clear/erase the content of the label of PyQt5 application. This can be done in two ways –
Using clear() method, this will clear the content of the label.Using setText() method with passing a blank string, this will update the content with blank string.
Using clear() method, this will clear the content of the label.
Using setText() method with passing a blank string, this will update the content with blank string.
Syntax : label.clear()
Argument : It takes no argument.
Code :
# importing the required libraries  from PyQt5.QtWidgets import * from PyQt5 import QtCorefrom PyQt5.QtGui import * import sys  class Window(QMainWindow):    def __init__(self):        super().__init__()                  # set the title        self.setWindowTitle("Label")          # setting  the geometry of window        self.setGeometry(0, 0, 400, 300)          # creating a label widget        self.label_1 = QLabel("Label", self)          # moving position        self.label_1.move(100, 100)          # setting up border        self.label_1.setStyleSheet("border: 1px solid black;")          # creating a label widget        self.label_2 = QLabel("Hidden Label", self)          # moving position        self.label_2.move(100, 150)          # setting up border        self.label_2.setStyleSheet("border: 1px solid black;")          # clearing the data        self.label_2.clear()            # show all the widgets        self.show()  # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Syntax : label.setText(“”)
Argument : It takes string as argument, here string will be blank.
Code :
# importing the required libraries  from PyQt5.QtWidgets import * from PyQt5 import QtCorefrom PyQt5.QtGui import * import sys  class Window(QMainWindow):    def __init__(self):        super().__init__()          # set the title        self.setWindowTitle("Label")          # setting  the geometry of window        self.setGeometry(0, 0, 400, 300)          # creating a label widget        self.label_1 = QLabel("Label", self)          # moving position        self.label_1.move(100, 100)          # setting up border        self.label_1.setStyleSheet("border: 1px solid black;")          # creating a label widget        self.label_2 = QLabel("Hidden Label", self)          # moving position        self.label_2.move(100, 150)          # setting up border        self.label_2.setStyleSheet("border: 1px solid black;")          # replacing content with blank        self.label_2.setText("")            # show all the widgets        self.show()    # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
HTTP headers | Transfer-Encoding

31 Oct, 2019
The HTTP Transfer-Encoding is a response-type header that performs as the hop-by-hop header, the hop-by-hop header connection is the single transport-level connection must not be re-transmitted. This header is performing between two nodes (single transport-level connection). If there is multi-node connection then have to use other Transfer-Encoding values. There is an end-to-end Content-Encoding header that can be use to compress the data over the whole connection.
syntax:
Transfer-Encoding: chunked | compress | deflate | gzip | identity
Directives: This header accepts five directives mentioned above and described below:
chunked: This directive is used to send the series of data in a chunk format, but have to mentioned the length of each chunk before sending the chunk of the data in hexadecimal format like '\r\n' and then the chunk itself, followed by another '\r\n'.
compress: It is a compression format using the Lempel-Ziv-Welch (LZW) algorithm.
deflate: It is a compression format using the zlib structure, with the deflate compression algorithm.
gzip: It is a compression format using the Lempel-Ziv coding (LZ77), with a 32-bit CRC.
identity: This directive Indicates the identity function which is always acceptable.
Note: The terminating chunks are the regular chunks, length of those chunks by default zero.
Example: The chunk encoding for this header is useful when the server sending the huge amount of series of data to the client. The total size of the response may be unknown until the request has been completed. Suppose there is a large amount of data from a database query, a chunked response looks like this
HTTP/1.0 200 OK 
Content-Type: text/plain 
Transfer-Encoding: chunked

0\r\n
Mozilla\r\n 
7\r\n
Developer\r\n
9\r\n
Network\r\n
0\r\n 
\r\n
To check this Transfer-Encoding in action go to Inspect Element -> Network check the request header for Transfer-Encoding like below, Transfer-Encoding is highlighted you can see.
Supported Browsers: The browsers are compatible with HTTP Transfer-Encoding header are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
HTTP-headers
Picked
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Django News App

14 Dec, 2020
Django is a high-level framework which is written in Python which allows us to create server-side web applications. In this article, we will see how to create a News application using Django. We will be using News Api and fetch all the headline news from the api. Read more about the api here news api.Do the Following steps in command prompt or terminal:  
Open the newsproject folder using a text editor. The directory structure should look like this  
Create a “templates” folder in your newsapp and it in settings.pySettings .py  
In views.py –In views, we create a view named index which takes a request and renders an html as a response. Firstly we import newsapi from NewsApiClient.  
# importing apifrom django.shortcuts import renderfrom newsapi import NewsApiClient  # Create your views here. def index(request):          newsapi = NewsApiClient(api_key ='YOURAPIKEY')    top = newsapi.get_top_headlines(sources ='techcrunch')      l = top['articles']    desc =[]    news =[]    img =[]      for i in range(len(l)):        f = l[i]        news.append(f['title'])        desc.append(f['description'])        img.append(f['urlToImage'])    mylist = zip(news, desc, img)      return render(request, 'index.html', context ={"mylist":mylist})
 Create a index.html in templates folder.  
html
<!DOCTYPE html><html lang="en" dir="ltr">  <head>    <meta charset="utf-8">    <title></title>  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"><!-- Optional theme -->  </head>  <body>    <div class="jumbotron" style="color:black">        <h1 style ="color:white">   Get The latest news on our website      </h1>      </div>        <div class="container">      {% for new, des, i in mylist %}              <img src="{{ i }}" alt="">              <h1>news:</h1> {{ new }}              {{ value|linebreaks }}                <h4>description:</h4>{{ des }}              {{ value|linebreaks }}        {% endfor %}    </div>    </body></html>
 Now map the views to urls.py  
from django.contrib import adminfrom django.urls import pathfrom newsapp import views  urlpatterns = [   path('', views.index, name ='index'),    path('admin/', admin.site.urls),]
Your output of the project should look like this –  
roopsai
Python Django
Project
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PHP Arrays

An array stores multiple values in one single variable:
An array is a special variable, which can hold more than one value at a time.
If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this:
However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300?
The solution is to create an array!
An array can hold many values under a single name, and you can access the values by referring to an index number.
In PHP, the array() function is used to create an array:
In PHP, there are three types of arrays:
Indexed arrays - Arrays with a numeric index
Associative arrays - Arrays with named keys
Multidimensional arrays - Arrays containing one or more arrays
The count() function is used to return the length (the number of elements) of 
an array:
For a complete reference of all array functions, go to our complete PHP Array Reference.
The reference contains a brief description, and examples of use, for each function!
Use the correct function to output the number of items in an array.
$fruits = array("Apple", "Banana", "Orange");
echo ;

We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
How to Animate Bullets in Lists using CSS

To style bullets in an unordered list, we can use the list-style por
The syntax of CSS li-style property as follows −
li {
   list-style: /*value*/
}
The following examples illustrate CSS li-style property.
 Live Demo
<!DOCTYPE html>
<html>
   <head>
      <style>
         li {
            margin: 3px 0;
            padding: 2%;
            width: 28%;
            line-height: 1.2%;
            list-style: none;
            border-radius: 5% 0 0 5%;
            box-shadow: -10px 2px 4px 0 chartreuse;
            color: cornflowerblue;
         }
         li:hover {
            box-shadow: -10px 2px 4px 0 blue!important;
            font-size: 1.4em;
         }
      </style>
   </head>
   <body>
      <ul>
         <li>a</li>
         <li>b</li>
         <li>c</li>
         <li>d</li>
      </ul>
   </body>
</html>
This gives the following output
 Live Demo
<!DOCTYPE html>
<html>
   <head>
      <style>
         ol {
            list-style: none;
            counter-reset: li;
            overflow: hidden;
         }
         li {
            margin-right: 10%;
            padding: 2%;
            width: 15%;
            float: left;
            line-height: 1.2%;
            font-weight: bold;
            counter-increment: li;
            box-shadow: inset 2px 14px 10px lightblue;
         }
         li:hover {
            box-shadow: inset 6px 14px 10px lightgreen!important;
            font-size: 1.4em;
         }
         li::before {
            content: counter(li);
            color: seagreen;
            display: inline-block;
            width: 40%;
            margin-left: -2em;
         }
      </style>
   </head>
   <body>
      <ol>
         <li>a</li>
         <li>b</li>
         <li>c</li>
      </ol>
   </body>
</html>
This gives the following output
Gerrit - Installation

Before you can use Gerrit, you have to install Git and perform some basic configuration changes. Following are the steps to install Git client on different platforms.
You can install the Git on Linux by using the software package management tool. For instance, if you are using Fedora, you can use as −
sudo yum install git

If you are using Debian-based distribution such as Ubuntu, then use the following command −
sudo apt-get install git

You can install Git on Windows by downloading it from the Git website. Just go to  msysgit.github.io link and click on the download button.
Git can be installed on Mac using the following command −
brew install git

Another way of installing Git is, by downloading it from Git website. Just go to Git install on Mac link, which will install Git for Mac platform.
 Print
 Add Notes
 Bookmark this page
Pascal - Nested if-then Statements

It is always legal in Pascal programming to nest if-else statements, which means you can use one if or else if statement inside another if or else if statement(s). Pascal allows nesting to any level, however, if depends on Pascal implementation on a particular system.
The syntax for a nested if statement is as follows −
if( boolean_expression 1) then
   if(boolean_expression 2)then S1

else
   S2;
You can nest else if-then-else in the similar way as you have nested if-then statement. Please note that, the nested if-then-else constructs gives rise to some ambiguity as to which else statement pairs with which if statement. The rule is that the else keyword matches the first if keyword (searching backwards) not already matched by an else keyword. 
The above syntax is equivalent to
if( boolean_expression 1) then
begin
   if(boolean_expression 2)then
      S1
   
   else
      S2;
end;
It is not equivalent to
if ( boolean_expression 1) then  
begin  
   if exp2 then  
      S1  
end;  
   else  
      S2;
Therefore, if the situation demands the later construct, then you must put begin and end keywords at the right place. 
program nested_ifelseChecking;
var
   { local variable definition }
   a, b : integer;

begin
   a := 100;
   b:= 200;
   
   (* check the boolean condition *)
   if (a = 100) then
      (* if condition is true then check the following *)
      if ( b = 200 ) then
         (* if nested if condition is true  then print the following *)
         writeln('Value of a is 100 and value of b is 200' );
   
   writeln('Exact value of a is: ', a );
   writeln('Exact value of b is: ', b );
end.
When the above code is compiled and executed, it produces the following result −
Value of a is 100 and b is 200
Exact value of a is : 100
Exact value of b is : 200


    94 Lectures 
     8.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
C library function - putc()

The C library function int putc(int char, FILE *stream) writes a character (an unsigned char) specified by the argument char to the specified stream and advances the position indicator for the stream.
Following is the declaration for putc() function.
int putc(int char, FILE *stream)
char − This is the character to be written. The character is passed as its int promotion.
char − This is the character to be written. The character is passed as its int promotion.
stream − This is the pointer to a FILE object that identifies the stream where the character is to be written.
stream − This is the pointer to a FILE object that identifies the stream where the character is to be written.
This function returns the character written as an unsigned char cast to an int or EOF on error.
The following example shows the usage of putc() function.
#include <stdio.h>

int main () {
   FILE *fp;
   int ch;

   fp = fopen("file.txt", "w");
   for( ch = 33 ; ch <= 100; ch++ ) {
      putc(ch, fp);
   }
   fclose(fp);
   
   return(0);
}
Let us compile and run the above program that will create a file file.txt in the current directory which will have following content −
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcd

Now let's see the content of the above file using the following program −
#include <stdio.h>

int main () {
   FILE *fp;
   int c;

   fp = fopen("file.txt","r");
   while(1) {
      c = fgetc(fp);
      if( feof(fp) ) {
         break ;
      }
      printf("%c", c);
   }
   fclose(fp);
   return(0);
}
Let us compile and run the above program to produce the following result −
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcd


    12 Lectures 
     2 hours 

 Nishant Malik

    12 Lectures 
     2.5 hours 

 Nishant Malik

    48 Lectures 
     6.5 hours 

 Asif Hussain

    12 Lectures 
     2 hours 

 Richa Maheshwari

    20 Lectures 
     3.5 hours 

 Vandana Annavaram

    44 Lectures 
     1 hours 

 Amit Diwan
 Print
 Add Notes
 Bookmark this page
Byte equals() method in Java with examples - GeeksforGeeks

05 Dec, 2018
The equals() method of Byte class is a built in method in Java which is used to compare the equality given Object with the instance of Byte invoking the equals() method.
Syntax
ByteObject.equals(Object a)
Parameters: It takes an Object type object a as input which is to be compared with the instance of the Byte object calling the equals method.
Return Value: It return an boolean value. It returns true if the value of ‘a’ is equal to the value of ByteObject.
Below is the implementation of equals() method in Java:
Example 1:
// Java code to demonstrate// Byte equals() method  class GFG {    public static void main(String[] args)    {          // creating a Byte object        Byte a = new Byte("20");          // creating a Byte object        Byte b = new Byte("20");          // equals method in Byte class        boolean output = a.equals(b);          // Printing the output        System.out.println("Does " + a + " equals "                           + b + " : " + output);    }}
Does 20 equals 20 : true

Example 2:
// Java code to demonstrate// Byte equals() method  class GFG {    public static void main(String[] args)    {          // creating a Byte object        Byte a = new Byte("2");          // creating a Byte object        Byte b = new Byte("20");          // equals method in Byte class        boolean output = a.equals(b);          // Printing the output        System.out.println("Does " + a + " equals "                           + b + " : " + output);    }}
Does 2 equals 20 : false

Java - util package
Java-Byte
Java-Functions
java-lang-reflect-package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Stream In Java
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java
Node.js zlib.unzip() Method - GeeksforGeeks

12 Oct, 2021
The zlib.unzip() method is an inbuilt application programming interface of the Zlib module which is used to decompress a chunk of data.
Syntax:
zlib.unzip( buffer, options, callback )
Parameters: This method accepts three parameters as mentioned above and described below:
buffer: It can be of type Buffer, TypedArray, DataView, ArrayBuffer, and string.
options: It is an optional parameter that holds the zlib options.
callback: It holds the callback function.
Return Value: It returns the chunk of data after decompression.
Below examples illustrate the use of zlib.unzip() method in Node.js:
Example 1:
// Node.js program to demonstrate the     // unzip() method  // Including zlib moduleconst zlib = require("zlib");  // Declaring input and assigning// it a value stringvar input = "GfG";  // Calling gzip methodzlib.gzip(input, (err, buffer) => {    // Calling unzip method zlib.unzip(buffer, (err, buffer) => {      console.log(buffer.toString('utf8'));          }); });  console.log("Data Decompressed...");
Output:
Data Decompressed...
GfG

Example 2:
// Node.js program to demonstrate the     // unzip() method  // Including zlib moduleconst zlib = require("zlib");  // Declaring input and assigning// it a value stringvar input = "GfG";  // Calling gzip methodzlib.gzip(input, (err, buffer) => {    // Calling unzip method zlib.unzip(buffer, (err, buffer) => {      console.log(buffer.toString('base64'));          }); });  console.log("Data Decompressed...");
Output:
Data Decompressed...
R2ZH

Reference: https://nodejs.org/api/zlib.html#zlib_zlib_unzip_buffer_options_callback
Node.js-Zlib-module
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js fs.writeFile() Method
Node.js fs.readFile() Method
How to install the previous version of node.js and npm ?
Difference between promise and async await in Node.js
How to use an ES6 import in Node.js?
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
Batch Script - Replace a String - GeeksforGeeks

28 Nov, 2021
In this article, we are going to Replace a substring with any given string.
@echo off 
set str=GFG is the platform for geeks. 
echo %str% 

set str=%str:the=best% 
echo %str%
pause
In the above example, we are going to replace ‘the’ by substring ‘best’ using %str:the=best% statement.
Explanation :
By using ‘ set ‘ we are getting input of any string
set str=input string
In the next line using ‘ echo %str% ‘ we are printing our string.
Using ‘ %str:the=best%’ statement , we are replacing substring ‘the’ with ‘best’.
Then using ‘pause’, to hold the screen until any key is pressed, so that we can read our output.
Output :
‘the’ is replaced by ‘best’
@echo off 
set str=GFG is the platform for geeks.
set word=best
echo %str% 

call set str=%%str:the=%word%%%
echo %str%
pause
Explanation :
Everything is as same as before, we are trying to replace the word ‘the’ with ‘best’ but we can also do this by calling another variable ‘word’ which is equal to ‘best’.
By using call there is another layer of variable expansion so we have to use ‘%’ for ‘word’ so that it will use ‘best’ as its value and replace the string.
output by 2nd approach
Batch-script
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
scp command in Linux with Examples
mv command in Linux with examples
Docker - COPY Instruction
SED command in Linux | Set 2
chown command in Linux with Examples
nohup Command in Linux with Examples
Named Pipe or FIFO with example C program
Thread functions in C/C++
uniq Command in LINUX with examples
Start/Stop/Restart Services Using Systemctl in Linux
Select first or last N rows in a Dataframe using head() and tail() method in Python-Pandas - GeeksforGeeks

02 Jul, 2020
Let’s discuss how to select top or bottom N number of rows from a Dataframe using head() & tail() methods.
1) Select first N Rows from a Dataframe using head() method of Pandas DataFrame :
Pandas head() method is used to return top n (5 by default) rows of a data frame or series
Syntax: Dataframe.head(n).
Parameters: (optional) n is integer value, number of rows to be returned.
Return: Dataframe with top n rows .
Let’s Create a dataframe
# import pandas library as pdimport pandas as pd  # List of Tuplesstudents = [('Ankit', 22, 'Up', 'Geu'),           ('Ankita', 31, 'Delhi', 'Gehu'),           ('Rahul', 16, 'Tokyo', 'Abes'),           ('Simran', 41, 'Delhi', 'Gehu'),           ('Shaurya', 33, 'Delhi', 'Geu'),           ('Harshita', 35, 'Mumbai', 'Bhu' ),           ('Swapnil', 35, 'Mp', 'Geu'),           ('Priya', 35, 'Uk', 'Geu'),           ('Jeet', 35, 'Guj', 'Gehu'),           ('Ananya', 35, 'Up', 'Bhu')            ]  # Create a DataFrame object from# list of tuples along with columns# and indices.details = pd.DataFrame(students, columns =['Name', 'Age',                                           'Place', 'College'],                        index =['a', 'b', 'c', 'd', 'e',                                'f', 'g', 'i', 'j', 'k'])  details
Output:
Example 1:
# Show first 5 rows of the details dataframe# from topdetails.head()
Output:
Example 2:
# display top 3 rows of the dataframedetails.head(3)
Output:
Example 3:
# display top 2 rows of the specific columnsdetails[['Name', 'Age']].head(2)
Output:
2) Select last N Rows from a Dataframe using tail() method of Pandas DataFrame :
Pandas tail() method is used to return bottom n (5 by default) rows of a data frame or series.
Syntax: Dataframe.tail(n)
Parameters: (optional) n is integer value, number of rows to be returned.
Return: Dataframe with bottom n rows .
Example 1:
# Show bottom 5 rows of the dataframedetails.tail()
Output:
Example 2:
# Show bottom 3 rows of the dataframedetails.tail(3)
Output:
Example 3:
# Show bottom 2 rows of the specific# columns from dataframedetails[['Name', 'Age']].tail(2)
Output:
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python program to print the binary value of the numbers from 1 to N - GeeksforGeeks

24 Jan, 2021
Given a positive number N, the task here is to print the binary value of numbers from 1 to N. For this purpose various approaches can be used. 
The binary representation of a number is its equivalent value using 1 and 0 only. Example for k = 15, binary value is 1 1 1 1
WORKING FOR METHOD 1
Approach
Divide k by 2.
Recursive call on the function and print remainder while returning from the recursive call.
Repeat the above steps till the k is greater than 1.
Repeat the above steps till we reach N
Program:
Python3
# code to print binary values of first 5 numbers  # recursive functiondef Print_Binary_Values(num):    # base condition    if(num > 1):        Print_Binary_Values(num // 2)    print(num % 2, end="")    # driver codeif __name__ == "__main__":    N = 5      # looping N times    for i in range(1, N+1):        Print_Binary_Values(i)        print(end=" ")
Output
1 10 11 100 101 
Approach
Check if k > 1
Right shift the number by 1 bit and perform a recursive call on the function
Print the bits of number
Repeat the steps till we reach N
Program:
Python3
# code to print binary values of first 5 numbers  # recursive function    def Print_Binary_Values(num):      # base condition    if(num > 1):        Print_Binary_Values(num >> 1)    print(num & 1, end="")    # driver codeif __name__ == "__main__":    N = 5      # looping N times    for i in range(1, N+1):        Print_Binary_Values(i)        print(end=" ")
Output
1 10 11 100 101 
bin() is an inbuilt python function that can convert any decimal number given to it as input to its equivalent binary.
Syntax:
bin (number) 
here number is the decimal number that gets converted to binary 
Program
Python3
# code to print first 5 binary number using builtIn library    def Print_Binary_Number(num):    for i in range(1, num+1):          # using bin to print binary value        print(int(bin(i).split('0b')[1]), end=" ")    # driver codeif __name__ == "__main__":    num = 5    Print_Binary_Number(num)
Output
1 10 11 100 101 
Picked
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
Node.js Buffer.swap16() Method - GeeksforGeeks

13 Oct, 2021
The Buffer.swap16() method is an inbuilt application programming interface of class Buffer within Buffer module which is used to swap the buffer byte order in-place. The swapping is performed by interpreting buffer as an array of 16-bit numbers.
Syntax:
Buffer.swap16()
Parameters: This method does not accept any parameters.
Return value: It returns a reference to the swapped buffer.
Error thrown: It throws ERR_INVALID_BUFFER_SIZE if length of buffer (buf.length) is not a multiple of 2.
Below examples illustrate the use of Buffer.swap16() Method in Node.js:
Example 1:
// Node.js program to demonstrate the // Buffer.swap16() method       // Creating a buffer const buf = Buffer.from([0x1, 0x2,        0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);   // Display the buffer value// before swap console.log(buf);   // Using Buffer.swap16() methodbuf.swap16();      // Display the result // after swapconsole.log(buf); 
Output:
<Buffer 01 02 03 04 05 06 07 08>
<Buffer 02 01 04 03 06 05 08 07>

Example 2: This example display the error thrown by this method.
// Node.js program to demonstrate the // Buffer.swap16() method       // Creating a buffer const buf = Buffer.from([0x7, 0x5, 0x2]);   // Display the buffer value// before swap console.log(buf);   try {    // Using Buffer.swap16() method    // It will throw error    buf.swap16();      // Display the result     // after swap    console.log(buf);  }catch(e) {    console.log("Entering catch block");      // Display error    console.log(e);}
Output:
<Buffer 07 05 02>
Entering catch block
RangeError [ERR_INVALID_BUFFER_SIZE]: Buffer size
must be a multiple of 16-bits
    at Buffer.swap16 (buffer.js:1042:11)
    at /home/runner/index.js:14:9
    ......

Note: The above program will compile and run by using the node index.js command.
Reference: https://nodejs.org/dist/latest-v13.x/docs/api/buffer.html#buffer_buf_swap16
Node.js-Buffer-module
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js fs.writeFile() Method
How to install the previous version of node.js and npm ?
Difference between promise and async await in Node.js
How to use an ES6 import in Node.js?
Express.js res.render() Function
Remove elements from a JavaScript Array
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?
Difference between var, let and const keywords in JavaScript
TypeScript | String substring() Method - GeeksforGeeks

18 Jun, 2020
The substring() is an inbuilt function in TypeScript which is used to return the subset of a String object.
 Syntax: 
string.substring(indexA, [indexB]) 
Parameter: This method accepts two parameter as mentioned above and described elow: 
indexA : This parameter is the integer between 0 and one less than the length of the string.
indexB : This parameter is the integer between 0 and length of the string.
Return Value: This method returns the subset of a String object. Below example illustrate the String substring() method in TypeScript.
Example 1:  
<script>    // Original strings    var str = "Geeksforgeeks - Best Platform";        // use of String substring() Method    var newstr = str.substring(0,5)        console.log(newstr);</script>
Output: 
Geeks

Example 2: 
<script>    // Original strings    var str = "Geeksforgeeks - Best Platform";        // use of String substring() Method    var newstr = str.substring(0,5)     console.log(newstr);       newstr = str.substring(-2,5)     console.log(newstr);       newstr = str.substring(12,22)     console.log(newstr);       newstr = str.substring(0,1)     console.log(newstr);</script>
Output: 
Geeks
Geeks
s - Best P
G

TypeScript
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
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?
Clearfix in Bootstrap - GeeksforGeeks

15 Jul, 2021
One of the major problems with the structure of HTML is that if you have a child div inside parent div, the child div automatically flows around the parent div. The solution to this problem is using clear property of CSS. Bootstrap allows us to use a class named clearfix which is used to clear the floated contents inside any container.Example 1: Without clearfix property. In the below program two buttons are floated to left and right.  
html
<!DOCTYPE html><html><head>    <title>Bootstrap Example</title>       <!-- Bootstrap CSS and JS -->    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>         <style>    .left{        float:left;    }         .right{        float:right;    }    </style></head> <body>    <div class="bg-info">        <button type="button" class="btn btn-secondary left">            floated left button        </button>                       <button type="button" class="btn btn-secondary right">            floated right button        </button>    </div></body></html>
Output:  
Clearfix property clear all the floated content of the element that it is applied to. It is also used to clear floated content within a container. Example 2: With clearfix property. Without using the clearfix class, the parent div may not wrap around the children button elements properly and can cause a broken layout.  
html
<!DOCTYPE html><html><head>    <title>Bootstrap Example</title>       <!-- Bootstrap CSS and JS -->    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>         <style>    .left{        float:left;    }         .right{        float:right;    }    </style></head> <body>    <div class="bg-info clearfix">        <button type="button" class="btn btn-secondary left">            floated left button        </button>                       <button type="button" class="btn btn-secondary right">            floated right button        </button>    </div></body></html>
Output: 
Supported Browser:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
ysachin2314
Picked
Bootstrap
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to change navigation bar color in Bootstrap ?
Form validation using jQuery
How to pass data into a bootstrap modal?
How to align navbar items to the right in Bootstrap 4 ?
How to Show Images on Click using HTML ?
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?
XML-RPC - Response Format

Responses are much like requests, with a few extra twists. If the response is successful - the procedure was found, executed correctly, and returned results - then the XML-RPC response will look much like a request, except that the methodCall element is replaced by a methodResponse element and there is no methodName element:
<?xml version="1.0"?>
<methodResponse>
   <params>
      <param>
         <value><double>18.24668429131</double></value>
      </param>
   </params>
</methodResponse>
An XML-RPC response can only contain one parameter.
An XML-RPC response can only contain one parameter.
That parameter may be an array or a struct, so it is possible to return multiple values.
That parameter may be an array or a struct, so it is possible to return multiple values.
It is always required to return a value in response. A "success value" - perhaps a Boolean set to true (1).
It is always required to return a value in response. A "success value" - perhaps a Boolean set to true (1).
Like requests, responses are packaged in HTTP and have HTTP headers. All XML-RPC
responses use the 200 OK response code, even if a fault is contained in the message.
Headers use a common structure similar to that of requests, and a typical set of headers
might look like:
HTTP/1.1 200 OK
Date: Sat, 06 Oct 2001 23:20:04 GMT
Server: Apache.1.3.12 (Unix)
Connection: close
Content-Type: text/xml
Content-Length: 124

XML-RPC only requires HTTP 1.0 support, but HTTP 1.1 is compatible.
XML-RPC only requires HTTP 1.0 support, but HTTP 1.1 is compatible.
The Content-Type must be set to text/xml.
The Content-Type must be set to text/xml.
The Content-Length header specifies the length of the response in bytes.
The Content-Length header specifies the length of the response in bytes.
A complete response, with both headers and a response payload, would look like:
HTTP/1.1 200 OK
Date: Sat, 06 Oct 2001 23:20:04 GMT
Server: Apache.1.3.12 (Unix)
Connection: close
Content-Type: text/xml
Content-Length: 124

<?xml version="1.0"?>
<methodResponse>
   <params>
      <param>
         <value><double>18.24668429131</double></value>
      </param>
   </params>
</methodResponse>
After the response is delivered from the XML-RPC server to the XML-RPC client, the connection is closed. Follow-up requests need to be sent as separate XML-RPC connections.
 Print
 Add Notes
 Bookmark this page
How to get element with max id in MongoDB?

To get the element with a max id, you can use the find() method. To understand the above concept, let us create a collection with the document. The query is as follows −
> db.getElementWithMaxIdDemo.insertOne({"Name":"John","Age":21});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8bbce480f10143d8431e1c")
}
> db.getElementWithMaxIdDemo.insertOne({"Name":"Larry","Age":24});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8bbcec80f10143d8431e1d")
}
> db.getElementWithMaxIdDemo.insertOne({"Name":"David","Age":23});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8bbcf580f10143d8431e1e")
}
> db.getElementWithMaxIdDemo.insertOne({"Name":"Chris","Age":20});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8bbcfe80f10143d8431e1f")
}
> db.getElementWithMaxIdDemo.insertOne({"Name":"Robert","Age":25});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8bbd0880f10143d8431e20")
}
Display all documents from a collection with the help of find() method. The query is as follows −
> db.getElementWithMaxIdDemo.find().pretty();
The following is the output −
{
   "_id" : ObjectId("5c8bbce480f10143d8431e1c"),
   "Name" : "John",
   "Age" : 21
}
{
   "_id" : ObjectId("5c8bbcec80f10143d8431e1d"),
   "Name" : "Larry",
   "Age" : 24
}
{
   "_id" : ObjectId("5c8bbcf580f10143d8431e1e"),
   "Name" : "David",
   "Age" : 23
}
{
   "_id" : ObjectId("5c8bbcfe80f10143d8431e1f"),
   "Name" : "Chris",
   "Age" : 20
}
{
   "_id" : ObjectId("5c8bbd0880f10143d8431e20"),
   "Name" : "Robert",
   "Age" : 25
}
Here is the query to get the element with max id −
> db.getElementWithMaxIdDemo.find().sort({_id:-1}).limit(1).pretty()
The following is the output with a record with maximum id −
{
   "_id" : ObjectId("5c8bbd0880f10143d8431e20"),
   "Name" : "Robert",
   "Age" : 25
}
How to change axes background color in Matplotlib?

To change the axes background color, we can use set_facecolor() method.
Set the figure size and adjust the padding between and around the subplots.
Set the figure size and adjust the padding between and around the subplots.
Get the current axes using gca() method.
Get the current axes using gca() method.
Set the facecolor of the axes.
Set the facecolor of the axes.
Create x and y data points using numpy.
Create x and y data points using numpy.
Plot x and y data points using plot() method.
Plot x and y data points using plot() method.
To display the figure, use show() method.
To display the figure, use show() method.
import numpy as np
import matplotlib.pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

ax = plt.gca()
ax.set_facecolor("orange")

x = np.linspace(-2, 2, 10)
y = np.exp(-x)

plt.plot(x, y, color='red')

plt.show()
GATE | GATE CS Mock 2018 | Question 50 - GeeksforGeeks

19 Nov, 2018
Consider an array A[999] & each element occupies 4 word. A 32 word cache is used and divided into 16 word blocks. What is the miss ratio for the following statement. Assume one block is read into cache in case of miss:
for(i=0; i < 1000; i++)
  A[i] = A[i] + 99

(A) 0.50(B) 0.75(C) 0.875(D) 0.125Answer: (D)Explanation: Since there is 16 word block, 4 element can stay in one block. Now notice that each element is referred twice, one read and one write operation.So when in a block when 1st element is referred for read, it will be miss, and hence that block will be copied to cache.Now 2nd, 3rd, and 4th references to that 1st element will be hit for read and write. So out of 8 reference, 1 miss and 7 hit for one block. Gets repeated for each and every block.Therefore, hit 7/8 and miss 1/8
Option (D) is correct.Quiz of this Question
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2014-(Set-1) | Question 30
GATE | GATE-CS-2001 | Question 23
GATE | GATE-CS-2015 (Set 1) | Question 65
GATE | GATE CS 2010 | Question 45
GATE | GATE-CS-2014-(Set-1) | Question 65
GATE | GATE-CS-2004 | Question 3
GATE | GATE-CS-2015 (Set 3) | Question 65
C++ Program to count Vowels in a string using Pointer
GATE | GATE CS 2012 | Question 40
Abstract Methods in Java with Examples - GeeksforGeeks

26 Dec, 2020
Sometimes, we require just method declaration in super-classes. This can be achieve by specifying the abstract type modifier. These methods are sometimes referred to as subclasser responsibility because they have no implementation specified in the super-class. Thus, a subclass must override them to provide method definition. To declare an abstract method, use this general form: 
abstract type method-name(parameter-list);
As you can see, no method body is present. Any concrete class(i.e. class without abstract keyword) that extends an abstract class must override all the abstract methods of the class.Important rules for abstract methods:  
Any class that contains one or more abstract methods must also be declared abstract
The following are various illegal combinations of other modifiers for methods with respect to abstract modifier: finalabstract nativeabstract synchronizedabstract staticabstract privateabstract strictfp
finalabstract nativeabstract synchronizedabstract staticabstract privateabstract strictfp
final
abstract native
abstract synchronized
abstract static
abstract private
abstract strictfp
Consider the following Java program, that illustrate the use of abstract keyword with classes and methods.  
Java
// A java program to demonstrate// use of abstract keyword. // abstract classabstract class A {    // abstract method    // it has no body    abstract void m1();     // concrete methods are still    // allowed in abstract classes    void m2()    {        System.out.println("This is "                           + "a concrete method.");    }} // concrete class Bclass B extends A {    // class B must override m1() method    // otherwise, compile-time    // exception will be thrown    void m1()    {        System.out.println("B's "                           + "implementation of m1.");    }} // Driver classpublic class AbstractDemo {    public static void main(String args[])    {        B b = new B();        b.m1();        b.m2();    }}
Output: 
B's implementation of m1.
This is a concrete method.
Note: Although abstract classes cannot be used to instantiate objects, they can be used to create object references, because Java’s approach to run-time polymorphism is implemented through the use of super-class references. Thus, it must be possible to create a reference to an abstract class so that it can be used to point to a subclass object. 
mukundpandey2000
slheymann1
Picked
Java
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Hashtable in Java
Constructors in Java
Different ways of Reading a text file in Java
Comparator Interface in Java with Examples
Java Math random() method with Examples
HashMap containsKey() Method in Java
How to Create Array of Objects in Java?
Convert Double to Integer in Java
Iterating over ArrayLists in Java
Generating random numbers in Java