code-rag-bench/online-tutorials huggingface dataset:
What are transmission and propagation delay?

Network delay is defined as how much time will take a bit of data to travel from one node to another node.
Network delay can be divided into following ways −
Transmission delay
Propagation delay
Let us learn about both of them in detail.
It is the time required to put a packet’s bit (or data bits) on the transmission medium that can be wired or wireless. Transmission delay depends on the length of the packet and bandwidth of the network.
Transmission delay can be calculated as follows −
Transmission delay = Packet size / bandwidth
         packet
                  Destination
      Data line ( 1 bit per second)
We have 12,000 bits Ethernet packet being sent out on a 100mbps = 100 * 106 bps link. So the transmission delay can be calculated as − 12000/100*106 = 0.12 milliseconds
Or
Consider, bandwidth of data line = 1 bit per second
Length of package = 10 bit
Transmission delay = 10/1= 10 seconds.
It is the time required for bits to reach its destination from the start point. A propagation delay depends on the distance and propagation speed.
Consider a sender S and a receiver D, it is not necessary that the receiver receives data as soon as the sender has finished sending, therefore when the sender sends some data it reaches the receiver only after a certain amount of time and that time is called propagation delay.
data
   Propagation delay
Propagation delay depends on some factors which are mentioned below −
distance(d) between sender and receiver(if both of them are far apart then propagation delay is high)
distance(d) between sender and receiver(if both of them are far apart then propagation delay is high)
speed of data line(v)
speed of data line(v)
Propagation delay can be calculated as follows −
Propagation delay = distance / transmission speed
We have a copper wires and optical fibres media to travel, these media have a speed about 2/3 the speed of light (i.e. speed of light = 3 * 108 m/s so speed of media = 2 * 108 m/s). We have a single wire around 5000km i.e. 5 * 106 meters. So the propagation delay can be calculated as: 5 * 106 / 2 * 108 = 0.25 milliseconds.
Or
Consider an optical fibre network where data needs to be carried along a distance of 2.1 km.
Here the speed is not mentioned, but we know the speed of data transfer in an optical fibre is 70% of the speed of light hence
Speed= velocity of light * 70%
Speed= ( 3*10^8 )*70%= 2.1 * 10^8
i.e.
Propagation delay = distance/speed=(2.1*10^3)/(2.1*10^8)
[Note 10^3 is used to convert km to m]
Propagation delay= 10^-5 sec
Determining If an Object Is an Array in Java

In order to determine if an object is an Object is an array in Java, we use the isArray() and getClass() methods.
The isArray() method checks whether the passed argument is an array. It returns a boolean value, either true or false
Syntax - The isArray() method has the following syntax -
Array.isArray(obj)
The getClass() method method returns the runtime class of an object. The getClass() method is a part of the java.lang.Object class.
Declaration − The java.lang.Object.getClass() method is declared as follows −
public final Class getClass()
The getClass() method acts as the intermediate method which returns an runtime class of the object, which enables the terminal method, isArray() to verify it.
Let us see a program to check if an object is an array or not −
 Live Demo
public class Example {
   public static void main(String[] args) throws Exception {
      String str = "Hello";
      String atr[][]= new String[10][20];
      System.out.println("Checking for str...");
      checkArray(str);
      System.out.println("Checking for atr...");
      checkArray(atr);
   }
   public static void checkArray( Object abc) {
      boolean x = abc.getClass().isArray();
      if(x == true)
         System.out.println("The Object is an Array");
      else
         System.out.println("The Object is not an Array");
   }
}
Checking for str...
The Object is not an Array
Checking for atr...
The Object is an Array
How to reset or clear an edit box in Selenium?

We can reset or clear an edit box in Selenium with the help of clear() method.
Code Implementation with clear().
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class ResetText {
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",    "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url = "https://www.tutorialspoint.com/index.htm";
      driver.get(url);
      driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);
      //entering text in the edit box
      driver.findElement(By.cssSelector("#gsc-i- id1")).sendKeys("Selenium");
      Thread.sleep(1000);
      // resetting text from the edit box with clear()
      driver.findElement(By.cssSelector("#gsc-i-id1")).clear();
      driver.close();
   }
}
How to keep your PC awake automatically using Python? - GeeksforGeeks

03 Jan, 2021
In this article, we are going to discuss how to keep your PC awake using Python. In order to perform this task, we are going to use an external Python module. 
Here we will be using a python package PyAutoGUI (cross-platform GUI automation Python module used to programmatically control the mouse & keyboard. ) This will keep your PC awake forever till you close the program. Use the below command to install this module:
pip install pyautogui
After installing the module execute the below program:
Python3
# Import required modulesimport pyautoguiimport time  # FAILSAFE to FALSE feature is enabled by default # so that you can easily stop execution of # your pyautogui program by manually moving the # mouse to the upper left corner of the screen. # Once the mouse is in this location,# pyautogui will throw an exception and exit.pyautogui.FAILSAFE = False  # We want to run this code for infinite # time till we stop it so we use infinite loop nowwhile True:        # time.sleep(t) is used to give a break of     # specified time t seconds so that its not     # too frequent    time.sleep(15)      # This for loop is used to move the mouse     # pointer to 500 pixels in this case(5*100)    for i in range(0, 100):        pyautogui.moveTo(0, i * 5)              # This for loop is used to press keyboard keys,    # in this case the harmless key shift key is     # used. You can change it according to your     # requirement. This works with all keys.    for i in range(0, 3):        pyautogui.press('shift')
On executing the above program, you will see that after the specified time in time.sleep() the mouse pointer moves to extreme left corner (can customize this too by mentioning the co-ordinates inside pyautogui.moveTo() to your preferred x co-ordinate and y co-ordinate of the screen and starts moving down.
Python-PyAutoGUI
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
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 | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
How to compare attributes of different objects in MongoDB object array?

To compare attributes, use letalongwithindexOfArray. Let us first create a collection with documents −
> db.demo366.insertOne(
...    {
...
...       "Name" : "Chris",
...       "details" : [
...       {
...          "Id" : "John1",
...          "value" : "test"
...       },
...       {
...          "Id" : "John2",
...          "value" : 18
...       },
...       {
...          "Id" : "John3",
...          "value" : 20
...       }
...    ]}
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e57ddd92ae06a1609a00ae7")
}
Display all documents from a collection with the help of find() method −
> db.demo366.find();
This will produce the following output −
{
   "_id" : ObjectId("5e57ddd92ae06a1609a00ae7"), "Name" : "Chris", "details" : [
      { "Id" : "John1", "value" : "test" }, { "Id" : "John2", "value" : 18 },
      { "Id" : "John3", "value" : 20 }
   ]
}
Following is the query to compare attributes of different objects in the MongoDB object array −
> db.demo366.find(
...    {"$expr":{
...       "$let":{
...          "vars":{
...             "john2":{"$arrayElemAt":["$details",{"$indexOfArray":["$details.Id","John2"]}]},
...             "john3":{"$arrayElemAt":["$details",{"$indexOfArray":["$details.Id","John3"]}]}
...    },
...    "in":{"$lt":["$$john2.value","$$john3.value"]}}
... }})
This will produce the following output −
{
   "_id" : ObjectId("5e57ddd92ae06a1609a00ae7"), "Name" : "Chris", "details" : [
      { "Id" : "John1", "value" : "test" }, { "Id" : "John2", "value" : 18 },
      { "Id" : "John3", "value" : 20 }
   ] 
}
Scala Iterator slice() method with example - GeeksforGeeks

06 Jun, 2019
The slice() method belongs to the concrete value members of the class AbstractIterator. It is defined in the class Iterator. It creates a new iterator for the interval given in the slice. The first value present in the slice indicates the start of the element in the new iterator and the second value present in the slice indicates the end.
Method Definition:def slice(from: Int, until: Int): Iterator[A]Where, from implies index of the first element and until implies index of the first element following the slice.
def slice(from: Int, until: Int): Iterator[A]
Where, from implies index of the first element and until implies index of the first element following the slice.
Return Type:It returns a new iterator with elements from from until until.
Example :
// Scala program of slice()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Declaring a iterator        val iter = Iterator(1, 2, 3, 4, 5)                  // Applying slice method        val iter1 = iter.slice(1, 4)                  // Using while loop to print the         // elements of new iterator        while(iter1.hasNext)        {                          // Displays output            println(iter1.next())                  }    }}
2
3
4

Here, if the interval present in the slice is like (n, m) then the elements will be printed from the nth index till (m-1)th index. The functions hasNext and next are used here to print the elements of the new iterator.Example :
// Scala program of slice()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Declaring a iterator        val iter = Iterator(2, 4, 5, 6)                  // Applying slice method        val iter1 = iter.slice(0, 3)                  // Using while loop to print the         // elements of new iterator        while(iter1.hasNext)        {                          // Displays output            println(iter1.next())              }    }}
2
4
5

Here, the elements are printed from the index zero till the second index.
Scala
Scala-Method
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Scala Tutorial – Learn Scala with Step By Step Guide
Scala Lists
Class and Object in Scala
Break statement in Scala
Lambda Expression in Scala
Scala String replace() method with example
Operators in Scala
Scala | Arrays
Scala Constructors
How to get the first element of List in Scala
How to convert Lower case to Upper Case using C#?

To convert Lower case to Upper case, use the ToUpper() method in C#.
Let’s say your string is −
str = "david";
To convert the above lowercase string in uppercase, use the ToUpper() method −
Console.WriteLine("Converted to UpperCase : {0}", str.ToUpper());
The following is the code in C# to convert character case −
using System;
using System.Collections.Generic;
using System.Text;

namespace Demo {
   class MyApplication {
      static void Main(string[] args) {

         string str;
         str = "david";
         Console.WriteLine("LowerCase : {0}", str);

         // convert to uppercase
         Console.WriteLine("Converted to UpperCase : {0}", str.ToUpper());
         Console.ReadLine();
      }
   }
}
Super keyword in JavaScript?

The super keyword is used to access and call functions on an object's parent. The super.prop and super[expr] expressions are legible in any method definition in both classes and object literals. It is used in the "extended" class, which uses "extends" keyword.
super(arguments);
In the following example, the characteristics of a class called "Person" have been extended to another class called "Student". In both classes, we have used unique properties. Here "super" keyword is used to access a property from parent class(Person) to the extended class(Student), whereas "this" keyword is used to access extended class's own property.
<html>
<body>
<script>
   class Person {
      constructor(name, grade) {
         this.name = name;
         this.grade = grade;
      }
      goal() {
         return `${this.name} wants to become a crickter!`;
      }
      interest() {
         return `${this.name} interested in cricket !`;
      }
   }
   class Student extends Person {
      constructor(name, grade) {
         super(name, grade);
      }
      need() {
         return `${this.name} needs a cricket kit`;
      }
      career() {
         return `${super.interest()}
         ${super.goal()}
         ${this.need()}`;
      }
   }
   const student = new Student('Rishab pant', '7');
   document.write(student.career());
</script>
</body>
</html>
Rishab pant interested in cricket !
Rishab pant wants to become a crickter!
Rishab pant needs a cricket kit
How to use autocomplete attribute in HTML?

The autocomplete attribute is used with form element to set the autocomplete feature on or off. If the autocomplete feature is on, the browser will automatically show values, based on what users entered before in the field.
If the autocomplete feature is off, the browser won’t automatically show values, based on what users entered before in the field.
The following are the attribute values −
You can try to run the following code to learn how to use autocomplete attribute in HTML. To check running the below code, enter some values in the input type text and click Submit. After that fill the field again and run the code again, so that on typing a value in the field, you can see the autocomplete values. This is for autocomplete on value.
For autocomplete off value, web browser won’t complete values based on what users entered before.
<!DOCTYPE html>
<html>
   <head>
      <title> HTML autocomplete attribute</title>
   </head>
   <body>
      <form action = "" method = "get" autocomplete="on">
         Details:<br><br>
         Student Name<br><input type = "name" name = "sname"><br>
         Training week<br><input type = "week" name = "week"><br>
         <input type = "submit" value = "Submit">
      </form>
   </body>
</html>
How to plot a gradient color line in matplotlib?

To plot a gradient color line in matplotlib, we can take the following steps −
Create x, y and c data points, using numpy.
Create x, y and c data points, using numpy.
Create scatter points over the axes (closely so as to get a line), using the scatter() method with c and marker='_'.
Create scatter points over the axes (closely so as to get a line), using the scatter() method with c and marker='_'.
To display the figure, use the show() method.
To display the figure, use the show() method.
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
x = np.linspace(-1, 1, 1000)
y = np.exp(x)
c = np.tan(x)
plt.scatter(x, y, c=c, marker='_')
plt.show()
C++ Program to Demonstrate the Implementation of 4-Color Problem

This is a C++ Program to Demonstrate the Implementation of 4-Color Problem.
Begin
   Develop function issafe() to check if the current color assignment
   is safe for vertex v i.e. checks whether the edge exists or not.
   If it exists,
      then next check whether the color to be filled in the new vertex is already used by its adjacent vertices.
End
Begin
   Function graphColoringtil(bool graph[V][V], int m, int col[], int v)
   solve 4 coloring problem:
   Here,
   g[V][V] = It is a 2D array where V is the number of vertices in graph
   m = maximum number of colors that can be used.
   col[] = an color array that should have numbers from 1 to m.
   if v == V
      return true
   For c = 1 to m
      if (isSafe(v, g, col, c))
         col[v] = c
         if (graphColoringtil (g, k, col, v+1) == true)
            return true
         col[v] = 0
   return false
End

Begin
   function graphColor():
      It mainly uses graphColoringUtil() to solve the problem.
         It returns false if the m colors cannot be assigned,
            otherwise return true.
End
#include <iostream>
#include <cstdio>
#define V 5
using namespace std;
bool isSafe (int v, bool graph[V][V], int col[], int C) {
   for (int i = 0; i < V; i++)
   if (graph[v][i] && C == col[i])
   return false;
   return true;
}
bool graphColoringtil(bool g[V][V], int k, int col[], int v) {
   if (v == V) //If all vertices are assigned a color then
   return true;
   for (int c = 1; c <= k; c++) { //Consider this vertex v and try different colors
      if (isSafe(v, g, col, c)) { //Check if assignment of color c to v is fine
         col[v] = c;
         if (graphColoringtil (g, k, col, v+1) == true) //recur to assign colors to rest of the vertices
            return true;
         col[v] = 0; //If assigning color c doesn't lead to a solution then remove it
      }
   }
   return false;
}
void solution(int color[]) {
   cout<<"The assigned colors are: \n";
   for (int i = 0; i < V; i++)
      cout<<color[i];
   cout<<"\n";
}
bool graphColor(bool graph[V][V], int k) {
   int *color = new int[V];
   //initialize all colors value as 0
   for (int i = 0; i < V; i++)
   color[i] = 0;
   if (graphColoringtil(graph, k, color, 0) == false) {
      cout<<"Solution does not exist";
      return false;
   }
   solution(color);
   return true;
}
int main() {
   bool g[V][V] = {
      {0, 0, 1, 0,1},
      {1, 1, 1, 0,0},
      {1, 1, 0, 0,1},
      {0, 1, 1, 0,0}
   };
   int k= 4;
   graphColor(g, k);
   return 0;
}
The assigned colors are:
1 2 3 1 1
Angular 2 - Lifecycle Hooks

Angular 2 application goes through an entire set of processes or has a lifecycle right from its initiation to the end of the application.
The following diagram shows the entire processes in the lifecycle of the Angular 2 application.
Following is a description of each lifecycle hook.
ngOnChanges − When the value of a data bound property changes, then this method is called.
ngOnChanges − When the value of a data bound property changes, then this method is called.
ngOnInit − This is called whenever the initialization of the directive/component after Angular first displays the data-bound properties happens.
ngOnInit − This is called whenever the initialization of the directive/component after Angular first displays the data-bound properties happens.
ngDoCheck − This is for the detection and to act on changes that Angular can't or won't detect on its own.
ngDoCheck − This is for the detection and to act on changes that Angular can't or won't detect on its own.
ngAfterContentInit − This is called in response after Angular projects external content into the component's view.
ngAfterContentInit − This is called in response after Angular projects external content into the component's view.
ngAfterContentChecked − This is called in response after Angular checks the content projected into the component.
ngAfterContentChecked − This is called in response after Angular checks the content projected into the component.
ngAfterViewInit − This is called in response after Angular initializes the component's views and child views.
ngAfterViewInit − This is called in response after Angular initializes the component's views and child views.
ngAfterViewChecked − This is called in response after Angular checks the component's views and child views.
ngAfterViewChecked − This is called in response after Angular checks the component's views and child views.
ngOnDestroy − This is the cleanup phase just before Angular destroys the directive/component.
ngOnDestroy − This is the cleanup phase just before Angular destroys the directive/component.
Following is an example of implementing one lifecycle hook. In the app.component.ts file, place the following code.
import { 
   Component 
} from '@angular/core';  

@Component ({ 
   selector: 'my-app', 
   template: '<div> {{values}} </div> ' 
}) 

export class AppComponent { 
   values = ''; 
   ngOnInit() { 
      this.values = "Hello"; 
   } 
}
In the above program, we are calling the ngOnInit lifecycle hook to specifically mention that the value of the this.values parameter should be set to “Hello”.
Once you save all the code changes and refresh the browser, you will get the following output.

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    28 Lectures 
     2.5 hours 

 Anadi Sharma

    11 Lectures 
     7.5 hours 

 SHIVPRASAD KOIRALA

    16 Lectures 
     2.5 hours 

 Frahaan Hussain

    69 Lectures 
     5 hours 

 Senol Atac

    53 Lectures 
     3.5 hours 

 Senol Atac
 Print
 Add Notes
 Bookmark this page
How to plot an array in Python using Matplotlib?

To plot an array in Python, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Create two arrays, x and y, using numpy.
Set the title of the curve using title() method.
Plot x and y data points, with red color.
To display the figure, use show() method.
import numpy as np
import matplotlib.pyplot as plt

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

x = np.array([5, 4, 1, 4, 5])
y = np.sort(x)

plt.title("Line graph")
plt.plot(x, y, color="red")

plt.show()
Aptitude - Number System Online Quiz

Following quiz provides Multiple Choice Questions (MCQs) related to Number System. You will have to read all the given answers and click over the correct answer. If you are not sure about the answer then you can check the answer using Show Answer button. You can use Next Quiz button to check new set of questions in the quiz.
Q 1 - The unit digit in 7153 is?
A - 6
B - 0
C - 7
D - 1
7153 = (74)38 x 7 Now, unit digit of (74)38 = 1  Therefore, unit digit of 7153 = 1 x 7                         = 7
Q 2 - (568 x 568 x 568 + 432 x 432 x 432) / (568 x 568 - 568 x 432 + 432 + 432) = ?
A - 568
B - 1000
C - 432
D - 10
This is solved using the following formulae: (a3 + b3) = (a + b)( a2 - ab + b2) The value of (a+b) = (a3 + b3) / ( a2 - ab + b2) = (568 + 432) = 1000
Q 3 - The difference of the squares of two consecutive even integers is divisible by which of the following integers?
A - 1
B - 5
C - 4
D - 2
Let the consecutive integers(even) be 2p and (2p + 2): = (2p + 2)2 - 2p2 = (2p + 2 + 2p)(2p + 2 -2p) = 2(4p + 2) = 4 (2p + 1) Therefore, divisible by 4.
Q 4 - How many natural numbers are there between 17 and 9 which are exactly divisible by 6?
A - 13
B - 15
C - 14
D - 16
Numbers -> 18, 24, 30, ... , 90 A.P: a = 18, d = 6, l = 90 tn = a + (n-1)d 90 = 18 + (n-1)6 90 = 18 + 6n -6 n = 13
Q 5 - 6 + 15 + 24 + 33 + ... + 123 = ?
A - 903
B - 603
C - 752
D - 690
a = 6, d = 9, l = 123 Let number of terms be n 123 = a + (n - 1)d 123 = 6 + (n - 1)9 123 = 9n - 9 n = 14 Sn = n⁄2 (a + l)      = 14⁄2 (6 + 123)   = 7 x 129   = 903
Q 6 - What is the unit digit in in 7105?
A - 5
B - 7
C - 9
D - 1
 Unit digit in (7)105 = unit digit in (74)26 x 71 = unit digit in (1 x 7) = 7 Thus Unit digit in (7)105 is 7.
Q 7 - 916 x y x 3 = 214344. What is y?
A - 78
B - 68
C - 84
D - 66
 916 x y x 3 = 214344 => 2748 x y = 214344 => y = 214344 / 2748 => y = 78  
Q 8 - 106 x 106 - 94 x 94 = y. What is y?
A - 2400
B - 2000
C - 1904
D - 1906
  y = 106 x 106 - 94 x 94     = (106)2 - (94)2   = (100 + 6)2 - (100 - 6)2   Using formulae (a+b)2 = a2 + b2 + 2ab  and  (a-b)2 = a2 + b2 - 2ab   (a+b)2 - (a-b)2 = 4ab   ∴ y = 4 x 100 x 6  = 2400  
Q 9 - Which of the following is a prime number?
A - 81
B - 33
C - 93
D - 97
97. As all other numbers are divisible by 3.
Q 10 - What is the common factor in (4743 + 4343) and (4747 + 4347)
A - 47-43
B - 47+43
C - 4743 + 4343
D - 4747 + 4347
an + bn is divisible by a + b if n is an odd number. ∴ each number is divisible by (47 + 43).

    87 Lectures 
     22.5 hours 

 Programming Line
 Print
 Add Notes
 Bookmark this page
Stop Installing Tensorflow using pip for performance sake! | by Michael Phi | Towards Data Science

Stop installing Tensorflow using pip! Use conda instead. If you don’t know what conda is, it’s an open source package and environment management system that runs cross-platform. So it works on Mac, Windows, and Linux. If you aren’t already using conda, I recommend that you start as it makes managing your data science tools much more enjoyable.
Here are two pretty big reasons why you should install Tensorflow using conda instead of pip.
The conda Tensorflow packages leverage the Intel Math Kernel Library for Deep Neural Networks or the MKL-DNN starting with version 1.9.0. This library gives a huge performance boost. Here is a chart to prove it!
As you can see, the performance of the conda installation can give over 8X the speed boost compared to the pip installation. That is great for people who still frequently use their CPU for training and inferencing. As a Machine Learning Engineer, I use my CPU to run a test train on my code before pushing it to a GPU enabled machine. This increase in speed will help me iterate faster. I also do a lot of inference on a CPU when I can, so this will help my models performance.
Not only does the MKL library speed up your Tensorflow packages, it also speeds up other widely used libraries like NumPy, NumpyExr, SciPy, and Scikit-Learn! See how you can get that set up from links below.
The conda install will automatically install the CUDA and CuDNN libraries needed for GPU support. The pip install will require you to do that manually. Everybody likes a one step process, especially when it comes to downloading libraries.
So I hope those two reasons are good enough for you to switch over to using conda. If you’re convinced here are the steps to get started.
pip uninstall tensorflow
Install Anaconda or Miniconda if you haven’t already. Miniconda is just installing conda and it’s dependencies while Anaconda will pre-install a lot of packages for you. I prefer Miniconda to get started. After conda is installed try this.
conda install tensorflow
Replace tensorflow with tensorflow-gpu if you want the GPU enabled version.
Besides being faster and simpler to use for Tensorflow, conda provides other sets of tools that makes it so much easier to integrate into your workflow. One of my favorites is their virtual environment features. You can read more about conda and tensorflow here. And more on the MKL optimization here. Hope this helps and as always, thanks for reading!
I write many more posts like this! if you enjoy this, check out my other content at micahelphi.com
✍🏽 Want more Content? Check out my blog at https://www.michaelphi.com
📺 Like to watch project-based videos? Check out my Youtube!
🥇 Stay up to date on articles and videos by signing up for my email newsletter!
Python - Normal Distribution in Statistics - GeeksforGeeks

10 Jan, 2020
scipy.stats.norm() is a normal continuous random variable. It is inherited from the of generic methods as an instance of the rv_continuous class. It completes the methods with details specific for this particular distribution.
Parameters :
q : lower and upper tail probabilityx : quantilesloc : [optional]location parameter. Default = 0scale : [optional]scale parameter. Default = 1size : [tuple of ints, optional] shape or random variates.moments : [optional] composed of letters [‘mvsk’]; ‘m’ = mean, ‘v’ = variance, ‘s’ = Fisher’s skew and ‘k’ = Fisher’s kurtosis. (default = ‘mv’).
Results : normal continuous random variable
Code #1 : Creating normal continuous random variable
# importing library  from scipy.stats import norm    numargs = norm.numargs a, b = 4.32, 3.18rv = norm(a, b)     print ("RV : \n", rv)  
Output :
RV : 
 scipy.stats._distn_infrastructure.rv_frozen object at 0x000002A9D81635C8

Code #2 : normal continuous variates and probability distribution
import numpy as np quantile = np.arange (0.01, 1, 0.1)   # Random Variates R = norm.rvs(a, b) print ("Random Variates : \n", R)   # PDF R = norm.pdf(a, b, quantile) print ("\nProbability Distribution : \n", R) 
Output :
Random Variates : 
 8.848528530091645

Probability Distribution : 
 [0.00000000e+00 1.72515030e-23 7.57695185e-07 1.48928058e-03
 2.03862091e-02 6.43213365e-02 1.14069546e-01 1.54822160e-01
 1.82936660e-01 2.00024445e-01]
 

Code #3 : Graphical Representation.
import numpy as np import matplotlib.pyplot as plt      distribution = np.linspace(0, np.minimum(rv.dist.b, 3)) print("Distribution : \n", distribution)      plot = plt.plot(distribution, rv.pdf(distribution)) 
Output :
Distribution : 
 [0.         0.04081633 0.08163265 0.12244898 0.16326531 0.20408163
 0.24489796 0.28571429 0.32653061 0.36734694 0.40816327 0.44897959
 0.48979592 0.53061224 0.57142857 0.6122449  0.65306122 0.69387755
 0.73469388 0.7755102  0.81632653 0.85714286 0.89795918 0.93877551
 0.97959184 1.02040816 1.06122449 1.10204082 1.14285714 1.18367347
 1.2244898  1.26530612 1.30612245 1.34693878 1.3877551  1.42857143
 1.46938776 1.51020408 1.55102041 1.59183673 1.63265306 1.67346939
 1.71428571 1.75510204 1.79591837 1.83673469 1.87755102 1.91836735
 1.95918367 2.        ]
 
Code #4 : Varying Positional Arguments
import matplotlib.pyplot as plt import numpy as np      x = np.linspace(0, 5, 100)      # Varying positional arguments y1 = norm .pdf(x, 1, 3, 5) y2 = norm .pdf(x, 1, 4, 4) plt.plot(x, y1, "*", x, y2, "r--") 
Output :
Python scipy-stats-functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Enumerate() in Python
Read a file line by line in Python
Defaultdict in Python
Different ways to create Pandas Dataframe
sum() function in Python
Iterate over a list in Python
Deque in Python
How to Install PIP on Windows ?
Python String | replace()
How to add CSS properties to an element dynamically using jQuery ? - GeeksforGeeks

24 Mar, 2021
In this article, we will see how to add some CSS properties dynamically using jQuery. To add CSS properties dynamically, we use css() method. The css() method is used to change style property of the selected element. 
The css() method can be used in different ways. This method can also be used to check the present value of the property for the selected element:
Syntax:
$(selector).css(property)
Here we have created two elements inside body tag i.e. <h1> and <h3> elements. We apply CSS property on <body> tag and <h1> tag using css() method dynamically.
Example:
HTML
<!DOCTYpe html><html>  <head>    <title>        How to add CSS properties to an        element dynamically using jQuery?    </title>      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">    </script>      <script>        $(document).ready(function () {            $("body").css("text-align", "center");            $("h1").css("color", "green");        });    </script></head>  <body>    <h1>GeeksforGeeks</h1>      <h3>        How to add CSS properties to an element        <br>dynamically using jQuery?    </h3></body>  </html>
Output:
HTML-Questions
HTML-Tags
jQuery-Methods
jQuery-Questions
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to prevent Body from scrolling when a modal is opened using jQuery ?
jQuery | ajax() Method
Difference Between JavaScript and jQuery
How to get the value in an input text box using jQuery ?
jQuery | parent() & parents() with Examples
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
What is the difference between break and continue statements in C#?

The break statement terminates the loop and transfers execution to the statement immediately following the loop.
The continue statement causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.
When the break statement is encountered inside a loop, the loop is immediately terminated and program control resumes at the next statement following the loop.
The continue statement in C# works somewhat like the break statement. Instead of forcing termination, however, continue forces the next iteration of the loop to take place, skipping any code in between.
The following is the complete code to use continue statement in a while loop −
using System;
namespace Demo {
   class Program {
      static void Main(string[] args) {

         /* local variable definition */
         int a = 10;

         /* loop execution */
         while (a > 20) {
            if (a == 15) {
               /* skip the iteration */
               a = a + 1;
               continue;
            }
            Console.WriteLine("value of a: {0}", a);
            a++;
         }
         Console.ReadLine();
      }
   }
}
The following is an example of break statement −
using System;
namespace Demo {
   class Program {
      static void Main(string[] args) {
         /* local variable definition */
         int a = 10;

         /* while loop execution */
         while (a < 20) {
            Console.WriteLine("value of a: {0}", a);
            a++;

            if (a > 15) {
               /* terminate the loop using break statement */
               break;
            }
         }
         Console.ReadLine();
      }
   }
}
Explain typecasting in Javascript?

Converting a data type into another is known as type casting. Sometimes there is a need to convert the data type of one value to another. Under some circumstances JavaScript will perform automatic type conversion.
Automatic Type Conversion
JavaScript expects a boolean in a conditional expression. So JavaScript will temporarily convert the value in parentheses to a boolean to evaluate the if expression −
if (val) {
   console.log( 'yes, val exists' );
}
The following values evaluate to false: 0, -0, '' (empty string), NaN, undefined, and null. All other values evaluate to true, even empty arrays and objects.
Type conversion is also performed when comparing values using the equal (==) and not equal (!=) operators. So when you compare the number 125 with a string '125' using the equals (==) operator, the expression evaluates to true −
console.log( 125 == '125' );
Type conversion is not performed when using the identical (===) and not identical (!==) operators.
parseInt and parseFloat
The parseInt function converts its first argument to a string, parses that string, then returns an integer or NaN.
The parseFloat() function parses an argument (converting it to a string first if needed) and returns a floating point number.
toString
The toString() method returns a string representing the object, ie, it tries to convert object to string.
let a = 1.015
console.log(a)
console.log(typeof a)
console.log(a.toString())
console.log(typeof a.toString())
1.015
number
1.015
string
Print Matrix in spiral way


This algorithm is used to print the array elements in a spiral way. At first starting from the first row, print the whole content and then follow the last column to print, then the last row and so on, thus it prints the elements in spiral fashion. 
The time complexity of this algorithm is O(MN), M is the number of rows and N is the number of columns.
Input:
The matrix:
 1   2   3   4   5   6
 7   8   9  10  11  12
13  14  15  16  17  18

Output:
Contents of an array as the spiral form
1 2 3 4 5 6 12 18 17 16 15 14 13 7 8 9 10 11 15 16
dispSpiral(mat, m, n)
Input: The matrix mat, row and column m and n.
Output: Print the elements of the matrix in a spiral way.
Begin
   currRow := 0 and currCol := 0
   while currRow and currCol are in the matrix range, do
      for i in range currCol and n-1, do
         display mat[currRow, i]
      done

      increase currRow by 1
      for i in range currRow and m-1, do
         display mat[i, n-1]
      done

      decrease n by 1
      if currRow < m, then
         for i := n-1 down to currCol, do
            display mat[m-1, i]
         done
         decrease m by 1
      if currCol < n, then
         for i := m-1 down to currRow, do
            display mat[i, currCol]
         done
         increase currCol by 1
   done
End
#include <iostream>
#define ROW 3
#define COL 6
using namespace std;

int array[ROW][COL] = {
   {1, 2, 3, 4, 5, 6},
   {7, 8, 9, 10, 11, 12},
   {13, 14, 15, 16, 17, 18}
};

void dispSpiral(int m, int n) {
   int i, currRow = 0, currCol = 0;
   while (currRow < ROW && currCol <COL) {
      for (i = currCol; i < n; i++) {          //print the first row normally
         cout << array[currRow][i]<<" ";
      }
      currRow++;           //point to next row

      for (i = currRow; i < m; ++i) {       //Print the last column
         cout << array[i][n-1]<<" ";
      }

      n--;               //set the n-1th column is current last column

      if ( currRow< m) {         //when currRow is in the range, print the last row
         for (i = n-1; i >= currCol; --i) {
            cout << array[m-1][i]<<" ";
         }
         m--; //decrease the row range
      }

      if (currCol <n) {      //when currCol is in the range, print the fist column
         for (i = m-1; i >= currRow; --i) {
            cout << array[i][currCol]<<" ";
         }
         currCol++;
      }
   }
}

int main() {
   dispSpiral(ROW, COL);
}
1 2 3 4 5 6 12 18 17 16 15 14 13 7 8 9 10 11 15 16
Selection Sort

In the selection sort technique, the list is divided into two parts. In one part all elements are sorted and in another part the items are unsorted. At first, we take the maximum or minimum data from the array. After getting the data (say minimum) we place it at the beginning of the list by replacing the data of first place with the minimum data. After performing the array is getting smaller. Thus this sorting technique is done.
Time Complexity: O(n^2)
Space Complexity: O(1)
Input:
The unsorted list: 5 9 7 23 78 20
Output:
Array before Sorting: 5 9 7 23 78 20
Array after Sorting: 5 7 9 20 23 78
selectionSort(array, size)
Input − An array of data, and the total number in the array
Output − The sorted Array
Begin
   for i := 0 to size-2 do //find minimum from ith location to size
      iMin := i;
      for j:= i+1 to size – 1 do
         if array[j] < array[iMin] then
            iMin := j
      done
      swap array[i] with array[iMin].
   done
End
#include<iostream>
using namespace std;

void swapping(int &a, int &b) { //swap the content of a and b
   int temp;
   temp = a;
   a = b;
   b = temp;
}

void display(int *array, int size) {
   for(int i = 0; i<size; i++)
      cout << array[i] << " ";
   cout << endl;
}

void selectionSort(int *array, int size) {
   int i, j, imin;

   for(i = 0; i<size-1; i++) {
      imin = i;//get index of minimum data
      for(j = i+1; j<size; j++)
         if(array[j] < array[imin])
            imin = j;
      //placing in correct position
      swap(array[i], array[imin]);
   }
}

int main() {
   int n;
   cout << "Enter the number of elements: ";
   cin >> n;
   int arr[n]; //create an array with given number of elements
   cout << "Enter elements:" << endl;

   for(int i = 0; i<n; i++) {
      cin >> arr[i];
   }

   cout << "Array before Sorting: ";
   display(arr, n);
   selectionSort(arr, n);
   cout << "Array after Sorting: ";
   display(arr, n);
}
Enter the number of elements: 6
Enter elements:
5 9 7 23 78 20      
Array before Sorting: 5 9 7 23 78 20
Array after Sorting: 5 7 9 20 23 78
Append data to an empty Pandas DataFrame - GeeksforGeeks

17 Aug, 2020
Let us see how to append data to an empty Pandas DataFrame.
Creating the Data Frame and assigning the columns to it
# importing the moduleimport pandas as pd  # creating the DataFrame of int and floata = [[1, 1.2], [2, 1.4], [3, 1.5], [4, 1.8]]t = pd.DataFrame(a, columns =["A", "B"])  # displaying the DataFrameprint(t)print(t.dtypes)
Output :
On appending the float values to the int valued data type column  the resultant data frame column type-caste into float in order to accommodate the float value
If we use the argument ignore_index = True  => that the index values will remain continuous instead of starting again from 0, be default it’s value is False
# Appending a Data Frame of float and ints = pd.DataFrame([[1.3, 9]], columns = ["A", "B"])display(s)  # makes index continuoust = t.append(s, ignore_index = True)  display(t)  # Resultant data frame is of type float and floatdisplay(t.dtypes)  
Output :
When we appended the boolean format data into the data frame that was already of the type of float columns then it will change the values accordingly in order to accommodate the boolean values in the float data type domain only.
# Appending a Data Frame of bool and boolu = pd.DataFrame([[True, False]], columns =["A", "B"])display(u)display(u.dtypes)  t = t.append(u)display(t)display(t.dtypes)  # type casted into float and float
Output :
On appending the data of different data types to the previously formed Data Frame then the resultant Data Frame columns type will always be of the wider spectrum data type.
# Appending a Data Frame of object and objectx = pd.DataFrame([["1.3", "9.2"]], columns = ["A", "B"])display(x)display(x.dtypes)  t = t.append(x)display(t)display(t.dtypes)
Output :
If we aim to create a data frame through a for loop then the most efficient way of doing that is as follows :
# Creating a DataFrame using a for loop in efficient mannery = pd.concat([pd.DataFrame([[i, i * 10]], columns = ["A", "B"])               for i in range(7, 10)], ignore_index = True)  # makes index continuoust = t.append(y, ignore_index = True)  display(t)display(t.dtypes)
Output
If we attempt to add different column than already in the data frame then results are as follows :
# Appending Different Columnsz = pd.DataFrame([["1.3", "9.2"]], columns = ["E", "F"])t = t.append(z)print(t)print(t.dtypes)print()
Output :
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
Python – Resolve Float Keys in Dictionary

01 Aug, 2020
Given a dictionary with variety of floating-point keys, find a way to access them as single value.
Input : test_dict = {“010.78” : “Gfg”, “9.0” : “is”, “10” : “Best”}, K = “09.0”Output : “is”Explanation : 09.0 -> 9.0 whose value is “is”.
Input : test_dict = {“010.78” : “Gfg”, “9.0” : “is”, “10” : “Best”}, K = “10.0”Output : “Best”Explanation : 10.0 -> 10 whose value is “Best”.
Method #1 : Using float() + loop
This is one of the ways to solve this problem. In this, strategy used is to convert key into float value using float(), it resolves to single value, and perform check of input string after conversion to float(), both resolve to common float value.
Python3
# Python3 code to demonstrate working of # Resolve Float Keys in Dictionary# Using float() + loop()  # initializing dictionarytest_dict = {"010.78" : "Gfg", "9.0" : "is", "10" : "Best"}  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # initializing K K = "10.78"  # performing resolutionres = dict()for key in test_dict:    res[float(key)] = test_dict[key]  # converting compare value to float convK = float(K)  # performing value access res = res[convK]  # printing result print("Value of resolved float Key : " + str(res)) 
The original dictionary is : {'010.78': 'Gfg', '9.0': 'is', '10': 'Best'}
Value of resolved float Key : Gfg

Method #2 : Using dictionary comprehension + float()
This computes in similar way as above method. The difference being for conversion one liner dictionary comprehension is employed.
Python3
# Python3 code to demonstrate working of # Resolve Float Keys in Dictionary# Using dictionary comprehension + float()  # initializing dictionarytest_dict = {"010.78" : "Gfg", "9.0" : "is", "10" : "Best"}  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # initializing K K = "10.78"  # performing resolution using dictionary comprehensionres = {float(key) : test_dict[key] for key in test_dict}  # converting compare value to float convK = float(K)  # performing value access res = res[convK]  # printing result print("Value of resolved float Key : " + str(res)) 
The original dictionary is : {'010.78': 'Gfg', '9.0': 'is', '10': 'Best'}
Value of resolved float Key : Gfg

Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Get duplicate tuples from list

21 Nov, 2019
Sometimes, while working with records, we can have a problem of extracting those records which occur more than once. This kind of application can occur in web development domain. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using list comprehension + set() + count()Initial approach that can be applied is that we can iterate on each tuple and check it’s count in list using count(), if greater than one, we can add to list. To remove multiple additions, we can convert the result to set using set().
# Python3 code to demonstrate working of# Get duplicate tuples from list# Using list comprehension + set() + count()  # initialize listtest_list = [(3, 4), (4, 5), (3, 4),              (3, 4), (4, 5), (6, 7)]  # printing original list print("The original list : " + str(test_list))  # Get duplicate tuples from list# Using list comprehension + set() + count()res = list(set([ele for ele in test_list            if test_list.count(ele) > 1]))  # printing resultprint("All the duplicates from list are : " + str(res))
The original list : [(3, 4), (4, 5), (3, 4), (3, 4), (4, 5), (6, 7)]
All the duplicates from list are : [(4, 5), (3, 4)]

 
Method #2 : Using Counter() + items() + list comprehensionThe combination of above functions can also be used to perform this particular task. In this, we just get the count of each occurrence of element using Counter() as dictionary and then extract all those whose value is above 1.
# Python3 code to demonstrate working of# Get duplicate tuples from list# Using list comprehension + Counter() + items()from collections import Counter  # initialize listtest_list = [(3, 4), (4, 5), (3, 4),              (3, 4), (4, 5), (6, 7)]  # printing original list print("The original list : " + str(test_list))  # Get duplicate tuples from list# Using list comprehension + Counter() + items()res = [ele for ele, count in Counter(test_list).items()                                          if count > 1]  # printing resultprint("All the duplicates from list are : " + str(res))
The original list : [(3, 4), (4, 5), (3, 4), (3, 4), (4, 5), (6, 7)]
All the duplicates from list are : [(4, 5), (3, 4)]

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to iterate through Excel rows in Python?
Rotate axis tick labels in Seaborn and Matplotlib
Deque in Python
Queue in Python
Defaultdict in Python
Defaultdict in Python
Python program to add two numbers
Python | Get dictionary keys as a list
Python Program for Fibonacci numbers
Python Program for factorial of a number