code-rag-bench/online-tutorials huggingface dataset:
Accessing all elements at given Python list of indexes

We can access the individual elements of a list using the [] brackets and the index number. But when we need to access some of the indices then we cannot apply this method. We need the below approaches to tackle this.
In this method, along with the original list, we take the indices as another list. Then we use a for loop to iterate through the indices and supply those values to the main list for retrieving the values.
 Live Demo
given_list = ["Mon","Tue","Wed","Thu","Fri"]
index_list = [1,3,4]

# printing the lists
print("Given list : " + str(given_list))
print("List of Indices : " + str(index_list))

# use list comprehension
res = [given_list[n] for n in index_list]

# Get the result
print("Result list : " + str(res))
Running the above code gives us the following result −
Given list : ['Mon', 'Tue', 'Wed', 'Thu', 'Fri']
List of Indices : [0, 1, 2, 3, 4]
Result list : ['Tue', 'Thu', 'Fri']
Instead of using the for loop above we can also use the map as well as getitem method to get the same result.
 Live Demo
given_list = ["Mon","Tue","Wed","Thu","Fri"]
index_list = [1, 3,4]

# printing the lists
print("Given list : " + str(given_list))
print("List of Indices : " + str(index_list))

# use list comprehension
res = list(map(given_list.__getitem__,index_list))

# Get the result
print("Result list : " + str(res))
Running the above code gives us the following result −
Given list : ['Mon', 'Tue', 'Wed', 'Thu', 'Fri']
List of Indices : [1, 3, 4]
Result list : ['Tue', 'Thu', 'Fri']
How to create barplot from data frame in R using rows as categories?

If we have small number of rows then we might want to create bar plot for rows instead of using columns as categories. This can be done by using barplot function but we need to convert the data frame to matrix and take the transpose of it. For example, if we have a data frame data_frame with 4 rows and 4 columns, then the barplot with rows as categories can be created as barplot(t(as.matrix(data_frame)),beside=TRUE)
Consider the below data frame −
 Live Demo
x1<-c(14,15,21,17,16)
x2<-c(24,21,15,18,25)
x3<-c(21,17,16,19,20)
x4<-c(19,27,24,18,20)
df<-data.frame(x1,x2,x3,x4)
df
  x1 x2 x3 x4
1 14 24 21 19
2 15 21 17 27
3 21 15 16 24
4 17 18 19 18
5 16 25 20 20
Creating the barplot by treating rows as categories −
barplot(t(as.matrix(df)),beside=TRUE)
Let’s have a look at another example −
 Live Demo
y1<-sample(51:99,4)
y2<-sample(51:99,4)
y3<-sample(51:99,4)
df_y<-data.frame(y1,y2,y3)
df_y
  y1 y2 y3
1 80 67 72
2 66 56 60
3 70 69 80
4 73 87 61
Creating the barplot by treating rows as categories −
barplot(t(as.matrix(df_y)),beside=TRUE)
Combining tuples in list of tuples in Python

For data analysis, we sometimes take a combination of data structures available in python. A list can contain tuples as its elements. In this article we will see how we can combine each element of a tuple with another given element and produce a list tuple combination.
In the below approach we create for loops that will create a pair of elements by taking each element of the tuple and looping through the element in the list.
 Live Demo
Alist = [([2, 8, 9], 'Mon'), ([7, 5, 6], 'Wed')]
# Given list of tuple
print("List of tuples : \n",Alist)
# Combine tuples in list of tuples
res = [(t1, t2) for i, t2 in Alist for t1 in i]
# print result
print("The list tuple combination : \n" ,res)
Running the above code gives us the following result −
List of tuples :
[([2, 8, 9], 'Mon'), ([7, 5, 6], 'Wed')]
The list tuple combination :
[(2, 'Mon'), (8, 'Mon'), (9, 'Mon'), (7, 'Wed'), (5, 'Wed'), (6, 'Wed')]
The itertools module has iterator named product which creates Cartesian product of parameters passed onto it. In this example we design for loops to go through each element of the tuple and form a pair with the non-list element in the tuple.
 Live Demo
from itertools import product
Alist = [([2, 8, 9], 'Mon'), ([7, 5, 6], 'Wed')]
# Given list of tuple
print("List of tuples : \n",Alist)
# Combine tuples in list of tuples
res = [x for i, j in Alist for x in product(i, [j])]
# print result
print("The list tuple combination : \n" ,res)
Running the above code gives us the following result −
List of tuples :
[([2, 8, 9], 'Mon'), ([7, 5, 6], 'Wed')]
The list tuple combination :
[(2, 'Mon'), (8, 'Mon'), (9, 'Mon'), (7, 'Wed'), (5, 'Wed'), (6, 'Wed')]
Do..Until Loops in VBScript

A Do..Until loop is used when we want to repeat a set of statements as long as the condition is false. The Condition may be checked at the beginning of the loop or at the end of loop.
The syntax of a Do..Until loop in VBScript is −
Do Until condition
   [statement 1]
   [statement 2]
   ...
   [statement n]
   [Exit Do]
   [statement 1]
   [statement 2]
   ...
   [statement n]
Loop           

The below example uses Do..Until loop to check the condition at the beginning of the loop. The Statements inside the loop are executed only if the condition is false. It exits out of the loop when the condition becomes true.
<!DOCTYPE html>
<html>
   <body>
      <script language = "vbscript" type = "text/vbscript">
         i = 10
         Do Until i>15  'Condition is False.Hence loop will be executed
            i = i + 1
            Document.write("The value of i is : " & i)
            Document.write("<br></br>")
         Loop 

      </script>
   </body>
</html>
When the above code is executed, it prints the following output in the console.
The value of i is : 11

The value of i is : 12

The value of i is : 13

The value of i is : 14

The value of i is : 15

The value of i is : 16

There is also an alternate Syntax for Do..Until loop which checks the condition at the end of the loop. The Major difference between these two syntax is explained below with an example.
Do 
   [statement 1]
   [statement 2]
   ...
   [statement n]
   [Exit Do]
   [statement 1]
   [statement 2]
   ...
   [statement n]
Loop Until condition

The below example uses Do..Until loop to check the condition at the end of the loop. The Statements inside the loop are executed at least once even if the condition is True.
<!DOCTYPE html>
<html>
   <body>
      <script language = "vbscript" type = "text/vbscript">        
         i = 10
         Do 
            i = i + 1
            Document.write("The value of i is : " & i)
            Document.write("<br></br>")
         Loop Until i<15 'Condition is True.Hence loop is executed once.
         
      </script>
   </body>
</html>
When the above code is executed, it prints the following output in the console.
The value of i is : 11


    63 Lectures 
     4 hours 

 Frahaan Hussain
 Print
 Add Notes
 Bookmark this page
killall - Unix, Linux Command

Signals can be specified either by name (e.g. -HUP) or by number
(e.g. -1) or by option -s.


If the command name is not regular expression (option -r)
and contains a slash (/), processes executing that
particular file will be selected for killing, independent of their name.


killall returns a zero return code if at least one process has been
killed for each listed command, or no commands were listed and at least
one process matched the -u and -Z search criteria. killall returns
non-zero otherwise.


A killall process never kills itself (but may kill other killall
processes).

/proc   location of the proc file system


Be warned that typing killall name may not have the desired
effect on non-Linux systems, especially when done by a privileged
user.


killall -w doesn’t detect if a process disappears and is replaced by
a new process with the same PID between scans.


If processes change their name, killall may not be able to match
them correctly.

kill (1)
kill (1)
ps (2)
ps (2)

Advertisements


    129 Lectures 
     23 hours 

 Eduonix Learning Solutions

    5 Lectures 
     4.5 hours 

 Frahaan Hussain

    35 Lectures 
     2 hours 

 Pradeep D

    41 Lectures 
     2.5 hours 

 Musab Zayadneh

    46 Lectures 
     4 hours 

 GUHARAJANM

    6 Lectures 
     4 hours 

 Uplatz
 Print
 Add Notes
 Bookmark this page
Python - Building URLs

The requests module can help us build the URLS and manipulate the URL value dynamically. Any sub-directory of the URL can be fetched programmatically and then
some part of it can be substituted with new values to build new URLs. 
The below example uses urljoin to fetch the different subfolders in the URL path. The urljoin method is used to add new values to the base URL.
from requests.compat import urljoin
base='https://stackoverflow.com/questions/3764291'
print urljoin(base,'.')
print urljoin(base,'..')
print urljoin(base,'...')
print urljoin(base,'/3764299/')
url_query = urljoin(base,'?vers=1.0')
print url_query
url_sec = urljoin(url_query,'#section-5.4')
print url_sec
When we run the above program, we get the following output −
https://stackoverflow.com/questions/
https://stackoverflow.com/
https://stackoverflow.com/questions/...
https://stackoverflow.com/3764299/
https://stackoverflow.com/questions/3764291?vers=1.0
https://stackoverflow.com/questions/3764291?vers=1.0#section-5.4

The URLs can also be split into many parts beyond the main address. The additional parameters which are used for a specific query or tags attached to the URL are separated by using the
urlparse method as shown below.
from requests.compat import urlparse
url1 = 'https://docs.python.org/2/py-modindex.html#cap-f'
url2='https://docs.python.org/2/search.html?q=urlparse'
print urlparse(url1)
print urlparse(url2)
When we run the above program, we get the following output −
ParseResult(scheme='https', netloc='docs.python.org', path='/2/py-modindex.html', params='', query='', fragment='cap-f')
ParseResult(scheme='https', netloc='docs.python.org', path='/2/search.html', params='', query='q=urlparse', fragment='')


    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 to disable a Combobox in Tkinter?

The Combobox widget is similar to the OptionMenu widget in Tkinter which gives the user a choice to select from the group of options. The Combobox widget allows users to select the option with an Entry widget that adds selected menu items from the dropdown list.
We can Enable or Disable the options in the given Combobox widget by providing the state property. The state property forces to make a widget either active or disabled. To disable the Combobox widget, we have to set the state property as readonly or disabled.
#Import the required Libraries
from tkinter import *
from tkinter import ttk

#Create an instance of Tkinter frame
win = Tk()

#Set the geometry of Tkinter Frame
win.geometry("750x250")

#Define a Label widget
Label(win, text= "Select an Option from the List", font=('Aerial', 14, 'bold')).pack(pady=15)

#Create a Combobox with list of items
var= StringVar()
my_combobox= ttk.Combobox(win, textvariable=var, values=["High", "Mid","Low"], state= 'disabled')
my_combobox.pack()

#Create a Button widget
win.mainloop()
In the above code snippet, we have disabled the Combobox widget by disabling the state. Now, to make the widget fully functional, just change the state of the widget using state= ‘normal’.
Difference between var and dynamic in C#

24 Aug, 2020
Implicitly Typed Local Variables – var are those variables which are declared without specifying the .NET type explicitly. In implicitly typed variable, the type of the variable is automatically deduced at compile time by the compiler from the value used to initialize the variable. The implicitly typed variable concept is introduced in C# 3.0. The implicitly typed variable is not designed to replace the normal variable declaration, it is designed to handle some special-case situation like LINQ(Language-Integrated Query).
Example:
// C# program to illustrate the concept// of the implicitly typed variableusing System;  class GFG {      // Main method    static public void Main()    {          // Creating and initializing        // implicitly typed variables        // Using var keyword        var a = 'f';        var b = "GeeksforGeeks";        var c = 30.67d;        var d = false;        var e = 54544;          // Display the type        Console.WriteLine("Type of 'a' is : {0} ", a.GetType());          Console.WriteLine("Type of 'b' is : {0} ", b.GetType());          Console.WriteLine("Type of 'c' is : {0} ", c.GetType());          Console.WriteLine("Type of 'd' is : {0} ", d.GetType());          Console.WriteLine("Type of 'e' is : {0} ", e.GetType());    }}
Output:
Type of 'a' is : System.Char 
Type of 'b' is : System.String 
Type of 'c' is : System.Double 
Type of 'd' is : System.Boolean 
Type of 'e' is : System.Int32 

In C# 4.0, a new type is introduced that is known as a dynamic type. It is used to avoid the compile-time type checking. The compiler does not check the type of the dynamic type variable at compile time, instead of this, the compiler gets the type at the run time. The dynamic type variable is created using dynamic keyword.
Example:
// C# program to illustrate how to get the// actual type of the dynamic type variableusing System;  class GFG {      // Main Method    static public void Main()    {          // Dynamic variables        dynamic val1 = "GeeksforGeeks";        dynamic val2 = 3234;        dynamic val3 = 32.55;        dynamic val4 = true;          // Get the actual type of        // dynamic variables        // Using GetType() method        Console.WriteLine("Get the actual type of val1: {0}",                                  val1.GetType().ToString());          Console.WriteLine("Get the actual type of val2: {0}",                                  val2.GetType().ToString());          Console.WriteLine("Get the actual type of val3: {0}",                                  val3.GetType().ToString());          Console.WriteLine("Get the actual type of val4: {0}",                                  val4.GetType().ToString());    }}
Output:
Get the actual type of val1: System.String
Get the actual type of val2: System.Int32
Get the actual type of val3: System.Double
Get the actual type of val4: System.Boolean

Below are some differences between var and dynamic keyword in C#:
vishalsingh80
CSharp-keyword
C#
Difference Between
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Ways to remove TLE

14 Sep, 2021
While solving problems on any online judge sometimes it might get Time Limit Exceeded. Below are some of the ways to optimize the code:
Minimize the use of loops inside loops i.e., Nested Loops: For Example:
     for(i = 0 ; i < n ; i++)
     {
           for(j = 0 ; j < n ; j++)
           {
                // Your Code
           }
      }
The above code will perform N*N iterations and will take more time, to avoid this, the idea is to think of an approach that minimizes the use of loops inside loops.
Don’t prefer a long chain of if-else, instead prefer to use Switch Statements: For Example:
if(condition 1)
{

}
else
{
   if(condition 2)
   {

   }
   else
   {
   
   }
}
Suppose there is another condition 3, then the flow of code is to first check condition 1, then condition 2 then it will reach condition 3. Therefore, it requires 3 number of operation. The idea is to use the below code:
switch (c)
{
    // Condition 1
    case 1:
       break;

    // Condition 2
    case 2 :
       break;

       // And so on
}
In the switch case, the compiler will directly go to the condition and execute them without executing the other conditions.
Instead of using “i = i + 1“, prefer using “++i”, and instead of “i = i + 3“, use “i +=3“.
Better prefer pre-increment or pre-decrement over post-increment and post-decrement until and unless it is required. For Example:
int i = 3;

// It will increment in the same step
++i;

// It will increment in the next step
// so it will take more time
i++;
Also use of pointer should be avoided, where can be avoided. A pointer points to the address of a variable, that address will be further used to access the variable. So try to directly access the variable as they can be directly used and hence time can be reduced.
Use StringBuilder or StringBuffer class for concatenation instead of ‘”+” operator
        1.Using "+" operator
        String x="";
        char c='a';
        for(int i=0;i<10000;i++)
          x+=c;
          
        2.Using StringBulider/StringBuffer Class
        StringBuilder sb=new StringBuilder("");
        char c='a';
        for(int i=0;i<10000;i++)
         sb.append(c);
        String x=sb.toString();
Both of them does the same work(making a string of 10000 copies of ‘a’ character). But the 2nd option takes 10 times less time than the 1st one.
So,it is always adviceable to use StringBuilder (in java) instead of “+” operator for concatenation.
jyoti369
surindertarika1234
Technical Scripter 2020
Articles
C++
Competitive Programming
GBlog
Technical Scripter
TechTips
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sort String Array alphabetically by the initial character only in Java

Here, we are sorting string array alphabetically by the initial character i.e. ‘J’ for ‘John’ will come after ‘Chris’ since the first character of ‘Chris’ is ‘C’.
Let us first create a String array:
String[] strArr = { "PQRS", "AB", "RSTUVW", "RST", "U", "UVWXY", "OUJBG" };
Now, sort the string array based on the first character:
Arrays.sort(strArr, (str1, str2) -> str1.charAt(0) - str2.charAt(0));
The following is an example to sort String Array alphabetically by the initial character only:
import java.util.Arrays;
public class Demo {
   public static void main(String[] args) {
      String[] strArr = { "PQRS", "AB", "RSTUVW", "RST", "U", "UVWXY", "OUJBG" };
      System.out.println("Sorting array strings = ");
      Arrays.sort(strArr, (str1, str2) -> str1.charAt(0) - str2.charAt(0));
      Arrays.asList(strArr).forEach(System.out::println);
   }
}
Sorting array strings =
AB
OUJBG
PQRS
RSTUVW
RST
U
UVWXY
How to create a data frame with combinations of values in R?

Suppose we have two values 0 and 1 then how many combinations of these values are possible, the answer is 8 and these combinations are (0,0), (1,0), (0,1), (1,1). In R, we can use expand.grid function to create these combinations but to save it in a data frame, we would need to use as.data.frame function.
 Live Demo
df1<-as.data.frame(expand.grid(c(0,1),c(0,1)))
df1
   Var1 Var2
1   0   0
2   1   0
3   0   1
4   1   1
 Live Demo
df2<-as.data.frame(expand.grid(c(0,1),c(0,1),c(0,1)))
df2
 Var1 Var2 Var3
1 0    0    0
2 1    0    0
3 0    1    0
4 1    1    0
5 0    0    1
6 1    0    1
7 0    1    1   
8 1    1    1
 Live Demo
df3<-as.data.frame(expand.grid(c(0,1,2),c(0,1,2),c(0,1,2)))
df3
  Var1 Var2 Var3
1  0    0    0
2  1    0    0
3  2    0    0
4  0    1    0
5  1    1    0
6  2    1    0
7  0    2    0
8  1    2    0
9  2    2    0
10 0    0    1
11 1    0    1
12 2    0    1
13 0    1    1
14 1    1    1
15 2    1    1
16 0    2    1
17 1    2    1
18 2    2    1
19 0    0    2
20 1    0    2
21 2    0    2
22 0    1    2
23 1    1    2
24 2    1    2
25 0    2    2
26 1    2    2
27 2    2    2
 Live Demo
df4<-as.data.frame(expand.grid(c(0,1,2),c(0,1,2)))
df4
Var1 Var2
1 0 0
2 1 0
3 2 0
4 0 1
5 1 1
6 2 1
7 0 2
8 1 2
9 2 2
 Live Demo
df5<-as.data.frame(expand.grid(c(1,2),c(1,2),c(1,2)))
df5
  Var1 Var2 Var3
1  1    1    1
2  2    1    1
3  1    2    1
4  2    2    1
5  1    1    2
6 2     1    2
7 1     2    2
8 2     2    2
Anagram Substring Search using Python

In this tutorial, we are going to write a program which searches for all the anagram from a string.
See some examples.
Input:
anagram = "cat"
string = "tacghactcat"
Output:
Anagram at 0
Anagram at 5
Anagram at 7
Anagram at 8
Let's see how to write the code. Follow the below steps to write code.
1. Initialize two strings.
2. Create a function which returns whether two strings are anagram to each other or not.
3. Iterate through the main string in which we have to search for the anagrams.
   3.1. Check whether substring is an anagram or not using the function that we have defined.
      3.1.1. If True, print the starting index.
Examine the code if you feel difficult to write.
# importing collections to check for anagrams
import collections
# initializing two strings
anagram = 'cat'
string = 'tacghactcat'
# function to check for anagrams
def is_anagram(string):
   # checking for anagram
   if collections.Counter(anagram) == collections.Counter(string):
      # returning True if anagrams
      return True
   else:
      # returning False if not
      return False
# getting lengths of both strings
anagram_len = len(anagram)
string_len = len(string)
# iterarint through the string
for i in range(string_len - anagram_len + 1):
   # checking for anagram
   if is_anagram(string[i:i+anagram_len]):
      # printing the index
      print(f'Anagram at {i}')
If you run the above program, you will get the following results.
Anagram at 0
Anagram at 5
Anagram at 7
Anagram at 8
If you have doubts regarding the tutorial, mention them in the comment section.
JavaScript Number.MAX_VALUE & Number.MIN_VALUE Property - GeeksforGeeks

08 Sep, 2020
Below is the example of the Number.MAX_VALUE & Number.MIN_VALUE Property.
Example:<script> function GFGFun() {     document.write(Number.MAX_VALUE+"<br>");    document.write(Number.MIN_VALUE+"<br>");} GFGFun(); </script> 
<script> function GFGFun() {     document.write(Number.MAX_VALUE+"<br>");    document.write(Number.MIN_VALUE+"<br>");} GFGFun(); </script> 
Output :1.7976931348623157e+308
5e-324

1.7976931348623157e+308
5e-324

Number.MAX_VALUE and Number.MIN_VALUE is used to represent maximum and minimum numeric value in javascript.
Syntax:
Number.MAX_VALUE 
Number.MIN_VALUE 

Return Type:Both Number.MAX_VALUE and Number.MIN_VALUE returns a numeric value.
MAX_VALUE has a value of approximately 1.79E+308. The values which are larger Number.MAX_VALUE are termed as Infinity.
MIN_VALUE has a value of approximately 5e-324. The values which are smaller than Number.MIN_VALUE are termed as underflow values.
Both MAX_VALUE and MIN_VALUE are static property of Number. Therefore using x.MAX_VALUE or x.MIN_VALUE will return undefined where x is a Number or Number Object.
Example 1:
Input : Number.MAX_VALUE
Output : 1.7976931348623157e+308
Example 2:
Input : Number.MIN_VALUE
Output : 5e-324
Program:
<script>   function GFGFun() {     // JavaScript Code to illustrate Number.MAX_VALUE    // & Number.MIN_VALUE    document.write(Number.MAX_VALUE+"<br>");    document.write(Number.MIN_VALUE+"<br>");      // Undefined Behaviour     var res = 1;     res = res.MAX_VALUE;     document.write(res); } GFGFun(); </script> 
Output :
1.7976931348623157e+308
5e-324
undefined
JavaScript-Properties
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
How to Use the JavaScript Fetch API to Get Data?
How to read a local text file using JavaScript?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Android Absolute Layout

An Absolute Layout lets you specify exact locations (x/y coordinates) of its children. Absolute layouts are less flexible and harder to maintain than other types of layouts without absolute positioning.
Following are the important attributes specific to AbsoluteLayout −
android:id
This is the ID which uniquely identifies the layout.
android:layout_x
This specifies the x-coordinate of the view.
android:layout_y
This specifies the y-coordinate of the view.
This example will take you through simple steps to show how to create your own Android application using absolute layout. Follow the following steps to modify the Android application we created in Hello World Example chapter −
Following is the content of the modified main activity file src/com.example.demo/MainActivity.java. This file can include each of the fundamental lifecycle methods.
package com.example.demo;

import android.os.Bundle;
import android.app.Activity;

public class MainActivity extends Activity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
   }
   
}
Following will be the content of res/layout/activity_main.xml file −
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent">
   
   <Button
      android:layout_width="100dp"
      android:layout_height="wrap_content"
      android:text="OK"
      android:layout_x="50px"
      android:layout_y="361px" />
   <Button
      android:layout_width="100dp"
      android:layout_height="wrap_content"
      android:text="Cancel"
      android:layout_x="225px"
      android:layout_y="361px" />

</AbsoluteLayout>
Following will be the content of  res/values/strings.xml to define two new constants −
<?xml version="1.0" encoding="utf-8"?>
<resources>
   <string name="app_name">demo</string>
   <string name="action_settings">Settings</string>
</resources>
Let's try to run our modified Hello World! application we just modified. I assume you had created your AVD while doing environment setup. To run the app from Android Studio, open one of your project's activity files and click Run  icon from the toolbar. Android Studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window −

    46 Lectures 
     7.5 hours 

 Aditya Dua

    32 Lectures 
     3.5 hours 

 Sharad Kumar

    9 Lectures 
     1 hours 

 Abhilash Nelson

    14 Lectures 
     1.5 hours 

 Abhilash Nelson

    15 Lectures 
     1.5 hours 

 Abhilash Nelson

    10 Lectures 
     1 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
ES6 - Array Method reduce()

reduce() method applies a function simultaneously against two values of the array (from left-to-right) as to reduce it to a single value.
array.reduce(callback[, initialValue]);   

callback − Function to execute on each value in the array.
callback − Function to execute on each value in the array.
initialValue − Object to use as the first argument to the first call of the callback.
initialValue − Object to use as the first argument to the first call of the callback.
Returns the reduced single value of the array.
var total = [0, 1, 2, 3].reduce(function(a, b){ return a + b; }); 
console.log("total is : " + total );     
total is : 6


    32 Lectures 
     3.5 hours 

 Sharad Kumar

    40 Lectures 
     5 hours 

 Richa Maheshwari

    16 Lectures 
     1 hours 

 Anadi Sharma

    50 Lectures 
     6.5 hours 

 Gowthami Swarna

    14 Lectures 
     1 hours 

 Deepti Trivedi

    31 Lectures 
     1.5 hours 

 Shweta
 Print
 Add Notes
 Bookmark this page
How to sort a list of complex types using Comparison delegate in C#?

Overloads of the Sort() method in List class expects Comparison delegate to be
passed as an argument.
public void Sort(Comparison<T> comparison)
CompareTo returns an integer that indicates whether the value of this instance is less than, equal to, or greater than the value of the specified object or the other Int16 instance.
The Int16.CompareTo() method in C# is used to compare this instance to a specified
object or another Int16 instance
class Program{
   public static void Main(){
      Employee Employee1 = new Employee(){
         ID = 101,
         Name = "Mark",
         Salary = 4000
      };
      Employee Employee2 = new Employee(){
         ID = 103,
         Name = "John",
         Salary = 7000
      };
      Employee Employee3 = new Employee(){
         ID = 102,
         Name = "Ken",
         Salary = 5500
      };
      List<Employee> listEmployees = new List<Employee>();
      listEmployees.Add(Employee1);
      listEmployees.Add(Employee2);
      listEmployees.Add(Employee3);
      Console.WriteLine("Employees before sorting");
      foreach (Employee Employee in listEmployees){
         Console.WriteLine(Employee.ID);
      }
      listEmployees.Sort((x, y) => x.ID.CompareTo(y.ID));
      Console.WriteLine("Employees after sorting by ID");
      foreach (Employee Employee in listEmployees){
         Console.WriteLine(Employee.ID);
      }
      listEmployees.Reverse();
      Console.WriteLine("Employees in descending order of ID");
      foreach (Employee Employee in listEmployees){
         Console.WriteLine(Employee.ID);
      }
   }
   // Approach 1 - Step 1
   // Method that contains the logic to compare Employees
   private static int CompareEmployees(Employee c1, Employee c2){
      return c1.ID.CompareTo(c2.ID);
   }
}
public class Employee{
   public int ID { get; set; }
   public string Name { get; set; }
   public int Salary { get; set; }
}
Employees before sorting
101
103
102
Employees after sorting by ID
101
102
103
Employees in descending order of ID
103
102
101
What is the use of setBounds() method in Java?

The layout managers are used to automatically decide the position and size of the added components. In the absence of a layout manager, the position and size of the components have to be set manually. The setBounds() method is used in such a situation to set the position and size. To specify the position and size of the components manually, the layout manager of the frame can be null.
The setBounds() method needs four arguments. The first two arguments are x and y coordinates of the top-left
corner of the component, the third argument is the width of the component and the fourth argument is the height of the component.
setBounds(int x-coordinate, int y-coordinate, int width, int height)
import javax.swing.*;
import java.awt.*;
public class SetBoundsTest {
   public static void main(String arg[]) {
      JFrame frame = new JFrame("SetBounds Method Test");
      frame.setSize(375, 250);
      // Setting layout as null
      frame.setLayout(null);
      // Creating Button
      JButton button = new JButton("Hello Java");
      // Setting position and size of a button
      button.setBounds(80,30,120,40);
      frame.add(button);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }
}
How to match anything except space and new line using Python regular expression?

The following code matches anything except space and new line in the given string using regex.
import re
print re.match(r'^[^ \n]*$', """IfindTutorialspointuseful""")
print re.match(r'^[^ \n]*$', """I find Tutorialspointuseful""")
print re.match(r'^[^ \n]*$', """Ifind
Tutorialspointuseful""")
This gives the output
<_sre.SRE_Match object at 0x00000000048965E0>
None
None
Check for Power of two in JavaScript

We are required to write a function, say isPowerOfTwo() that takes in a positive number and
returns a boolean based on the fact whether or not the number is some power of 2.
For example −
console.log(isPowerOfTwo(3)); //false
console.log(isPowerOfTwo(32)); //true
console.log(isPowerOfTwo(2048)); //true
console.log(isPowerOfTwo(256)); //true
console.log(isPowerOfTwo(22)); //false
Let’s write the code for this function, it will be a very straightforward recursive function that
keeps recurring until the number stays divisible by 2, if in this process the number gets reduced
all the way down to 1, it is a power of 2 otherwise it isn’t. Here is the code −
const isPowerOfTwo = num => {
   if(num === 1){
      return true;
   };
   if(num % 2 !== 0){
      return false;
   }
   return isPowerOfTwo(num / 2);
}
console.log(isPowerOfTwo(3));
console.log(isPowerOfTwo(32));
console.log(isPowerOfTwo(2048));
console.log(isPowerOfTwo(256));
console.log(isPowerOfTwo(22));
The output in the console will be −
false
true
true
true
false
JSON Schema Support using Jackson in Java?

JSON Schema is a specification for JSON based format for defining the structure of JSON data. The JsonSchema class can provide a contract for what JSON data is required for a given application and how to interact with it. The JsonSchema can define validation, documentation, hyperlink navigation, and interaction control of JSON data. We can generate the JSON schema using the generateSchema() method of JsonSchemaGenerator, this class wraps the JSON schema generation functionality.
public JsonSchema generateSchema(Class<T> type) throws com.fasterxml.jackson.databind.JsonMappingException
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.module.jsonSchema.JsonSchema;
import com.fasterxml.jackson.module.jsonSchema.JsonSchemaGenerator;
import java.util.List;
public class JSONSchemaTest {
   public static void main(String[] args) throws JsonProcessingException {
      ObjectMapper jacksonObjectMapper = new ObjectMapper();
      JsonSchemaGenerator schemaGen = new JsonSchemaGenerator(jacksonObjectMapper);
      JsonSchema schema = schemaGen.generateSchema(Person.class);
      String schemaString = jacksonObjectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(schema);
      System.out.println(schemaString);
   }
}
// Person class
class Person {
   private String name;
   private int age;
   private List<String> courses;
   private Address address;
   public String getName() {
      return name;
   }
   public int getAge(){
      return age;
   }
   public List<String> getCourse() {
      return courses;
   }
   public Address getAddress() {
      return address;
   }
}
// Address class
class Address {
   private String firstLine;
   private String secondLine;
   private String thirdLine;
   public String getFirstLine() {
      return firstLine;
   }
   public String getSecondLine() {
      return secondLine;
   }
   public String getThirdLine() {
      return thirdLine;
   }
}
{
   "type" : "object",
   "id" : "urn:jsonschema:Person",
   "properties" : {
      "name" : {
         "type" : "string"
      },
      "age" : {
         "type" : "integer"
      },
      "address" : {
         "type" : "object",
         "id" : "urn:jsonschema:Address",
         "properties" : {
            "firstLine" : {
               "type" : "string"
            },
            "secondLine" : {
               "type" : "string"
            },
            "thirdLine" : {
               "type" : "string"
            }
         }
      },
      "course" : {
         "type" : "array",
         "items" : {
            "type" : "string"
         }
      }
   }
}
Field selection within MongoDB query using dot notation?

For this, use dot notation for field selection in MongoDB find(). Let us create a collection with documents −
> db.demo302.insertOne({"Id":101,"details":[{"Name":"Chris",Age:21,"Subject":"MySQL"}]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4d746f5d93261e4bc9ea52")
}
> db.demo302.insertOne({"Id":102,"details":[{"Name":"Bob",Age:23,"Subject":"MongoDB"}]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4d74815d93261e4bc9ea53")
}
> db.demo302.insertOne({"Id":103,"details":[{"Name":"David",Age:20,"Subject":"Java"}]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4d74955d93261e4bc9ea54")
}
Display all documents from a collection with the help of find() method −
> db.demo302.find();
This will produce the following output −
{ "_id" : ObjectId("5e4d746f5d93261e4bc9ea52"), "Id" : 101, "details" : [ { "Name" : "Chris", "Age" : 21, "Subject" : "MySQL" } ] }
{ "_id" : ObjectId("5e4d74815d93261e4bc9ea53"), "Id" : 102, "details" : [ { "Name" : "Bob", "Age" : 23, "Subject" : "MongoDB" } ] }
{ "_id" : ObjectId("5e4d74955d93261e4bc9ea54"), "Id" : 103, "details" : [ { "Name" : "David", "Age" : 20, "Subject" : "Java" } ] }
Following is the query for field selection using dot notation −
>db.demo302.find({"details.Subject":"MongoDB"},{"details.Name":0,"details.Age":0,_id:0,Id:0});
This will produce the following output −
{ "details" : [ { "Subject" : "MongoDB" } ] }
How do I turn a string in dot notation into a nested object with a value – JavaScript?

Let’s say the following is our string in dot notation −
const keys = "details1.details2.details3.details4.details5"
And the following is our array −
const firsName = "David";
To turn into a nested object, use the concept of split(‘.’) along with map().
Following is the code −
const keys = "details1.details2.details3.details4.details5"
const firsName = "David";
var tempObject = {};
var container = tempObject;
keys.split('.').map((k, i, values) => {
   container = (container[k] = (i == values.length - 1 ? firsName : {}))
});
console.log(JSON.stringify(tempObject, null, ' '));
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo227.js.
The output is as follows −
PS C:\Users\Amit\JavaScript-code> node demo227.js
{
 "details1": {
  "details2": {
   "details3": {
    "details4": {
     "details5": "David"
    }
   }
  }
 }
}
VB.Net - Exit Statement

The Exit statement transfers the control from a procedure or block immediately to the statement following the procedure call or the block definition. It terminates the loop, procedure, try block or the select block from where it is called.
If you are using nested loops (i.e., one loop inside another loop), the Exit statement will stop the execution of the innermost loop and start executing the next line of code after the block.
The syntax for the Exit statement is −
Exit { Do | For | Function | Property | Select | Sub | Try | While }

Module loops
   Sub Main()
      ' local variable definition 
      Dim a As Integer = 10
      ' while loop execution '
      
      While (a < 20)
         Console.WriteLine("value of a: {0}", a)
         a = a + 1
         If (a > 15) Then
            'terminate the loop using exit statement 
            Exit While
         End If
      End While
      Console.ReadLine()
   End Sub
End Module
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15


    63 Lectures 
     4 hours 

 Frahaan Hussain

    103 Lectures 
     12 hours 

 Arnold Higuit

    60 Lectures 
     9.5 hours 

 Arnold Higuit

    97 Lectures 
     9 hours 

 Arnold Higuit
 Print
 Add Notes
 Bookmark this page
Python – Word Frequency in a String

When it is required to find the frequency of words using the string shorthand, dictionary comprehension can be used.
Below is a demonstration of the same
my_str = 'Hi there Will, how are you Will, Will you say Hi to me'
print("The string is : " )
print(my_str)
my_result = {key: my_str.count(key) for key in my_str.split()}
print("The word frequency is : ")
print(my_result)
The string is :
Hi there Will, how are you Will, Will you say Hi to me
The word frequency is :
{'Hi': 2, 'there': 1, 'Will,': 2, 'how': 1, 'are': 1, 'you': 2, 'Will': 3, 'say': 1, 'to': 1, 'me': 1}
A string is defined, and is displayed on the console.
A string is defined, and is displayed on the console.
The dictionary comprehension is used to iterate through the string, and split it based on spaces.
The dictionary comprehension is used to iterate through the string, and split it based on spaces.
The count of ‘key’ is determined, and is assigned to a variable.
The count of ‘key’ is determined, and is assigned to a variable.
This variable is displayed as output on the console.
This variable is displayed as output on the console.
chmod() - Unix, Linux System Call

Unix - Home
Unix - Getting Started
Unix - File Management
Unix - Directories
Unix - File Permission
Unix - Environment
Unix - Basic Utilities
Unix - Pipes & Filters
Unix - Processes
Unix - Communication
Unix - The vi Editor
Unix - What is Shell?
Unix - Using Variables
Unix - Special Variables
Unix - Using Arrays
Unix - Basic Operators
Unix - Decision Making
Unix - Shell Loops
Unix - Loop Control
Unix - Shell Substitutions
Unix - Quoting Mechanisms
Unix - IO Redirections
Unix - Shell Functions
Unix - Manpage Help
Unix - Regular Expressions
Unix - File System Basics
Unix - User Administration
Unix - System Performance
Unix - System Logging
Unix - Signals and Traps
Unix - Useful Commands
Unix - Quick Guide
Unix - Builtin Functions
Unix - System Calls
Unix - Commands List
Unix Useful Resources
Computer Glossary
Who is Who
Copyright © 2014 by tutorialspoint
chmod, fchmod - change permissions of a file
#include <sys/types.h>
#include <sys/stat.h> 
int chmod(const char *path, mode_t mode);
int fchmod(int fildes, mode_t mode); 


int chmod(const char *path, mode_t mode);
int fchmod(int fildes, mode_t mode); 

The mode of the file given by path or referenced by fildes is changed.
Modes are specified by or’ing the following: 
The effective UID of the calling process must match the owner of the file, or the process must be privileged (Linux: it must have the CAP_FOWNER capability).
If the calling process is not privileged (Linux: does not have the CAP_FSETID capability), and the group of the file does not match the effective group ID of the process or one of its
supplementary group IDs, the S_ISGID bit will be turned off, but this will not cause an error to be returned.
As a security measure, depending on the file system, the set-user-ID and set-group-ID execution bits may be turned off if a file is written.
(On Linux this occurs if the writing process does not have the CAP_FSETID capability.) On some file systems, only the superuser can set the sticky bit,
which may have a special meaning. For the sticky bit, and for set-user-ID and set-group-ID bits on directories, see
stat(2).
On NFS file systems, restricting the permissions will immediately influence already open files, because the access control is done on the server, but open files are maintained by the client.  Widening the permissions may be
delayed for other clients if attribute caching is enabled on them.
On success, zero is returned.  On error, -1 is returned, and errno is set appropriately.
Depending on the file system, other errors can be returned.  The more general errors for chmod() are listed below: 
4.4BSD, SVr4, POSIX.1-2001.
chown (2)
chown (2)
execve (2)
execve (2)
fchmodat (2)
fchmodat (2)
open (2)
open (2)
path_resolution (2)
path_resolution (2)
stat (2)
stat (2)

Advertisements


    129 Lectures 
     23 hours 

 Eduonix Learning Solutions

    5 Lectures 
     4.5 hours 

 Frahaan Hussain

    35 Lectures 
     2 hours 

 Pradeep D

    41 Lectures 
     2.5 hours 

 Musab Zayadneh

    46 Lectures 
     4 hours 

 GUHARAJANM

    6 Lectures 
     4 hours 

 Uplatz
 Print
 Add Notes
 Bookmark this page
C | Pointer Basics | Question 15 - GeeksforGeeks

28 Jun, 2021
#include<stdio.h>  void swap (char *x, char *y){    char *t = x;    x = y;    y = t;}  int main(){    char *x = "geeksquiz";    char *y = "geeksforgeeks";    char *t;    swap(x, y);    printf("(%s, %s)", x, y);    t = x;    x = y;    y = t;    printf("\n(%s, %s)", x, y);    return 0;}
(A)
(geeksquiz, geeksforgeeks)
(geeksforgeeks, geeksquiz)
(B)
(geeksforgeeks, geeksquiz)
(geeksquiz, geeksforgeeks)
(C)
(geeksquiz, geeksforgeeks)
(geeksquiz, geeksforgeeks)
(D)
(geeksforgeeks, geeksquiz)
(geeksforgeeks, geeksquiz)
Answer: (A)Explanation: See C function to Swap stringsQuiz of this Question
C-Pointer Basics
C Language
C Quiz
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Function Pointer in C
std::string class in C++
TCP Server-Client implementation in C
Structures in C
Exception Handling in C++
Compiling a C program:- Behind the Scenes
Operator Precedence and Associativity in C
C | File Handling | Question 1
C | Arrays | Question 7
C | Misc | Question 7
Difference Between && and ; chaining operators in Linux - GeeksforGeeks

14 Oct, 2020
Logical AND operator(&&): 
The second command will only execute if the first command has executed successfully i.e, its exit status is zero. This operator can be used to check if the first command has been successfully executed. This is one of the most used commands in the command line.
Syntax:
command1 && command2

command2 will execute if command1 has executed successfully. This operator allows us to check the exit status of command1.
Semi-Colon Operator(;):
It is used to execute multiple commands in one go. Several commands can be chained together using this operator. The execution of the command succeeding this operator will always execute after the command preceding it has executed irrespective of the exit status of the preceding command. The commands always execute sequentially.  Commands separated by a semicolon operator are executed sequentially, the shell waits for each command to terminate in turn.  The return status is the exit status of the last command executed.
Syntax:
command1 ; command2

The execution of the second command is independent of the exit status of the first command. If the first command does not get successfully executed, then also the second command will get executed.
&& (logical AND) operator
; (Semi-colon) operator
[ -z $b ] && b = 10
[ -z $b ] && b = 15

The first command checks if a variable b exists and if it exists, it is initialized with 10. Consider that b does not exist, so the first command has an exit status 0 and therefore the second command is executed and b is initialized with 10. Now, if we again try to initialize it using the same command, then it will not be executed as the first command has an exit status 1 as b already exists. If we display b again using echo we will get the previously initialized value.
[ -z $b ] ; b = 10
[ -z $b ] ; b = 15

Even if the exit status of the first command is 1 i.e, b already exists, the second command will get executed and b will be again initialized with a new value.
[ -f a.txt ] && echo "file exists"

“File exists” will only get displayed if the file exists in the current directory. When the first command returns 0 i.e, the file exists, then only the next command will get executed else nothing will be displayed.
[ -f a.txt ] ; echo "file exists"

“File exists” will always get displayed. It is independent of the exit status of the first command.
File exists is displayed only when it is created using the touch command in case of && operator. But even after removing the file using rm command file exists is displayed when we use; operator
Difference Between
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between IPv4 and IPv6
Difference Between Method Overloading and Method Overriding in Java
Stack vs Heap Memory Allocation
Differences between JDK, JRE and JVM
Sed Command in Linux/Unix with examples
AWK command in Unix/Linux with examples
grep command in Unix/Linux
cut command in Linux with examples
cp command in Linux with examples