code-rag-bench/online-tutorials huggingface dataset:
Duplicating Objects using a Constructor in Java

A copy constructor can be used to duplicate an object in Java. The copy constructor takes a single parameter i.e. the object of the same class that is to be copied. However, the copy constructor can only be explicitly created by the programmer as there is no default copy constructor provided by Java.
A program that demonstrates this is given as follows −
 Live Demo
class NumberValue {
   private int num;
   public NumberValue(int n) {
      num = n;
   }
   public NumberValue(NumberValue obj) {
      num = obj.num;
   }
   public void display() {
      System.out.println("The number is: " + num);
   }
}
public class Demo {
   public static void main(String[] args) {
      NumberValue obj1 = new NumberValue(12);
      NumberValue obj2 = new NumberValue(obj1);
      obj1.display();
      obj2.display();
   }
}
The number is: 12
The number is: 12
Now let us understand the above program.
The NumberValue class is created with a data member num and single member function display() that displays the value of num. There are two constructors in class NumberValue where one of these takes a single parameter of type int and another is a copy constructor that takes a single parameter i.e. an object of class NumberValue. A code snippet which demonstrates this is as follows −
class NumberValue {
   private int num;
   public NumberValue(int n) {
      num = n;
   }
   public NumberValue(NumberValue obj) {
      num = obj.num;
   }
   public void display() {
      System.out.println("The number is: " + num);
   }
}
In the main() method, objects obj1 and obj2 of class NumberValue are created and the display() method is called for both of them. A code snippet which demonstrates this is as follows −
public class Demo {
   public static void main(String[] args) {
      NumberValue obj1 = new NumberValue(12);
      NumberValue obj2 = new NumberValue(obj1);
      obj1.display();
      obj2.display();
   }
}
Add a new column to table and fill it with the data of two other columns of the same table in MySQL?

Let us first create a table −
mysql> create table DemoTable
(
   Price int,
   Quantity int
);
Query OK, 0 rows affected (0.71 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(45,3);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values(90,2);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values(440,1);
Query OK, 1 row affected (0.09 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-------+----------+
| Price | Quantity |
+-------+----------+
|    45 |        3 |
|    90 |        2 |
|   440 |        1 |
+-------+----------+
3 rows in set (0.00 sec)
Following is the query to add a new column to the table and fill with the data of 2 other columns. Here, we have added new column TotalAmount and the data in it is the multiplication of the values from the first two columns −
mysql> select Price,Quantity, Price*Quantity AS TotalAmount from DemoTable;
This will produce the following output −
+-------+----------+-------------+
| Price | Quantity | TotalAmount |
+-------+----------+-------------+
|    45 |        3 |         135 |
|    90 |        2 |         180 |
|   440 |        1 |         440 |
+-------+----------+-------------+
3 rows in set (0.00 sec)
DAX Filter - ISFILTERED function

Returns TRUE when columnName is being filtered directly.
If there is no filter on the column or if the filtering happens because a different column in the same table or in a related table is being filtered, then the DAX ISFILTERED function returns FALSE.
ISFILTERED (<columnName>) 

columnName
The name of a column in a table.
It cannot be an expression.
TRUE or FALSE.
A column is said to be filtered directly when the filter or filters apply over the column.
A column is said to be filtered directly when the filter or filters apply over the column.
A column columnName is said to be cross-filtered when a filter applied to another column in the same table or in a related table affects columnName by filtering it.
A column columnName is said to be cross-filtered when a filter applied to another column in the same table or in a related table affects columnName by filtering it.
You can use DAX ISCROSSFILTERED function to find if a column is cross-filtered.
= ISFILTERED (Sales[Product]) 

    53 Lectures 
     5.5 hours 

 Abhay Gadiya

    24 Lectures 
     2 hours 

 Randy Minder

    26 Lectures 
     4.5 hours 

 Randy Minder
 Print
 Add Notes
 Bookmark this page
How can I round a number to 1 decimal place in JavaScript?

To round a number to 1 decimal place in JavaScript, use the toFixed() method.
The following is the syntax, wherein digits are the number of digits to appear after the decimal poin −
number.toFixed( [digits] )
You can try to run the following code to round a number to 1 decimal places in JavaScript −
Live Demo
<html>
   <head>
      <title>JavaScript toFixed() Method</title>
   </head>
   
   <body>
      <script>
         var num = 488.234;
         document.write("num.toFixed(1) is : " + num.toFixed(1));
         document.write("<br />");
      </script>
   </body>
</html>
Java Examples - Search min and max

How to search the minimum and the maximum element in an array ?
This example shows how to search the minimum and maximum element in an array by using Collection.max() and Collection.min() methods of Collection class .
import java.util.Arrays;
import java.util.Collections;

public class Main {
   public static void main(String[] args) {
      Integer[] numbers = { 8, 2, 7, 1, 4, 9, 5};
      int min = (int) Collections.min(Arrays.asList(numbers));
      int max = (int) Collections.max(Arrays.asList(numbers));
      
      System.out.println("Min number: " + min);
      System.out.println("Max number: " + max);
   }
}
The above code sample will produce the following result.
Min number: 1
Max number: 9

Another sample example of the minimum and the maximum element in an array.
public class HelloWorld {
   public static void main(String[] args) {
      int numbers[] = new int[]{8, 2, 7, 1, 4, 9, 5};
      int s = numbers[0];
      int l = numbers[0];
      
      for(int i = 1; i < numbers.length; i++) {
         if(numbers[i] > l)l = numbers[i];
         else if (numbers[i] < s)s = numbers[i];
      } 
      System.out.println("Largest Number is : " + l);
      System.out.println("Smallest Number is : " + s);
   }
}
The above code sample will produce the following result.
Largest Number is : 9
Smallest Number is : 1   

 Print
 Add Notes
 Bookmark this page
What Are Whitespace and Line Breaks in JavaScript?

JavaScript ignores spaces, tabs, and newlines that appear in JavaScript programs. You can use spaces, tabs, and newlines freely in your program and you are free to format and indent your programs in a neat and consistent way that makes the code easy to read and understand.
JavaScript ignores whitespaces. For example, the following are same:
var employee = "Amit";
var employee="Amit";
Line breaks in JavaScript:
<!DOCTYPE html>
<html>
   <body>
      <p>Line-break in an alert box. Click below button.</p>
      <button onclick="alert('Hi\nWelcome to Tutorialspoint')">Click</button>
   </body>
</html>
How to prevent duplicate INSERT in MySQL?

For this, you can use UNIQUE INDEX −
alter table yourTableName ADD UNIQUE INDEX(yourColumnName1, yourColumnName2,....N);
Let us first create a table −
mysql> create table DemoTable
   -> (
   -> Value1 int,
   -> Value2 int
   -> );
Query OK, 0 rows affected (0.55 sec)
Following is the query to add unique index −
mysql> alter table DemoTable ADD UNIQUE INDEX(Value1, Value2);
Query OK, 0 rows affected (0.54 sec)
Records: 0  Duplicates: 0  Warnings: 0
Insert some records in the table using insert command −
Note − Use the INSERT IGNORE command rather than the INSERT command. If a record doesn't duplicate an existing record, then MySQL inserts it as usual. If the record is a duplicate, then the IGNORE keyword tells MySQL to discard it silently without generating an error.
mysql> insert ignore into DemoTable values(10,20);
Query OK, 1 row affected (0.14 sec)

mysql> insert ignore into DemoTable values(10,20);
Query OK, 0 rows affected, 1 warning (0.10 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+--------+--------+
| Value1 | Value2 |
+--------+--------+
|     10 |   20   |
+--------+--------+
1 row in set (0.00 sec)
Bootstrap .tab("show") method

Use the Bootstrap .tab(“show”) method to display the tabs.
The following are the nav tabs −
<ul class="nav nav-tabs">
  <li class="active"><a href="#home">Home</a></li>
  <li><a href="#two">PHP</a></li>
  <li><a href="#three">C#.NET</a></li>
  <li><a href="#four">Ruby</a></li>
  <li><a href="#five">HTML5</a></li>
</ul>
Using a script and the tab(“show”) method, the above tabs are displayed as in the following code snippet −
$(document).ready(function(){
  $(".nav-tabs a").click(function(){
    $(this).tab('show');
 });
});
Let us see an example to learn how to display tabs using the tab(“show”) method −
Live Demo
<!DOCTYPE html>
<html>
  <head>
    <title>Bootstrap Example</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/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.3.7/js/bootstrap.min.js"></script>
  </head>

<body>

<div class="container">
  <h2>Web Dev</h2>
  <ul class="nav nav-tabs">
    <li class="active"><a href="#home">Home</a></li>
    <li><a href="#two">PHP</a></li>
    <li><a href="#three">C#.NET</a></li>
    <li><a href="#four">Ruby</a></li>
    <li><a href="#five">HTML5</a></li>
  </ul>
  <div class="tab-content">
    <div id="home" class="tab-pane fade in active">
      <h3>Home</h3>
      <p>This is demo text!</p>
    </div>
    <div id="two" class="tab-pane fade">
      <h3>PHP</h3>
      <p>This is demo text!</p>
    </div>
    <div id="three" class="tab-pane fade">
      <h3>C#.NET</h3>
      <p>This is demo text!</p>
    </div>
    <div id="four" class="tab-pane fade">
      <h3>Ruby</h3>
      <p>This is demo text!</p>
    </div>
    <div id="five" class="tab-pane fade">
      <h3>HTML5</h3>
      <p>This is demo text!</p>
    </div>
  </div>
</div>

<script>
$(document).ready(function(){
  $(".nav-tabs a").click(function(){
     $(this).tab('show');
  });
});
</script>

</body>
</html>
Type Inference in Lambda expression in Java?

Type Inference states that the data type of any expression. For instance, a method return type or argument type can be understood automatically by the compiler. Types in the argument list can be omitted since java already know the types of the expected parameters for the single abstract method of functional interface.
(var1, var2 ...) -> { method body }
In the below example, we can sort a String[] array by its last character.
import java.util.Arrays;

public class TypeInferencingLambdaTest {
   public static void main(String[] args) {
      String[] names = {"Raja", "Jai", "Adithya", "Surya", "Chaitanya", "Ravi", "Krishna"};
      Arrays.sort(names, (s1, s2) -> {    // Lambda Expression
         return (s1.charAt(s1.length()-1) - s2.charAt(s2.length()-1));
      });
      for(String str : names) {
         System.out.println(str);
      }
   }
}
Raja
Adithya
Surya
Chaitanya
Krishna
Jai
Ravi
Different Star Pattern Programs in C#

Like any other programming languages such as C, C++, Java, we can easily display start pattern programs in C#.
Let us see them one by one.
 Live Demo
using System.IO;
using System;
class Program {
   static void Main() {
      for (int i = 1; i <= 6; ++i) {
         for (int j = 1; j <= i; ++j) {
            Console.Write("*");
         }
         Console.WriteLine();
      }
   }
}
*
**
***
****
*****
******
Let us see another series.
using System.IO;
using System;
class Program {
   static void Main() {
      int i, j, k;
      int n = 6,
      // loop to print the series
      for (i = 1; i <= n; i++) {
         for (j = 1; j <= n - i; j++) {
               Console.Write(" ");
         }
         for (k = 1; k <= i; k++) {
            Console.Write("*");
         }
         Console.WriteLine("");
      }
      Console.ReadLine();
   }
}
*
**
***
****
*****
******
Let us see another series.
using System.IO;
using System;
class Program {
   static void Main() {
      for (int i = 6; i >= 1; --i) {
         for (int j = 1; j >= i; ++j) {
            Console.Write("*");
         }
         Console.WriteLine();
      }
   }
}
******
*****
****
***
**
*
Here is another series.
 Live Demo
using System.IO;
using System;
class Demo {
   static void Main() {
      int a = 1, spaces, k = 6, i = 0, j = 0;
      spaces = k - 1;
      for(i=1; i<k*2; i++) {
         for(j=1; j<=spaces; j++) {
            Console.Write(" ");
         }
         for(j=1; j<a*2; j++) {
            Console.Write("*");
         }
         Console.WriteLine("");
         if(i < k) {
            spaces--;
            a++;
         } else {
            spaces++;
            a--;
         }
      }
   }
}
*
***
*****
*******
*********
***********
*********
*******
*****
***
*
Perform MySQL search between two dates

To perform MySQL search between two dates, use BETWEEN keyword. Let us first create a table −
mysql> create table DemoTable1456
   -> (
   -> CustomerName varchar(30),
   -> StartOfferDate  date,
   -> EndOfferDate date
   -> );
Query OK, 0 rows affected (0.54 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1456 values('Chris','2019-09-01','2019-09-30');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable1456 values('David','2019-09-01','2019-10-30');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable1456 values('Bob','2018-10-01','2018-10-20');
Query OK, 1 row affected (0.15 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1456;
This will produce the following output −
+--------------+----------------+--------------+
| CustomerName | StartOfferDate | EndOfferDate |
+--------------+----------------+--------------+
| Chris        |    2019-09-01  |   2019-09-30 |
| David        |     2019-09-01 |   2019-10-30 |
| Bob          |    2018-10-01  |   2018-10-20 |
+--------------+----------------+--------------+
3 rows in set (0.00 sec)
Following is the query to perform search between two dates and fetch records −
mysql> select * from DemoTable1456
   -> where date(now())  between StartOfferDate and EndOfferDate;
This will produce the following output −
+--------------+----------------+--------------+
| CustomerName | StartOfferDate | EndOfferDate |
+--------------+----------------+--------------+
| David        | 2019-09-01    |   2019-10-30  |
+--------------+----------------+--------------+
1 row in set (0.04 sec)
Finding edges in an image using Pillow

In this program, we will find the edges in an image using the pillow library. The FIND_EDGES function in the ImageFilter class helps us to find the edges in our image.
Step 1: Import Image and ImageFilter from Pillow.
Step 2: Open the image.
Step 3: Call the filter function and specify the find_edges function.
Step 4: Display the output.
from PIL import Image, ImageFilter

im = Image.open('testimage.jpg')
im = im.filter(ImageFilter.FIND_EDGES)
im.show()
What is the difference between every() and some() methods in JavaScript ? - GeeksforGeeks

04 Apr, 2022
The Array.every() method in JavaScript is used to check whether all the elements of the array satisfy the given condition or not. 
The Array.some() method in JavaScript is used to check whether at least one of the elements of the array satisfies the given condition or not. The only difference is that the some() method will return true if any predicate is true while every() method will return true if all predicates are true. 
Example 1: This example implements the some() method. 
javascript
<script> // JavaScript code for some() functionfunction isodd(element, index, array) {    return (element % 2 == 1);}     function geeks() {    var arr = [ 6, 1, 8, 32, 35 ];         // check for odd number    var value = arr.some(isodd);    console.log(value);}geeks();</script>
Output:
true
Example 2: This example implements the every() method. 
javascript
<script> // JavaScript code for every() functionfunction isodd(element, index, array) {    return (element % 2 == 1);}     function geeks() {    var arr = [ 6, 1, 8, 32, 35 ];         // check for odd number    var value = arr.every(isodd);    console.log(value);}geeks();</script>
Output:
false
Let us see the Differences in Tabular Form -:
Its Syntax is -: 
array.every(function(value, index, array), thisValue)
Its syntax is -:
array.some(function(value, index, array), this)
Its supported browsers are -:
Chrome, Internet Explorer 9 – 11, Firefox, Safari, Microsoft Edge, Opera
Its supported browsers are -:
Chrome, Internet Explorer, Firefox, Safari, Microsoft Edge, Opera
mayank007rawa
JavaScript-Misc
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
Difference between var, let and const keywords in JavaScript
How to append HTML code to a div using JavaScript ?
How to Open URL in New Tab using JavaScript ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
How to get the timing Execution Speed of Python Code?

To measure time of a program's execution, either use time.clock() or time.time() functions. The python docs state that this function should be used for benchmarking purposes. 
import time
t0= time.clock()
print("Hello")
t1 = time.clock() - t0
print("Time elapsed: ", t1 - t0) # CPU seconds elapsed (floating point)
This will give the output −
Time elapsed:  0.0009403145040156798
You can also use the timeit module to get proper statistical analysis of a code snippet's execution time.  It runs the snippet multiple times and then it tells you how long the shortest run took. You can use it as follows:
def f(x):
  return x * x
 
import timeit
timeit.repeat("for x in range(100): f(x)", "from __main__ import f", number=100000)
This will give the output −
[2.0640320777893066, 2.0876040458679199, 2.0520210266113281]
How to animate a line plot in Matplotlib?

To animate the line plot in matplotlib, we can take the following steps −
Create a figure and a set of subplots using subplots() method.
Create a figure and a set of subplots using subplots() method.
Limit x and y axes scale.
Limit x and y axes scale.
Create x and t data points using numpy.
Create x and t data points using numpy.
Return coordinate matrices from coordinate vectors, X2 and T2.
Return coordinate matrices from coordinate vectors, X2 and T2.
Plot a line with x and F data points using plot() method.
Plot a line with x and F data points using plot() method.
To make animation plot, update y data.
To make animation plot, update y data.
Make an animation by repeatedly calling a function *func*, current fig, animate, and interval.
Make an animation by repeatedly calling a function *func*, current fig, animate, and interval.
To display the figure, use show() method.
To display the figure, use show() method.
import numpy as np
from matplotlib import pyplot as plt, animation
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
fig, ax = plt.subplots()
ax.set(xlim=(-3, 3), ylim=(-1, 1))
x = np.linspace(-3, 3, 91)
t = np.linspace(1, 25, 30)
X2, T2 = np.meshgrid(x, t)
sinT2 = np.sin(2 * np.pi * T2 / T2.max())
F = 0.9 * sinT2 * np.sinc(X2 * (1 + sinT2))
line, = ax.plot(x, F[0, :], color='k', lw=2)
def animate(i):
   line.set_ydata(F[i, :])
anim = animation.FuncAnimation(fig, animate, interval=100, frames=len(t) - 1)
anim.save('503.gif')
plt.show()
When we execute this code, it will display a line plot with animation.
Hive - Partitioning

Hive organizes tables into partitions. It is a way of dividing a table into related parts based on the values of partitioned columns such as date, city, and department. Using partition, it is easy to query a portion of the data.
Tables or partitions are sub-divided into buckets, to provide extra structure to the data that may be used for more efficient querying. Bucketing works based on the value of hash function of some column of a table.
For example, a table named Tab1 contains employee data such as id, name, dept, and yoj (i.e., year of joining). Suppose you need to retrieve the details of all employees who joined in 2012. A query searches the whole table for the required information. However, if you partition the employee data with the year and store it in a separate file, it reduces the query processing time. The following example shows how to partition a file and its data:
The following file contains employeedata table.
/tab1/employeedata/file1
id, name, dept, yoj
1, gopal, TP, 2012
2, kiran, HR, 2012
3, kaleel,SC, 2013
4, Prasanth, SC, 2013

The above data is partitioned into two files using year.
/tab1/employeedata/2012/file2
1, gopal, TP, 2012
2, kiran, HR, 2012

/tab1/employeedata/2013/file3
3, kaleel,SC, 2013
4, Prasanth, SC, 2013

We can add partitions to a table by altering the table. Let us assume we have a table called employee with fields such as Id, Name, Salary, Designation, Dept, and yoj.
ALTER TABLE table_name ADD [IF NOT EXISTS] PARTITION partition_spec
[LOCATION 'location1'] partition_spec [LOCATION 'location2'] ...;

partition_spec:
: (p_column = p_col_value, p_column = p_col_value, ...)
The following query is used to add a partition to the employee table.
hive> ALTER TABLE employee
> ADD PARTITION (year=’2012’)
> location '/2012/part2012';
The syntax of this command is as follows.
ALTER TABLE table_name PARTITION partition_spec RENAME TO PARTITION partition_spec;
The following query is used to rename a partition:
hive> ALTER TABLE employee PARTITION (year=’1203’)
   > RENAME TO PARTITION (Yoj=’1203’);
The following syntax is used to drop a partition:
ALTER TABLE table_name DROP [IF EXISTS] PARTITION partition_spec, PARTITION partition_spec,...;
The following query is used to drop a partition:
hive> ALTER TABLE employee DROP [IF EXISTS]
   > PARTITION (year=’1203’);

    50 Lectures 
     4 hours 

 Navdeep Kaur

    67 Lectures 
     4 hours 

 Bigdata Engineer

    109 Lectures 
     2 hours 

 Bigdata Engineer
 Print
 Add Notes
 Bookmark this page
How to add a column to a Tkinter TreeView widget?

Tkinter TreeView widget is used to present data in a hierarchical manner in the form of rows and columns. To create a Treeview widget, you have to first create a constructor of Treeview(master, column, show='headings') widget. Here, you can specify the list of columns and pass the value to the column parameter that you want to include in the table.
The indexing of data in the Treeview widget starts from 0. Therefore, to avoid counting the first column, we need to use the show=heading parameter. Let us create an application to show a table with two columns "ID" and "Company" of car manufacturers. For each column, there will be some data that can be inserted by using the insert() method.
# Import the required libraries
from tkinter import *
from tkinter import ttk

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

# Set the size of the tkinter window
win.geometry("700x300")

# Create an instance of Style widget
style = ttk.Style()
style.theme_use('clam')

# Add a Treeview widget
tree = ttk.Treeview(win, column=("c1", "c2"), show='headings', height=8)
tree.column("# 1", anchor=CENTER)
tree.heading("# 1", text="ID")
tree.column("# 2", anchor=CENTER)
tree.heading("# 2", text="Company")

# Insert the data in Treeview widget
tree.insert('', 'end', text="1", values=('1', 'Honda'))
tree.insert('', 'end', text="2", values=('2', 'Hyundai'))
tree.insert('', 'end', text="3", values=('3', 'Tesla'))
tree.insert('', 'end', text="4", values=('4', 'Wolkswagon'))
tree.insert('', 'end', text="5", values=('5', 'Tata Motors'))
tree.insert('', 'end', text="6", values=('6', 'Renault'))

tree.pack()

win.mainloop()
Running the above code will display a Treeview widget with a list of vehicle manufacturers.
You can also modify/replace the row and column values by using the insert() method.
How to install Node.js on a webserver ? - GeeksforGeeks

06 Oct, 2021
To access web pages on any web application, we need a webserver to handle all the HTTP requests for the web application.Node.js provides the capabilities to create our own webserver which will handle HTTP requests asynchronously.
Below are the steps to install a simple HTTP web server on our local machine using NodeJS:
Step 1: Download and install Node js: Use this link to download the latest version of Node.js and then install it on your local machine using all the default options.
Step 2: Install the http-server package from npm: You can run the Node.js application directly from a command prompt or a command-line window. Now, you need to install the http-server module, it should be installed as a global npm package.
Open command prompt/command line and enter the following command:
npm install -g http-server
Step 3: Start a web server from a directory containing static website files: Now, after installing the module, you need to start the server. For that, you first need to change to the directory containing your static web files (HTML/CSS/JS, etc). Use the cd command for that.
In command prompt/command line, enter the following command:
cd projects\node
Now, start the server with the following command:
http-server
Now, you will see the following output on screen:
Step 4: Browse to your local website with a browser: Open any browser and go to http://localhost:8080/ (URL which we get from as output after we execute the above command).
Now we can see our local website running, this is how we can install Node.js on a web server.
how-to-install
NodeJS-Questions
Picked
How To
Installation Guide
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install FFmpeg on Windows?
How to Set Git Username and Password in GitBash?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Install Jupyter Notebook on MacOS?
How to Check the OS Version in Linux?
Installation of Node.js on Linux
How to Install FFmpeg on Windows?
How to Install Pygame on Windows ?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Install Jupyter Notebook on MacOS?
Sass - Placeholder Selectors

SASS supports placeholder selector using class or id selector. In normal CSS, these are specified with "#" or ".", but in SASS they are replaced with "%". To work with placeholder selector, they can be used with @extend directive. Without using @extend directive, you cannot display the result in CSS.
The following example demonstrates the use of placeholder selectors in the SCSS file −
<html>
   <head>
      <title>Placeholder Selectors</title>
      <link rel = "stylesheet" type = "text/css" href = "style.css" />
      <link rel = "stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
      <script src = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
   </head>

   <body>
      <h1>First Heading</h1>
      <p class = "frst_para">It is a CSS pre-processor which helps to reduce repetition with CSS and save the time. </p>
      <h1>Second Heading</h1>
      <p class = "sec_para">It was initially designed by Hampton Catlin and developed by Natalie Weizenbaum in 2006.</p>
   </body>
</html>
Next, create file style.scss.
.frst_para {
   color: green;
}
.sec_para {
   @extend .frst_para;
   font-size:20px;
}
Here, we have used the @extend directive, which allows one selector to inherit styles of another selector. You can tell SASS to watch the file and update the CSS whenever Sass file changes, by using the following command −
sass --watch C:\ruby\lib\sass\style.scss:style.css

Next, execute the above command; it will create the style.css file automatically with the following code −
.frst_para, .sec_para {
   color: green;
}
.sec_para {
   font-size: 20px;
}
Let us carry out the following steps to see how the above given code works −
Save the above given html code in placeholder_selectors.html file.
Save the above given html code in placeholder_selectors.html file.
Open this HTML file in a browser, an output is displayed as shown below.
Open this HTML file in a browser, an output is displayed as shown below.

    50 Lectures 
     5.5 hours 

 Code And Create

    124 Lectures 
     30 hours 

 Juan Galvan

    162 Lectures 
     31.5 hours 

 Yossef Ayman Zedan

    167 Lectures 
     45.5 hours 

 Muslim Helalee
 Print
 Add Notes
 Bookmark this page
How can I set an ImageView's width and height programmatically in Android using Kotlin?

This example demonstrates how to set an ImageView's width and height programmatically in Android using Kotlin.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:id="@+id/relativeLayout"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:padding="4dp"
   tools:context=".MainActivity">
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.kt
import android.os.Bundle
import android.widget.ImageView
import android.widget.RelativeLayout
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
   override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)
      title = "KotlinApp"
      val relativeLayout: RelativeLayout = findViewById(R.id.relativeLayout)
      val imageView = ImageView(this)
      imageView.setImageResource(R.drawable.image)
      val params = RelativeLayout.LayoutParams(
         RelativeLayout.LayoutParams.MATCH_PARENT,
         RelativeLayout.LayoutParams.MATCH_PARENT
      )
      imageView.layoutParams = params
      relativeLayout.addView(imageView)
   }
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.q11">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen
Java - isWhitespace() Method

The method determines whether the specified char value is a white space, which includes space, tab, or new line.
boolean isWhitespace(char ch)

Here is the detail of parameters −
ch − Primitive character type.
ch − Primitive character type.
This method returns true, if the passed character is really a white space.
public class Test {

   public static void main(String args[]) {
      System.out.println(Character.isWhitespace('c'));
      System.out.println(Character.isWhitespace(' '));
      System.out.println(Character.isWhitespace('\n'));
      System.out.println(Character.isWhitespace('\t'));
   }
}
This will produce the following result −
false
true
true
true


    16 Lectures 
     2 hours 

 Malhar Lathkar

    19 Lectures 
     5 hours 

 Malhar Lathkar

    25 Lectures 
     2.5 hours 

 Anadi Sharma

    126 Lectures 
     7 hours 

  Tushar Kale

    119 Lectures 
     17.5 hours 

 Monica Mittal

    76 Lectures 
     7 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
Python Blockchain - Creating Genesis Block

We assume that the originator of TPCoins initially gives out 500 TPCoins to a known client Dinesh. For this, he first creates a Dinesh instance −
Dinesh = Client()

We then create a genesis transaction and send 500 TPCoins to Dinesh’s public address.
t0 = Transaction (
   "Genesis",
   Dinesh.identity,
   500.0
)

Now, we create an instance of Block class and call it block0.
block0 = Block()

We initialize the previous_block_hash and Nonce instance variables to None, as this is the very first transaction to be stored in our blockchain.
block0.previous_block_hash = None
Nonce = None

Next, we will add the above t0 transaction to the verified_transactions list maintained within the block −
block0.verified_transactions.append (t0)

At this point, the block is completely initialized and is ready to be added to our blockchain. We will be creating the blockchain for this purpose. Before we add the block to the blockchain, we will hash the block and store its value in the global variable called last_block_hash that we declared previously. This value will be used by the next miner in his block.
We use the following two lines of coding for hashing the block and storing the digest value.
digest = hash (block0)
last_block_hash = digest

Finally, we create a blockchain as we see in the next chapter.

    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
numpy.char.splitlines()

This function returns a list of elements in the array, breaking at line boundaries.
import numpy as np 
print np.char.splitlines('hello\nhow are you?') 
print np.char.splitlines('hello\rhow are you?')
Its output is as follows −
['hello', 'how are you?']
['hello', 'how are you?']

'\n', '\r', '\r\n' can be used as line boundaries.

    63 Lectures 
     6 hours 

 Abhilash Nelson

    19 Lectures 
     8 hours 

 DATAhill Solutions Srinivas Reddy

    12 Lectures 
     3 hours 

 DATAhill Solutions Srinivas Reddy

    10 Lectures 
     2.5 hours 

 Akbar Khan

    20 Lectures 
     2 hours 

 Pruthviraja L

    63 Lectures 
     6 hours 

 Anmol
 Print
 Add Notes
 Bookmark this page
PyQt5 – Setting/Disabling the frame of ComboBox

22 Apr, 2020
In this article we will see how we can set or disable the frame of the combo box. By default when we create a combo box it has frame although we can change it. In order to set or disable frame we use setFrame method.
Syntax : combo_box.setFrame(False)
Argument : It takes bool as argument
Action performed : It will disable the frame of check box
Below is the implementation –
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys    class Window(QMainWindow):      def __init__(self):        super().__init__()          # setting title        self.setWindowTitle("Python ")          # setting geometry        self.setGeometry(100, 100, 600, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()      # method for widgets    def UiComponents(self):          # creating a combo box widget        self.combo_box = QComboBox(self)          # setting geometry of combo box        self.combo_box.setGeometry(200, 150, 120, 30)          # geek list        geek_list = ["Geek", "Geeky Geek", "Legend Geek", "Ultra Legend Geek"]          # adding list of items to combo box        self.combo_box.addItems(geek_list)          # disabling the frame        self.combo_box.setFrame(False)          # finding if combo box is having frame or not        check = self.combo_box.hasFrame()          # creating label to show check        label = QLabel("Frame = " + str(check), self)          # setting geometry of label        label.setGeometry(200, 200, 200, 30)    # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python PyQt5-ComboBox
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
JavaScript | Add new elements at the beginning of an array

01 Apr, 2019
Adding new elements at the beginning of existing array can be done by using Array unshift() method. This method is similar to push() method but it adds element at the beginning of the array.
Syntax:
ArrayObject.unshift( arrayElement );
ArrayObject: It is the array, where to insert the element.
arrayElement: It is the element, which is to be inserted.
Example: This example inserts the element 6 at the beginning of array GFG_Array.
<!DOCTYPE html> <html>   <head>     <title>         JavaScript | Insert at beginning    </title></head>           <body style = "text-align:center;">           <h1 style = "color:green;" >         GeeksForGeeks     </h1>                   <p id="up"></p>          <button onclick="myGFG()">         Click to insert    </button>           <p id="down" style="color: green"></p>          <!-- Script to add element at beginning of array -->    <script>         var GFG_Array = [1, 2, 3, 4, 5];        var up = document.getElementById("up");        up.innerHTML = GFG_Array;        var down = document.getElementById("down");        down.innerHTML = "elements of GFG_Array = "                + GFG_Array;                          function myGFG() {            GFG_Array.unshift("6");            down = document.getElementById("down");            down.innerHTML = "element of GFG_Array = "                    + GFG_Array;        }    </script> </body>   </html>                    
Output:
Before clicking the button:
After clicking the button:
Example: This example inserts the element GFG_7 at the beginning of the GFG_Array.
<!DOCTYPE html> <html>   <head>     <title>         JavaScript | Insert at beginning    </title></head>           <body style = "text-align:center;">           <h1 style = "color:green;" >         GeeksForGeeks     </h1>                   <p id="up"></p>          <button onclick="myGFG()">         Click to insert    </button>           <p id="down" style="color: green"></p>                  <script>         var GFG_Array = ["GFG_1", "GFG_2", "GFG_3", "GFG_4"];        var up = document.getElementById("up");        up.innerHTML = GFG_Array;        var down = document.getElementById("down");        down.innerHTML = "elements of GFG_Array = "                + GFG_Array;                  function myGFG() {            GFG_Array.unshift("GFG_7");            down = document.getElementById("down");            down.innerHTML = "element of GFG_Array = "                    + GFG_Array;        }    </script> </body>   </html>                    
Output:
Before clicking the button:
After clicking the button:
javascript-array
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between Applets and Servlets

15 Jun, 2022
Prerequisite: Servlets and Applets
Examples:
Creating “hello world” Applet. 
Java
// A Hello World Applet// Save file as HelloWorld.java import java.applet.Applet;import java.awt.Graphics; // HelloWorld class extends Appletpublic class HelloWorld extends Applet {     // Overriding paint() method    @Override    public void paint(Graphics g)    {        g.drawString("Hello World", 20, 20);    }}
Creating “hello world” Servlet. 
Java
// Import required java librariesimport java.io.*;import javax.servlet.*;import javax.servlet.http.*; // Extend HttpServlet classpublic class HelloWorld extends HttpServlet {     private String message;     public void init() throws ServletException    {        // Do required initialization        message = "Hello World";    }     public void doGet(HttpServletRequest request,                      HttpServletResponse response)        throws ServletException, IOException    {         // Set response content type        response.setContentType("text/html");         // Actual logic goes here.        PrintWriter out = response.getWriter();        out.println("<h1>" + message + "</h1>");    }     public void destroy()    {        // do nothing.    }}
harshitdevda97
java-applet
java-servlet
Picked
Java
Web technologies Questions
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Google Charts - Basic bar chart

Following is an example of a basic bar chart. We've already seen the configuration used to draw this chart in Google Charts Configuration Syntax chapter. So let's see the complete example.
We've used BarChart class to show area based chart.
//bar chart
var chart = new google.visualization.BarChart(document.getElementById('container'));

googlecharts_bar_basic.htm
<html>
   <head>
      <title>Google Charts Tutorial</title>
      <script type = "text/javascript" src = "https://www.gstatic.com/charts/loader.js">
      </script>
      <script type = "text/javascript">
         google.charts.load('current', {packages: ['corechart']});     
      </script>
   </head>
   
   <body>
      <div id = "container" style = "width: 550px; height: 400px; margin: 0 auto">
      </div>
      <script language = "JavaScript">
         function drawChart() {
            // Define the chart to be drawn.
            var data = google.visualization.arrayToDataTable([
               ['Year', 'Asia'],
               ['2012',  900],
               ['2013',  1000],
               ['2014',  1170],
               ['2015',  1250],
               ['2016',  1530]
            ]);

            var options = {title: 'Population (in millions)'}; 

            // Instantiate and draw the chart.
            var chart = new google.visualization.BarChart(document.getElementById('container'));
            chart.draw(data, options);
         }
         google.charts.setOnLoadCallback(drawChart);
      </script>
   </body>
</html>
Verify the result.
GATE | GATE CS 1997 | Question 48

07 Feb, 2019
Each Process Pi, i= 1.......9 is coded as follows
 repeat 
    P(mutex)
    {Critical section}
    V(mutex)
 forever

The code for P10 is identical except it uses V(mutex) in place of P(mutex). What is the largest number of processes that can be inside the critical section at any moment?(A) 1(B) 2(C) 3(D) None of aboveAnswer: (D)Explanation: Consider code for i= 1 to 9Initially mutex value set to 1, so it can allow only 1 process at a time. Now p1 enter into critical section and by this time remaining all are in block state. (i.e blocked processes= 2,3,4,5,6,7,8,9). But consider code for 10th process, it tells that unblock any process because it contain operation. Because of this it can unblock the processes and send it to the critical section. By doing this all processes can enter into critical section. So, finally there are 10 processes at maximum can enter into critical section.
Alternative Way-There is loop which runs forever So P10 runs forever. And it has capability to put all other processes to Critical Section. Moreover they Asked Maximum Number of process that can be Present at critical Section So Answer is 10.
Option (D) is correct.
 This explanation is contributed by Ajay Puri.Quiz of this QuestionQuiz of this Question
tejasgokani
GATE CS 1997
GATE-GATE CS 1997
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33
GATE | GATE-CS-2014-(Set-3) | Question 20
GATE | GATE CS 2008 | Question 40
GATE | GATE CS 2008 | Question 46
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 2011 | Question 49
GATE | GATE CS 1996 | Question 38
GATE | GATE-CS-2004 | Question 31
Multiple Exception Handling in Python

12 Jun, 2019
Given a piece of code that can throw any of several different exceptions, and one needs to account for all of the potential exceptions that could be raised without creating duplicate code or long, meandering code passages.
If you can handle different exceptions all using a single block of code, they can be grouped together in a tuple as shown in the code given below :
Code #1 :
try:    client_obj.get_url(url)except (URLError, ValueError, SocketTimeout):    client_obj.remove_url(url)
The remove_url() method will be called if any of the listed exceptions occurs. If, on the other hand, if one of the exceptions has to be handled differently, then put it into its own except clause as shown in the code given below :
Code #2 :
try:    client_obj.get_url(url)except (URLError, ValueError):    client_obj.remove_url(url)except SocketTimeout:    client_obj.handle_url_timeout(url)
Many exceptions are grouped into an inheritance hierarchy. For such exceptions, all of the exceptions can be caught by simply specifying a base class. For example, instead of writing code as shown in the code given below –
Code #3 :
try:    f = open(filename)except (FileNotFoundError, PermissionError):    ...
Except statement can be re-written as in the code given below. This works because OSError is a base class that’s common to both the FileNotFoundError and PermissionError exceptions.
Code #4 :
try:    f = open(filename)except OSError:    ...
Although it’s not specific to handle multiple exceptions per se, it is worth noting that one can get a handle to the thrown exception using them as a keyword as shown in the code given below.
Code #5 :
try:    f = open(filename)  except OSError as e:    if e.errno == errno.ENOENT:        logger.error('File not found')    elif e.errno == errno.EACCES:        logger.error('Permission denied')    else:        logger.error('Unexpected error: % d', e.errno)
The e variable holds an instance of the raised OSError. This is useful if the exception has to be invested further, such as processing it based on the value of the additional status code. The except clauses are checked in the order listed and the first match executes.
Code #6 : Create situations where multiple except clauses might match
f = open('missing')
Output :
Traceback (most recent call last):
File "", line 1, in 
FileNotFoundError: [Errno 2] No such file or directory: 'miss

try:    f = open('missing')    except OSError:        print('It failed')    except FileNotFoundError:        print('File not found')
Output :
Failed

Here the except FileNotFoundError clause doesn’t execute because the OSError is more general, matches the FileNotFoundError exception, and was listed first.
Python-exceptions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.