code-rag-bench/online-tutorials huggingface dataset:
How to match text at the start or end of a string in Python?

Assume you need to check the start or end of a string for a specific text patterns. The common patterns might be filename extensions but can also be anything. I will show you few methods on how you can do this.
A simple way to check the beginning of a string is by using startswith() method.
text = "Is USA colder than Australia?"
print(f"output \n {text.startswith('Is')}")
True
filename = "Hello_world.txt"
print(f"output \n {filename.startswith('Hello')}")
True
site_url = 'https://www.something.com'
print(f"output \n {site_url.startswith('http:')}")
False
print(f"output \n {site_url.startswith('https:')}")
True
A simple way to check the ending of a string is by using endswith() method.
text = "Is USA colder than Australia?"
print(f"output \n {text.endswith('?')}")
True
filename = "Hello_world.txt"
print(f"output \n {filename.endswith('.txt')}")
True
Now if we want to check for multiple choices with the above methods we need to provide tuples. One of the common usage is the check for file extensions let us say we need to validate for ".txt" and ".csv" files in a directory.
import os
filenames = os.listdir('.')
# Let us first check if there are files
print(f"output \n {any(name.endswith(('.csv',',txt')) for name in filenames)}")
True
[name for name in filenames if name.endswith(('.csv', '.txt')) ]
['file1.csv',
'HRDataset.csv',
'Input.csv',
'input.txt',
'input_copy.txt',
'movies_data.csv',
'my_html_data_to_csv.csv',
'temporary_file1_for_zip.csv',
'temporary_file2_for_zip.csv',
'test.csv',
'test1.txt',
'test2.txt',
'tmdb_5000_movies.csv']
Remember these methods accepts tuples, if you have a list of choices to search, then we need to convert them in tuples.
import os

# list with choices
patters = ['.csv','.txt']

# get the file names
filenames = os.listdir('.')

# Let us first check if there are files
any(name.endswith(patters) for name in filenames)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
in
8
9 # Let us first check if there are files
---> 10 any(name.endswith(patters) for name in filenames)

in (.0)
8
9 # Let us first check if there are files
---> 10 any(name.endswith(patters) for name in filenames)

TypeError: endswith first arg must be str or a tuple of str, not list
The above command returned an error, so we need to convert the list into a tuple.
# Let us first check if there are files
any(name.endswith(tuple(patters)) for name in filenames)
True
Similarly, we need to convert list to tuple to get the file names.
[name for name in filenames if name.endswith(tuple(patters)) ]
['file1.csv',
'HRDataset.csv',
'Input.csv',
'input.txt',
'input_copy.txt',
'movies_data.csv',
'my_html_data_to_csv.csv',
'temporary_file1_for_zip.csv',
'temporary_file2_for_zip.csv',
'test.csv',
'test1.txt',
'test2.txt',
'tmdb_5000_movies.csv']
Finally, the startswith() and endswith() methods look nice when combined with other operations, such as common data reductions. For example:
if any(name.endswith(tuple(patters)) for name in filenames):
<perform the logic here>
Convert List of Vectors to DataFrame in R - GeeksforGeeks

09 May, 2021
In this article, we will discuss how to convert the given list of vectors to Dataframe using the help of different functions in the R Programming Language.
For all the methods discussed below, few functions are common because of their functionality. Let us discuss them first.
as.data.frame() is one of the simplest methods to convert the given list of vectors to the DataFrame in R language with just calling the as.data.frame() function and passing the required parameters, and further this function will be returning the DataFrame converted from the list of vectors given before. 
Syntax: as.data.frame(x, row.names = NULL, optional = FALSE, ...)
Further, with the as.data.frame() function user needs to also call the do.call() function which is used here to constructs and executes a function call from a name or a function and a list of arguments to be passed to it.
Syntax: do.call(what, args, quote = FALSE, envir = parent.frame())
Parameters:
what:-either a function or a non-empty character string naming the function to be called.
args:a list of arguments to the function call. The names attribute of args gives the argument names.
quote:-a logical value indicating whether to quote the arguments.
envir:-an environment within which to evaluate the call.
cbind() function stands for column-bind. This function can be used to combine several vectors, matrices, or DataFrames by columns.
Syntax: cbind(x1, x2, ..., deparse.level = 1)
In this approach, a single vector is considered as one column and then these columns are combined to form a dataframe.
Example:
R
my_list <- list(A =c(1,2,3,4,5),                 B =c(6,7,8,9,10))  my_list  as.data.frame(do.call(cbind, my_list))   
Output:
rbind() function stands for row-bind. This function can be used to combine several vectors, matrices, or DataFrames by rows.
Syntax: rbind(x1, x2, ..., deparse.level = 1)
Parameters:x1, x2: vector, matrix, DataFramesdeparse.level: This value determines how the column names generated. The default value of deparse.level is 1.
In this approach, each vector is considered a row and then these rows are combined to form a dataframe.
Example:
R
my_list <- list(A =c(1,2,3,4,5),                 B =c(6,7,8,9,10))  my_list  as.data.frame(do.call(rbind, my_list))   
Output:
Picked
R DataFrame-Programs
R-DataFrame
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
How to filter R dataframe by multiple conditions?
Replace Specific Characters in String in R
Convert Matrix to Dataframe in R
Deleting a binary tree using the delete keyword in C++ program

In this tutorial, we are going to learn how to delete a binary tree using the delete keyword.
We are going to use a destructor member function to delete the binary. The destructor member function is invoked automatically when the object goes out of the scope or it is destroyed by calling delete.
The destructor member function has the name as a class with tilde (~) before it.
Let's see the steps to solve the problem.
Write a class called Node.
Write a class called Node.
Write a constructor function that accepts data for the node.
Write a constructor function that accepts data for the node.
Write a destructor function.Delete the left node.Delete the right node.Print the current node data.
Write a destructor function.
Delete the left node.
Delete the left node.
Delete the right node.
Delete the right node.
Print the current node data.
Print the current node data.
Initialize the binary tree with dummy data.
Initialize the binary tree with dummy data.
Delete the binary tress using the delete root statement.
Delete the binary tress using the delete root statement.
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Node {
   public:
   int data;
   Node* left;
   Node* right;
   // constructor
   Node(int data) {
      this->data = data;
      this->left = NULL;
      this->right = NULL;
   }
   // destructor
   ~Node() {
      // deleting the left and right pointers
      delete left;
      delete right;
      // printing node data
      cout << "Deleted node with data " << this->data << endl;
   }
};
int main() {
   Node* root = new Node(1);
   root->left = new Node(2);
   root->right = new Node(3);
   root->left->left = new Node(4);
   root->left->right = new Node(5);
   root->right->left = new Node(6);
   root->right->right = new Node(7);
   // deleting the entire tree using destructure function
   delete root;
   return 0;
}
If you execute the above program, then you will get the following result.
Deleted node with data 4
Deleted node with data 5
Deleted node with data 2
Deleted node with data 6
Deleted node with data 7
Deleted node with data 3
Deleted node with data 1
If you have any queries in the tutorial, mention them in the comment section.
How to handle the ArithmeticException (unchecked) in Java?


The java.lang.ArithmeticException is an unchecked exception in Java. Usually, one would come across java.lang.ArithmeticException: / by zero which occurs when an attempt is made to divide two numbers and the number in the denominator is zero. ArithmeticException objects may be constructed by the JVM.
Live Demo
public class ArithmeticExceptionTest {
   public static void main(String[] args) {
      int a = 0, b = 10;
      int c = b/a;
      System.out.println("Value of c is : "+ c);
   }
}
In the above example,  ArithmeticExeption is occurred due to denominator value is zero.
java.lang.ArithmeticException: Exception thrown by java during division.
/ by zero: is the detail message given to ArithmeticException class while creating the ArithmeticException object.
Exception in thread "main" java.lang.ArithmeticException: / by zero
      at ArithmeticExceptionTest.main(ArithmeticExceptionTest.java:5)
Let us handle the ArithmeticException using try and catch blocks.
Surround the statements that can throw ArithmeticException with try and catch blocks.
We can Catch the ArithmeticException
Take necessary action for our program, as the execution doesn’t abort.
Live Demo
public class ArithmeticExceptionTest {
   public static void main(String[] args) {
      int a = 0, b = 10 ;
      int c = 0;
      try {
         c = b/a;
      } catch (ArithmeticException e) {
         e.printStackTrace();
         System.out.println("We are just printing the stack trace.\n"+ "ArithmeticException is handled. But take care of the variable \"c\"");
      }
      System.out.println("Value of c :"+ c);
   }
}
When an exception occurs, the execution falls to the catch block from the point of occurrence of an exception. It executes the statement in the catch block and continues with the statement present after the try and catch blocks.
We are just printing the stack trace.
ArithmeticException is handled. But take care of the variable "c"
Value of c is : 0
java.lang.ArithmeticException: / by zero
        at ArithmeticExceptionTest.main(ArithmeticExceptionTest.java:6)
Difference between Linker and Loader - GeeksforGeeks

14 Mar, 2022
In execution of the program, major role is played by two utility programs known as Linker and Loader. 
1. Linker : A linker is special program that combines the object files, generated by compiler/assembler, and other pieces of codes to originate an executable file have. exe extension. In the object file, linker searches and append all libraries needed for execution of file. It regulates the memory space that will hold the code from each module. It also merges two or more separate object programs and establishes link among them. Generally, linkers are of two types : 
1. Linkage Editor
2. Dynamic Linker 
2. Loader : The loader is special program that takes input of executable files from linker, loads it to main memory, and prepares this code for execution by computer. Loader allocates memory space to program. Even it settles down symbolic reference between objects. It is in charge of loading programs and libraries in operating system. The embedded computer systems don’t have loaders. In them, code is executed through ROM. There are following various loading schemes: 
1. Absolute Loaders
2. Relocating Loaders
3. Direct Linking Loaders
4. Bootstrap Loaders
Difference Between Linker and Loader :  
sukhseeratkaur
zubymantasha
aftab1x0
vai43
Picked
Compiler Design
Difference Between
Operating Systems
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Construction of LL(1) Parsing Table
Introduction of Lexical Analysis
Flex (Fast Lexical Analyzer Generator )
C program to detect tokens in a C program
Introduction of Compiler Design
Difference between BFS and DFS
Class method vs Static method in Python
Difference between var, let and const keywords in JavaScript
Differences between TCP and UDP
Difference between Process and Thread
Creating array with repeated elements in Julia - repeat() Method - GeeksforGeeks

26 Mar, 2020
The repeat() is an inbuilt function in julia which is used to construct an array by repeating the specified array elements with the specified number of times.
Syntax:repeat(A::AbstractArray, counts::Integer...)orrepeat(A::AbstractArray; inner, outer)orrepeat(s::AbstractString, r::Integer)orrepeat(c::AbstractChar, r::Integer)
Parameters:
A::AbstractArray: Specified array.
counts::Integer: Specified number of times each element get repeated.
inner: It says the repetition of individual element.
outer: It says the repetition of whole slice.
s::AbstractString: Specified string.
r::Integer: Specified number of times each element get repeated.
c::AbstractChar: Specified character.
Returns: It returns a new constructed array.
Example 1:
# Julia program to illustrate # the use of Array repeat() method  # Constructing an array by repeating# the specified 1D array with the # specified number of times.A = [1, 2, 3, 4];println(repeat(A, 1))  # Constructing an array by repeating# the specified 1D array with the # specified number of times.B = [1, 2, 3, 4];println(repeat(B, 1, 2))  # Constructing an array by repeating# the specified 2D array with the # specified number of times.C = [1 2; 3 4];println(repeat(C, 2))  # Constructing an array by repeating# the specified 2D array with the # specified number of times.D = [1 2; 3 4];println(repeat(D, 2, 2))
Output:
Example 2:
# Julia program to illustrate # the use of Array repeat() method  # Constructing an array by repeating# the specified elements with the # specified inner valueprintln(repeat(1:3, inner = 2))  # Constructing an array by repeating# the specified elements with the # specified outer valueprintln(repeat(2:4, outer = 2))  # Constructing an array by repeating# the specified elements with the # specified inner and outer valueprintln(repeat([5 10; 15 20], inner =(2, 1), outer =(1, 3)))
Output:
Example 3:
# Julia program to illustrate # the use of Array repeat() method  # Getting new string after repetition of# specified string or characterprintln(repeat("GFG", 3))println(repeat("GeeksforGeeks", 2))println(repeat("a", 4))println(repeat("A", 5))
Output:
GFGGFGGFG
GeeksforGeeksGeeksforGeeks
aaaa
AAAAA
Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Working with Date and Time in Julia
Get array dimensions and size of a dimension in Julia - size() Method
Functions in Julia
Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)
Getting the maximum value from a list in Julia - max() Method
Julia Language Introduction
Regular Expressions in Julia
Broadcasting across arrays in Julia
How to Install Julia on Windows ?
How to install NumPy package in Julia?
Redis - Publish Subscribe

Redis Pub/Sub implements the messaging system where the senders (in redis terminology called publishers) sends the messages while the receivers (subscribers) receive them. The link by which the messages are transferred is called channel.
In Redis, a client can subscribe any number of channels.
Following example explains how publish subscriber concept works. In the following example, one client subscribes a channel named ‘redisChat’.
redis 127.0.0.1:6379> SUBSCRIBE redisChat  
Reading messages... (press Ctrl-C to quit) 
1) "subscribe" 
2) "redisChat" 
3) (integer) 1 

Now, two clients are publishing the messages on the same channel named ‘redisChat’ and the above subscribed client is receiving messages.
redis 127.0.0.1:6379> PUBLISH redisChat "Redis is a great caching technique"  
(integer) 1  
redis 127.0.0.1:6379> PUBLISH redisChat "Learn redis by tutorials point"  
(integer) 1   
1) "message" 
2) "redisChat" 
3) "Redis is a great caching technique" 
1) "message" 
2) "redisChat" 
3) "Learn redis by tutorials point" 

Following table lists some basic commands related to Redis Pub/Sub.
Subscribes to channels matching the given patterns.
Tells the state of Pub/Sub system. For example, which clients are active on the server.
Posts a message to a channel.
Stops listening for messages posted to channels matching the given patterns.
Listens for messages published to the given channels.
Stops listening for messages posted to the given channels.

    22 Lectures 
     40 mins

 Skillbakerystudios
 Print
 Add Notes
 Bookmark this page
Python 3 - os.open() Method

The method open() opens the file file and set various flags according to flags and possibly its mode according to mode.The default mode is 0777 (octal), and the current umask value is first masked out.
Following is the syntax for open() method −
os.open(file, flags[, mode]);

file − File name to be opened.
flags − The following constants are options for the flags. They can be combined using the bitwise OR operator |. Some of them are not available on all platforms.
os.O_RDONLY − open for reading only
os.O_RDONLY − open for reading only
os.O_WRONLY − open for writing only
os.O_WRONLY − open for writing only
os.O_RDWR − open for reading and writing
os.O_RDWR − open for reading and writing
os.O_NONBLOCK − do not block on open
os.O_NONBLOCK − do not block on open
os.O_APPEND − append on each write
os.O_APPEND − append on each write
os.O_CREAT − create file if it does not exist
os.O_CREAT − create file if it does not exist
os.O_TRUNC − truncate size to 0
os.O_TRUNC − truncate size to 0
os.O_EXCL − error if create and file exists
os.O_EXCL − error if create and file exists
os.O_SHLOCK − atomically obtain a shared lock
os.O_SHLOCK − atomically obtain a shared lock
os.O_EXLOCK − atomically obtain an exclusive lock
os.O_EXLOCK − atomically obtain an exclusive lock
os.O_DIRECT − eliminate or reduce cache effects
os.O_DIRECT − eliminate or reduce cache effects
os.O_FSYNC  − synchronous writes
os.O_FSYNC  − synchronous writes
os.O_NOFOLLOW − do not follow symlinks
os.O_NOFOLLOW − do not follow symlinks
mode − This work in similar way as it works for chmod() method.
This method returns the file descriptor for the newly opened file.
The following example shows the usage of open() method.
#!/usr/bin/python3
import os, sys

# Open a file
fd = os.open( "foo.txt", os.O_RDWR|os.O_CREAT )

# Write one string

line = "this is test" 
# string needs to be converted byte object
b = str.encode(line)
os.write(fd, b)

# Close opened file
os.close( fd)

print ("Closed the file successfully!!")
This would create given file foo.txt and then would write given content in that file and would produce following result −
Closed the file successfully!!


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
How MySQL use YEAR data type to store year value in a table?

MySQL permits to declare a column YEAR type, with the help of which we can store year values in that column.
mysql> Create table year1 (Year_Copyright YEAR);
Query OK, 0 rows affected (0.21 sec)

mysql> Insert into year1(Year_Copyright) values (2017);
Query OK, 1 row affected (0.08 sec)

mysql> Select * from year1;
+----------------+
| Year_Copyright |
+----------------+
|          2017  |
+----------------+
1 row in set (0.00 sec)
GATE | GATE CS 2012 | Question 41 - GeeksforGeeks

28 Jun, 2021
Suppose (A, B) and (C,D) are two relation schemas. Let r1 and r2 be the corresponding relation instances. B is a foreign key that refers to C in r2. If data in r1 and r2 satisfy referential integrity constraints, which of the following is ALWAYS TRUE?
(A) A(B) B(C) C(D) DAnswer: (A)Explanation: See Question 3 of https://www.geeksforgeeks.org/database-management-system-set-2/Quiz of this Question
GATE-CS-2012
GATE-GATE CS 2012
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-2001 | Question 39
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 IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
How to define important text using HTML5 ? - GeeksforGeeks

27 May, 2020
In this article, we define an important text by using the <strong> tag in HTML. It is the parsed tag and used to show the importance of the text. It reflects the text as bold.
Syntax:
<strong> Contents... </strong>
Example 1:
<!DOCTYPE html><html>  <head>    <title>        How to define important        text in HTML?    </title>      <style>        body {            text-align: center;        }          h1 {            color: green;        }    </style></head>  <body>    <h1>GeeksforGeeks</h1>      <h2>        How to define important        text using HTML5?    </h2>      <strong>        Welcome to GeeksforGeeks!    </strong></body>  </html>
Output:
Example 2:
<!DOCTYPE html><html>  <head>    <title>        How to define important        text in HTML?    </title>      <style>        body {            text-align: center;        }          h1 {            color: green;        }          .gfg {            font-weight: bold;        }    </style></head>  <body>    <h1>GeeksforGeeks</h1>      <h2 class="gfg">        How to define important        text using HTML5?    </h2>      <div class="gfg">        Welcome to GeeksforGeeks!    </div></body>  </html>              
Output:
Supported Browsers:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
CSS-Misc
HTML-Misc
HTML5
CSS
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a web page using HTML and CSS
How to set space between the flexbox ?
Form validation using jQuery
Search Bar using HTML, CSS and JavaScript
How to style a checkbox using CSS?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
How to set input type date in dd-mm-yyyy format using HTML ?
REST API (Introduction)
How to Insert Form Data into Database using PHP ?
Allow only alphabets in column in SQL Server - GeeksforGeeks

30 Aug, 2021
There may occur some situations when data in column should only be in alphabets, for example: Name column in details table. If user try to input other than alphabets, it will give error. To allow only alphabets in a column check constraint can be applied over column. To get information about Constraints and Check Constraints, refer below article links:  
SQL | Constraints
SQL | CHECK Constraint
Syntax:  
CONSTRAINT (Constraint_Name) 
CHECK ( BOOLEAN EXPRESSION)
Example 1: In this example, constraints are applied on ADDRESS column to check if value inserted in ADDRESS column consist of only alphabets or not. The value inserted in ADDRESS column consists of only alphabets and thus it works fine and does not show any error. The condition NOT LIKE %[^A-Z]% checks is input values are alphabets or not.  
Output:  
Example 2: In this example, constraints are applied on ADDRESS column to check if entered value consist of only alphabets or not. The value inserted in ADDRESS column consists of alphabets and integer and thus it shows error. The ADDRESS “GEEKS1” is responsible for error.  
Output:  
 
ruhelaa48
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
SQL | Subquery
How to Create a Table With Multiple Foreign Keys in SQL?
What is Temporary Table in SQL?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL Query to Convert VARCHAR to INT
SQL using Python
How to Write a SQL Query For a Specific Date Range and Date Time?
How to Select Data Between Two Dates and Times in SQL Server?
SQL Query to Compare Two Dates
PostgreSQL - EXTRACT Function - GeeksforGeeks

07 Oct, 2021
The PostgreSQL EXTRACT() function is used to query for field associated with date and time such as a year, month, and day from a date/time value.
Syntax: EXTRACT(field FROM source)
Let’s analyze the above syntax:
In the above syntax the field argument is used to specify fields that is to be extracted from the date/time value.
The source is generally either a TIMESTAMP type or an INTERVAL type. Depending upon the values passed the type is set. For instance, if we pass a DATE value, the function adapt to a TIMESTAMP type value.
Example 1:
The below statement extracts year from a timestamp:
SELECT EXTRACT(YEAR FROM TIMESTAMP '2020-12-31 13:30:15');
Output:
Example 2:
The below statement extracts the quarter from a timestamp:
SELECT EXTRACT(QUARTER FROM TIMESTAMP '2020-12-31 13:30:15');
Output:
Example 3:
The below statement extracts month from a timestamp:
SELECT EXTRACT(MONTH FROM TIMESTAMP '2020-12-31 13:30:15');
Output:
ruhelaa48
PostgreSQL-Date-function
PostgreSQL-function
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL - Psql commands
PostgreSQL - Change Column Type
PostgreSQL - For Loops
PostgreSQL - Function Returning A Table
PostgreSQL - Create Auto-increment Column using SERIAL
PostgreSQL - CREATE PROCEDURE
PostgreSQL - ARRAY_AGG() Function
PostgreSQL - DROP INDEX
PostgreSQL - Copy Table
PostgreSQL - Identity Column
numpy.arcsin() in Python - GeeksforGeeks

29 Nov, 2018
numpy.arcsin(x[, out]) = ufunc ‘arcsin’) : This mathematical function helps user to calculate inverse sine for all x(being the array elements).
Parameters :
array  : [array_like]elements are in radians.
out    : [array_like]array of same shape as x.

Return :
An array with inverse sine of x
for all x i.e. array elements. 

The values are in the closed interval [-pi/2, pi/2].

 Code #1 : Working
# Python program explaining# arcsin() function  import numpy as np  in_array = [0, 1, 0.3, -1]print ("Input array : \n", in_array)  arcsin_Values = np.arcsin(in_array)print ("\nInverse Sine values : \n", arcsin_Values)
Output :
Input array : 
 [0, 1, 0.3, -1]

Inverse Sine values : 
 [ 0.          1.57079633  0.30469265 -1.57079633]
 Code #2 : Graphical representation
# Python program showing# Graphical representation of # arcsin() function  import numpy as npimport matplotlib.pyplot as plt  in_array = np.linspace(-np.pi, np.pi, 12)out_array1 = np.sin(in_array)out_array2 = np.arcsin(in_array)  print("in_array : ", in_array)print("\nout_array with sin : ", out_array1)print("\nout_arraywith arcsin : ", out_array1)  # red for numpy.arcsin()plt.plot(in_array, out_array1,            color = 'blue', marker = "*")              plt.plot(in_array, out_array2,            color = 'red', marker = "o")              plt.title("blue : numpy.sin() \nred : numpy.arcsin()")plt.xlabel("X")plt.ylabel("Y")plt.show()
Output :

in_array :  [-3.14159265 -2.57039399 -1.99919533 -1.42799666 -0.856798   -0.28559933
  0.28559933  0.856798    1.42799666  1.99919533  2.57039399  3.14159265]

out_array with sin :  [ -1.22464680e-16  -5.40640817e-01  -9.09631995e-01  -9.89821442e-01
  -7.55749574e-01  -2.81732557e-01   2.81732557e-01   7.55749574e-01
   9.89821442e-01   9.09631995e-01   5.40640817e-01   1.22464680e-16]

out_arraywith arcsin :  [ -1.22464680e-16  -5.40640817e-01  -9.09631995e-01  -9.89821442e-01
  -7.55749574e-01  -2.81732557e-01   2.81732557e-01   7.55749574e-01
   9.89821442e-01   9.09631995e-01   5.40640817e-01   1.22464680e-16]
RuntimeWarning: invalid value encountered in arcsin
  out_array2 = np.arcsin(in_array)
References :https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.arcsin.html#numpy.arcsin.
Python numpy-Mathematical Function
Python-numpy
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()
Django - Admin Interface

Django provides a ready-to-use user interface for administrative activities. We all know how an admin interface is important for a web project. Django automatically generates admin UI based on your project models.
The Admin interface depends on the django.countrib module. To have it working you need to make sure some modules are imported in the INSTALLED_APPS and MIDDLEWARE_CLASSES tuples of the myproject/settings.py file.
For INSTALLED_APPS make sure you have −
INSTALLED_APPS = (
   'django.contrib.admin',
   'django.contrib.auth',
   'django.contrib.contenttypes',
   'django.contrib.sessions',
   'django.contrib.messages',
   'django.contrib.staticfiles',
   'myapp',
)
For MIDDLEWARE_CLASSES −
MIDDLEWARE_CLASSES = (
   'django.contrib.sessions.middleware.SessionMiddleware',
   'django.middleware.common.CommonMiddleware',
   'django.middleware.csrf.CsrfViewMiddleware',
   'django.contrib.auth.middleware.AuthenticationMiddleware',
   'django.contrib.messages.middleware.MessageMiddleware',
   'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
Before launching your server, to access your Admin Interface, you need to initiate the database −
$ python manage.py migrate

syncdb will create necessary tables or collections depending on your db type, necessary for the admin interface to run. Even if you don't have a superuser, you will be prompted to create one.
If you already have a superuser or have forgotten it, you can always create one using the following code −
$ python manage.py createsuperuser

Now to start the Admin Interface, we need to make sure we have configured a URL for our admin interface. Open the myproject/url.py and you should have something like −
from django.conf.urls import patterns, include, url

from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
   # Examples:
   # url(r'^$', 'myproject.views.home', name = 'home'),
   # url(r'^blog/', include('blog.urls')),

   url(r'^admin/', include(admin.site.urls)),
)
Now just run the server.
$ python manage.py runserver

And your admin interface is accessible at: http://127.0.0.1:8000/admin/
Once connected with your superuser account, you will see the following screen −
That interface will let you administrate Django groups and users, and all registered models in your app. The interface gives you the ability to do at least the "CRUD" (Create, Read, Update, Delete) operations on your models.

    39 Lectures 
     3.5 hours 

 John Elder

    36 Lectures 
     2.5 hours 

 John Elder

    28 Lectures 
     2 hours 

 John Elder

    20 Lectures 
     1 hours 

 John Elder

    35 Lectures 
     3 hours 

 John Elder

    79 Lectures 
     10 hours 

 Rathan Kumar
 Print
 Add Notes
 Bookmark this page
3D Wireframe plotting in Python using Matplotlib - GeeksforGeeks

03 Feb, 2022
To create static, animated and interactive visualizations of data, we use the Matplotlib module in Python. The below programs will depict 3D wireframe. visualization of data in Python. In-order to visualize data using 3D wireframe we require some modules from matplotlib, mpl_toolkits and numpy library. Example 1:  
Python3
# importing modulesfrom mpl_toolkits.mplot3d import axes3dfrom matplotlib import pyplot  # creating the visualizationfig = pyplot.figure()wf = fig.add_subplot(111, projection='3d')x, y, z = axes3d.get_test_data(0.05)wf.plot_wireframe(x,y,z, rstride=2,                  cstride=2,color='green')  # displaying the visualizationwf.set_title('Example 1')pyplot.show()
Output:  
In the above program, a 3D wireframe is plotted using test values for coordinates.Example 2:  
Python3
# importing modulesfrom mpl_toolkits import mplot3dimport numpyfrom matplotlib import pyplot # assigning coordinates   a = numpy.linspace(-5, 5, 25)b = numpy.linspace(-5, 5, 25)x, y = numpy.meshgrid(a, b)z = numpy.sin(numpy.sqrt(x**2 + y**2)) # creating the visualizationfig = pyplot.figure()wf = pyplot.axes(projection ='3d')wf.plot_wireframe(x, y, z, color ='green') # displaying the visualizationwf.set_title('Example 2')pyplot.show()
Output:  
 
singghakshay
rkbhola5
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Taking input in Python
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Why Char[] array is more secure (store sensitive data) than String in Java?

Both String and Char[] array are used to store the textual data but choosing one over the other is more difficult. Maybe we can get the idea from the immutability of String why char[] array is preferred over String for storing sensitive information data like password, SSN, etc.
Using the plain string is a much higher chance of accidentally printing the password to logs or some other insecure places where char[] array is less vulnerable.
Since String is immutable, there is no method defined that allow us to change or overwrite the content of the string. This feature makes string objects unstable for storing secure information such as passwords, SSN, etc. We should always store the secure information in char[] array rather than String.
Since String is immutable if we store the password as plain text it will be available in memory until the garbage
collector cleans it. Since string used String Constant Pool (SCP) for re-usability of a string, there will be a pretty chance that it will remain in memory for a long duration. Since anyone who has access to memory dump can easily find the password in plain text that's another reason should use encrypt
password than plain text.
If we notice in Java Swing applications, there is a method of JPasswordField
getPassword() which return char[] and the deprecated method getText() which return the password in plain text. So java itself recommending to use the get password() method.
Another reason for storing a password in char[] array, because char[] can be sanitized, for example, after usage one can override a clear password with junk, while String is immutable in Java.
 Live Demo
public class SecureInfoData {
   public static void main(String args[]) {
      String pwd = "string_pass_word";
      System.out.println("String Password is: " + pwd);
      char charPwd[] = "char_pass_word".toCharArray();
      System.out.println("Character Password is: " + charPwd);
   }
}
String Password is: string_pass_word
Character Password is: [C@6d06d69c
TypeScript - Array concat()

concat() method returns a new array comprised of this array joined with two or more arrays.
array.concat(value1, value2, ..., valueN);

valueN − Arrays and/or values to concatenate to the resulting array.
Returns a new array.
var alpha = ["a", "b", "c"]; 
var numeric = [1, 2, 3];

var alphaNumeric = alpha.concat(numeric); 
console.log("alphaNumeric : " + alphaNumeric );

On compiling, it will generate the same code in JavaScript.
Its output is as follows −
alphaNumeric : a,b,c,1,2,3


    45 Lectures 
     4 hours 

 Antonio Papa

    41 Lectures 
     7 hours 

 Haider Malik

    60 Lectures 
     2.5 hours 

 Skillbakerystudios

    77 Lectures 
     8 hours 

 Sean Bradley

    77 Lectures 
     3.5 hours 

 TELCOMA Global

    19 Lectures 
     3 hours 

 Christopher Frewin
 Print
 Add Notes
 Bookmark this page
How to perform Friedman test in R?

To perform Friedman test in R, we can follow the below steps −
First of all, create a matrix.
Then, use friedman.test function to perform the Friedman test.
Let's create a data matrix as shown below −
 Live Demo
First<-sample(1:100,20)
Second<-sample(1:100,20)
Third<-sample(1:100,20)
Fourth<-sample(1:100,20)
Period<-matrix(c(First,Second,Third,Fourth),byrow=FALSE,nrow=20)
Period
On executing, the above script generates the below output(this output will vary on your system due to randomization) −
     [,1] [,2] [,3] [,4]
[1,]  56   19   61  100
[2,]  16   1    89  82
[3,]  34   18   13  13
[4,]  85   85   35  55
[5,]  10   29   42  79
[6,]  99   52   11  92
[7,]  27   42   87  86
[8,]  42   26   6   63
[9,]  19   3    90  16
[10,] 48   80   93   4
[11,] 89   43   94  52
[12,] 46   62   54  30
[13,] 61   68   57  71
[14,] 5    2    64  64
[15,] 15   93   45  91
[16,] 86   61   28 36
[17,] 66   53   84 28
[18,] 80   90   73 33
[19,] 18   23   7 24
[20,] 26   73   95 2
Using friedman.test function to perform the test on data in Period −
 Live Demo
First<-sample(1:100,20)
Second<-sample(1:100,20)
Third<-sample(1:100,20)
Fourth<-sample(1:100,20)
Period<-matrix(c(First,Second,Third,Fourth),byrow=FALSE,nrow=20)
friedman.test(Period)
Friedman rank sum test
data: Period
Friedman chi-squared = 0.19797, df = 3, p-value = 0.9779
Create the matrix
Let's create a data matrix as shown below −
 Live Demo
Jan<-round(rnorm(20),2)
Feb<-round(rnorm(20),2)
Mar<-round(rnorm(20),2)
Apr<-round(rnorm(20),2)
May<-round(rnorm(20),2)
Time<-matrix(c(Jan,Feb,Mar,Apr,May),byrow=FALSE,nrow=20)
Time
On executing, the above script generates the below output(this output will vary on your system due to randomization) −
    [,1] [,2] [,3] [,4] [,5]
[1,] 1.30 -1.21 -0.26 0.94 1.19
[2,] 1.14 -0.77 -1.54 0.67 1.77
[3,] 0.18 -0.50 0.72 0.76 -1.58
[4,] 1.51 0.13 2.71 0.51 0.62
[5,] -1.10 0.09 0.47 0.25 0.26
[6,] 1.31 0.51 -1.79 -1.67 0.32
[7,] 0.00 0.59 0.20 0.55 -0.20
[8,] 1.25 -0.91 -1.34 1.33 0.07
[9,] -0.19 -1.39 0.09 -2.08 -1.63
[10,] 0.66 1.17 -0.66 -0.02 -0.07
[11,] 0.05 -1.31 0.55 0.68 0.97
[12,] 1.57 -2.80 1.00 -1.55 -1.90
[13,] -0.67 0.29 0.60 2.28 1.34
[14,] 0.43 -3.66 -0.23 0.41 0.69
[15,] -0.56 0.11 0.60 1.09 -1.34
[16,] 1.87 0.48 0.49 -1.00 0.91
[17,] 1.01 0.64 0.74 -0.88 1.20
[18,] 0.90 -0.43 -0.61 0.27 0.10
[19,] 1.98 -0.54 1.02 0.89 -0.52
[20,] 0.11 -1.29 2.31 -0.18 1.41
Using friedman.test function to perform the test on data in Period −
 Live Demo
Jan<-round(rnorm(20),2)
Feb<-round(rnorm(20),2)
Mar<-round(rnorm(20),2)
Apr<-round(rnorm(20),2)
May<-round(rnorm(20),2)
Time<-matrix(c(Jan,Feb,Mar,Apr,May),byrow=FALSE,nrow=20)
friedman.test(Time)
Friedman rank sum test
data: Time
Friedman chi-squared = 8.92, df = 4, p-value = 0.06313
How to change the Certificate's friendly name using PowerShell?

Suppose we know the Thumbprint of the certificate then we can use the below command to update or change the certificate's friendly name.
$cert = Get-ChildItem `
   -Path Cert:\LocalMachine\My\43E6035D120EBE9ECE8100E8F38B85A9F1C1140F
$cert.FriendlyName = "mysitecert"
The above command will update the certificate-friendly name to "mysitecert". If you don't know the thumbprint or how to retrieve it, you can use different properties like Subject name, friendly name, etc.
$cert = Get-ChildItem -path `
   Cert:\LocalMachine\My\`
   |  where{$_.Subject -eq "CN=mysite.local"}
$cert.FriendlyName = "mysitecert"
Python - Convert Lists into Similar key value lists - GeeksforGeeks

29 Aug, 2020
Given two lists, one of key and other values, convert it to dictionary with list values, if keys map to different values on basis of index, add in its value list.
Input : test_list1 = [5, 6, 6, 6], test_list2 = [8, 3, 2, 9]Output : {5: [8], 6: [3, 2, 9]}Explanation : Elements with index 6 in corresponding list, are mapped to 6.
Input : test_list1 = [6, 6, 6, 6], test_list2 = [8, 3, 2, 9]Output : {6: [8, 3, 2, 9]}Explanation : All mapped to single number.
Method #1 : Using zip() + loop
This is one of the ways in which this task can be performed. In this, we perform mapping the keys to required values using zip() and loop is used to perform iteration of keys.
Python3
# Python3 code to demonstrate working of # Convert Lists into Similar key value lists# Using loop + zip()  # initializing liststest_list1 = [5, 6, 6, 4, 5, 6] test_list2 = [8, 3, 2, 9, 10, 4]  # printing original listsprint("The original list 1 is : " + str(test_list1))print("The original list 2 is : " + str(test_list2))  # creating a mesh of keys with empty values listres = {key: [] for key in test_list1}  # loop to iterate through keys and valuesfor key, val in zip(test_list1, test_list2):    res[key].append(val)  # printing result print("The mapped dictionary : " + str(res)) 
The original list 1 is : [5, 6, 6, 4, 5, 6]
The original list 2 is : [8, 3, 2, 9, 10, 4]
The mapped dictionary : {5: [8, 10], 6: [3, 2, 4], 4: [9]}

Method #2 : Using defaultdict() + list comprehension + zip()
The combination of above functions can be used to solve this problem. In this, we perform task as one liner and defaultdict() is used to preassign values with empty lists.
Python3
# Python3 code to demonstrate working of # Convert Lists into Similar key value lists# Using defaultdict() + list comprehension + zip()from collections import defaultdict  # initializing liststest_list1 = [5, 6, 6, 4, 5, 6] test_list2 = [8, 3, 2, 9, 10, 4]  # printing original listsprint("The original list 1 is : " + str(test_list1))print("The original list 2 is : " + str(test_list2))  # creating a mesh of keys using defaultdictres = defaultdict(list)[res[key].append(val) for key, val in zip(test_list1, test_list2)]  # printing result print("The mapped dictionary : " + str(dict(res))) 
The original list 1 is : [5, 6, 6, 4, 5, 6]
The original list 2 is : [8, 3, 2, 9, 10, 4]
The mapped dictionary : {5: [8, 10], 6: [3, 2, 4], 4: [9]}

Python dictionary-programs
Python list-programs
Python
Python Programs
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 ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Defaultdict in Python
Python | Split string into list of characters
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python program to check whether a number is Prime or not
How to add column to an existing table in PostgreSQL?

The syntax to add a new column to an existing table is quite straightforward.
ALTER TABLE table_name
ADD COLUMN column_name column_type column_constraint;
Say you have existing table marks. An example is given below −
Now, suppose you want to add a column named subject. You can do that using −
ALTER TABLE marks
ADD COLUMN subject VARCHAR;
Now if you query the table again using,
SELECT * from marks
You will see the following output  −
Note that the values in the subject column are null because we have just created the column, not populated it. We can populate it using the UPDATE statements. The statement syntax is as follows −
UPDATE table_name
SET column_name = column_value
WHERE condition
For instance, if, in the above example, Yash has scored 42 marks in Maths, the UPDATE statement will look like this −
UPDATE marks
SET subject 'Maths'
WHERE roll_no = 26
You could have also added the name=’Yash’ condition instead of roll_no=26. Now, if you query the table, you will see the following output −
If you don’t add any condition in the UPDATE statement, the value of every row will be changed for that column. For instance, if I run the following query −
UPDATE marks
SET subject = 'Science'
And then query the table, I’ll see the following output −
Rust - Slices

A slice is a pointer to a block of memory. Slices can be used to access portions of data stored in contiguous memory blocks. It can be used with data structures like arrays, vectors and strings. Slices use index numbers to access portions of data. The size of a slice is determined at runtime.
Slices are pointers to the actual data. They are passed by reference to functions, which is also known as borrowing.
For example, slices can be used to fetch a portion of a string value. A sliced string is a pointer to the actual string object. Therefore, we need to specify the starting and ending index of a String. Index starts from 0 just like arrays.
let sliced_value = &data_structure[start_index..end_index]

The minimum index value is 0 and the maximum index value is the size of the data structure. NOTE that the end_index will not be included in final string.
The diagram below shows a sample string Tutorials, that has 9 characters. The index of the first character is 0 and that of the last character is 8.
The following code fetches 5 characters from the string (starting from index 4).
fn main() {
   let n1 = "Tutorials".to_string();
   println!("length of string is {}",n1.len());
   let c1 = &n1[4..9]; 
   
   // fetches characters at 4,5,6,7, and 8 indexes
   println!("{}",c1);
}
length of string is 9
rials

The main() function declares an array with 5 elements. It invokes the use_slice() function and passes to it a slice of three elements (points to the data array). The slices are passed by reference. The use_slice() function prints the value of the slice and its length.
fn main(){
   let data = [10,20,30,40,50];
   use_slice(&data[1..4]);
   //this is effectively borrowing elements for a while
}
fn use_slice(slice:&[i32]) { 
   // is taking a slice or borrowing a part of an array of i32s
   println!("length of slice is {:?}",slice.len());
   println!("{:?}",slice);
}
length of slice is 3
[20, 30, 40]

The &mut  keyword can be used to mark a slice as mutable.
fn main(){
   let mut data = [10,20,30,40,50];
   use_slice(&mut data[1..4]);
   // passes references of 
   20, 30 and 40
   println!("{:?}",data);
}
fn use_slice(slice:&mut [i32]) {
   println!("length of slice is {:?}",slice.len());
   println!("{:?}",slice);
   slice[0] = 1010; // replaces 20 with 1010
}
length of slice is 3
[20, 30, 40]
[10, 1010, 30, 40, 50]

The above code passes a mutable slice to the use_slice() function. The function modifies the second element of the original array.

    45 Lectures 
     4.5 hours 

 Stone River ELearning

    10 Lectures 
     33 mins

 Ken Burke
 Print
 Add Notes
 Bookmark this page