code-rag-bench/online-tutorials huggingface dataset:
Python | Remove last character in list of strings - GeeksforGeeks

15 Mar, 2019
Sometimes, we come across an issue in which we require to delete the last character from each string, that we might have added by mistake and we need to extend this to the whole list. This type of utility is common in web development. Having shorthands to perform this particular job is always a plus. Let’s discuss certain ways in which this can be achieved.
Method #1 : Using list comprehension + list slicingThis task can be performed by using the ability of list slicing to remove the characters and the list comprehension helps in extending that logic to whole list.
# Python3 code to demonstrate# remove last character from list of strings# using list comprehension + list slicing  # initializing listtest_list = ['Manjeets', 'Akashs', 'Akshats', 'Nikhils']  # printing original list print("The original list : " + str(test_list))  # using list comprehension + list slicing# remove last character from list of stringsres = [sub[ : -1] for sub in test_list]  # printing resultprint("The list after removing last characters : " + str(res))
The original list : ['Manjeets', 'Akashs', 'Akshats', 'Nikhils']
The list after removing last characters : ['Manjeet', 'Akash', 'Akshat', 'Nikhil']

 
Method #2 : Using map() + lambdaThe map function can perform the task of getting the functionality executed for all the members of list and lambda function performs the task of removal of last element using list comprehension.
# Python3 code to demonstrate# remove last character from list of strings# using map() + lambda  # initializing listtest_list = ['Manjeets', 'Akashs', 'Akshats', 'Nikhils']  # printing original list print("The original list : " + str(test_list))  # using map() + lambda# remove last character from list of stringsres = list(map(lambda i: i[ : -1], test_list))  # printing resultprint("The list after removing last characters : " + str(res))
The original list : ['Manjeets', 'Akashs', 'Akshats', 'Nikhils']
The list after removing last characters : ['Manjeet', 'Akash', 'Akshat', 'Nikhil']

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
Python Dictionary
Enumerate() in Python
Iterate over a list in Python
Read a file line by line in Python
Python OOPs Concepts
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
Tryit Editor v3.7

Tryit: Automatic numbering with counters
Fix ERROR 1093 (HY000): You can't specify target table for update in FROM clause while deleting the lowest value from a MySQL column?

Let us first create a table −
mysql> create table DemoTable1597
   -> (
   -> Marks int
   -> );
Query OK, 0 rows affected (0.69 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1597 values(45);
Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable1597 values(59);
Query OK, 1 row affected (0.24 sec)
mysql> insert into DemoTable1597 values(43);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable1597 values(85);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable1597 values(89);
Query OK, 1 row affected (0.12 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1597;
This will produce the following output −
+-------+
| Marks |
+-------+
|    45 |
|    59 |
|    43 |
|    85 |
|    89 |
+-------+
5 rows in set (0.00 sec)
Here is the query to remove ERROR 1093 (HY000). We are deleting the lowest value here −
mysql> delete from DemoTable1597
   -> where Marks=(
   -> select lowestMarks from ( select min(Marks) as lowestMarks from DemoTable1597 ) as deleteRecord
   -> ) limit 1;
Query OK, 1 row affected (0.11 sec)
Let us check the table records once again −
mysql> select * from DemoTable1597;
This will produce the following output −
+-------+
| Marks |
+-------+
|    45 |
|    59 |
|    85 |
|    89 |
+-------+
4 rows in set (0.00 sec)
Groovy - Relational Operators

Relational operators allow of the comparison of objects. Following are the relational operators available in Groovy −
The following code snippet shows how the various operators can be used.
class Example { 
   static void main(String[] args) { 
      def x = 5;
      def y = 10;
      def z = 8;
		
      if(x == y) { 
         println("x is equal to y"); 
      } else 
         println("x is not equal to y"); 
			
      if(z != y) { 
         println("z is not equal to y"); 
      } else 
         println("z is equal to y"); 
				
      if(z != y) { 
         println("z is not equal to y"); 
      } else 
         println("z is equal to y"); 
					
      if(z<y) { 
         println("z is less than y"); 
      } else 
         println("z is greater than y"); 
						
      if(x<=y) { 
         println("x is less than y"); 
      } else 
         println("x is greater than y"); 
			
      if(x>y) { 
         println("x is greater than y"); 
      } else 
         println("x is less than y"); 
			
      if(x>=y) { 
         println("x is greater or equal to y"); 
      } else 
         println("x is less than y"); 
   } 
} 
When we run the above program, we will get the following result. It can be seen that the results are as expected from the description of the operators as shown above.
x is not equal to y 
z is not equal to y 
z is not equal to y 
z is less than y
x is less than y 
x is less than y 
x is less than y 


    52 Lectures 
     8 hours 

 Krishna Sakinala

    49 Lectures 
     2.5 hours 

 Packt Publishing
 Print
 Add Notes
 Bookmark this page
How to declare global Variables in JavaScript?

A global variable has global scope. The scope of a variable is the region of your program in which it is defined. JavaScript variables have only two scopes.
Global Variables − A global variable has global scope which means it can be defined anywhere in your JavaScript code.
Local Variables − A local variable will be visible only within a function where it is defined. Function parameters are always local to that function.
Within the body of a function, a local variable takes precedence over a global variable with the same name. If you declare a local variable or function parameter with the same name as a global variable, you effectively hide the global variable.Here’s how you can declare a global variable −
<html>
   <body onload = checkscope();>
      <script>
         <!--
            var myVar = "global"; // Declare a global variable
            function checkscope( ) {
               var myVar = "local"; // Declare a local variable
               document.write(myVar);
            }
           //-->
      </script>
   </body>
</html>
Sort id and reverse the items with MongoDB

The $natural returns the documents in natural order. To reverse the items, use $natural:-1. Let us create a collection with documents −
> db.demo710.insertOne({id:101,Name:"Robert"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea83a855d33e20ed1097b7a")
}
> db.demo710.insertOne({id:102,Name:"Carol"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea83a8d5d33e20ed1097b7b")
}
> db.demo710.insertOne({id:103,Name:"Mike"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea83a935d33e20ed1097b7c")
}
> db.demo710.insertOne({id:104,Name:"Sam"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea83a9b5d33e20ed1097b7d")
}
Display all documents from a collection with the help of find() method −
> db.demo710.find();
This will produce the following output −
{ "_id" : ObjectId("5ea83a855d33e20ed1097b7a"), "id" : 101, "Name" : "Robert" }
{ "_id" : ObjectId("5ea83a8d5d33e20ed1097b7b"), "id" : 102, "Name" : "Carol" }
{ "_id" : ObjectId("5ea83a935d33e20ed1097b7c"), "id" : 103, "Name" : "Mike" }
{ "_id" : ObjectId("5ea83a9b5d33e20ed1097b7d"), "id" : 104, "Name" : "Sam" }
Following is the query to sort and reverse the items −
> db.demo710.find().sort({$natural:-1});
This will produce the following output −
{ "_id" : ObjectId("5ea83a9b5d33e20ed1097b7d"), "id" : 104, "Name" : "Sam" }
{ "_id" : ObjectId("5ea83a935d33e20ed1097b7c"), "id" : 103, "Name" : "Mike" }
{ "_id" : ObjectId("5ea83a8d5d33e20ed1097b7b"), "id" : 102, "Name" : "Carol" }
{ "_id" : ObjectId("5ea83a855d33e20ed1097b7a"), "id" : 101, "Name" : "Robert" }
Docker - Building Files

We created our Docker File in the last chapter. It’s now time to build the Docker File. The Docker File can be built with the following command −
docker build 

Let’s learn more about this command.
This method allows the users to build their own Docker images.
docker build  -t ImageName:TagName dir

-t − is to mention a tag to the image 
-t − is to mention a tag to the image 
ImageName − This is the name you want to give to your image.
ImageName − This is the name you want to give to your image.
TagName − This is the tag you want to give to your image.
TagName − This is the tag you want to give to your image.
Dir − The directory where the Docker File is present.
Dir − The directory where the Docker File is present.
None
sudo docker build –t myimage:0.1. 
Here, myimage is the name we are giving to the Image and 0.1 is the tag number we are giving to our image.
Since the Docker File is in the present working directory, we used "." at the end of the command to signify the present working directory.
From the output, you will first see that the Ubuntu Image will be downloaded from Docker Hub, because there is no image available locally on the machine.
Finally, when the build is complete, all the necessary commands would have run on the image.
You will then see the successfully built message and the ID of the new Image. When you run the Docker images command, you would then be able to see your new image.
You can now build containers from your new Image.

    70 Lectures 
     12 hours 

 Anshul Chauhan

    41 Lectures 
     5 hours 

 AR Shankar

    31 Lectures 
     3 hours 

 Abhilash Nelson

    15 Lectures 
     2 hours 

 Harshit Srivastava, Pranjal Srivastava

    33 Lectures 
     4 hours 

 Mumshad Mannambeth

    13 Lectures 
     53 mins

 Musab Zayadneh
 Print
 Add Notes
 Bookmark this page
How can I write a MySQL stored function that calculates the factorial of a given number?

Following is the example of a stored function that can calculate the factorial of a given number −
CREATE FUNCTION factorial (n DECIMAL(3,0))
RETURNS DECIMAL(20,0)
DETERMINISTIC
BEGIN
DECLARE factorial DECIMAL(20,0) DEFAULT 1;
DECLARE counter DECIMAL(3,0);
SET counter = n;
factorial_loop: REPEAT
SET factorial = factorial * counter;
SET counter = counter - 1;
UNTIL counter = 1
END REPEAT;
RETURN factorial;
END //

mysql> Select Factorial(5)//
+--------------+
| Factorial(5) |
+--------------+
|          120 |
+--------------+
1 row in set (0.27 sec)

mysql> Select Factorial(6)//
+--------------+
| Factorial(6) |
+--------------+
|          720 |
+--------------+
1 row in set (0.00 sec)
How to integrate Sikuli scripts into Selenium?

We can integrate Sikuli scripts into Selenium webdriver. Sikuli is an automation tool which is open-source. It has the feature to capture the images on the elements as well as perform operations on them.
Some of the advantages of Sikuli are −
Desktop or Windows applications can be automated.
Desktop or Windows applications can be automated.
Can be used for flash testing.
Can be used for flash testing.
Can be used on platforms like mobile, Mac, and Linux.
Can be used on platforms like mobile, Mac, and Linux.
It is based on image recognition technique.
It is based on image recognition technique.
Can be easily integrated with Selenium.
Can be easily integrated with Selenium.
To integrate Sikuli with Selenium, follow the below steps − Navigate to the link − https://launchpad.net/sikuli/+download.
Click on the jar to download it (which can be used for Java environments) and save it in a location.
Add the jar to the Java project in Eclipse IDE. Right−click on the project and select Properties. Then click on Java Build Path. Go to the Java Build Path tab. Click on Libraries. Then click on Add External JARs. Browse and add the Sikuli jar that we downloaded. Finally, click on Apply and Close.
Capture the image of the edit box on which we will enter Selenium with the help of Sikuli and save it in a location.
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.sikuli.script.FindFailed;
import org.sikuli.script.Pattern;
import org.sikuli.script.Screen;
public class SikuliIntegrate{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",       "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      driver.get("https://www.tutorialspoint.com/index.htm");
      // Screen class to access Sikuli methods
      Screen s = new Screen();
      //object of Pattern to specify image path
      Pattern e = new Pattern("C:\\Users\\ghs6kor\\Image.png");
      //add wait time
      s.wait(e, 5);
      //enter text and click
      s.type(e, "Selenium");
      s.click(e);
   }
}
Groovy - String Length

Syntax − The length of the string determined by the length() method of the string.
Parameters − No parameters.
Return Value − An Integer showing the length of the string.
Following is an example of the usage of strings in Groovy −
class Example {
   static void main(String[] args) {
      String a = "Hello";
      println(a.length());
   } 
}
When we run the above program, we will get the following result −
5


    52 Lectures 
     8 hours 

 Krishna Sakinala

    49 Lectures 
     2.5 hours 

 Packt Publishing
 Print
 Add Notes
 Bookmark this page
Count odd and even digits in a number in PL/SQL

We are given a positive integer of digits and the task is to calculate the count of odd and even digits in a number using PL/SQL.
PL/SQL is a combination of SQL along with the procedural features of programming languages. It was developed by Oracle Corporation in the early 90's to enhance the capabilities of SQL.
PL/SQL is one of three key programming languages embedded in the Oracle Database, along with SQL itself and Java.
Input − int number = 23146579
Output 
count of odd digits in a number are : 5
count of even digits in a number are : 3
Explanation − In the given number, we have 2, 4, 6 as an even digits therefore count of even digits in a number are 3 and we have 3, 1, 5, 7 and 9 as an odd digits therefore count of odd digits in a number are 5.
Input − int number = 4567228
Output 
count of odd digits in a number are : 2
count of even digits in a number are : 5
Explanation − In the given number, we have 5 and 7 as an odd digits therefore count of odd digits in a number are 2 and we have 4, 6, 2, 2 and 8 as an even digits therefore count of even digits in a number are 5.
Input a number in an integer type variable of datatype NUMBER used in PL/SQL.
Input a number in an integer type variable of datatype NUMBER used in PL/SQL.
Take a length of type VARCHAR(50) which describes the maximum size length can store.
Take a length of type VARCHAR(50) which describes the maximum size length can store.
Take two variables as count for odd digits and count for even digits and initially set them to 0
Take two variables as count for odd digits and count for even digits and initially set them to 0
Start Loop For from 1 till the length while pass a number to it
Start Loop For from 1 till the length while pass a number to it
Inside the loop, set length as substr(number, i, 1)
Inside the loop, set length as substr(number, i, 1)
Now, check IF mod of length by 2 is not equals to 0 then increase the count for odd digits in a number
Now, check IF mod of length by 2 is not equals to 0 then increase the count for odd digits in a number
Else, increase the count of even digits in a number
Else, increase the count of even digits in a number
Print the result.
Print the result.
DECLARE
   digits NUMBER := 23146579;
   length VARCHAR2(50);
   count_odd NUMBER(10) := 0;
   count_even NUMBER(10) := 0;
BEGIN
   FOR i IN 1..Length(digits)
   LOOP
      length := Substr(digits, i, 1);
      IF mod(length, 2) != 0 THEN
         count_odd := count_odd + 1;
      ELSE
         count_even := count_even + 1;
      END IF;
   END LOOP;
   dbms_output.Put_line('count of odd digits in a number are : ' || count_odd);
   dbms_output.Put_line('count of even digits in a number are : ' || count_even);
END;
If we run the above code it will generate the following output −
count of odd digits in a number are : 5
count of even digits in a number are : 3
Node.js Date.format() API - GeeksforGeeks

21 Jan, 2022
The date-and-time.Date.format() is a minimalist collection of functions for manipulating JS date and time module which is used to format the date according to a certain pattern. 
Required Module: Install the module by npm or used it locally.
By using npm.
npm install date-and-time --save
By using CDN link.
<script src="/path/to/date-and-time.min.js"></script>
Syntax:
format(dateObj, formatString[, utc])
Parameters: This method takes the following arguments as parameters:
dateObj: It is the object of the date.
formatString: It is the new string format in which date will be shown.
Return Value: This method returns formatted date and time.
Example 1:
index.js
// Node.js program to demonstrate the  // Date.format() method  // Importing moduleconst date = require('date-and-time')  // Creating object of current date and time // by using Date() const now  =  new Date();  // Formatting the date and time// by using date.format() methodconst value = date.format(now,'YYYY/MM/DD HH:mm:ss');  // Display the resultconsole.log("current date and time : " + value)
Run the index.js file using the following command:
node index.js
Output:
current date and time : 2021/03/07 12:13:46
Example 2:
index.js
// Node.js program to demonstrate the  // Date.format() method  // Importing moduleconst date = require('date-and-time')  // Formatting the date and time// by using date.format() methodconst value = date.format((new Date('December 17, 1995 03:24:00')),  'YYYY/MM/DD HH:mm:ss');  // Display the resultconsole.log("date and time : " + value)
Run the index.js file using the following command:
node index.js
Output:
date and time : 1995/12/17 03:24:00
Reference: https://github.com/knowledgecode/date-and-time
adnanirshad158
NodeJS date-time
NodeJS-API
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to build a basic CRUD app with Node.js and ReactJS ?
How to connect Node.js with React.js ?
Mongoose Populate() Method
Express.js req.params Property
Mongoose find() Function
Top 10 Front End Developer Skills That You Need in 2022
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
Contour hatching in Matplotlib plot

To plot contour with hatching, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Create x, y and z data points using numpy.
Flat the x and y data points.
Create a figure and a set of subplots.
Plot a contour with different hatches.
Create a colorbar for a scalar mappable instance.
To display the figure, use show() method.
import matplotlib.pyplot as plt
import numpy as np

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

x = np.linspace(-3, 5, 150).reshape(1, -1)
y = np.linspace(-3, 5, 120).reshape(-1, 1)
z = np.cos(x) + np.sin(y)

x, y = x.flatten(), y.flatten()

fig1, ax1 = plt.subplots()

cs = ax1.contourf(x, y, z, hatches=['-', '/', '\\', '//'],
                  cmap='gray', extend='both', alpha=0.5)
fig1.colorbar(cs)

plt.show()
Determine the type of an image in Python?

In this section we are going to see the type of image file we have. So consider a situation, where in a directory we have hundreds of image file and we want to get all the jgeg(or any particular image file type) file type. All this we are going to do programmatically using python.
Python provide
library to determine the type of an image, on such library is imghdr.
The python imghdr package determines the type of image contained in a file or byte stream.
There is a very much chances that if you are using python 3.6 or higher, imghdr module is an standard package and will come with python installation.
To install imghdr in your machine, just run below command in your command terminal:
pip install imghdr
After successful installation, to verify imghdr is installed properly or not just import the module in your python shell.
>>> import imghdr
>>>
In case you are getting no error, it means imghdr is installed in your machine.
The imghdr package defines the following function:
imghdr.what(filename[, h])
Filename: tests the image data contained in the file named by filename and returns a string describing the image type.
Filename: tests the image data contained in the file named by filename and returns a string describing the image type.
h: Its optional, in case h is there- then the filename is ignored and h is assumed to contain the byte stream to test.
h: Its optional, in case h is there- then the filename is ignored and h is assumed to contain the byte stream to test.
Below are the permitted image types which are recognized using imghdr package.
But we can extend the list of file types which imghdr package can recognise by appending to this variable.
This function contains list of functions performing the individual tests. Each function takes two arguments: the byte-stream and an open file-like object. However, when what() is called with a byte-stream, the file-like object will be None.
The test function will return the image type as a string else None if it failed.
>>> import imghdr
>>> imghdr.what('clock.jpg')
'jpeg'
Below is just one implementation of imghdr package, where if some particular imagefile extension is there do particular operation:
def identify_filetype(url, imageName, folderName):
   session = _setupSession()
   try:
      # time out is another parameter tuned
      image = session.get(url, timeout = 5)
      with open(os.path.join(folderName, imageName),'wb') as fout:
      fout.write(image.content)
      fileExtension = imghdr.what(os.path.join(folderName, imageName))
      if fileExtension is None:
         os.remove(os.path.join(folderName, imageName))
      else:
         newName = imageName + '.' + str(fileExtension)
         os.rename(os.path.join(folderName, imageName), os.path.join(folderName, newName))
except Exception as e:
print ("failed to download one pages with url of " + str(url))
How to create a 3D-array from data frame in R?

A 3D-array is a 3-dimensional array and it is actually a collection of 2D arrays. We can create a 3D-array of a data frame in R by using simplify2array function, this function will break the data frame into arrays that will form a 3D-array.
Consider the below data frame:
Live Demo
> set.seed(254)
> x<-sample(0:1,20,replace=TRUE)
> y<-rpois(20,5)
> z<-rpois(20,3)
> a<-rpois(20,5)
> b<-rpois(20,4)
> c<-rpois(20,8)
> df1<-data.frame(x,y,z,a,b,c)
> df1
x y z a b c
1 0 4 6 9 5 5
2 0 5 1 4 2 1
3 0 6 1 4 5 6
4 1 6 3 5 4 12
5 1 9 8 6 6 11
6 1 8 2 6 2 7
7 0 4 4 6 4 4
8 1 6 2 4 3 4
9 0 5 0 3 4 9
10 0 2 2 4 3 7
11 1 6 1 5 5 7
12 1 8 1 2 4 9
13 0 3 3 4 4 11
14 1 7 3 2 6 11
15 1 8 2 6 4 15
16 0 7 1 5 2 12
17 1 6 1 2 5 7
18 1 6 6 3 2 10
19 1 7 1 5 2 5
20 1 4 2 6 2 6
Creating 3D-array from df1:
> simplify2array(by(df1,df1$x,as.matrix))
df1$x: 0
x y z a b c
1 0 4 6 9 5 5
2 0 5 1 4 2 1
3 0 6 1 4 5 6
7 0 4 4 6 4 4
9 0 5 0 3 4 9
10 0 2 2 4 3 7
13 0 3 3 4 4 11
16 0 7 1 5 2 12
df1$x: 1
x y z a b c
4 1 6 3 5 4 12
5 1 9 8 6 6 11
6 1 8 2 6 2 7
8 1 6 2 4 3 4
11 1 6 1 5 5 7
12 1 8 1 2 4 9
14 1 7 3 2 6 11
15 1 8 2 6 4 15
17 1 6 1 2 5 7
18 1 6 6 3 2 10
19 1 7 1 5 2 5
20 1 4 2 6 2 6
Live Demo
> g1<-sample(1:4,20,replace=TRUE)
> g2<-rnorm(20,1,0.3)
> g3<-runif(20,1,2)
> g4<-rpois(20,5)
> df2<-data.frame(g1,g2,g3,g4)
> df2
g1 g2 g3 g4
1 2 1.3239241 1.467573 6
2 1 0.7099436 1.881370 3
3 4 0.9902820 1.161732 11
4 4 0.7175320 1.814506 4
5 1 0.5081105 1.162827 7
6 2 1.4972085 1.847154 8
7 4 1.5698800 1.570466 11
8 3 0.6383917 1.471682 7
9 1 1.1184017 1.003588 5
10 4 0.4746240 1.243342 11
11 1 1.1368320 1.158829 7
12 4 1.4137269 1.289525 5
13 2 0.7776044 1.070726 7
14 4 1.3936072 1.313207 5
15 4 0.6832531 1.496392 3
16 2 0.9838087 1.807298 6
17 3 1.0371888 1.039574 9
18 4 1.7064870 1.517545 6
19 3 1.0512661 1.013286 4
20 1 1.0290387 1.899809 9
> simplify2array(by(df2,df2$g1,as.matrix))
df2$g1: 1
g1 g2 g3 g4
2 1 0.7099436 1.881370 3
5 1 0.5081105 1.162827 7
9 1 1.1184017 1.003588 5
11 1 1.1368320 1.158829 7
20 1 1.0290387 1.899809 9
df2$g1: 2
g1 g2 g3 g4
1 2 1.3239241 1.467573 6
6 2 1.4972085 1.847154 8
13 2 0.7776044 1.070726 7
16 2 0.9838087 1.807298 6
df2$g1: 3
g1 g2 g3 g4
8 3 0.6383917 1.471682 7
17 3 1.0371888 1.039574 9
19 3 1.0512661 1.013286 4
df2$g1: 4
g1 g2 g3 g4
3 4 0.9902820 1.161732 11
4 4 0.7175320 1.814506 4
7 4 1.5698800 1.570466 11
10 4 0.4746240 1.243342 11
12 4 1.4137269 1.289525 5
14 4 1.3936072 1.313207 5
15 4 0.6832531 1.496392 3
18 4 1.7064870 1.517545 6
How to replace NA with 0 and other values to 1 in an R data frame column?

Sometimes we want to convert a column of an R data frame to binary column using 0 and 1, it is especially done in situations where we have some NAs in the column of the data frame and the other values can be converted to 1 due to some characteristics. To replace NA with 0 and other values to 1, we can use ifelse function.
 Live Demo
Consider the below data frame −
x1<−1:20
x2<−sample(c(NA,rnorm(5)),20,replace=TRUE)
df1<−data.frame(x1,x2)
df1
x1 x2
1 1 1.6562106
2 2 NA
3 3 2.2323438
4 4 2.2323438
5 5 1.2038679
6 6 2.2323438
7 7 NA
8 8 1.6562106
9 9 NA
10 10 1.2038679
11 11 −0.6898052
12 12 2.2323438
13 13 2.2323438
14 14 1.6562106
15 15 NA
16 16 1.2038679
17 17 NA
18 18 −0.6898052
19 19 2.2323438
20 20 2.2323438
Replacing NAs with 0 and other values to 1 in column x2 −
df1$x2<−ifelse(is.na(df1$x2),0,1)
df1
x1 x2
1 1 1
2 2 0
3 3 1
4 4 1
5 5 1
6 6 1
7 7 0
8 8 1
9 9 0
10 10 1
11 11 1
12 12 1
13 13 1
14 14 1
15 15 0
16 16 1
17 17 0
18 18 1
19 19 1
20 20 1
 Live Demo
y1<−LETTERS[1:20]
y2<−sample(c(NA,rpois(5,2)),20,replace=TRUE)
df2<−data.frame(y1,y2)
df2
y1 y2
1 A 2
2 B 5
3 C NA
4 D 3
5 E 1
6 F NA
7 G 1
8 H 3
9 I 5
10 J 5
11 K NA
12 L NA
13 M 2
14 N 5
15 O 3
16 P 2
17 Q 2
18 R 1
19 S 2
20 T NA
Replacing NAs with 0 and other values to 1 in column y2 −
df2$y2<−ifelse(is.na(df2$y2),0,1)
df2
y1 y2
1 A 1
2 B 1
3 C 0
4 D 1
5 E 1
6 F 0
7 G 1
8 H 1
9 I 1
10 J 1
11 K 0
12 L 0
13 M 1
14 N 1
15 O 1
16 P 1
17 Q 1
18 R 1
19 S 1
20 T 0
Redis - String Get Command

Redis GET command is used to get the value stored in the specified key. If the key does not exist, then nil is returned. If the returned value is not a string, then error is returned.
Simple string reply. Value or key or nil.
Following is the basic syntax of Redis GET command.
redis 127.0.0.1:6379> GET KEY_NAME

First, set a key in Redis and then get it.
redis 127.0.0.1:6379> SET tutorialspoint redis 
OK 
redis 127.0.0.1:6379> GET tutorialspoint 
"redis" 


    22 Lectures 
     40 mins

 Skillbakerystudios
 Print
 Add Notes
 Bookmark this page
Convert short to String in Java

The valueOf() method is used in Java to convert short to string.
Let’s say we have the following short value.
short val = 20;
Converting the above short value to string.
String.valueOf(val);
 Live Demo
public class Demo {
   public static void main(String[] args) {
      short shortVal = 55;
      // converting short to String
      String str = String.valueOf(shortVal);
      System.out.println("String: "+str);
   }
}
String: 55
Binomial Coefficient in C++

Binomial coefficient denoted as c(n,k) or ncr is defined as coefficient of xk in the binomial expansion of (1+X)n.
The Binomial coefficient also gives the value of the number of ways in which k items are chosen from among n objects i.e. k-combinations of n-element set. The order of selection of items not considered.
Here, we are given two parameters n and k and we have to return the value of binomial coefficient nck .
Input : n = 8 and k = 3
Output : 56
There can be multiple solutions to this problem,
There is a method to calculate the value of c(n,k) using a recursive call. The standard formula for finding the value of binomial coefficients that uses recursive call is −
c(n,k) = c(n-1 , k-1) + c(n-1, k)
c(n, 0) = c(n, n) = 1
The implementation of a recursive call that uses the above formula −
#include <iostream>
using namespace std;
int binomialCoefficients(int n, int k) {
   if (k == 0 || k == n)
   return 1;
   return binomialCoefficients(n - 1, k - 1) + binomialCoefficients(n - 1, k);
}
int main() {
   int n=8 , k=5;
   cout<<"The value of C("<<n<<", "<<k<<") is "<<binomialCoefficients(n, k);
   return 0;
}
The value of C(8, 5) is 56
Another solution might be using overlapping subproblem. So, we will use dynamic programming algorithm to avoid subproblem.
#include <bits/stdc++.h>>
using namespace std;
int binomialCoefficients(int n, int k) {
   int C[k+1];
   memset(C, 0, sizeof(C));
   C[0] = 1;
   for (int i = 1; i <= n; i++) {
      for (int j = min(i, k); j > 0; j--)
         C[j] = C[j] + C[j-1];
   }
   return C[k];
}
int main() {
   int n=8, k=5;
   cout<<"The value of C("<<n<<", "<<k<<") is "<<binomialCoefficients(n,k);
   return 0;
}
The value of C(8, 5) is 56
How to subtract days from a date in JavaScript?

To subtract days to a JavaScript Date object, use the setDate() method. Under that, get the current days and subtract days. JavaScript date setDate() method sets the day of the month for a specified date according to local time.
You can try to run the following code to subtract 10 days from the current date.
 Live Demo
<html>
   <head>
      <title>JavaScript setDate Method</title>
   </head>
   <body>
      <script>
         var dt = new Date("December 30, 2017 11:20:25");
         dt.setDate( dt.getDate() - 10 );
         document.write( dt );
      </script>
   </body>
</html>
Wed Dec 20 2017 11:20:25 GMT+0530 (India Standard Time)
Recursive factorial method in Java

The factorial of any non-negative integer is basically the product of all the integers that are smaller than or equal to it. The factorial can be obtained using a recursive method.
A program that demonstrates this is given as follows:
 Live Demo
public class Demo {
   public static long fact(long n) {
      if (n <= 1)
         return 1;
      else
         return n * fact(n - 1);
   }
   public static void main(String args[]) {
      System.out.println("The factorial of 6 is: " + fact(6));
      System.out.println("The factorial of 0 is: " + fact(0));
   }
}
The factorial of 6 is: 720
The factorial of 0 is: 1
Now let us understand the above program.
The method fact() calculates the factorial of a number n. If n is less than or equal to 1, it returns 1. Otherwise it recursively calls itself and returns n * fact(n - 1). A code snippet which demonstrates this is as follows:
public static long fact(long n) {
   if (n <= 1)
      return 1;
   else
      return n * fact(n - 1);
}
In main(), the method fact() is called with different values. A code snippet which demonstrates this is as follows:
public static void main(String args[]) {
   System.out.println("The factorial of 6 is: " + fact(6));
   System.out.println("The factorial of 0 is: " + fact(0));
}
Boolean.ToString() Method in C#

The Boolean.ToString() method in C# converts the value of this instance to its equivalent string representation (either "True" or "False").
Following is the syntax −
public override string ToString ();
Let us now see an example to implement the Boolean.ToString() method −
using System;
public class Demo {
   public static void Main(){
      bool b = true;
      string res = b.ToString();
      Console.WriteLine("Return Value = "+res);
   }
}
This will produce the following output −
Return Value = True
Let us now see another example to implement the Boolean.ToString() method −
using System;
public class Demo {
   public static void Main(){
      bool b = false;
      string res = b.ToString();
      Console.WriteLine("Return Value = "+res);
   }
}
This will produce the following output −
Return Value = False
How to create pill buttons with CSS?

Following is the code to create pill buttons −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
button {
   font-family: "Lucida Sans", "Lucida Sans Regular", "Lucida Grande",
"Lucida Sans Unicode", Geneva, Verdana, sans-serif;
   background-color: rgb(193, 255, 236);
   border: none;
   color: rgb(0, 0, 0);
   padding: 10px 20px;
   text-align: center;
   text-decoration: none;
   display: inline-block;
   margin: 4px 2px;
   cursor: pointer;
   font-size: 30px;
   border-radius: 32px;
}
button:hover {
   background-color: #9affe1;
}
</style>
</head>
<body>
<h1>Pill Buttons Example</h1>
<button>Button 1</button>
<button>Button 2</button>
<div></div>
<button>Button 3</button>
<button>Button 4</button>
</body>
</html>
The above code will produce the following output −
C++ Memory Library - make_shared

It constructs an object of type T passing args to its constructor, and returns an object of type shared_ptr that owns and stores a pointer to it.
Following is the declaration for std::make_shared.
template <class T, class... Args>
   shared_ptr<T> make_shared (Args&&... args);
template <class T, class... Args>
   shared_ptr<T> make_shared (Args&&... args);
args − It is a list of zero or more types.
It returns a shared_ptr object.
noexcep − It doesn't throw any exceptions.
In below example explains about std::minus.
#include <iostream>
#include <memory>

int main () {

   std::shared_ptr<int> foo = std::make_shared<int> (100);
   std::shared_ptr<int> foo2 (new int(100));

   auto bar = std::make_shared<int> (200);

   auto baz = std::make_shared<std::pair<int,int>> (300,400);

   std::cout << "*foo: " << *foo << '\n';
   std::cout << "*bar: " << *bar << '\n';
   std::cout << "*baz: " << baz->first << ' ' << baz->second << '\n';

   return 0;
}
Let us compile and run the above program, this will produce the following result −
*foo: 100
*bar: 200
*baz: 300 400

 Print
 Add Notes
 Bookmark this page
While chaining, can we throw unchecked exception from a checked exception in java?

When an exception is cached in a catch block, you can re-throw it using the throw keyword (which is used to throw the exception objects).
While re-throwing exceptions you can throw the same exception as it is with out adjusting it as −
try {
   int result = (arr[a])/(arr[b]);
   System.out.println("Result of "+arr[a]+"/"+arr[b]+": "+result);
}catch(ArithmeticException e) {
   throw e;
}
Or, wrap it within a new exception and throw it. When you wrap a cached exception within another exception and throw it, it is known as exception chaining or, exception wrapping, by doing this you can adjust your exception, throwing higher level of exception maintaining the abstraction.
try {
   int result = (arr[a])/(arr[b]);
   System.out.println("Result of "+arr[a]+"/"+arr[b]+": "+result);
}catch(ArrayIndexOutOfBoundsException e) {
   throw new IndexOutOfBoundsException();
}
Yes, we can catch compile time exception (checked) and in the catch block we can wrap it with in a run time exception (unchecked) and re-throw it. But since we are re-throwing using checked exception we need to either wrap it inside an implicit try-catch pair or, skip handling it using the throws clause.
In the following Java example we have created a user defined (checked) exception named SampleException.
We are displaying an integer array of 6 elements and letting user to select the position of the two values and dividing the selected numbers. While choosing the position the user my use index value, beyond the length of the array, which causes an ArrayIndexOutOfBoundsException which is unchecked exception.
In the catch block we are re-throwing this object by wrapping it with in the above created Sample exception, which is checked.
import java.util.Arrays;
import java.util.Scanner;
class SampleException extends Exception {
   SampleException(String msg){
      super(msg);
   }
}
public class Rethrow {
   public void demoMethod() {
      Scanner sc = new Scanner(System.in);
      int[] arr = {10, 20, 30, 2, 5, 8};
      System.out.println("Array: "+Arrays.toString(arr));
      System.out.println("Choose numerator and denominator(not 0) from this array (enter positions 0 to 5)");
      int a = sc.nextInt();
      int b = sc.nextInt();
      try {
         int result = (arr[a])/(arr[b]);
         System.out.println("Result of "+arr[a]+"/"+arr[b]+": "+result);
      }catch(ArrayIndexOutOfBoundsException e) {
         try {
            throw new SampleException("This is a checked exception");
         } catch (SampleException e1) {
            System.out.println("Checked exception in the catch block");
         }
      }
   }
   public static void main(String [] args) {
      new Rethrow().demoMethod();
   }
}
Array: [10, 20, 30, 2, 0, 8]
Choose numerator and denominator(not 0) from this array (enter positions 0 to 5)
25
24
Checked exception in the catch block
C# Program to perform all Basic Arithmetic Operations

Basic Arithmetic Operators in C#, include the following −
To add, use the Addition Operator −
num1 + num2;
In the same way, it works for Subtraction, Multiplication, Division, and other operators.
Let us see a complete example to learn how to implement Arithmetic operators in C#.
Live Demo
using System;
namespace Sample {
   class Demo {
      static void Main(string[] args) {
         int num1 = 50;
         int num2 = 25;
         int result;
         result = num1 + num2;
         Console.WriteLine("Value is {0}", result);
         result = num1 - num2;
         Console.WriteLine("Value is {0}", result);
         result = num1 * num2;
         Console.WriteLine("Value is {0}", result);
         result = num1 / num2;
         Console.WriteLine("Value is {0}", result);
         result = num1 % num2;
         Console.WriteLine("Value is {0}", result);
         result = num1++;
         Console.WriteLine("Value is {0}", result);
         result = num1--;
         Console.WriteLine("Value is {0}", result);
         Console.ReadLine();
      }
   }
}
Value is 75
Value is 25
Value is 1250
Value is 2
Value is 0
Value is 50
Value is 51
How to import local json file data to my JavaScript variable?

We have an employee.json file in a directory, within the same directory we have a js file, in
which we want to import the content of the json file.
The content of employees.json −
employees.json
"Employees" : [
   {
      "userId":"ravjy", "jobTitleName":"Developer", "firstName":"Ran","lastName":"Vijay",
      "preferredFullName":"Ran Vijay","employeeCode":"H9","region":"DL","phoneNumber":"34567689",
      "emailAddress":"ranvijay.k.ran@gmail.com"
   },
   {
      "userId":"mrvjy","jobTitleName":"Developer","firstName":"Murli","lastName":"Vijay",
      "preferredFullName":"Murli Vijay","employeeCode":"A2","region":"MU",
      "phoneNumber":"6543565","emailAddress":"murli@vijay.com"
      }
   ]
}
We can use any of the two ways to access the json file −
Code to access employees.json using require module −
const data = require('./employees.json');
console.log(data);
Code to access employees.json using fetch function −
fetch("./employees.json")
.then(response => {
   return response.json();
})
.then(data => console.log(data));
Note − While the first function is better suited for node environment, the second function only works in the web environment because the fetch API is only accessible in the web environment.
After running any of the above using require or fetch function, the console output is as follows −
{
   Employees: [
      {
         userId: 'ravjy',
         jobTitleName: 'Developer',
         firstName: 'Ran',
         lastName: 'Vijay',
         preferredFullName: 'Ran Vijay',
         employeeCode: 'H9',
         region: 'DL',
         phoneNumber: '34567689',
         emailAddress: 'ranvijay.k.ran@gmail.com'
      },
      {
         userId: 'mrvjy',
         jobTitleName: 'Developer',
         firstName: 'Murli',
         lastName: 'Vijay',
         preferredFullName: 'Murli Vijay',
         employeeCode: 'A2',
         region: 'MU',
         phoneNumber: '6543565',
         emailAddress: 'murli@vijay.com'
      }
   ]
}
Add DATE and TIME fields to get DATETIME field in MySQL?

You can use CONCAT() function to set date and time fields to get DATETIME field.
Let us create a demo table
mysql> create table getDateTimeFieldsDemo
   -> (
   -> ShippingDate date,
   -> ShippingTime time,
   -> Shippingdatetime datetime
   -> );
Query OK, 0 rows affected (0.50 sec)
Insert some records in the table using insert command. The query is as follows −
mysql> insert into getDateTimeFieldsDemo(ShippingDate,ShippingTime) values('2018-01-21','09:45:34');
Query OK, 1 row affected (0.16 sec)
mysql> insert into getDateTimeFieldsDemo(ShippingDate,ShippingTime) values('2013-07-26','13:21:20');
Query OK, 1 row affected (0.13 sec)
mysql> insert into getDateTimeFieldsDemo(ShippingDate,ShippingTime) values('2017-12-31','15:31:40');
Query OK, 1 row affected (0.17 sec)
mysql> insert into getDateTimeFieldsDemo(ShippingDate,ShippingTime) values('2019-03-07','12:13:34');
Query OK, 1 row affected (0.41 sec)
Display all records from the table using select statement. The query is as follows −
mysql> select *from getDateTimeFieldsDemo;
The following is the output
+--------------+--------------+------------------+
| ShippingDate | ShippingTime | Shippingdatetime |
+--------------+--------------+------------------+
| 2018-01-21   | 09:45:34     | NULL             |
| 2013-07-26   | 13:21:20     | NULL             |
| 2017-12-31   | 15:31:40     | NULL             |
| 2019-03-07   | 12:13:34     | NULL             |
+--------------+--------------+------------------+
4 rows in set (0.00 sec)
Here is the query to add DATE and TIME fields to get DATETIME field in MySQL
mysql> update getDateTimeFieldsDemo set Shippingdatetime=concat(ShippingDate," ",ShippingTime);
Query OK, 4 rows affected (0.09 sec)
Rows matched: 4 Changed: 4 Warnings: 0
Now check table records once again. The query is as follows −
mysql> select *from getDateTimeFieldsDemo;
The following is the output
+--------------+--------------+---------------------+
| ShippingDate | ShippingTime | Shippingdatetime    |
+--------------+--------------+---------------------+
| 2018-01-21   | 09:45:34     | 2018-01-21 09:45:34 |
| 2013-07-26   | 13:21:20     | 2013-07-26 13:21:20 |
| 2017-12-31   | 15:31:40     | 2017-12-31 15:31:40 |
| 2019-03-07   | 12:13:34     | 2019-03-07 12:13:34 |
+--------------+--------------+---------------------+
4 rows in set (0.00 sec)
__attribute__((constructor)) and __attribute__((destructor)) syntaxes in C - GeeksforGeeks

02 Jun, 2017
Write two functions in C using GCC compiler, one of which executes before main function and other executes after the main function.
GCC specific syntaxes :
1. __attribute__((constructor)) syntax : This particular GCC syntax, when used with a function, executes the same function at the startup of the program, i.e before main() function.
2. __attribute__((destructor)) syntax : This particular GCC syntax, when used with a function, executes the same function just before the program terminates through _exit, i.e after main() function.
Explanation :The way constructors and destructors work is that the shared object file contains special sections (.ctors and .dtors on ELF) which contain references to the functions marked with the constructor and destructor attributes, respectively. When the library is loaded/unloaded, the dynamic loader program checks whether such sections exist, and if so, calls the functions referenced therein.
Few points regarding these are worth noting :1. __attribute__((constructor)) runs when a shared library is loaded, typically during program startup.2. __attribute__((destructor)) runs when the shared library is unloaded, typically at program exit.3. The two parentheses are presumably to distinguish them from function calls.4. __attribute__ is a GCC specific syntax;not a function or a macro.
Driver code :
// C program to demonstrate working of// __attribute__((constructor)) and// __attribute__((destructor))#include<stdio.h>  // Assigning functions to be executed before and// after main()void __attribute__((constructor)) calledFirst();void __attribute__((destructor)) calledLast();  void main(){    printf("\nI am in main");}  // This function is assigned to execute before// main using __attribute__((constructor))void calledFirst(){    printf("\nI am called first");}  // This function is assigned to execute after// main using __attribute__((destructor))void calledLast(){    printf("\nI am called last");}
Output:
I am called first
I am in main
I am called last

This article is contributed by Rishav Raj. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
C-Library
CPP-Library
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
TCP Server-Client implementation in C
Exception Handling in C++
Multithreading in C
Arrow operator -> in C/C++ with Examples
'this' pointer in C++
Vector in C++ STL
Initialize a vector in C++ (6 different ways)
Map in C++ Standard Template Library (STL)
Inheritance in C++
Constructors in C++
How to access nested Python dictionary items via a list of keys?

The easiest and most readable way to access nested properties in a Python dict is to use for loop and loop over each item while getting the next value, until the end. 
def getFromDict(dataDict, mapList):
for k in mapList: dataDict = dataDict[k]
return dataDict
a = {
   'foo': 45,'bar': {
      'baz': 100,'tru': "Hello"
   }
}
print(getFromDict(a, ["bar", "baz"]))
This will give the output −
100
Logo - Strings

Any sequence of alpha-numeric characters, for example – “america”, “emp1234”, etc. are examples of a string. Counting the characters is the most basic of all string processes. The answer to the question stringlength "abc12ef is given by the following procedure −
to stringlength :s
   make "inputstring :s
   make "count 0
   while [not emptyp :s] [
      make "count :count + 1
      print first :s
      make "s butfirst :s
   ]
   print (sentence :inputstring "has :count "letters)
end
In the above procedure –‘s’ is the variable containing the input string. Variable inputstring contains the copy of the input string. Variable count is initialized with 0. In the while loop, the condition checks whether the string has become empty or not. In each loop count, a variable is being increased by 1 to hold the length count. The statement print first :s, prints the first character only of the string stored in ‘s’.
The statement make "s butfirst :s, retrieves the sub-string excluding the first character. After exiting from the while-loop, we have printed the character count or the length of the input string. Following is the execution and output of the code.

    48 Lectures 
     6 hours 

 Arnab Chakraborty

    38 Lectures 
     2.5 hours 

 Rob Cubbon

    81 Lectures 
     7.5 hours 

 YouAccel

    8 Lectures 
     34 mins

 Yash Rajoliya
 Print
 Add Notes
 Bookmark this page