code-rag-bench/online-tutorials huggingface dataset:
How to create a responsive "timeline" with CSS?

To create a responsive timeline with CSS, the code is as follows −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" event="width=device-width, initial-scale=1.0">
<style>
   * {
      box-sizing: border-box;
   }
   body {
      background-color: #9037f5;
      font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif
   }
   h2{
      text-align: center;
   }
   .timeline {
      position: relative;
      max-width: 1200px;
      margin: 0 auto;
   }
   .timeline::after {
      content: " ";
      position: absolute;
      width: 6px;
      background-color: rgb(253, 203, 255);
      top: 0;
      bottom: 0;
      left: 50%;
      margin-left: -3px;
   }
   /* eventsContainer around event */
   .eventsContainer {
      padding: 10px 40px;
      position: relative;
      background-color: inherit;
      width: 50%;
   }
   .eventsContainer::after {
      content: " ";
      position: absolute;
      width: 25px;
      height: 25px;
      right: -17px;
      background-color: rgb(219, 255, 12);
      border: 4px dashed rgb(255, 0, 0);
      background-clip: content-box;
      top: 15px;
      z-index: 1;
   }
   .displayLeft {
      left: 0;
   }
   .displayRight {
      left: 50%;
   }
   .displayLeft::before {
      content: " ";
      height: 0;
      position: absolute;
      top: 22px;
      width: 0;
      z-index: 1;
      right: 30px;
      border: medium solid rgb(225, 246, 255);
      border-width: 10px 0 10px 10px;
      border-color: transparent transparent transparent white;
   }
   .displayRight::before {
      content: " ";
      height: 0;
      position: absolute;
      top: 22px;
      width: 0;
      z-index: 1;
      left: 30px;
      border: medium solid white;
      border-width: 10px 10px 10px 0;
      border-color: transparent white transparent transparent;
   }
   .displayRight::after {
      left: -16px;
   }
   .event {
      padding: 20px 30px;
      background-color: white;
      position: relative;
      border-radius: 6px;
   }
   @media screen and (max-width: 600px) {
      .timeline::after {
         left: 31px;
      }
      .eventsContainer {
         width: 100%;
         padding-left: 70px;
         padding-right: 25px;
      }
      .eventsContainer::before {
         left: 60px;
         border: medium solid white;
         border-width: 10px 10px 10px 0;
         border-color: transparent white transparent transparent;
      }
      .displayLeft::after, .displayRight::after {
         left: 15px;
      }
      .displayRight {
         left: 0%;
      }
   }
</style>
</head>
<body>
<div class="timeline">
<div class="eventsContainer displayLeft">
<div class="event">
<h2>2017</h2>
<h3>Donald Trump became the 45th president of US</h3>
</div>
</div>
<div class="eventsContainer displayRight">
<div class="event">
<h2>2016</h2>
<h3>Summer Olympics are held in rio de Janerio</h3>
</div>
</div>
<div class="eventsContainer displayLeft">
<div class="event">
<h2>2015</h2>
<h3>7.8 Magnitude Earthquake strikes nepal</h3>
</div>
</div>
</div>
</body>
</html>
The above code will produce the following output −
On resizing the screen −
How to retrieve the OS of the Azure VM using Azure CLI in PowerShell?

To retrieve the Azure VM OS using Azure CLI, we can use the “az vm” command but before that, need to make sure that you are connected to the Azure cloud and the subscription.
PS C:\> az vm show -n VMName -g VMRG --query
"[storageProfile.imageReference.offer]" -otsv
OR
PS C:\> az vm show -n VMName -g VMRG --query storageProfile.imageReference.offer -
otsv
WindowsServer
To get the OS SKU or the operating system version, you can use,
PS C:\> az vm show -n VMName -g VMRG --query
"[storageProfile.imageReference.sku]" -otsv
2016-Datacenter
You can also use the below command to get the OS of the VM without providing the resource group name.
PS C:\> az vm list --query
"[?name==VMName].{os:storageProfile.imageReference.offer}" -otsv
To get the OS version or SKU,
PS C:\> az vm list --query "[?name==VMName].{os:storageProfile.imageReference.sku}"
-otsv
To combine all the outputs in the table format,
az vm list --query "[].{vmName:name, ResourceGroup:resourceGroup,
os:storageProfile.imageReference.offer, version:storageProfile.imageReference.sku}" -
otable
How to query on list field in MongoDB?

To understand the query on list field, and/or, you can create a collection with documents.
The query to create a collection with a document is as follows −
> db.andOrDemo.insertOne({"StudentName":"Larry","StudentScore":[33,40,50,60,70]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9522d316f542d757e2b444")
}
> db.andOrDemo.insertOne({"StudentName":"Larry","StudentScore":[87,67,79,98,90]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c95230916f542d757e2b445")
}
Display all documents from a collection with the help of find() method. The query is as follows −
> db.andOrDemo.find().pretty();
The following is the output −
{
   "_id" : ObjectId("5c9522d316f542d757e2b444"),
   "StudentName" : "Larry",
   "StudentScore" : [
      33,
      40,
      50,
      60,
      70
   ]
}
{
   "_id" : ObjectId("5c95230916f542d757e2b445"),
   "StudentName" : "Larry",
   "StudentScore" : [
      87,
      67,
      79,
      98,
      90
   ]
}
Here is the query on list field.
The query is as follows −
> db.andOrDemo.find({"StudentScore":70}).pretty();
The following is the output:
{
   "_id" : ObjectId("5c9522d316f542d757e2b444"),
   "StudentName" : "Larry",
   "StudentScore" : [
      33,
      40,
      50,
      60,
      70
   ]
}
Case 3 − Here is the query for or list field.
The query is as follows −
> db.andOrDemo.find({"$or":[ {"StudentScore":60}, {"StudentScore":90}]}).pretty();
Sample Output −
{
   "_id" : ObjectId("5c9522d316f542d757e2b444"),
   "StudentName" : "Larry",
   "StudentScore" : [
      33,
      40,
      50,
      60,
      70
   ]
}
{
   "_id" : ObjectId("5c95230916f542d757e2b445"),
   "StudentName" : "Larry",
   "StudentScore" : [
      87,
      67,
      79,
      98,
      90
   ]
}
Program for decimal to hexadecimal conversion in C++

Given with a decimal number as an input, the task is to convert the given decimal number into a hexadecimal number.
Hexadecimal number in computers is represented with base 16 and decimal number is represented with base 10 and represented with values 0 - 9 whereas hexadecimal number have digits starting from 0 – 15 in which 10 is represented as A, 11 as B, 12 as C, 13 as D, 14 as E and 15 as F.
To convert a decimal number into a hexadecimal number follow the given steps −
Firstly divide the given number with the base value of conversion number e.g. dividing 6789 by 16 because we need to convert 6789 into a hexadecimal numbers which have base 16 and then obtain a quotient and store it. If the remainder is between 0-9 store them as it is and if the remainder lies between 10-15 convert them in their character form as A - F
Divide the obtained quotient with the base value of hexadecimal number which is 16 and keep storing the bits.
Keep doing right shift to the stored bits
Repeat the step until the remainder left indivisible
Given below is the pictorial representation of converting a decimal number into a hexadecimal number.
Input-: 6789
   Divide the 6789 with base 16 : 6789 / 16 = 5 (remainder) 424(quotient)
   Divide quotient with base: 424 / 16 = 8(remainder) 26(quotient)
   Divide quotient with base: 26 / 16 = 10(remainder) 1(quotient)
   Now reverse the remainder obtained for final hexadecimal value.
Output-: 1A85
Start
Step 1-> Declare function to convert decimal to hexadecimal
   void convert(int num)
      declare char arr[100]
      set int i = 0
      Loop While(num!=0)
         Set int temp = 0
         Set temp = num % 16
         IF temp < 10
            Set arr[i] = temp + 48
            Increment i++
         End
         Else
            Set arr[i] = temp + 55
            Increment i++
         End
         Set num = num/16
      End
      Loop For int j=i-1 j>=0 j—
         Print arr[j]
Step 2-> In main()
   Set int num = 6789
   Call convert(num)
Stop
 Live Demo
#include<iostream>
using namespace std;
//convert decimal to hexadecimal
void convert(int num) {
   char arr[100];
   int i = 0;
   while(num!=0) {
      int temp = 0;
      temp = num % 16;
      if(temp < 10) {
         arr[i] = temp + 48;
         i++;
      } else {
         arr[i] = temp + 55;
         i++;
      }
      num = num/16;
   }
   for(int j=i-1; j>=0; j--)
   cout << arr[j];
}
int main() {
   int num = 6789;
   cout<<num<< " converted to hexadeciaml: ";
   convert(num);
   return 0;
}
IF WE RUN THE ABOVE CODE IT WILL GENERATE FOLLOWING OUTPUT
6789 converted to hexadeciaml: 1A85
How do we convert a string to a set in Python?

Python’s standard library contains built-in function set() which converts an iterable to set. A set object doesn’t contain repeated items. So, if a string contains any character more than once, that character appears only once in the set object. Again, the characters may not appear in the same sequence as in the string as set() function has its own hashing mechanism
>>> set("hello")
{'l', 'h', 'o', 'e'}
What is the correct way to define class variables in Python?

Class variables are variables that are declared outside the__init__method. These are static elements, meaning, they belong to the class rather than to the class instances. These class variables are shared by all instances of that class. Example code for class variables 
class MyClass:
  __item1 = 123
  __item2 = "abc"
  def __init__(self):
    #pass or something else
You'll understand more clearly with more code −
class MyClass:
    stat_elem = 456
    def __init__(self):
        self.object_elem = 789
c1 = MyClass()
c2 = MyClass()
# Initial values of both elements
>>> print c1.stat_elem, c1.object_elem
456 789
>>> print c2.stat_elem, c2.object_elem
456 789
# Let's try changing the static element
MyClass.static_elem = 888
>>> print c1.stat_elem, c1.object_elem
888 789
>>> print c2.stat_elem, c2.object_elem
888 789
# Now, let's try changing the object element
c1.object_elem = 777
>>> print c1.stat_elem, c1.object_elem
888 777
>>> print c2.stat_elem, c2.object_elem
888 789
C program for Binomial Coefficients table

Given with a positive integer value let’s say ‘val’ and the task is to print the value of binomial coefficient B(n, k) where, n and k be any value between 0 to val and hence display the result.
Binomial coefficient (n, k) is the order of choosing ‘k’ results from the given ‘n’ possibilities. The value of binomial coefficient of positive n and k is given by
Ckn=n!(n−k)!k!
where, n >= k
Input-: B(9,2)
Output-:
B29=9!(9−2)!2! 
9×8×7×6×5×4×3×2×16×5×4×3×2×1)×2×1=362,8801440=252
The Binomial Coefficient Table is formed for calculating the multiple values that can be generated between n and k.
Input-: value = 5
Output-:
Approach used in the below program is as follows −
Input the variable ‘val’ from the user for generating the table
Start the loop from 0 to ‘val’ because the value of binomial coefficient will lie between 0 to ‘val’
Apply the formula given, if n and k is not 0B(m, x) = B(m, x - 1) * (m - x + 1) / x
Apply the formula given, if n and k is not 0
B(m, x) = B(m, x - 1) * (m - x + 1) / x
Print the result
START
Step 1-> declare function for binomial coefficient table
   int bin_table(int val)
   Loop For int i = 0 and i <= val and i++
      print i
      Declare int num = 1
      Loop For int j = 0 and j <= i and j++
      If (i != 0 && j != 0)
         set num = num * (i - j + 1) / j
      End
         print num
   End
   print \n
Step 2-> In main()
   Declare int value = 5
   call bin_table(value)
STOP
#include <stdio.h>
// Function for binomial coefficient table
int bin_table(int val) {
   for (int i = 0; i <= val; i++) {
      printf("%2d", i);
      int num = 1;
      for (int j = 0; j <= i; j++) {
         if (i != 0 && j != 0)
         num = num * (i - j + 1) / j;
         printf("%4d", num);
      }
      printf("\n");
   }
}
int main() {
   int value = 5;
   bin_table(value);
   return 0;
}
How to form a MySQL Conditional Insert?

For this, you can insert using MySQL dual table. Let us create a table to understand the concept conditional insert. The query to create a table is as follows −
mysql> create table ConditionalInsertDemo
   -> (
   -> UserId int,
   -> TotalUser int,
   -> NumberOfItems int
   -> );
Query OK, 0 rows affected (0.58 sec)
Insert some records in the table using insert command. The query is as follows −
mysql> insert into ConditionalInsertDemo values(101,560,780);
Query OK, 1 row affected (0.19 sec)

mysql> insert into ConditionalInsertDemo values(102,660,890);
Query OK, 1 row affected (0.20 sec)

mysql> insert into ConditionalInsertDemo values(103,450,50);
Query OK, 1 row affected (0.15 sec)
Display all records from the table using select statement. The query is as follows −
mysql> select *from ConditionalInsertDemo;
+--------+-----------+---------------+
| UserId | TotalUser | NumberOfItems |
+--------+-----------+---------------+
|    101 | 560       |           780 |
|    102 | 660       |           890 |
|    103 | 450       |            50 |
+--------+-----------+---------------+
3 rows in set (0.00 sec)
Now you have 3 records in the table. You can insert the next records with conditional insert with the help of dual table. The query inserts records in the table whenever UserId=104 and NumberOfItems=3500 must not be present in the table already. The conditional insert query is as follows −
mysql> insert into ConditionalInsertDemo(UserId,TotalUser,NumberOfItems)
   -> select 104,900,3500 from dual
   -> WHERE NOT EXISTS (SELECT * FROM ConditionalInsertDemo
   -> where UserId=104 and NumberOfItems=3500);
Query OK, 1 row affected (0.18 sec)
Records: 1 Duplicates: 0 Warnings: 0
Now you can check the table, the record is inserted or not. The query to display all records is as follows −
mysql> select *from ConditionalInsertDemo;
+--------+-----------+---------------+
| UserId | TotalUser | NumberOfItems |
+--------+-----------+---------------+
|    101 |       560 |           780 |
|    102 |       660 |           890 |
|    103 |       450 |            50 |
|    104 |       900 |          3500 |
+--------+-----------+---------------+
4 rows in set (0.00 sec)
A Utopian Simplex Protocol

The Simplex protocol is data link layer protocol for transmission of frames over computer network. It is hypothetical protocol designed for unidirectional data transmission over an ideal channel, i.e. a channel through which transmission can never go wrong.
It is assumed that both the sender and the receiver are always ready for data processing and both of them have infinite buffer. The sender simply sends all its data available onto the channel as soon as they are available its buffer. The receiver is assumed to process all incoming data instantly. It is does not handle flow control or error control. Since this protocol is totally unrealistic, it is often called Utopian Simplex protocol.
The significance of this protocol lies in the fact that it shows the basic structure on which the usable protocols are built upon.
Sender Site: The data link layer in the sender site waits for the network layer to send a data packet. On receiving the packet, it immediately processes it and sends it to the physical layer for transmission.
Sender Site: The data link layer in the sender site waits for the network layer to send a data packet. On receiving the packet, it immediately processes it and sends it to the physical layer for transmission.
Receiver Site: The data link layer in the receiver site waits for a frame to be available. When it is available, it immediately processes it and sends it to the network layer.
Receiver Site: The data link layer in the receiver site waits for a frame to be available. When it is available, it immediately processes it and sends it to the network layer.
begin
   while (true)      //check repeatedly
   do
      Wait_For_Event();      //wait for availability of packet
      if ( Event(Frame_Available)) then
         Get_Data_From_Network_Layer();
         Make_Frame();
         Send_Frame_To_Physical_Layer();
      end if
   end while
end
begin
   while (true)       //check repeatedly
   do
      Wait_For_Event();      //wait for arrival of frame
      if ( Event(Frame_Arrival)) then
         Receive_Frame_From_Physical_Layer();
         Extract_Data();
         Deliver_Data_To_Network_Layer();
      end if
   end while
end
The following flow diagram depicts communication via simplex protocol.
Remove names or dimnames from an Object in R Programming - unname() Function - GeeksforGeeks

16 Jun, 2020
unname() function in R Language is used to remove the names or dimnames from an Object.
Syntax: unname(x)
Parameters:x: Object
Example 1:
# R Program to remove names from an object# Creating a matrixA = matrix(c(1:9), 3, 3)      # Naming rows rownames(A) = c("a", "b", "c")      # Naming columns colnames(A) = c("c", "d", "e")      print(A)   # Removing names using unname() functionunname(A)
Output:
  c d e
a 1 4 7
b 2 5 8
c 3 6 9
     [, 1] [, 2] [, 3]
[1, ]    1    4    7
[2, ]    2    5    8
[3, ]    3    6    9

Example 2:
# R Program to remove names from an object  # Calling pre-defined data setBOD  # Removing names using unname() functionunname(BOD)
Output:
  Time demand
1    1    8.3
2    2   10.3
3    3   19.0
4    4   16.0
5    5   15.6
6    7   19.8
        
1 1  8.3
2 2 10.3
3 3 19.0
4 4 16.0
5 5 15.6
6 7 19.8

R Object-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Replace specific values in column in R DataFrame ?
How to change Row Names of DataFrame in R ?
Filter data by multiple conditions in R using Dplyr
Change Color of Bars in Barchart using ggplot2 in R
Loops in R (for, while, repeat)
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
K-Means Clustering in R Programming
Remove rows with NA in one column of R DataFrame
Java Program to adjust LocalDate to last Day of Year with TemporalAdjusters class

Let us first set a date:
LocalDate localDate = LocalDate.of(2019, Month.FEBRUARY, 11);
Now, adjust LocalDate to last Day of year:
LocalDate day = localDate.with(TemporalAdjusters.lastDayOfYear());
import java.time.LocalDate;
import java.time.Month;
import java.time.temporal.TemporalAdjusters;
public class Demo {
   public static void main(String[] args) {
      LocalDate localDate = LocalDate.of(2019, Month.FEBRUARY, 11);
      System.out.println("Current Date = "+localDate);
      System.out.println("Current Month = "+localDate.getMonth());
      LocalDate day = localDate.with(TemporalAdjusters.firstDayOfMonth());
      System.out.println("First day of month = "+day);
      day = localDate.with(TemporalAdjusters.lastDayOfMonth());
      System.out.println("Last day of month = "+day);
      day = localDate.with(TemporalAdjusters.lastDayOfYear());
      System.out.println("Last day of year = "+day);
      day = localDate.with(TemporalAdjusters.firstDayOfNextMonth());
      System.out.println("First day of next month = "+day);
   }
}
Current Date = 2019-02-11
Current Month = FEBRUARY
First day of month = 2019-02-01
Last day of month = 2019-02-28
Last day of year = 2019-12-31
First day of next month = 2019-03-01
Neo4j - Index

Neo4j SQL supports Indexes on node or relationship properties to improve the performance of the application. We can create indexes on properties for all nodes, which have the same label name.
We can use these indexed columns on MATCH or WHERE or IN operator to improve the execution of CQL command.
In this chapter, we will discuss how to −
Create an Index
Delete an Index
Neo4j CQL provides "CREATE INDEX" command to create indexes on Node or Relationship properties.
Following is the syntax to create an index in Neo4j.
CREATE INDEX ON:label (node) 

Before proceeding with the example, create a node Dhawan as shown below.
CREATE (Dhawan:player{name: "shikar Dhawan", YOB: 1995, POB: "Delhi"})
Following is a sample Cypher Query to create an index on the node Dhawan in Neo4j.
CREATE INDEX ON:player(Dhawan) 
To execute the above query, carry out the following steps −
Step 1 − Open the Neo4j desktop App and start the Neo4j Server. Open the built-in browser app of Neo4j using the URL http://localhost:7474/ as shown below.
Step 2 − Copy and paste the desired query in the dollar prompt and press the play button (to execute the query) highlighted in the following screenshot.
On executing, you will get the following result.
Neo4j CQL provides a "DROP INDEX" command to drop an existing index of a Node or Relationshis property.
Following is the syntax to create an index in Neo4j.
DROP INDEX ON:label(node) 

Following is a sample Cypher Query to create an index on the node named “Dhawan” in Neo4j.
DROP INDEX ON:player(Dhawan) 
To execute the above query, carry out the following steps −
Step 1 − Open the Neo4j desktop App and start the Neo4j Server. Open the built-in browser app of Neo4j using the URL http://localhost:7474/ as shown in the following screenshot.
Step 2 − Copy and paste the desired query in the dollar prompt and press the play button (to execute the query) highlighted in the following screenshot.
On executing, you will get the following result.
 Print
 Add Notes
 Bookmark this page
How regular expression alternatives work in  Python?

In real world applications, we often use regular expressions that match any one of two or more alternatives. Also, we sometimes use a quantifier to apply to several expressions. All such goals are achieved by grouping with parentheses; and, in the use of alternatives, applying alternation with the vertical bar (|).
Alternation is useful when we need to match any one of several different alternatives. For example, the regex airways|airplane|bomber will match any text that contains airways or airplane or bomber. The same is achieved by using the regex air(ways|plane)|bomber.
If we used the regex (airways|airplane|bomber), it would match any of the three expressions. Consider the regex (air(ways|plane)|bomber), which has two captures if the first expression matches (airways or airplane as the first capture and ways or plane as the second capture), and one capture if the second expression matches (bomber). We can switch off the capturing effect by following an opening parenthesis with ?: like this:
(air(?:ways|plane)|bomber)
 This will have only one capture if it matches (airways or airplane or bomber).
The following code illustrates the points discussed above −
import re
s = 'airways aircraft airplane bomber'
result = re.findall(r'(airways|airplane|bomber)', s)
print result
result2 = re.findall(r'(air(ways|plane)|bomber)', s)
print result2
result3 = re.findall(r'(air(?:ways|plane)|bomber)', s)
print result3
This gives the output
['airways', 'airplane', 'bomber']
[('airways', 'ways'), ('airplane', 'plane'), ('bomber', '')]
['airways', 'airplane', 'bomber']
Biopython - Testing Techniques

Biopython have extensive test script to test the software under different conditions to make sure that the software is bug-free. To run the test script, download the source code of the Biopython and then run the below command −
python run_tests.py

This will run all the test scripts and gives the following output −
Python version: 2.7.12 (v2.7.12:d33e0cf91556, Jun 26 2016, 12:10:39) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] 
Operating system: posix darwin 
test_Ace ... ok 
test_Affy ... ok 
test_AlignIO ... ok 
test_AlignIO_ClustalIO ... ok 
test_AlignIO_EmbossIO ... ok 
test_AlignIO_FastaIO ... ok 
test_AlignIO_MauveIO ... ok 
test_AlignIO_PhylipIO ... ok 
test_AlignIO_convert ... ok 
........................................... 
...........................................

We can also run individual test script as specified below −
python test_AlignIO.py

As we have learned, Biopython is one of the important software in the field of bioinformatics. Being written in python (easy to learn and write), It provides extensive functionality to deal with any computation and operation in the field of bioinformatics. It also provides easy and flexible interface to almost all the popular bioinformatics software to exploit the its functionality as well.
 Print
 Add Notes
 Bookmark this page
CSS - speak

The speak property is used to specify that the text will be used for aural media. It also specifies how it will be spoken, for example normal or spelt out.
normal − Directs the user agent to speak the text using the pronunciation rules for that element and its children.
normal − Directs the user agent to speak the text using the pronunciation rules for that element and its children.
none − Prevents the element from being spoken.
none − Prevents the element from being spoken.
spell-out − Causes the user agent to speak the text one letter at a time, which is useful for speaking acronyms.
spell-out − Causes the user agent to speak the text one letter at a time, which is useful for speaking acronyms.
object.style.speak = "spell-out";

All the HTML elements 
Here is the example −
<style type = "text/css">
   <!--
      acronym {speak: spell-out;}
      *.hidden {speak: none;}
   -->
</style>

    33 Lectures 
     2.5 hours 

 Anadi Sharma

    26 Lectures 
     2.5 hours 

 Frahaan Hussain

    44 Lectures 
     4.5 hours 

 DigiFisk (Programming Is Fun)

    21 Lectures 
     2.5 hours 

 DigiFisk (Programming Is Fun)

    51 Lectures 
     7.5 hours 

 DigiFisk (Programming Is Fun)

    52 Lectures 
     4 hours 

 DigiFisk (Programming Is Fun)
 Print
 Add Notes
 Bookmark this page
Creating multiple Java objects by one type only

You can create a List of object easily. Consider the following example, where I'll create an array of Employee objects and print their details in a for loop.
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

public class Tester implements Cloneable {
   private int data;

   public int getData() {
      return data;
   }
   public void setData(int data) {
      this.data = data;
   }
   public Tester(int data){
      this.data = data;
   }

   public static void main(String[] args) {
      List<Tester> testerList = new ArrayList<Tester>();

      testerList.add(new Tester(1));
      testerList.add(new Tester(2));
      testerList.add(new Tester(3));
      testerList.add(new Tester(4));

      for(Tester tester : testerList){
         System.out.println(tester.getData());
      }
   }
}
DAX Text - REPLACE function

Replaces part of a text string, based on the number of characters you specify, with a different text string.
REPLACE (<old_text>, <start_num>, <num_chars>, <new_text>) 

old_text
The string of text that contains the characters you want to replace, or a reference to a column that contains text.
start_num
The starting position in the old_text that you want to replace with new_text.
num_chars
The number of characters that you want to replace.
new_text
The replacement text for the specified characters in old_text.
A text string.
DAX uses Unicode and therefore stores all characters as the same length.
Note − If the argument, num_chars, is a blank or is a reference to a column that evaluates to a blank, then new_text is inserted at the position start_num, without replacing any characters. This is the same behavior as in Excel.
DAX REPLACE function is similar to DAX SUBSTITUTE function.
You can use REPLACE function, if you want to replace any text of variable length that occurs at a specific position in a text string.
You can use REPLACE function, if you want to replace any text of variable length that occurs at a specific position in a text string.
You can use SUBSTITUTE function, if you want to replace specific text in a text string.
You can use SUBSTITUTE function, if you want to replace specific text in a text string.
= REPLACE([Product],1,2, [No. of Units]) 
This returns a calculated column with the first two characters of the Product in a row replaced with the value No. of Units in the same row.

    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
Program to find length of longest contiguously strictly increasing sublist after removal in Python

Suppose we have a list of numbers called nums, we have to find the maximum length of a contiguous strictly increasing sublist. We are allowed to remove at most single element from the list.
So, if the input is like nums = [35, 5, 6, 7, 8, 9, 12, 11, 26], then the output will be 7, because if we remove 12 from nums, the list will be [5, 6, 7, 8, 9, 11, 26], the length is 7, this is the longest, contiguous, strictly increasing sub-list.
To solve this, we will follow these steps −
if nums is empty, thenreturn 0
return 0
end := a list of size same as nums and fill with 1
start := a list of size same as nums and fill with 1
for i in range 1 to size of nums - 1, doif nums[i] > nums[i - 1], thenend[i] := end[i - 1] + 1
if nums[i] > nums[i - 1], thenend[i] := end[i - 1] + 1
end[i] := end[i - 1] + 1
for j in range size of nums - 2 to 0, decrease by 1, doif nums[j + 1] > nums[j], thenstart[j] := start[j + 1] + 1
if nums[j + 1] > nums[j], thenstart[j] := start[j + 1] + 1
start[j] := start[j + 1] + 1
res := maximum of the elements of end and element of start
for k in range 1 to size of nums - 2, doif nums[k - 1] < nums[k + 1], thenres := maximum of res and (end[k - 1] + start[k + 1])
if nums[k - 1] < nums[k + 1], thenres := maximum of res and (end[k - 1] + start[k + 1])
res := maximum of res and (end[k - 1] + start[k + 1])
return res
Let us see the following implementation to get better understanding −
def solve(nums):
   if not nums:
      return 0
   end = [1 for i in nums]
   start = [1 for i in nums]

   for i in range(1, len(nums)):
      if nums[i] > nums[i - 1]:
         end[i] = end[i - 1] + 1

   for j in range(len(nums) - 2, -1, -1):
      if nums[j + 1] > nums[j]:
         start[j] = start[j + 1] + 1

   res = max(max(end), max(start))

   for k in range(1, len(nums) - 1):
      if nums[k - 1] < nums[k + 1]:
         res = max(res, end[k - 1] + start[k + 1])

   return res

nums = [35, 5, 6, 7, 8, 9, 12, 11, 26]
print(solve(nums))
[35, 5, 6, 7, 8, 9, 12, 11, 26]
7
Find LCM of two numbers

In mathematics Least Common Multiple (LCM) is the smallest possible integer, that is divisible by both numbers.
LCM can be calculated by many methods, like factorization, etc. but in this algorithm, we have multiplied the bigger number with 1, 2, 3.... n until we find a number which is divisible by the second number.
Input:
Two numbers: 6 and 9
Output:
The LCM is: 18
LCMofTwo(a, b)
Input: Two numbers a and b, considered a > b.
Output: LCM of a and b.
Begin
   lcm := a
   i := 2
   while lcm mod b ≠ 0, do
      lcm := a * i
      i := i + 1
   done

   return lcm
End
#include<iostream>
using namespace std;

int findLCM(int a, int b) {    //assume a is greater than b
   int lcm = a, i = 2;

   while(lcm % b != 0) {    //try to find number which is multiple of b
      lcm = a*i;
      i++;
   }
   return lcm;    //the lcm of a and b
}

int lcmOfTwo(int a, int b) {
   int lcm;
   if(a>b)    //to send as first argument is greater than second
      lcm = findLCM(a,b);
   else
      lcm = findLCM(b,a);
   return lcm;
}

int main() {
   int a, b;
   cout << "Enter Two numbers to find LCM: "; cin >> a >> b;
   cout << "The LCM is: " << lcmOfTwo(a,b);
}
Enter Two numbers to find LCM: 6 9
The LCM is: 18
How to restart an Activity in Android?

This example demonstrates how do I restart an Activity in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity">
   <TextView
      android:id="@+id/textView"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerInParent="true"
      android:textSize="24sp"
      android:textStyle="bold"/>
   <Button
      android:id="@+id/button"
      android:layout_below="@id/textView"
      android:layout_marginTop="16sp"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerInParent="true"
      android:text="Restart Activity"/>
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
   TextView textView;
   Button button;
   Random random = new Random();
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      textView = findViewById(R.id.textView);
      button = findViewById(R.id.button);
      textView.setText("Random Number: " + random.nextInt(100));
      button.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            Intent intent = getIntent();
            finish();
            startActivity(intent);
         }
      });
   }
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
Click here to download the project code.
C library function - realloc()

The C library function void *realloc(void *ptr, size_t size) attempts to resize the memory block pointed to by ptr that was previously allocated with a call to malloc or calloc.
Following is the declaration for realloc() function.
void *realloc(void *ptr, size_t size)
ptr − This is the pointer to a memory block previously allocated with malloc, calloc or realloc to be reallocated. If this is NULL, a new block is allocated and a pointer to it is returned by the function.
ptr − This is the pointer to a memory block previously allocated with malloc, calloc or realloc to be reallocated. If this is NULL, a new block is allocated and a pointer to it is returned by the function.
size − This is the new size for the memory block, in bytes. If it is 0 and ptr points to an existing block of memory, the memory block pointed by ptr is deallocated and a NULL pointer is returned.
size − This is the new size for the memory block, in bytes. If it is 0 and ptr points to an existing block of memory, the memory block pointed by ptr is deallocated and a NULL pointer is returned.
This function returns a pointer to the newly allocated memory, or NULL if the request fails.
The following example shows the usage of realloc() function.
#include <stdio.h>
#include <stdlib.h>

int main () {
   char *str;

   /* Initial memory allocation */
   str = (char *) malloc(15);
   strcpy(str, "tutorialspoint");
   printf("String = %s,  Address = %u\n", str, str);

   /* Reallocating memory */
   str = (char *) realloc(str, 25);
   strcat(str, ".com");
   printf("String = %s,  Address = %u\n", str, str);

   free(str);
   
   return(0);
}
Let us compile and run the above program that will produce the following result −
String = tutorialspoint, Address = 355090448
String = tutorialspoint.com, Address = 355090448


    12 Lectures 
     2 hours 

 Nishant Malik

    12 Lectures 
     2.5 hours 

 Nishant Malik

    48 Lectures 
     6.5 hours 

 Asif Hussain

    12 Lectures 
     2 hours 

 Richa Maheshwari

    20 Lectures 
     3.5 hours 

 Vandana Annavaram

    44 Lectures 
     1 hours 

 Amit Diwan
 Print
 Add Notes
 Bookmark this page
Python Number shuffle() Method

Python number method shuffle() randomizes the items of a list in place.
Following is the syntax for shuffle() method −
shuffle (lst )

Note − This function is not accessible directly, so we need to import shuffle module and then we need to call this function using random static object.
lst − This could be a list or tuple.
lst − This could be a list or tuple.
This method does not return any value.
The following example shows the usage of shuffle() method.
#!/usr/bin/python
import random

list = [20, 16, 10, 5];
random.shuffle(list)
print "Reshuffled list : ",  list

random.shuffle(list)
print "Reshuffled list : ",  list
When we run above program, it produces following result −
Reshuffled list :  [16, 5, 10, 20]
Reshuffled list :  [16, 5, 20, 10]


    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
Keras - Lambda Layers

Lambda is used to transform the input data using an expression or function. For example, if Lambda with expression lambda x: x ** 2 is applied to a layer, then its input data will be squared before processing.
RepeatVector has four arguments and it is as follows −
keras.layers.Lambda(function, output_shape = None, mask = None, arguments = None)

function represent the lambda function.
function represent the lambda function.
output_shape represent the shape of the transformed input.
output_shape represent the shape of the transformed input.
mask represent the mask to be applied, if any.
mask represent the mask to be applied, if any.
arguments represent the optional argument for the lamda function as dictionary.
arguments represent the optional argument for the lamda function as dictionary.

    87 Lectures 
     11 hours 

 Abhilash Nelson

    61 Lectures 
     9 hours 

 Abhishek And Pukhraj

    57 Lectures 
     7 hours 

 Abhishek And Pukhraj

    52 Lectures 
     7 hours 

 Abhishek And Pukhraj

    52 Lectures 
     6 hours 

 Abhishek And Pukhraj

    68 Lectures 
     2 hours 

 Mike West
 Print
 Add Notes
 Bookmark this page
Sum of the alphabetical values of the characters of a string in C++

In this problem, we are given an array of string str[]. Our task is to find the score of all strings in the array. The score is defined as the product of the position of the string with the sum of the alphabetical values of the characters of the string.
Let’s take an example to understand the problem,
Input 
str[] = {“Learn”, “programming”, “tutorials”, “point” }
Explanation 
Position of “Learn” − 1 →
sum = 12 + 5 + 1 + 18 + 14 = 50. Score = 50
Position of “programming” − 2 →
sum = 16 + 18 + 15 + 7 + 18 + 1 + 13 + 13 + 9 + 14 + 7 = 131
Score = 262
Position of “tutorials” − 1 →
sum = 20 + 21 + 20 + 15 + 18 + 9 + 1 + 12 +
19 = 135
Score = 405
Position of “point” − 1 →
sum = 16 + 15 + 9 + 14 + 20 = 74
Score = 296
To solve this problem, a simple approach will be iterating over all strings of the array. For each string, store the position and find the sum of alphabetical values of the string. The multiple position and sum and return the product.
Step 1 − Iterate over the string and store the position and for each string follow step 2 and 3 −
Step 2 − Calculate the sum of the alphabets of the string.
Step 3 − print the product of position and sum.
Program to illustrate the working of the above solution,
 Live Demo
#include <iostream>
using namespace std;
int strScore(string str[], string s, int n, int index){
   int score = 0;
   for (int j = 0; j < s.length(); j++)
      score += s[j] - 'a' + 1;
   score *= index;
   return score;
}
int main(){
   string str[] = { "learn", "programming", "tutorials", "point" };
   int n = sizeof(str) / sizeof(str[0]);
   string s = str[0];
   for(int i = 0; i<n; i++){
      s = str[i];
      cout<<"The score of string ' "<<str[i]<<" ' is "<<strScore(str, s, n, i+1)<<endl;
   }
   return 0;
}
The score of string ' learn ' is 50
The score of string ' programming ' is 262
The score of string ' tutorials ' is 405
The score of string ' point ' is 296
numpy.transpose

This function permutes the dimension of the given array. It returns a view wherever possible. The function takes the following parameters.
numpy.transpose(arr, axes)

Where,
arr
The array to be transposed
axes
List of ints, corresponding to the dimensions. By default, the dimensions are reversed
import numpy as np 
a = np.arange(12).reshape(3,4) 

print 'The original array is:' 
print a  
print '\n' 

print 'The transposed array is:' 
print np.transpose(a)
Its output would be as follows −
The original array is:
[[ 0 1 2 3]
 [ 4 5 6 7]
 [ 8 9 10 11]]

The transposed array is:
[[ 0 4 8]
 [ 1 5 9]
 [ 2 6 10]
 [ 3 7 11]]


    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
Remove First Node of the Linked List using C++

Given a linked list, we need to remove its first element and return the pointer to the head of the new list.
Input : 1 -> 2 -> 3 -> 4 -> 5 -> NULL
Output : 2 -> 3 -> 4 -> 5 -> NULL

Input : 2 -> 4 -> 6 -> 8 -> 33 -> 67 -> NULL
Output : 4 -> 6 -> 8 -> 33 -> 67 -> NULL
In the given problem, we need to remove the first node of the list and move our head to the second element and return the head.
In this problem, we can move the head to the next location and then free the previous node.
#include <iostream>
using namespace std;
/* Link list node */
struct Node {
   int data;
   struct Node* next;
};
void push(struct Node** head_ref, int new_data) { // pushing the data into the list
   struct Node* new_node = new Node;
   new_node->data = new_data;
   new_node->next = (*head_ref);
   (*head_ref) = new_node;
}
int main() {
   Node* head = NULL;
   push(&head, 12);
   push(&head, 29);
   push(&head, 11);
   push(&head, 23);
   push(&head, 8);
   auto temp = head; // temp becomes head
   head = head -> next; // our head becomes the next element
   delete temp; // we delete temp i.e. the first element
   for (temp = head; temp != NULL; temp = temp->next) // printing the list
      cout << temp->data << " ";
   return 0;
}
23 11 29 12
We just need to shift the head to its next element in this program and then delete the previous element and then print the new list. The overall time complexity of the given program is O(1) which means that our program doesn’t depend on the given input, and it is the best complexity we can achieve.
In this article, we solve a problem to Remove the first node of the linked list. We also learned the C++ program for this problem and the complete approach we solved. We can write the same program in other languages such as C, java, python, and other languages. We hope you find this article helpful.
PHP - Function MySQLi Num Rows

int mysqli_num_rows ( mysqli_result $result );

It returns the number of rows in a result set
It returns the number of rows in a result set.
result
It is a result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result()
Try out the following example
<?php
   $connection_mysql = mysqli_connect("localhost","user","password","db");
   
   if (mysqli_connect_errno($connection_mysql)){
      echo "Failed to connect to MySQL: " . mysqli_connect_error();
   }
   $sql = "SELECT Lastname FROM Persons";
   
   if ($result = mysqli_query($connection_mysql,$sql)){
      $rowcount = mysqli_num_rows($result);
      
      printf("Result set has %d rows.\n",$rowcount);
      mysqli_free_result($result);
   }
   mysqli_close($connection_mysql);
?>

    45 Lectures 
     9 hours 

 Malhar Lathkar

    34 Lectures 
     4 hours 

 Syed Raza

    84 Lectures 
     5.5 hours 

 Frahaan Hussain

    17 Lectures 
     1 hours 

 Nivedita Jain

    100 Lectures 
     34 hours 

 Azaz Patel

    43 Lectures 
     5.5 hours 

 Vijay Kumar Parvatha Reddy
 Print
 Add Notes
 Bookmark this page
C library function - modf()

The C library function double modf(double x, double *integer) returns the fraction component (part after the decimal), and sets integer to the integer component.
Following is the declaration for modf() function.
double modf(double x, double *integer)
x − This is the floating point value.
x − This is the floating point value.
integer − This is the pointer to an object where the integral part is to be stored.
integer − This is the pointer to an object where the integral part is to be stored.
This function returns the fractional part of x, with the same sign.
The following example shows the usage of modf() function.
#include<stdio.h>
#include<math.h>

int main () {
   double x, fractpart, intpart;

   x = 8.123456;
   fractpart = modf(x, &intpart);

   printf("Integral part = %lf\n", intpart);
   printf("Fraction Part = %lf \n", fractpart);
   
   return(0);
}
Let us compile and run the above program that will produce the following result −
Integral part = 8.000000
Fraction Part = 0.123456 


    12 Lectures 
     2 hours 

 Nishant Malik

    12 Lectures 
     2.5 hours 

 Nishant Malik

    48 Lectures 
     6.5 hours 

 Asif Hussain

    12 Lectures 
     2 hours 

 Richa Maheshwari

    20 Lectures 
     3.5 hours 

 Vandana Annavaram

    44 Lectures 
     1 hours 

 Amit Diwan
 Print
 Add Notes
 Bookmark this page
Chef - Files & Packages

In Chef, creating configuration files and moving packages are the key components. There are multiple ways how Chef manages the same. There are multiple ways how Chef supports in dealing with the files and software packages.
Step 1 − Edit the default recipe of the cookbook.
vipin@laptop:~/chef-repo $ subl cookbooks/test_cookbook/recipes/default.rb 
include_recipe "apt" 
apt_repository "s3tools" do 
   uri "http://s3tools.org/repo/deb-all" 
   components ["stable/"] 
   key "http://s3tools.org/repo/deb-all/stable/s3tools.key" 
   action :add 
end 
package "s3cmd"
Step 2 − Edit the metadata to add dependency on the apt cookbook.
vipin@laptop:~/chef-repo $ subl cookbooks/my_cookbook/metadata.rb 
... 
depends "apt"

Step 3 − Upload the modified cookbook to the Chef server.
Step 4 − Validate that the package you are trying to install, is not yet installed.
Step 5 − Validate the default repo.
Step 6 − Run Chef-Client on the node.
Step 7 − Validate that the required package is installed.
If one needs to install a piece of software that is not available as a package for a given platform, one needs to compile it oneself. In Chef, we can do this by using the script resource.
Step 1 − Edit the default recipe.
vipin@laptop:~/chef-repo $ subl cookbooks/my_cookbook/recipes/ 
default.rb 
version = "1.3.9" 
bash "install_nginx_from_source" do 
   cwd Chef::Config['file_cache_path'] 
   code ≪-EOH 
      wget http://nginx.org/download/nginx-#{version}.tar.gz 
      tar zxf nginx-#{version}.tar.gz && 
      cd nginx-#{version} && 
      ./configure && make && make install 
   EOH 
Step 2 − Upload the modified cookbook to the Chef server.
Step 3 − Run the Chef-Client on the node.
Step 4 − Validate that the nginx is installed.
 Print
 Add Notes
 Bookmark this page