code-rag-bench/online-tutorials huggingface dataset:
D3.js | d3.map.keys() Function - GeeksforGeeks

28 Jun, 2019
The map.keys() function in D3.js is used to return an array of string keys for every entry in the created map. The order of the returned keys is arbitrary.
Syntax:
map.keys()
Parameters: This function does not accept any parameters.
Return Value: This function returns an array of string keys for every entry in the created map.
Below programs illustrate the d3.map.keys() function in D3.js:
Example 1:
<!DOCTYPE html><html>  <head>    <title>d3.map.keys() function</title>      <script src='https://d3js.org/d3.v4.min.js'></script></head>  <body>    <script>                  // Creating a map        var map = d3.map({"Ram": 5, "Geeks": 10, "gfg": 15});                // Calling the map.keys() function        A = map.keys();                // Getting an array of string keys for        // every entry in the map.        console.log(A);    </script></body>  </html>
Output:
["Ram", "Geeks", "gfg"]

Example 2:
<!DOCTYPE html><html>  <head>    <title>d3.map.keys() function</title>      <script src='https://d3js.org/d3.v4.min.js'></script></head>  <body>    <script>                  // Creating some maps        var map1 = d3.map({"Ram": 5});        var map2 = d3.map({"Geeks": 10});        var map3 = d3.map({"Ram": 5, "Geeks": 10});        var map4 = d3.map();                // Calling the map.keys() function        A = map1.keys();        B = map2.keys();        C = map3.keys();        D = map4.keys();                // Getting an array of string keys for        // every entry in the map.        console.log(A);        console.log(B);        console.log(C);        console.log(D);    </script></body>  </html>
Output:
["Ram"]
["Geeks"]
["Ram", "Geeks"]
[]

Ref: https://devdocs.io/d3~5/d3-collection#map_keys
D3.js
JavaScript
Web Technologies
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
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to Open URL in New Tab using JavaScript ?
Difference Between PUT and PATCH Request
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
Python | Pandas Series.diff()

20 Nov, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas Series.diff() is used to find difference between elements of the same series. The difference is sequential and depends on period parameter passed to diff() method.
Syntax: Series.diff(periods=1)
Parameters:periods: integer value, subtracts element before/after period from current element. Negative values are also accepted
Return type: Series
 Example:In this example, two series are created from Python lists. diff() method is called on both series, one time with positive period and one time with negative value passed to period parameter.
# importing pandas module import pandas as pd     # importing numpy module import numpy as np     # creating listlist =[15, 2, 34, 12, 4, 0, 9, 7]  # creating seriesseries = pd.Series(list)  # calling method with period 2period2 = series.diff(2)  # Passing Negative value to period# passing period of -1period_1 = series.diff(-1)  # displayprint('Diff with period 2:\n{}\n\       Diff with period -1:\n{}'.format(period2, period_1))
Output:
Diff with period 2:
0     NaN
1     NaN
2    19.0
3    10.0
4   -30.0
5   -12.0
6     5.0
7     7.0
dtype: float64

Diff with period -1:
0    13.0
1   -32.0
2    22.0
3     8.0
4     4.0
5    -9.0
6     2.0
7     NaN
dtype: float64
Explanation: In the first output with period 2, value at ith position were subtracted from (i+2)th position and stored at (i+2)th position. In second output, value at ith position were subtracted from values at (i-1)th position and stored at (i-1)th position.
Note: First/Last n values in output series are NaN depending on sign of period.(First if period is positive and Last if negative where n is period).
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js MySQL Update Statement

17 Feb, 2021
Node.js is an open-source platform for executing JavaScript code on the server-side. It can be downloaded from here. MySQL is an open-source Relational Database Management System (RDBMS) that uses Structured Query Language (SQL). It is the most popular language for adding, accessing, and managing content in a database. Here we will use the MySQL as a database for our node application. It can be downloaded from here.
Update statement: Update command is a DML command which is used for manipulating the records of a table.
Syntax:
UPDATE [table_name] SET column_A = value_A, 
  column_B = value_B, ... WHERE condition
Modules:
mysql: mysql module is used for interaction between the MySQL server and the node.js application.
Installing module:
npm install mysql
SQL publishers Table preview:
Example 1: Update all salary to 0.
index.js
// Importing moduleconst mysql = require("mysql");  // Creating connectionlet db_con  = mysql.createConnection({    host: "localhost",    user: "root",    password: '',    database: 'gfg_db'});  db_con.connect((err) => {    if (err) {      console.log("Database Connection Failed !!!", err);      return;    }      console.log("We are connected to gfg_db database");      // Creating Query    let query = "UPDATE publishers SET salary=0";      // Executing Query    db_con.query(query, (err, rows) => {        if(err) throw err;        console.log(rows);    });});
Run index.js file using below command:
node index.js
Console Output: Using the Where clause is very important in UPDATE. Otherwise, the whole table may become useless.
Example 2: Increase the salary of publishers by 1000 who are earning more than 7000.
index.js
// Importing moduleconst mysql = require("mysql");  // Creating connectionlet db_con  = mysql.createConnection({    host: "localhost",    user: "root",    password: '',    database: 'gfg_db'});  db_con.connect((err) => {    if (err) {      console.log("Database Connection Failed !!!", err);      return;    }      console.log("We are connected to gfg_db database");      // Generating Query    let query = "UPDATE publishers SET salary=salary+1000 WHERE salary > 7000";      // Executing Query    db_con.query(query, (err, rows) => {        if(err) throw err;          console.log(rows);    });});
Run index.js file using below command:
node index.js
Console Output: Notice previous and current salary of users with id 6, 8
NodeJS-MySQL
Technical Scripter 2020
Node.js
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Installation of Node.js on Windows
JWT Authentication with Node.js
Difference between dependencies, devDependencies and peerDependencies
Mongoose Populate() Method
Mongoose find() Function
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
CASE WHEN column1 IS NULL THEN NULL ELSE column2 END with MySQL

For this, you can use the CASE statement. Let us first create a table−
mysql> create table DemoTable
   -> (
   -> Name varchar(20),
   -> Marks1 int,
   -> Marks2 int
   -> );
Query OK, 0 rows affected (0.72 sec)
Insert some records in the table using insert command−
mysql> insert into DemoTable values('Chris',45,null);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('David',null,78);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values('Bob',67,98);
Query OK, 1 row affected (0.14 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-------+--------+--------+
| Name  | Marks1 | Marks2 |
+-------+--------+--------+
| Chris |     45 |   NULL |
| David |   NULL |     78 |
| Bob   |     67 |     98 |
+-------+--------+--------+
3 rows in set (0.00 sec)
Here is the query to implement CASE WHEN −
mysql> select *,
   -> (case when Marks1 is null then null else Marks2 end ) as Value
   -> from DemoTable;
This will produce the following output −
+-------+--------+--------+-------+
| Name  | Marks1 | Marks2 | Value |
+-------+--------+--------+-------+
| Chris |     45 |   NULL |  NULL |
| David |   NULL |     78 |  NULL |
| Bob   |     67 |     98 |    98 |
+-------+--------+--------+-------+
3 rows in set (0.00 sec)
Convert IntStream to String in Java

If you have IntStream with ASCII values, then easily convert it to string using the below given example.
For IntStream class, import the following package
import java.util.stream.IntStream;
Let’s say the following is our IntStream
IntStream stream = "Example".chars();
Now, convert the IntStream to string
String str = stream.collect(StringBuilder::new,
   StringBuilder::appendCodePoint,
   StringBuilder::append).toString();
The following is an example to convert IntStream to String in Java
import java.util.stream.IntStream;
class Demo {
   public static void main(String[] args) {
      IntStream stream = "Example".chars();
      System.out.println("The ASCII values...");
      String str = stream.collect(StringBuilder::new,
      StringBuilder::appendCodePoint,
      StringBuilder::append).toString();
      System.out.println("The converted string = " + str);
   }
}
The ASCII values...
The converted string = Example
Prefix and Postfix Expressions in Data Structure

The way to write arithmetic expression is known as a notation. An arithmetic expression can be written in three different but equivalent notations, i.e., without changing the essence or output of an expression. These notations are –
Infix
Infix
Prefix
Prefix
Postfix
Postfix
Infix notations are normal notations, that are used by us while write different mathematical expressions. The Prefix and Postfix notations are quite different.
In this notation, operator is prefixed to operands, i.e. operator is written ahead of operands. For example, +ab. This is equivalent to its infix notation a + b. Prefix notation is also known as Polish Notation.
This notation style is known as Reversed Polish Notation. In this notation style, the operator is postfixed to the operands i.e., the operator is written after the operands. For example, ab+. This is equivalent to its infix notation a + b.
As we have discussed, it is not a very efficient way to design an algorithm or program to parse infix notations. Instead, these infix notations are first converted into either postfix or prefix notations and then computed.
To parse any arithmetic expression, we need to take care of operator precedence and associativity also.
When an operand is in between two different operators, which operator will take the operand first, is decided by the precedence of an operator over others. For example –
a + b ∗ c → a + (b ∗ c)
As multiplication operation has precedence over addition, b * c will be evaluated first. A table of operator precedence is provided later.
Is it possible to color a specific item in a Tkinter Listbox widget?

Tkinter ListBox widget is generally used for creating a list of items in the form of a list. The items can be chosen through the mouse buttons whenever we click a particular List Item. Each item in the ListBox is configured with the default color, which can be changed by defining the ‘background’ and ‘foreground’ color in itemconfig(options) method.
In this example, we will create a ListBox that contains a list of items. We will provide different colors to a few of the list items.
#Import required libraries
from tkinter import *
#Create an instance of tkinter frame
win= Tk()

#Define the geometry of the window
win.geometry("750x250")

#Create a ListBox
listbox= Listbox(win)
listbox.pack(expand=True, fill=BOTH)

#Adding Items in the ListBox
for item in ["C++","Python", "JavaScript", "Go"]:
   listbox.insert("end", item)

#Configure the listitems
listbox.itemconfig(1,{'bg':'OrangeRed3'})
listbox.itemconfig(3,{'bg':'khaki3'})

win.mainloop()
Running the above code will display listbox with list items. List Items color can be configured by changing the value of ‘bg’.
How to SELECT min and max value from the part of a table in MySQL?

To select min and max value from the part of a table in MySQL, use the following syntax −
select min(yourColumnName) as yourAliasName1,max(yourColumnName) as
yourAliasName2 from
(select yourColumnName from yourTableName limit yourLimitValue) tbl1;
Let us first create a table. Following is the query −
mysql> create table MinAndMaxValueDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> Value int
   -> );
Query OK, 0 rows affected (0.52 sec)
Insert records in the table using insert command. Following is the query −
mysql> insert into MinAndMaxValueDemo(Value) values(10);
Query OK, 1 row affected (0.16 sec)

mysql> insert into MinAndMaxValueDemo(Value) values(100);
Query OK, 1 row affected (0.11 sec)

mysql> insert into MinAndMaxValueDemo(Value) values(50);
Query OK, 1 row affected (0.13 sec)

mysql> insert into MinAndMaxValueDemo(Value) values(40);
Query OK, 1 row affected (0.12 sec)
Following is the query to display all records from the table using select statement −
mysql> select * from MinAndMaxValueDemo;
This will produce the following output −
+----+-------+
| Id | Value |
+----+-------+
| 1  | 10    |
| 2  | 100   |
| 3  | 50    |
| 4  | 40    |
+----+-------+
4 rows in set (0.00 sec)
Following is the query to select min and max value from the part of a table in MySQL −
mysql> select min(Value) as MinimumValue,max(Value) as MaximumValue from
   -> (select Value from MinAndMaxValueDemo limit 3) tbl1;
This will produce the following output −
+--------------+--------------+
| MinimumValue | MaximumValue |
+--------------+--------------+
| 10           | 100          |
+--------------+--------------+
1 row in set (0.07 sec)
Apache POI - Workbooks

Here the term 'Workbook' means Microsoft Excel file. After completion of this chapter, you will be able to create new Workbooks and open existing Workbooks with your Java program.
The following simple program is used to create a blank Microsoft Excel Workbook.
import java.io.*;
import org.apache.poi.xssf.usermodel.*;

public class CreateWorkBook {
   public static void main(String[] args)throws Exception {
      //Create Blank workbook
      XSSFWorkbook workbook = new XSSFWorkbook(); 

      //Create file system using specific name
      FileOutputStream out = new FileOutputStream(new File("createworkbook.xlsx"));

      //write operation workbook using file out object 
      workbook.write(out);
      out.close();
      System.out.println("createworkbook.xlsx written successfully");
   }
}
Let us save the above Java code as CreateWorkBook.java, and then compile and execute it from the command prompt as follows −
$javac CreateWorkBook.java
$java CreateWorkBook

If your system environment is configured with the POI library, it will compile and execute to generate the blank Excel file named createworkbook.xlsx in your current directory and display the following output in the command prompt.
createworkbook.xlsx written successfully

Use the following code to open an existing workbook.
import java.io.*;
import org.apache.poi.xssf.usermodel.*;

public class OpenWorkBook {
   public static void main(String args[])throws Exception { 
	   try {
         File file = new File("openworkbook.xlsx");
         FileInputStream fIP = new FileInputStream(file);

         //Get the workbook instance for XLSX file 
         XSSFWorkbook workbook = new XSSFWorkbook(fIP);

         if(file.isFile() && file.exists()) {
            System.out.println("openworkbook.xlsx file open successfully.");
         } else {
            System.out.println("Error to open openworkbook.xlsx file.");
         }
      } catch(Exception e) {
         System.out.println("Error to open openworkbook.xlsx file." + e.getMessage());
      }
   }
}
Save the above Java code as OpenWorkBook.java, and then compile and execute it from the command prompt as follows −
$javac OpenWorkBook.java
$java OpenWorkBook

It will compile and execute to generate the following output.
openworkbook.xlsx file open successfully.

After opening a workbook, you can perform read and write operations on it.

    46 Lectures 
     3.5 hours 

 Arnab Chakraborty

    23 Lectures 
     1.5 hours 

 Mukund Kumar Mishra

    16 Lectures 
     1 hours 

 Nilay Mehta

    52 Lectures 
     1.5 hours 

 Bigdata Engineer

    14 Lectures 
     1 hours 

 Bigdata Engineer

    23 Lectures 
     1 hours 

 Bigdata Engineer
 Print
 Add Notes
 Bookmark this page
Plus One in Python

Suppose we have an array of integers, say A. A will hold n elements, and they are non-negative. The whole array A is representing one large number. So if A = [5, 3, 2, 4] is given, it indicates the number 5324. We have to take that array A, then increase the number by 1, and again return the number like an array as given. So after increasing A will be [5, 3, 2, 5]
To solve this, we will follow these steps.
Take the array and append each character into a string to make it string
then convert the string to an integer, then increase the number by 1
then split each digit and make another array
Let us see the following implementation to get a better understanding −
 Live Demo
class Solution(object):
   def plusOne(self, digits):
      """
      :type digits: List[int]
      :rtype: List[int]
      """
      num = ""
      for i in digits:
         num +=str(i)
      num = int(num)
      num+=1
      num = str(num)
      ans = []
      for i in num:
         ans.append(int(i))
      return ans
digits = [5,3,2,4]
ob1 = Solution()
print(ob1.plusOne(digits))
digits = [5,3,2,4]
[5,3,2,5]
Data Structures - Asymptotic Analysis

Asymptotic analysis of an algorithm refers to defining the mathematical boundation/framing of its run-time performance. Using asymptotic analysis, we can very well conclude the best case, average case, and worst case scenario of an algorithm.
Asymptotic analysis is input bound i.e., if there's no input to the algorithm, it is concluded to work in a constant time. Other than the "input" all other factors are considered constant.
Asymptotic analysis refers to computing the running time of any operation in mathematical units of computation. For example, the running time of one operation is computed as f(n) and may be for another operation it is computed as g(n2). This means the first operation running time will increase linearly with the increase in n and the running time of the second operation will increase exponentially when n increases. Similarly, the running time of both operations will be nearly the same if n is significantly small.
Usually, the time required by an algorithm falls under three types −
Best Case − Minimum time required for program execution.
Best Case − Minimum time required for program execution.
Average Case − Average time required for program execution.
Average Case − Average time required for program execution.
Worst Case − Maximum time required for program execution.
Worst Case − Maximum time required for program execution.
Following are the commonly used asymptotic notations to calculate the running time complexity of an algorithm.
Ο Notation
Ω Notation
θ Notation
The notation Ο(n) is the formal way to express the upper bound of an algorithm's running time. It measures the worst case time complexity or the longest amount of time an algorithm can possibly take to complete.
For example, for a function f(n)
Ο(f(n)) = { g(n) : there exists c > 0 and n0 such that f(n) ≤ c.g(n) for all n > n0. }

The notation Ω(n) is the formal way to express the lower bound of an algorithm's running time. It measures the best case time complexity or the best amount of time an algorithm can possibly take to complete.
For example, for a function f(n)
Ω(f(n)) ≥ { g(n) : there exists c > 0 and n0 such that g(n) ≤ c.f(n) for all n > n0. }

The notation θ(n) is the formal way to express both the lower bound and the upper bound of an algorithm's running time. It is represented as follows −
θ(f(n)) = { g(n) if and only if g(n) =  Ο(f(n)) and g(n) = Ω(f(n)) for all n > n0. }

Following is a list of some common asymptotic notations −

    42 Lectures 
     1.5 hours 

 Ravi Kiran

    141 Lectures 
     13 hours 

 Arnab Chakraborty

    26 Lectures 
     8.5 hours 

 Parth Panjabi

    65 Lectures 
     6 hours 

 Arnab Chakraborty

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    64 Lectures 
     10.5 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page
How to get the innerHTML of a cell with JavaScript DOM?

Use the innerHTML property in JavaScript to get the innerHTML of a cell. You can try to run the following code to get the innerHTML of a cell in JavaScript −
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <script>
         function cellFunc(x) {      
            var cell = document.getElementById(x).rows[0].cells;      
            document.write(cell[0].innerHTML);
         }
      </script>
   </head>
   <body>  
      <table style="border:2px solid black" id="newtable">
         <tr>
            <td>One</td>
            <td>Two</td>
         </tr>
         <tr>
            <td>Three</td>
            <td>Four</td>
         </tr>
         <tr>
            <td>Five</td>
            <td>Six</td>
         </tr>
      </table>  
      <p>
         <input type="button" onclick="cellFunc('newtable')" value="Display Table Cell">
      </p>  
   </body>
</html>
D3.js format() Function - GeeksforGeeks

23 Jul, 2020
The format() function in D3.js is used to format the numbers in different styles available in D3. It is the alias for locale.format.
Syntax:
d3.format(specifier)(value);
Parameters: It takes the parameters given above and described below.
specifier: It specifies the format type.
value: It is the number to be formatted.
Return Value: It returns the Number.
Below given are a few examples of the above function.
Example1:
<!DOCTYPE html><html lang="en"><head>  <meta charset="UTF-8">  <meta name="viewport"        content="width=device-width,                 initial-scale=1.0">  <title>Document</title></head><style></style><body>  <!--Fetching from CDN of D3.js -->  <script type = "text/javascript"           src = "https://d3js.org/d3.v4.min.js">   </script>  <script>    // It gives the floating point up to two decimals    console.log(d3.format(".2f")(42.444))    // It sets the SI-Prefix with two significant digits    console.log(d3.format(".4s")(42000))    // Currency sign i.e $    console.log(d3.format("$, ")(4200))    /* Left and right side of the number is        filled with dots and centered.*/    console.log(d3.format("^, ")(42.444))    // Localised fixed-point currency    console.log(d3.format("($.2f")(42.444))    console.log(d3.format(".^20")(42))    // Prefixed lowercase hexadecimal number    console.log(d3.format("#x")(2))    // Prefixed lowercase hexadecimal number    console.log(d3.format("#x")(42))    /* Number is grouped thousand with       two significant digits*/    console.log(d3.format(", .2r")(42124)) </script></body></html>
Output:
D3.js
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?
How can we implement a JToggleButton in Java?

A JToggleButton is an extension of AbstractButton and it can be used to represent buttons that can be toggled ON and OFF.
When JToggleButton is pressed for the first time, it remains pressed and it can be released only when it is pressed for the second time.
A JToggleButton generates an ActionEvent each time it is pressed.
A JToggleButton can also generate an ItemEvent, this event is used by those components that support the concept of selection. When a JToggleButton is pressed in, it is selected. When it is popped out, it is deselected.
To handle item events, you must implement the ItemListener interface. This interface defines the itemStateChanged( ) method that is invoked when the state of an item changes. A toggle button’s state is by calling the isSelected( ) method on the button that generated the event.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class JToggleButtonTest extends JFrame implements ItemListener {
   private JToggleButton jtb;
   JToggleButtonTest() {
      setTitle("JToggleButton Test");
      setLayout(new FlowLayout());
      setJToggleButton();
      setAction();
      setSize(450, 300);
      setLocationRelativeTo(null);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setVisible(true);
   }
   private void setJToggleButton() {
      jtb = new JToggleButton("ON");
      add(jtb);
   }
   private void setAction() {
      jtb.addItemListener(this);
   }
   public void itemStateChanged(ItemEvent eve) {
      if(jtb.isSelected())
         jtb.setText("OFF");
      else
         jtb.setText("ON");
   }
}
public class MainApp {
   public static void main(String[] args) {
      new JToggleButtonTest();
   }
}
Puppeteer - Attribute Selector

Once we navigate to a webpage, we have to interact with the webelements available on the page like clicking a link/button, entering text within an edit box, and so on to complete our automation test case.
For this, our first job is to identify the element. If an attribute and its value is used only one time in a tag, we can use it as an attribute selector. If there are multiple elements with the same attribute value, only the first matching element on the page shall be identified.
The syntax for attribute selector is as follows −
const f = await page.$("ul[name='val']")

Here, ul is the tagname and val is the value set for the name attribute.
In the below image, let us obtain the text - About Tutorialspoint for the highlighted element −
The attribute selector expression for the above element shall be li[class='heading'].
To begin, follow Steps 1 to 2 from the Chapter of Basic Test on Puppeteer which are as follows −
Step 1 − Create a new file within the directory where the node_modules folder is created (location where the Puppeteer and Puppeteer core have been installed).
The details on Puppeteer installation is discussed in the Chapter of Puppeteer Installation.
Right-click on the folder where the node_modules folder is created, then click on the New file button.
Step 2 − Enter a filename, say testcase1.js.
Step 3 − Add the below code within the testcase1.js file created.
//Puppeteer library
const pt= require('puppeteer')
async function selectorAttribute(){
   //launch browser in headed mode
   const browser = await pt.launch()
   //browser new page
   const page = await browser.newPage()
   //launch URL
   await page.goto('https://www.tutorialspoint.com/about/about_careers.htm')
   //identify element with attribute selector
   const n = await page.$("li[class='heading']")
   //obtain text
   const t = await (await n.getProperty('textContent')).jsonValue()
   console.log("Obtained text is: " + t)
}
selectorAttribute()
Step 4 − Execute the code with the command given below −
node <filename>

So in our example, we shall run the following command −
node testcase1.js

After the command has been successfully executed, the text of the element - About Tutorialspoint gets printed in the console.
 Print
 Add Notes
 Bookmark this page
What is the PowerShell Workflow?

PowerShell workflow is built on the .Net based Windows Workflow Foundation (WWF) and it has a separate Workflow engine to execute the code because it translates code into XAML for the WWF framework.
PowerShell workflow is series of steps that is mainly used for
Running activities parallelly on more than one machine.
Running activities parallelly on more than one machine.
Long-running scripts.
Long-running scripts.
Structuring steps (Which steps will execute parallel and which in sequence)
Structuring steps (Which steps will execute parallel and which in sequence)
Frequently used tasks.
Frequently used tasks.
Resuming the script from where it was terminated due to system failure or any other interruption by defining checkpoints.
Resuming the script from where it was terminated due to system failure or any other interruption by defining checkpoints.
The PowerShell workflow was introduced in PowerShell 3.0 and discontinued for windows in the Core version (6.0 onwards) and only supported in the PowerShell framework version. PowerShell workflow is considered the backbone for the Microsoft Azure Runbooks and essentials for designing runbook steps.
The disadvantage with this method is, not all the cmdlets are supported in Workflow and you can check the MS link to find the difference between the PowerShell workflow and scripts.
https://docs.microsoft.com/en-us/previous-versions/windows/it-pro/windows-server-2012-R2-and-2012/jj574140(v=ws.11)
PowerShell workflow is defined the same as the PowerShell function but using the “Workflow” keyword and can be called by using its name only like PowerShell function.
Workflow TestWF{
   Write-Output "First PS Workflow"
}
PS C:\WINDOWS\system32> TestWF
First PS Workflow
Once the TestWF workflow is executed it creates a XAML code for it and you can check it using the below command.
Get-Command TestWF | fl *
Python | Convert a set into dictionary - GeeksforGeeks

11 Sep, 2021
Sometimes we need to convert one data structure into another for various operations and problems in our day to day coding and web development. Like we may want to get a dictionary from the given set elements.Let’s discuss a few methods to convert given set into a dictionary.
Method #1: Using fromkeys() 
Python3
# Python code to demonstrate# converting set into dictionary# using fromkeys() # initializing setini_set = {1, 2, 3, 4, 5} # printing initialized setprint ("initial string", ini_set)print (type(ini_set)) # Converting set to dictionaryres = dict.fromkeys(ini_set, 0) # printing final result and its typeprint ("final list", res)print (type(res))
initial string {1, 2, 3, 4, 5}
<class 'set'>
final list {1: 0, 2: 0, 3: 0, 4: 0, 5: 0}
<class 'dict'>
 
Method #2: Using dict comprehension 
Python3
# Python code to demonstrate# converting set into dictionary# using dict comprehension  # initializing setini_set = {1, 2, 3, 4, 5} # printing initialized setprint ("initial string", ini_set)print (type(ini_set)) str = 'fg'# Converting set to dictres = {element:'Geek'+str for element in ini_set} # printing final result and its typeprint ("final list", res)print (type(res))
initial string {1, 2, 3, 4, 5}
<class 'set'>
final list {1: 'Geek', 2: 'Geek', 3: 'Geek', 4: 'Geek', 5: 'Geek'}
<class 'dict'>
 
arorakashish0911
Python dictionary-programs
python-dict
Python
Python Programs
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Selecting rows in pandas DataFrame based on conditions
Check if element exists in list in Python
Defaultdict in Python
Python | Split string into list of characters
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python program to check whether a number is Prime or not
How to Find cofactor of a matrix using Numpy

23 Nov, 2021
In this article, we are going to see how to find the cofactor of a given matrix using NumPy. There is no direct way to find the cofactor of a given matrix using Numpy.
Formula to find the inverse of a matrix:
A-1 = ( 1 / det(A) )* Adj(A)      ----(1)
Adj(A) is the Adjoint matrix of A which can be found by taking the Transpose of the cofactor matrix of A:
Adj(A) = (cofactor(A))T            ----(2)
Substituting equation 2 in equation 1 we get the following:
A-1 = ( 1/det(A) ) *  (cofactor(A))T 
Sending det(A) to another side of the equation:
det(A) * A-1 = (cofactor(A))T 
Removing transpose on the Right-hand side(RHS) of the equation will result in applying transpose on the Left-hand side(LHS) of the equation. We can apply transpose after multiplying A-1 by det(A) but for simplicity, we will apply transpose to A-1 then multiply by det(A), however, both results are the same.
det(A) * (A-1)T = cofactor(A)      
Finally, we derived the formula to find the cofactor of a matrix:
cofactor(A) = (A-1)T * det(A)
Steps Needed:
Finding the determinant of a given matrix.
Finding the inverse of a matrix and transposing it.
Example 1: Finding cofactor in the 2D matrix
Python3
import numpy as np   def matrix_cofactor(matrix):     try:        determinant = np.linalg.det(matrix)        if(determinant!=0):            cofactor = None            cofactor = np.linalg.inv(matrix).T * determinant            # return cofactor matrix of the given matrix            return cofactor        else:            raise Exception("singular matrix")    except Exception as e:        print("could not find cofactor matrix due to",e)   print(matrix_cofactor([[1, 2], [3, 4]]))
Output:
[[ 4. -3.]
 [-2.  1.]]
Example 2: Finding cofactor 3D matrix
Python3
import numpy as np   def matrix_cofactor(matrix):     try:        determinant = np.linalg.det(matrix)        if(determinant!=0):            cofactor = None            cofactor = np.linalg.inv(matrix).T * determinant            # return cofactor matrix of the given matrix            return cofactor        else:            raise Exception("singular matrix")    except Exception as e:        print("could not find cofactor matrix due to",e)   print(matrix_cofactor([[1, 9, 3],                       [2, 5, 4],                       [3, 7, 8]]))
Output:
[[ 12.  -4.  -1.]
 [-51.  -1.  20.]
 [ 21.   2. -13.]]
gurukiranx
Python numpy-Matrix Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – Extract Indices of substring matches

29 Aug, 2020
Given a String List, and a substring, extract list of indices of Strings, in which that substring occurs.
Input : test_list = [“Gfg is good”, “for Geeks”, “I love Gfg”, “Gfg is useful”], K = “Gfg”Output : [0, 2, 3]Explanation : “Gfg” is present in 0th, 2nd and 3rd element as substring.
Input : test_list = [“Gfg is good”, “for Geeks”, “I love Gfg”, “Gfg is useful”], K = “good”Output : [0]Explanation : “good” is present in 0th substring.
Method #2 : Using loop + enumerate()
This is brute way in which this task can be done. In this, we iterate for all the elements along with their indices using enumerate() and conditional statements are used to get required result.
Python3
# Python3 code to demonstrate working of # Extract Indices of substring matches# Using loop + enumerate()  # initializing listtest_list = ["Gfg is good", "for Geeks", "I love Gfg", "Its useful"]  # initializing K K = "Gfg"  # printing original listprint("The original list : " + str(test_list))  # using loop to iterate through list res = []for idx, ele in enumerate(test_list):  if K in ele:    res.append(idx)  # printing result print("The indices list : " + str(res))
The original list : ['Gfg is good', 'for Geeks', 'I love Gfg', 'Its useful']
The indices list : [0, 2]

Method #2 : Using list comprehension + enumerate() 
This is yet another way in which this task can be solved. In this, we perform the similar task as above method using list comprehension and enumerate() is used to get compact solution.
Python3
# Python3 code to demonstrate working of # Extract Indices of substring matches# Using list comprehension + enumerate()  # initializing listtest_list = ["Gfg is good", "for Geeks", "I love Gfg", "Its useful"]  # initializing K K = "Gfg"  # printing original listprint("The original list : " + str(test_list))  # using list comprehension and enumerate to offer compact solutionres = [idx for idx, val in enumerate(test_list) if K in val]  # printing result print("The indices list : " + str(res))
The original list : ['Gfg is good', 'for Geeks', 'I love Gfg', 'Its useful']
The indices list : [0, 2]

Python list-programs
Python string-programs
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 ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary
How to create a Cumulative Histogram in Plotly?

05 Sep, 2020
Plotly is a Python library that is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library.
A cumulative histogram is a histogram that counts the cumulative cases over the range of cases. It can be created by passing True to the cumulative_enabled parameter.
Example 1: Vertical cumulative histogram
Python3
import plotly.express as px import plotly.graph_objects as go     df = px.data.iris()     fig = go.Figure(data=[go.Histogram(x=df['sepal_width'],                                    cumulative_enabled=True)]) fig.show()
Output:
Example 2: Horizontal cumulative histogram
Python3
import plotly.express as px import plotly.graph_objects as go     df = px.data.iris()     fig = go.Figure(data=[go.Histogram(y=df['sepal_width'],                                    cumulative_enabled=True)]) fig.show()
Output:
Python-Plotly
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
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
Determine if a Preference Node exists in Java

In order to determine the existence a preference node in Java, we use the nodeExists() method. The nodeExists() method returns a boolean value. It returns true when the specified preference node exists in the same tree as this node.
Declaration − The java.util.prefs.Preferences.remove() method is declared as follows −
public abstract boolean nodeExists(String pathname)throws BackingStoreException
where pathname is the path name of the node whose existence needs to be determined.
Let us see a program to determine if a preference node exists in Java −
 Live Demo
import java.util.prefs.Preferences;
public class Example {
   public static void main(String[] args) throws Exception {
      boolean exist = Preferences.userRoot().nodeExists("/node");
      System.out.println("Checking node existence before creation: "+exist);
      Preferences.userRoot().node("/node");
      exist = Preferences.userRoot().nodeExists("/node");
      System.out.println("Checking node existence after creation: "+exist);
   }
}
Checking node existence before creation: false
Checking node existence after creation: true
Dec 26, 2018 7:12:10 AM java.util.prefs.FileSystemPreferences$1 run
INFO: Created user preferences directory.
HTML - <bgsound> Tag

The HTML <bgsound> tag is used to play a soundtrack in the background. This tag is for Internet Explorer only.
<!DOCTYPE html>
<html>

   <head>
      <title>HTML bgsound Tag</title>
   </head>

   <body>
      <bgsound src = "/html/yourfile.mdi"/>
      
      <p>This does create any result on the screen but it plays sound file
         in the background.</p>
   </body>

</html>
This will produce the following result −
This does create any result on the screen but it plays sound file in the background.
The HTML <bgsound> tag also supports the following  additional attributes −

    19 Lectures 
     2 hours 

 Anadi Sharma

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    18 Lectures 
     1.5 hours 

 Frahaan Hussain

    57 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)

    54 Lectures 
     6 hours 

 DigiFisk (Programming Is Fun)

    45 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)
 Print
 Add Notes
 Bookmark this page
Program to find number of good pairs in Python

Suppose we have an array nums. Here a pair (i,j) is said to be a good pair if nums[i] is same as nums[j] and i < j. We have to count the number of good pairs.
So, if the input is like nums = [5,6,7,5,5,7], then the output will be 4 as there are 4 good pairs the indices are (0, 3), (0, 4) (3, 4), (2, 5)
To solve this, we will follow these steps −
count:= 0
count:= 0
n:= size of nums
n:= size of nums
for i in range 0 to n - 1, dofor j in range i+1 to n - 1, doif nums[i] is same as nums[j], thencount := count + 1
for i in range 0 to n - 1, do
for j in range i+1 to n - 1, doif nums[i] is same as nums[j], thencount := count + 1
for j in range i+1 to n - 1, do
if nums[i] is same as nums[j], thencount := count + 1
if nums[i] is same as nums[j], then
count := count + 1
count := count + 1
return count
return count
Let us see the following implementation to get better understanding −
 Live Demo
def solve(nums):
   count=0
   n=len(nums)
   for i in range(n):
      for j in range(i+1,n):
         if nums[i] == nums[j]:
            count+=1
   return count

nums = [5,6,7,5,5,7]
print(solve(nums))
[5,6,7,5,5,7]
4
Redshift from the command line. Getting started with psql is super... | by Siobhán K Cronin | Towards Data Science

I recently found myself writing and referencing Saved Queries in the AWS Redshift console, and knew there must be an easier way to keep track of my common sql statements (which I mostly use for bespoke COPY jobs or checking the logs, since we use Mode for all of our BI).
Turns out there IS an easier way, and it’s called psql (Postgres’ terminal-based interactive tool)! Getting started with psql is super easy, and you’ll rejoice in the amount of AWS console clicking it cuts out.
Start by installing postgres.
$ brew install postgres
Next, connect to your Redshift cluster.
Since you will be using psql ALL the time, I recommend creating an alias in your ~/.bash_profile so you can easily establish your database connection with a single word. I use redshift as my alias. You can use the credentials you’ve defined in your .bash_profile:
alias redshift='psql "host=$REDSHIFT_HOST user=$REDSHIFT_USER dbname=$REDSHIFT_DB port=$REDSHIFT_PORT sslmode=verify-ca     sslrootcert=<path to your postgres root .crt file> password=$REDSHIFT_PASSWORD"'
You will need to ensure your cluster security group is set to receive inbound traffic from whatever IP address you’ll be using in development. If your cluster is in a custom VPC, you can do this from the command line using the CLI’s authorize-security-group-ingress. Otherwise, if you’re using the default VPC, you can add your IP address to the Inbound rules for the Security Group manually in the console
Now that you’re connected, type redshift on the command line, and try out these handy commands:
\dt — view your tables\df — view your functions\dg — list database roles\dn — list schemas\dy — list event triggers\dp — show access privileges for tables, views, and sequences
$ SELECT * FROM your_schema.your_table LIMIT 10;
Open your favorite text editor and write a simple transaction (a series of sql — statements to be run as a single body of work, doing nothing if any one of them fails), for example:
BEGIN; INSERT INTO your_table VALUES (1), (2), (3), (4);INSERT INTO your_table VALUES (5), (6), (7), (8);INSERT INTO your_table VALUES (9), (10), (11), (12);COMMIT;
Save this transaction and run in the psql repl with the \i command:
dev=# \i your_transaction.sql
Have fun and let me know what you discover!
Siobhán is the Data Engineering Lead at Landed. Landed is on a mission to help essential professionals build financial security near the communities they serve, and we invest alongside educators when they’re ready to buy homes in expensive markets. Sound awesome? Join us!
SEO - Optimized Metatags

There are two important meta tags:
Meta description tags
Meta keyword tags
Some search engines may display the meta description as a part of the search results, but the meta keyword tags should not appear in search results.
The general consensus among SEO experts is that metatags are dead. Even so, many of these same experts continue to use metatags in their own sites.
For Google, adding the description meta tag does not result in a boost in the Search Engine Results Pages (SERPs), but the description might be used for the description for your SERP listings in Google.
Yahoo! says, they use the Keyword Meta Tag when it ranks a page. Hence it makes sense to add one for Yahoo! and any other minor search engines that still use.
You can add the following in the head section of the web page:
<meta name="keywords" 
         content="KEYWORD1 KEYWORD2 KEYPHRASE1 etc. 
         about 30 to 40 unique words">

<meta name="description" 
         content="An accurate, keyword-rich description 
         about 150 characters">
Important tips for good Meta description tags:
Use keywords in your meta description tag.
Use keywords in your meta description tag.
Try not to repeat the words overly often, but try to use multiple syntaxes of your key words.
Try not to repeat the words overly often, but try to use multiple syntaxes of your key words.
There should not be more than 150 characters in a description metatag of a single web page.
There should not be more than 150 characters in a description metatag of a single web page.
Use a different meta description tag for each page, as each page is different and stands a better chance of being found if you place a good title and description on it.
Use a different meta description tag for each page, as each page is different and stands a better chance of being found if you place a good title and description on it.
Please refer to the previous chapter for identifying good keywords. Use the following tips for preparing good meta keywords tags.
Use synonyms.
Use unique keywords.
No need to repeat any given phrase.
You can repeat a word any number of time, as long as each time it is part of a different phrase.
The important metatag that you may need sometime is the Robots Metatag which looks like this:
<meta name="robots" content="noindex,nofollow">
Using the above metatag, you can tell a spider or a robot that you do not want some of your pages indexed, or that you do not want your links followed.

    33 Lectures 
     4 hours 

 Asif Hussain

    33 Lectures 
     2.5 hours 

 Sasha Miller

    20 Lectures 
     3 hours 

 Sasha Miller

    38 Lectures 
     3 hours 

 Sasha Miller

    15 Lectures 
     1 hours 

 Zach Miller

    22 Lectures 
     1.5 hours 

 Zach Miller
 Print
 Add Notes
 Bookmark this page