code-rag-bench/online-tutorials huggingface dataset:
PHP Using namespaces

Class, function or constant in a namespace can be used in following ways:
Using a class in current namespace
specifying a namespace relative to current namespace
giving a fully qualified name of namespace
In this example a namespace is loaded from test1.php. Function or class name referred to without namespace accesses those in current namespace
#test1.php
<?php
namespace myspace\space1;
const MAX = 100;
function hello() {echo "hello in space1\n";}
class myclass{
   static function hellomethod() {echo "hello in space1\n";}
}
?>
Use this file in following code
 Live Demo
<?php
namespace myspace;
include 'test1.php';
const MAX = 200;
function hello() {echo "hello in myspace\n";}
class myclass{
   static function hellomethod() {echo "hello in myspace\n";}
}
hello();
myclass::hellomethod();
echo MAX;
?>
hello in myspace
hello in myspace
200
In following example function and class is accesed with relative namespace
<?php
namespace myspace;
include 'test1.php';
const MAX = 200;
function hello() {echo "hello in myspace\n";}
class myclass{
   static function hellomethod() {echo "hello in myspace\n";}
}
space1\hello();
space1\myclass::hellomethod();
echo space1\MAX;
?>
Above code shows following output
hello in space1
hello in space1
100
Functions and classes are given absolute namespace name
<?php
namespace myspace;
include 'test1.php';
const MAX = 200;
function hello() {echo "hello in myspace\n";}
class myclass{
   static function hellomethod() {echo "hello in myspace\n";}
}
\myspace\hello();
\myspace\space1\hello();
\myspace\myclass::hellomethod();
\myspace\space1\myclass::hellomethod();
echo \myspace\MAX . "\n";
echo \myspace\space1\MAX;
?>
Above code shows following output
hello in myspace
hello in space1
hello in myspace
hello in space1
200
100
Compare Pandas Dataframes using DataComPy - GeeksforGeeks

04 May, 2020
It’s well known that Python is a multi-paradigm, general-purpose language that is widely used for data analytics because of its extensive library support and an active community. The most commonly known methods to compare two Pandas dataframes using python are:
Using difflib
Using fuzzywuzzy
Regex Match
These methods are widely in use by seasoned and new developers but what if we require a report to find all of the matching/mismatching columns & rows? Here’s when the DataComPy library comes into the picture.
DataComPy is a Pandas library open-sourced by capitalone. It was started with an aim to replace PROC COMPARE for Pandas data frames. It takes two dataframes as input and gives us a human-readable report containing statistics that lets us know the similarities and dissimilarities between the two dataframes.
Install via pip3:
pip3 install datacompy

Example:
from io import StringIOimport pandas as pdimport datacompy         data1 = """employee_id, name1, rajiv kapoor2, rahul agarwal3, alice johnson"""   data2 = """employee_id, name1, rajiv khanna2, rahul aggarwal3, alice tyson"""   df1 = pd.read_csv(StringIO(data1))df2 = pd.read_csv(StringIO(data2))   compare = datacompy.Compare(    df1,    df2,          # You can also specify a list    # of columns    join_columns = 'employee_id',           # Optional, defaults to 0    abs_tol = 0,          # Optional, defaults to 0    rel_tol = 0,           # Optional, defaults to 'df1'    df1_name = 'Original',          # Optional, defaults to 'df2'    df2_name = 'New'     )  # if ignore_exra_columns=True, # the function won't return False# in case of non-overlapping # column namescompare.matches(ignore_extra_columns = False)      # This method prints out a human-readable # report summarizing and sampling # differencesprint(compare.report())
Output:
Explanation:
In the above example, we are joining the two data frames on a matching column. We can also pass: on_index = True instead of “join_columns” to join on the index instead.
Compare.matches() is a Boolean function. It returns True if there’s a match, else it returns False.
DataComPy by default returns True only if there’s a 100% match. We can tweak this by setting the values of abs_tol & rel_tol to non-zero, which empowers us to specify an amount of deviation between numeric values that can be tolerated. They stand for absolute tolerance and relative tolerance respectively.
We can see from the above example that DataComPy is a really powerful library & it is extremely helpful in cases when we have to generate a comparison report of 2 dataframes.
Python pandas-dataFrame
Python
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Convert integer to string in Python
Convert string to integer in Python
Python infinity
How to set input type date in dd-mm-yyyy format using HTML ?
Matplotlib.pyplot.title() in Python
Java Program for Gnome Sort

Gnome Sort works with one lement at a time and gets it to the actual position. Let us see an example to implement Gnome Sort −
 Live Demo
import java.util.Arrays;
public class Demo{
   static void gnome_sort(int my_arr[], int n){
      int index = 0;
      while (index < n){
         if (index == 0)
            index++;
         if (my_arr[index] >= my_arr[index - 1])
            index++;
         else{
            int temp = 0;
            temp = my_arr[index];
            my_arr[index] = my_arr[index - 1];
            my_arr[index - 1] = temp;
            index--;
         }
      }
      return;
   }
   public static void main(String[] args){
      int my_arr[] = { 34, 67, 89, 11, 0 , -21 };
      gnome_sort(my_arr, my_arr.length);
      System.out.println("The array after perfroming gnome sort on it is ");
      System.out.println(Arrays.toString(my_arr));
   }
}
The array after perfroming gnome sort on it is
[-21, 0, 11, 34, 67, 89]
A class named Demo contains a static function named ‘gnome_sort’. Here, a variable ‘index’ is assigned to 0. If that index value is less than the length of the array, the index value is checked for 0. If it is 0, it is incremented by 1. Otherwise, if the value at a specific index is greater than the value at array’s ‘index-1’, a variable named ‘temp’ is assigned 0 and the elements are swapped. The ‘index’ value is decremented.
In the main function, an array is defined with certain values and the ‘gnome_sort’ function is called on this array and the length of the array. The output is printed on the console.
C library function - wcstombs()

The C library function size_t wcstombs(char *str, const wchar_t *pwcs, size_t n) converts the wide-character string pwcs to a multibyte string starting at str. At most n bytes are written to str.
Following is the declaration for wcstombs() function.
size_t wcstombs(char *str, const wchar_t *pwcs, size_t n)
str − This is the pointer to an array of char elements at least n bytes long.
str − This is the pointer to an array of char elements at least n bytes long.
pwcs − This is wide-character string to be converted.
pwcs − This is wide-character string to be converted.
n − This is the maximum number of bytes to be written to str.
n − This is the maximum number of bytes to be written to str.
This function returns the number of bytes (not characters) converted and written to str, excluding the ending null-character. If an invalid multibyte character is encountered, -1 value is returned.
The following example shows the usage of wcstombs() function.
#include <stdio.h>
#include <stdlib.h>

#define BUFFER_SIZE 50

int main () {
   size_t ret;
   char *MB = (char *)malloc( BUFFER_SIZE );
   wchar_t *WC = L"http://www.tutorialspoint.com";

   /* converting wide-character string */
   ret = wcstombs(MB, WC, BUFFER_SIZE);
   
   printf("Characters converted = %u\n", ret);
   printf("Multibyte character = %s\n\n", MB);
   
   return(0);
}
Let us compile and run the above program that will produce the following result −
Characters converted = 29
Multibyte character = http://www.tutorialspoint.com


    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
C++ Program for Coefficient of variation

We are given with an array of float values of size n and the task is to find the coefficient of variation and display the result.
What is the coefficient of variation?
In statistic measure, coefficient of variation is used to find the range of variability through the data given. In terms of finance, coefficient of variation is used to find the amount of risk involved with respect to the amount invested. If the ratio between standard deviation and mean is low then the risk involved in the investment is also low. Coefficient of variation is the ratio between standard deviation and mean and it is given by −
Coefficient of variation = Standard Deviation / Mean 
Input-: array[] = { 10.0, 21, 23, 90.0, 10.5, 32.56, 24, 45, 70.0 }
Output-: coefficient of variation is : 0.75772

Input-: array[] = { 15.0, 36.0, 53.67, 25.45, 67.8, 56, 78.09}
Output-: coefficient of variation is : 0.48177
Approach used in the given program is as follows −
Input the array containing float values
Calculate the value of mean and standard deviation on the given array
Calculate the value of coefficient of variation by dividing the value of standard deviation with mean
Display the result as coefficient of variation 
Start
Step 1-> declare function to calculate the value of mean
   float cal_mean(float arr[], int size)
   Declare float sum = 0
   Loop For i = 0 and i < size and i++
      Set sum = sum + arr[i]
   End
   return sum / size
Step 2-> declare function to calculate the value of standard deviation
   float StandardDeviation(float arr[], int size)
   Declare float sum = 0
   Loop For i = 0 and i < size and i++
      Set sum = sum + (arr[i] - cal_mean(arr, size)) * (arr[i] -
   End
   Call cal_mean(arr, size))
   return sqrt(sum / (size - 1))
Step 3-> Declare function to calculate coefficient of variation
   float CoefficientOfVariation(float arr[], int size)
   return StandardDeviation(arr, size) / cal_mean(arr, size)
Step 4-> In main()
   Declare an array of float arr[] = { 10.0, 21, 23, 90.0, 10.5, 32.56, 24, 45, 70.0}
   Calculate the size of array as int size = sizeof(arr) / sizeof(arr[0])
   Call function as CoefficientOfVariation(arr, size)
Stop
 Live Demo
#include <bits/stdc++.h>
using namespace std;
// function to calculate the mean.
float cal_mean(float arr[], int size) {
   float sum = 0;
   for (int i = 0; i < size; i++)
   sum = sum + arr[i];
   return sum / size;
}
//function to calculate the standard deviation
float StandardDeviation(float arr[], int size) {
   float sum = 0;
   for (int i = 0; i < size; i++)
   sum = sum + (arr[i] - cal_mean(arr, size)) * (arr[i] - cal_mean(arr, size));
   return sqrt(sum / (size - 1));
}
// function to calculate the coefficient of variation.
float CoefficientOfVariation(float arr[], int size) {
   return StandardDeviation(arr, size) / cal_mean(arr, size);
}
int main() {
   float arr[] = { 10.0, 21, 23, 90.0, 10.5, 32.56, 24, 45, 70.0};
   int size = sizeof(arr) / sizeof(arr[0]);
   cout<<"coefficient of variation is : "<<CoefficientOfVariation(arr, size);
   return 0;
}
coefficient of variation is : 0.75772
GATE | GATE-CS-2015 (Set 1) | Question 45 - GeeksforGeeks

28 Jun, 2021
What is the output of the following C code? Assume that the address of x is 2000 (in decimal) and an integer requires four bytes of memory.
#include <stdio.h>int main(){    unsigned int x[4][3] = {{1, 2, 3}, {4, 5, 6},                            {7, 8, 9}, {10, 11, 12}};   printf("%u, %u, %u", x+3, *(x+3), *(x+2)+3);}
(A) 2036, 2036, 2036(B) 2012, 4, 2204(C) 2036, 10, 10(D) 2012, 4, 6Answer: (A)Explanation:
x = 2000

Since x is considered as a pointer to an 
array of 3 integers and an integer takes 4
bytes, value of x + 3 = 2000 + 3*3*4 = 2036

The expression, *(x + 3) also prints same 
address as x is 2D array.


The expression *(x + 2) + 3 = 2000 + 2*3*4 + 3*4
                            = 2036

Quiz of this Question
GATE-CS-2015 (Set 1)
GATE-GATE-CS-2015 (Set 1)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE-CS-2006 | Question 47
GATE | GATE MOCK 2017 | Question 24
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2015 (Set 1) | Question 53
GATE | GATE CS 2010 | Question 28
GATE | GATE-IT-2004 | Question 13
MySQL query to divide column by 100?

Let us first create a table −
mysql> create table DemoTable
   (
   Number float
   );
Query OK, 0 rows affected (0.47 sec)
Insert records in the table using insert command −
mysql> insert into DemoTable values(1000);
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values(1);
Query OK, 1 row affected (0.27 sec)
mysql> insert into DemoTable values(10);
Query OK, 1 row affected (0.30 sec)
mysql> insert into DemoTable values(100);
Query OK, 1 row affected (0.24 sec)
mysql> insert into DemoTable values(390);
Query OK, 1 row affected (0.09 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output−
+--------+
| Number |
+--------+
| 1000   |
| 1      |
| 10     |
| 100    |
| 390    |
+--------+
5 rows in set (0.00 sec)
Following is the query to divide column by 100−
mysql> update DemoTable set Number=Number/100;
Query OK, 5 rows affected (0.09 sec)
Rows matched: 5 Changed: 5 Warnings: 0
Let us display table records once again −
mysql> select * from DemoTable;
This will produce the following output −
+--------+
| Number |
+--------+
| 10     |
| 0.01   |
| 0.1    |
| 1      |
| 3.9    |
+--------+
5 rows in set (0.00 sec)
How to create Frame by Frame Animation using CSS and JavaScript ? - GeeksforGeeks

28 Jul, 2021
Frame by frame animation is a technique where a set of images are shown, one by one in a particular order, maintaining fixed time interval gaps between two consecutive images, to make an illusion of motion to the eyes. Now, in a more technical way, we can say that frame-by-frame animation is a technique where different frames appear, one after another, maintaining fixed time interval gaps in different frames to make the illusion of movement.
We can use the JavaScript setInterval() method to create a frame-by-frame animation. The setInterval() method is used to repeat a particular function at every given time interval, so it can be used in the frame-by-frame animation on the set of frames so that they appear to have fixed time interval gaps in between them.
Syntax:
setInterval(function, milliseconds);
Parameters:
function: The function that has to be executed.
milliseconds: It indicates the length of the time interval in milliseconds between each frame.
Example:
HTML
<!DOCTYPE html><html>  <head>    <style>        img {            height: 250px;            width: 250px;        }          .center {            position: absolute;            top: 50%;            left: 50%;            transform: translate(-50%, -50%);            width: 250px;            height: 250px;            border: 3px solid #73AD21;            padding: 2px;        }    </style></head>  <body>    <script>        var images = new Array()        images = ["https://media.geeksforgeeks.org/wp-content/uploads/20210721215006/frame1.PNG","https://media.geeksforgeeks.org/wp-content/uploads/20210721215014/frame2-200x190.PNG","https://media.geeksforgeeks.org/wp-content/uploads/20210721215021/frame3-200x182.PNG"        ];          setInterval("Animate()", 400);        var x = 0;          function Animate() {            document.getElementById("img").src = images[x]            x++;            if (images.length == x) {                x = 0;            }        }    </script>      <div class="center">        <img id="img" src="https://media.geeksforgeeks.org/wp-content/uploads/20210721215006/frame1.PNG">          <h3>Frame by Frame Animation</h3>    </div></body>  </html>
Output:
Animation of frames
CSS-Properties
CSS-Questions
JavaScript-Methods
JavaScript-Questions
Picked
CSS
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to set space between the flexbox ?
Design a web page using HTML and CSS
Form validation using jQuery
Search Bar using HTML, CSS and JavaScript
How to style a checkbox using CSS?
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
TypeScript | Array forEach() Method - GeeksforGeeks

18 Jun, 2020
The Array.forEach() is an inbuilt TypeScript function which is used to calls a function for each element in the array. Syntax: 
array.forEach(callback[, thisObject])
Parameter: This method accepts two parameter as mentioned above and described below: 
callback : This parameter is the Function to test for each element.
thisObject : This parameter is the Object to use as this when executing callback.
Return Value: This method returns created array. Below example illustrate the Array forEach() Method in TypeScript.
Example 1: 
JavaScript
<script>    // Driver code    var arr = [ 11, 89, 23, 7, 98 ];            // printing eah element    arr.forEach(function (value) {        console.log(value);    });</script>
Output: 
11
89
23
7
98

Example 2: 
JavaScript
<script>    // Driver code    var arr = [ 1, 2, 3, 4, 5 ];            // printing square of  element    arr.forEach(function (value) {        console.log(value * value);    });</script>
Output: 
1
4
9
16
25

TypeScript
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
RapidScan – The Multi-Tool Web Vulnerability Scanner in Kali Linux - GeeksforGeeks

30 Jun, 2021
RapidScan is a free and open-source tool available on GitHub which is based upon Open Source Intelligence (OSINT), the easiest and useful tool for reconnaissance. The RapidScan interface is very similar to Metasploit 1 and Metasploit 2, which provides a command-line interface that you can run on Kali Linux. This tool can be used to get information about our target(domain), which can be a website or an IP address. The interactive console provides a number of helpful features, such as command completion and contextual help. RapidScan is a web reconnaissance tool written in python. It has so many modules, such as database interaction, built-in convenience functions, interactive help, and command completion. RapidScan provides a powerful environment in which open-source web-based reconnaissance can be conducted and you can gather all the information about the target.
RapidScan’s interactive console provides a number of helpful features.
RapidScan is used for information gathering and vulnerability assessment of web applications.
RapidScan uses the Shodan search engine to scan IoT devices.
RapidScan can easily find loopholes in the code of web applications and websites.
RapidScan has the following modules: Geo lookup, banner grabbing, DNS lookup, port scanning. These modules make this tool so powerful.
Step 1: Use the following command to install the tool.
git clone https://github.com/skavngr/rapidscan.git
cd rapidscan
Step 2: Now give permission to the tool using the following command and run the tool using the following command.
chmod +x rapidscan.py

./rapidscan.py
 The tool has been downloaded successfully.
Example 1: Use the RapidScan tool to scan a website.
./rapidscan.py <domain>
We have scanned our geeksforgeeks.org domain.
Example 2: Use the RapidScan tool to scan another website.
./rapidscan.py <domain>
Kali-Linux
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
scp command in Linux with Examples
mv command in Linux with examples
Docker - COPY Instruction
SED command in Linux | Set 2
chown command in Linux with Examples
nohup Command in Linux with Examples
Named Pipe or FIFO with example C program
Thread functions in C/C++
uniq Command in LINUX with examples
Start/Stop/Restart Services Using Systemctl in Linux
Handling OSError exception in Python - GeeksforGeeks

19 Aug, 2020
Let us see how to handle OSError Exceptions in Python. OSError is a built-in exception in Python and serves as the error class for the os module, which is raised when an os specific system function returns a system-related error, including I/O failures such as “file not found” or “disk full”.
Below is an example of OSError:
Python
# Importing os moduleimport os  # os.ttyname() method in Python is used to get the terminal # device associated with the specified file descriptor.# and raises an exception if the specified file descriptor # is not associated with any terminal device.print(os.ttyname(1))
Output :
OSError: [Errno 25] Inappropriate ioctl for device

We can handle an ODError exception using try...except statements.
Python
# importing os module  import os      # create a pipe using os.pipe() method # it will return a pair of  # file descriptors (r, w) usable for # reading and writing, respectively. r, w = os.pipe()   # (using exception handling technique) # try to get the terminal device associated  # with the file descriptor r or w try :     print(os.ttyname(r))        except OSError as error :     print(error)     print("File descriptor is not associated with any terminal device") 
[Errno 25] Inappropriate ioctl for device
File descriptor is not associated with any terminal device
Python-exceptions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
Check if element exists in list in Python
Convert integer to string in Python
Tree Traversals - GeeksforGeeks

01 Jun, 2021
                              a
                           /    \
                        /          \
                      b             c
                   /   \          /   \
                 /       \      /       \
               d         e    f          g
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Must Do Coding Questions for Product Based Companies
How to Replace Values in Column Based on Condition in Pandas?
How to Fix: SyntaxError: positional argument follows keyword argument in Python
C Program to read contents of Whole File
How to Download and Install Spring Tool Suite (Spring Tools 4 for Eclipse) IDE?
How to Replace Values in a List in Python?
How to Select Data Between Two Dates and Times in SQL Server?
How to Read Text Files with Pandas?
How to Calculate Moving Averages in Python?
How to Compare Two Columns in Pandas?
PHP | create_function() Function - GeeksforGeeks

25 Jun, 2018
The create_function() is an inbuilt function in PHP which is used to create an anonymous (lambda-style) function in the PHP.
Syntax:
string create_function ( $args, $code )
Parameters: This function accepts two parameters which is describes below:
$args: It is a string type function argument.
$code: It is a string type function code.
Note: Usually, these parameters will be passed as single quote delimited strings. The reason for using single quoted strings is to protect the variable names from parsing, otherwise, double quotes will be needed to escape the variable names, e.g. \$avar.
Return Value: This function returns a unique function name as a string, Otherwise returns FALSE on error.
Below programs illustrate the create_function() function in PHP:
Program 1: Creating an anonymous function with create_function()
<?php//create a function from information // gathered at run time,  $newfunc = create_function('$a, $b', 'return       "ln($a) + ln($b) = " . log($a * $b);');  echo "New anonymous function: $newfunc\n";echo $newfunc(2, M_E) . "\n";?>
New anonymous function: lambda_1
ln(2) + ln(2.718281828459) = 1.6931471805599

Program 2: Create a general function with create_function()
<?php// General function that can apply a set of // operations to a list of parameters.  function Program($value1, $value2, $arr){    foreach ($arr as $val) {        echo $val($value1, $value2) . "\n";    }}  // create a bunch of math functions$f1 = 'if ($a >= 0) { return "b * a^2 = ".       $b * sqrt($a);} else { return false; }';  $f2 = "return \"min(a, b) = \".min(\$a, \$b);";  $farr = array(    create_function('$x, $y', 'return        "a hypotenuse: ".sqrt($x * $x + $y * $y);'),          create_function('$a, $b', $f1),    create_function('$a, $b', $f2));  echo "first array of anonymous functions" .         "\nParameter is a = 2 and b = 3\n";Program(2, 3, $farr);  // now make a bunch of string functions$sarr = array(    create_function('$a, $b', 'return      "Lower case : " . strtolower($a) ;'),    create_function('$a, $b', 'return     "Similar Character : " .    similar_text($a, $b, $percent);'));  echo "\nSecond array of anonymous functions" .      "\nParameter is a = GeeksForGeeks and" .      "b = GeeksForGeeks\n";  Program("GeeksForGeeks", "GeeksForGeeks", $sarr);?>
first array of anonymous functions
Parameter is a = 2 and b = 3
a hypotenuse: 3.605551275464
b * a^2 = 4.2426406871193
min(a, b) = 2

Second array of anonymous functions
Parameter is a = GeeksForGeeks andb = GeeksForGeeks
Lower case : geeksforgeeks
Similar Character : 13

References: http://php.net/manual/en/function.create-function.php
PHP-function
Misc
PHP
Misc
Misc
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Activation Functions
Characteristics of Internet of Things
Advantages and Disadvantages of OOP
Sensors in Internet of Things(IoT)
Challenges in Internet of things (IoT)
How to execute PHP code using command line ?
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
PHP in_array() Function
How to pop an alert message box using PHP ?
Python | Pandas Index.repeat() - GeeksforGeeks

18 Dec, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas Index.repeat() function repeat elements of an Index. The function returns a new index where each element of the current index is repeated consecutively a given number of times.
Syntax: Index.repeat(repeats, *args, **kwargs)
Parameters :repeats : The number of repetitions for each element.**kwargs : Additional keywords have no effect but might be accepted for compatibility with numpy.
Returns : Newly created Index with repeated elements.
Example #1: Use Index.repeat()() function to repeat the elements of the index 2 times.
# importing pandas as pdimport pandas as pd  # Creating the indexidx = pd.Index(['Beagle', 'Pug', 'Labrador', 'Pug',                        'Mastiff', None, 'Beagle'])  # Print the Indexidx
Output :
Let’s repeat the index elements 2 times.
# to repeat the valuesidx.repeat(2)
Output :As we can see in the output, the function has returned a new index with all the values repeated 2 times. One important thing to notice is that the function has also repeated the NaN value.
Example #2: Use Index.repeat() function to repeat the value of index 3 times.
# importing pandas as pdimport pandas as pd  # Creating the indexidx = pd.Index([22, 14, 8, 56, None, 21, None, 23])  # Print the Indexidx
Output :
Let’s repeat the index elements 3 times.
# to repeat the valuesidx.repeat(3)
Output :
As we can see in the output, the function has returned a new index with all the values repeated 3 times. One important thing to notice is that the function has also repeated the NaN value.
Python pandas-indexing
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?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
Python program to print the initials of a name with last name in full?

Here we use different python inbuilt function. First we use split().split the words into a list. Then traverse till the second last word and upper() function is used for print first character in capital and then add the last word which is title of a name and here we use title(),title function converts the first alphabet to capital.
Input Pradip Chandra Sarkar
Output P.C Sarkar

fullname(str1)
/* str1 is a string */
Step 1: first we split the string into a list.
Step 2: newspace is initialized by a space(“”)
Step 3: then traverse the list till the second last word.
Step 4: then adds the capital first character using the upper function.
Step 5: then get the last item of the list.

# python program to print initials of a name 
def fullname(str1):
   # split the string into a list 
   lst = str1.split()
   newspace = ""
   # traverse in the list 
   for i in range(len(lst)-1):
      str1 = lst[i]
   # adds the capital first character 
      newspace += (str1[0].upper()+'.')
   # l[-1] gives last item of list l.
      newspace += lst[-1].title()
   return newspace 
# Driver code            
str1=input("Enter Full Name ::>")
print("Short Form of Name Is ::>",fullname(str1))        
Enter Full Name ::>pradip chandra sarkar
Short Form of Name Is ::> P.C.Sarkar
Angular Material 7 - Button

The <mat-button>, an Angular Directive, is used to create a button with material styling and animations.
In this chapter, we will showcase the configuration required to draw a button control using Angular Material.
Follow the following steps to update the Angular application we created in Angular 6 - Project Setup chapter −
Following is the content of the modified module descriptor app.module.ts.
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {MatButtonModule,MatIconModule} from '@angular/material'
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
@NgModule({
   declarations: [
      AppComponent
   ],
   imports: [
      BrowserModule,
      BrowserAnimationsModule,
      MatButtonModule,MatIconModule,
      FormsModule,
      ReactiveFormsModule
   ],
   providers: [],
   bootstrap: [AppComponent]
})
export class AppModule { }
Following is the content of the modified CSS file app.component.css.
.tp-button-row button,
.tp-button-row a {
   margin-right: 8px;
}
Following is the content of the modified HTML host file app.component.html.
<div class = "example-button-row">
   <button mat-button>Basic</button>
   <button mat-raised-button>Raised</button>
   <button mat-stroked-button>Stroked</button>
   <button mat-flat-button>Flat</button>
   <button mat-icon-button>
      <mat-icon aria-label="Heart">favorite</mat-icon>
   </button>
   <button mat-fab>Fab</button>
   <button mat-mini-fab>Mini</button>
   <a mat-button routerLink = ".">Link</a>
</div>
Verify the result.
Here, we've created buttons using various variants of mat-buttons.

    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
Python | Percentage occurrence at index - GeeksforGeeks

27 Mar, 2019
Sometimes while dealing with statistics, we might come across this particular problem in which we require to find the percentage of occurrence of element at particular index in list of list. Let’s discuss certain ways in which this can be done.
Method #1 : Using loop + list comprehensionWe can perform this particular task using the loop for each list index, and for that we can compute the percentage occurrence of element using the list comprehension logic.
# Python3 code to demonstrate# index percentage calculation of element# using loop + list comprehension  # initializing test listtest_list = [[3, 4, 5], [2, 4, 6], [3, 5, 4]]  # printing original list print("The original list : " + str(test_list))  # using loop + list comprehension# index percentage calculation of elementres = []for i in range(len(test_list[1])):    res.append(len([j[i] for j in test_list if j[i]== 4 ])/len(test_list))  # print resultprint("The percentage of 4 each index is : " + str(res))
The original list : [[3, 4, 5], [2, 4, 6], [3, 5, 4]]
The percentage of 4 each index is : [0.0, 0.6666666666666666, 0.3333333333333333]

 
Method #2 : Using zip() + count() + list comprehensionThis particular task can also be performed using the combination of above functions. The count and zip function do the task of percentage computation and grouping respectively.
# Python3 code to demonstrate# index percentage calculation of element# using zip() + count() + list comprehension  # initializing test listtest_list = [[3, 4, 5], [2, 4, 6], [3, 5, 4]]  # printing original list print("The original list : " + str(test_list))  # using zip() + count() + list comprehension# index percentage calculation of elementres = [sub.count(4)/len(sub) for sub in zip(*test_list)]  # print resultprint("The percentage of 4 each index is : " + str(res))
The original list : [[3, 4, 5], [2, 4, 6], [3, 5, 4]]
The percentage of 4 each index is : [0.0, 0.6666666666666666, 0.3333333333333333]

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Python program to convert a list to string
Python | Split string into list of characters
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python program to check whether a number is Prime or not
Creating a tkinter GUI layout using frames and grid

Tkinter is a well-known Python library for creating GUI-based applications. You can create a fully featured application with the help of widgets, functions, and modules that are already present in Tkinter library.
Sometimes, selecting the right GUI of the application becomes a daunting task for many of us. Tkinter comes with a set of inbuilt functions and extensions to create good-looking GUIs.
Generally, the Frame widget in Tkinter manages all the widgets in an application as a container. It inherits all the properties that the main window can contain. To design the layout of the widgets, we can use any of the geometry managers. Geometry Manager helps to create the layout of the widget and place them in a certain order. The Grid geometry manager places all the widgets in the form of X and Y coordinate system. We can provide the row and column property to place the widget anywhere in the application.
In this example, we will create the GUI of a Registration Form.
# Import the Required libraries
from tkinter import *

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

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

# Add a Frame widget
frame = Frame(win)

# Define a function to get the data and display a message
def on_key_up():
   name = fname
   frame.pack_forget()
   win.configure(bg="green4")
   Label(win, text="Hey " + fname.get() + " Welcome to TutorialsPoint",
      font=('Segoe UI', 18, 'bold'),
      background="white").pack(pady=30)
# Create a Label widget
   Label(frame, text="Registration Form",
   font=('Helvetica 16 bold'),
background="green3").grid(row=5, column=0, pady=30)
frame.pack()

# Add Field for First Value
Label(frame, text="First Name").grid(row=7, column=0, padx=5)
fname = Entry(frame)
fname.grid(row=10, column=0, padx=10)

# Add Field for Second Value
Label(frame, text="Family name").grid(row=12, column=0, padx=5)
sname = Entry(frame)
sname.grid(row=15, column=0, padx=10)

# Add Field for Email Address
Label(frame, text="Email address").grid(row=17, column=0, padx=5)
email = Entry(frame)
email.grid(row=20, column=0, padx=10)

# Add another field for accepting password value
Label(frame, text="Enter a Password").grid(row=22, column=0, padx=5)
password = Entry(frame, show="*")
password.grid(row=25, column=0, padx=10)

# Create a button
Button(frame, text="Register", command=on_key_up).grid(row=15,
column=1, padx=5)

win.mainloop()
Running the above code will display a registration form template and a button to register the information.
Tryit Editor v3.7

Tryit: Canvas with a circle
Get Seconds from timestamp in Python-Pandas - GeeksforGeeks

05 Apr, 2022
In this program our task is to create a program in python which will extract seconds from a given timestamp. We will use the s attribute of the DateTime object to extract the second.Example : If we have a data frame that contains 5 different time stamps such as:  
Timestamp
2012-12-11 04:12:01
2013-10-13 04:12:04
2014-12-14 04:12:05
2015-11-15 04:12:06
2016-10-15 04:12:07
And our task is to extract that seconds from given timestamps. So the output here will be:  
seconds
1
4
5
6
7
Example 1 :  
Python3
# importing the moduleimport pandas as pd # generating 10 timestamp starting from '2016-10-10 09:21:12'date1 = pd.Series(pd.date_range('2016-10-10 09:21:12',                                periods = 10, freq = 's')) # converting pandas series into data framedf = pd.DataFrame(dict(GENERATEDTIMESTAMP = date1)) # extracting seconds from time stampdf['extracted_seconds_timestamp'] = df['GENERATEDTIMESTAMP'].dt.second # displaying  DataFramedisplay(df)
Output :  
Example 2 :  
Python3
# importing the moduleimport pandas as pd # generating 5 timestamp starting from '2020-01-01 00:00:00'date1 = pd.Series(pd.date_range('2020-01-01 00:00:00',                                periods = 5, freq = 's')) # converting pandas series into data framedf = pd.DataFrame(dict(GENERATEDTIMESTAMP = date1)) # extracting seconds from time stampdf['extracted_seconds_timestamp'] = df['GENERATEDTIMESTAMP'].dt.second # displaying  DataFramedisplay(df)
Output :  
 
ruhelaa48
simmytarika5
Python pandas-dataFrame
Python Pandas-exercise
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
*args and **kwargs in Python
How To Convert Python Dictionary To JSON?
SAP Scripts - Create a Script in the System

To start a script, you have to run Transaction SE71 and this will open the Form Painter.
In the Form Painter, request screen, enter a name and language for a SAPscript form in the Form and Language fields, respectively. Let’s enter 'RVINVOICE01' and 'EN' respectively in these fields.
Paragraph provides all the information required to format a paragraph of text and fonts. To create a Paragraph, click the Paragraph Formats tab as shown in the following screenshot.
Enter the left margin, right margin, alignment and line spacing to define the Paragraph format.
Click the Character Formats tab to enter character format and meaning as shown in the following screenshot.
Enter the following settings for format option −
Format
Meaning
Size
Then, you have to define Layout of the document. Click the Layout tab to design the window.
Using Layout, gives a GUI editor where you can drag the window position and it is easy to use.
By default, you can see the Main Window in the Layout. To create a new window, you can right-click on Layout → Create Window as seen in the following screenshot.
You can also add graph/logo to the layout part. Go to the Graph button next to Window tab and enter the details.
To make an element on the respective window, click the Edit text button.
You can define a driver program under Transaction SE38 to call this script. Use function modules to define the calling program −
START_FORM
WRITE_FORM
END_FORM
CLOSE_FORM
This is how you can develop a script and add multiple windows and define the paragraph and layout of the form.
Form OPEN_FORM 
CALL FUNCTION 'OPEN_FORM' 
EXPORTING 
Form        = 'FormName' 
Endform                    “OPEN_FORM 

Form START_FORM  
CALL FUNCTION 'START_FORM' 
EXPORTING 
Form        = 'FormName'. 
Endform                    “START_FORM 

CALL FUNCTION 'WRITE_FORM' 
EXPORTING 
Window      = 'GRAPHNAME’ 

CALL FUNCTION 'WRITE_FORM' 
EXPORTING 
Element     = 'ELEMENTNAME' 
FUNCTION    = 'SET' 
TYPE        = 'BODY' 
Window      = 'MAIN’ 
endform.                   " WRITE_FORM 

CALL FUNCTION 'END_FORM' 
IMPORTING 
RESULT      = 
EXCEPTIONS 
UNOPENED    =  1 
OTHERS      =  5 
endform.                    " END_FORM 

CALL FUNCTION 'CLOSE_FORM'  
IMPORTING 
RESULT      = 
EXCEPTIONS 
UNOPENED    =  1 
OTHERS      =  5 
endform.                    "CLOSE-FORM 


    25 Lectures 
     6 hours 

 Sanjo Thomas

    26 Lectures 
     2 hours 

 Neha Gupta

    30 Lectures 
     2.5 hours 

 Sumit Agarwal

    30 Lectures 
     4 hours 

 Sumit Agarwal

    14 Lectures 
     1.5 hours 

 Neha Malik

    13 Lectures 
     1.5 hours 

 Neha Malik
 Print
 Add Notes
 Bookmark this page
How to write PHP script to fetch data, based on some conditions, from MySQL table?

If we want to fetch conditional data from MySQL table then we can write WHERE clause in SQL statement and use it with a PHP script. While writing the PHP script we can use PHP function mysql_query(). This function is used to execute the SQL command and later another PHP function mysql_fetch_array() can be used to fetch all the selected data. This function returns a row as an associative array, a numeric array, or both. This function returns FALSE if there are no more rows. To illustrate it we are having the following example −
In this example we are writing a PHP script that will return all the records from the table named ‘tutorial_tbl’ for which the author name is Sanjay −
<?php
   $dbhost = 'localhost:3036';
   $dbuser = 'root';
   $dbpass = 'rootpassword';
   $conn = mysql_connect($dbhost, $dbuser, $dbpass);
   
   if(! $conn ) {
      die('Could not connect: ' . mysql_error());
   }
   $sql = 'SELECT tutorial_id, tutorial_title,
      tutorial_author, submission_date
      FROM tutorials_tbl
      WHERE tutorial_author = "Sanjay"';

   mysql_select_db('TUTORIALS');
   $retval = mysql_query( $sql, $conn );
   
   if(! $retval ) {
      die('Could not get data: ' . mysql_error());
   }
   
   while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {
      echo "Tutorial ID :{$row['tutorial_id']} <br> ".
         "Title: {$row['tutorial_title']} <br> ".
         "Author: {$row['tutorial_author']} <br> ".
         "Submission Date : {$row['submission_date']} <br> ".
         "--------------------------------<br>";
   }
   echo "Fetched data successfully\n";
   mysql_close($conn);
?>
Split Button Dropdowns with Bootstrap

Split button dropdowns use the same general style as the dropdown button but add a primary action along with the dropdown. Split buttons have the primary action on the left and a toggle on the right that displays the dropdown.
You can try to run the following code to split button dropdowns −
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Example</title>
      <link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet">
      <script src = "/scripts/jquery.min.js"></script>
      <script src = "/bootstrap/js/bootstrap.min.js"></script>
   </head>
   <body>
      <div class = "btn-group">
         <button type = "button" class = "btn btn-default">Admissions</button>
         <button type = "button" class = "btn btn-default dropdown-toggle" data-toggle = "dropdown">
            <span class = "caret"></span>
            <span class = "sr-only">Toggle Dropdown</span>
         </button>
         <ul class = "dropdown-menu" role = "menu">
            <li><a href = "#">Masters</a></li>
            <li><a href = "#">Bachelors</a></li>
         </ul>
      </div>
      <div class = "btn-group">
         <button type = "button" class = "btn btn-primary">Faculty</button>
         <button type = "button" class = "btn btn-primary dropdown-toggle" data-toggle = "dropdown">
            <span class = "caret"></span>
            <span class = "sr-only">Toggle Dropdown</span>
         </button>
         <ul class = "dropdown-menu" role = "menu">
            <li><a href = "#">Management</a></li>
            <li><a href = "#">Technical</a></li>
            <li><a href = "#">Staff</a></li>
         </ul>
      </div>
   </body>
</html>
Dropdown Menus - Tkinter - GeeksforGeeks

26 Nov, 2020
Prerequisite: Python GUI – tkinter
Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter is the fastest and easiest way to create GUI applications. Creating a GUI using Tkinter is an easy task.
OptionMenu is an important part of any GUI. It creates a popup menu, and a button to display it. It is similar to the combobox widgets commonly used on Windows.
Syntax:
OptionMenu(master,options)
Parameters:
master: This parameter is used to represents the parent window.
options: Contain the Menu values
Define the datatype of menu text, means integer, string, or any other datatypeSet initial menu text (That display initially)Add menu value in option as a listCreate Dropdown menu
Define the datatype of menu text, means integer, string, or any other datatype
Set initial menu text (That display initially)
Add menu value in option as a list
Create Dropdown menu
Below is an Implementation that creates Dropdown menus in Tkinter:
Python3
# Import modulefrom tkinter import *  # Create objectroot = Tk()  # Adjust sizeroot.geometry( "200x200" )  # Change the label textdef show():    label.config( text = clicked.get() )  # Dropdown menu optionsoptions = [    "Monday",    "Tuesday",    "Wednesday",    "Thursday",    "Friday",    "Saturday",    "Sunday"]  # datatype of menu textclicked = StringVar()  # initial menu textclicked.set( "Monday" )  # Create Dropdown menudrop = OptionMenu( root , clicked , *options )drop.pack()  # Create button, it will change label textbutton = Button( root , text = "click Me" , command = show ).pack()  # Create Labellabel = Label( root , text = " " )label.pack()  # Execute tkinterroot.mainloop()
Output:-
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
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
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Create a directory in Python
Python | Pandas dataframe.groupby()