code-rag-bench/online-tutorials huggingface dataset:
Fabric.js Canvas selection Property - GeeksforGeeks

30 Jul, 2021
In this article, we are going to see how to enable or disable the selection of objects in a canvas in Fabric.js using the selection property. The canvas in Fabric.js is used as a wrapper over the native canvas object provided by HTML. It provides high-level access to the underlying canvas allowing it to have an object model, allow parsing for SVG files, and allowing the canvas to be interacted with in an intuitive manner.
Approach: To make it possible we are going to use a JavaScript library called Fabric.js. After importing the library, we will create the canvas block in the body tag. After this, we will initialize an instance of the canvas object provided by Fabric.js and set the selection mode needed for the canvas using the selection property.
Syntax:
fabric.Canvas(canvasElement, {
    selection: Boolean
});
Parameters: This property accepts a single parameter as mentioned above and described below.
selection: It is a boolean that specifies whether the selection of objects should be enabled or not on the canvas.
Example: The below example illustrates the use of Fabric.js Canvas selection property in JavaScript.
HTML
<!DOCTYPE html><html>  <head>    <!-- Adding the FabricJS library -->    <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.2/fabric.min.js">    </script></head>  <body>    <div style="text-align: center;              width: 500px;">        <h1 style="color: green;">            GeeksforGeeks        </h1>          <b>            Fabric.js | Canvas selection Property        </b>    </div>      <b>Selection Disabled</b>    <canvas id="canvas" width="500" height="250"         style="border:1px solid #000000">    </canvas>      <b>Selection Enabled</b>    <canvas id="canvas2" width="500" height="250"         style="border:1px solid #000000">    </canvas>      <script>          let circle = new fabric.Circle({            radius: 30,        });          let circle2 = new fabric.Circle({            radius: 30,        });          // Initiate a Canvas instance         let canvas = new fabric.Canvas("canvas", {              // Disable selection            // in this Canvas            selection: false        });          // Initiate a Canvas instance         let canvas2 = new fabric.Canvas("canvas2", {                          // Enable selection            // in this Canvas            selection: true        });          canvas.add(circle);        canvas.centerObject(circle);        canvas2.add(circle2);        canvas2.centerObject(circle2);    </script></body>  </html>
Output:
Fabric.js
HTML
JavaScript
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
HTML Cheat Sheet - A Basic Guide to HTML
Design a web page using HTML and CSS
Form validation using jQuery
Angular File Upload
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
How to Fix: Length of values does not match length of index - GeeksforGeeks

22 Nov, 2021
In this article we will fix the error: The length of values does not match the length of the index in Python.
Python3
# importing pandasimport pandas as pd  sepal_length = [5.1, 4.9, 4.7, 4.6, 5.0, 5.4,                 4.6, 5.0, 4.4, 4.9]sepal_width = [4.6, 5.0, 5.4, 4.6, 5.0, 4.4,                4.9, 5.1, 5.2, 5.3]petal_length = [3.3, 4.6, 4.7, 5.6, 6.7, 5.0, 4.8]petal_width = [3.6, 5.6, 5.4, 4.6, 4.4, 5.0, 4.9]  # DataFrame with 2 columnsdf = pd.DataFrame({'sepal_length(cm)': sepal_length,                   'sepal_width(cm)': sepal_width})  df['petal_length(cm)'] = petal_lengthdf['petal_width(cm)'] = petal_width  print(df)
Output:
ValueError: Length of values (7) does not match length of index (10)
The length of the index of the pandas DataFrame(i.e length of the column of present DataFrame) which is 10 in this case is not equal to the length of the new list or NumPy array which is 7 in this case.
pd.Index.size!=len(petal_width)
This error can be fixed by preprocessing the new list or NumPy array that is going to be a column of the DataFrame by using the pandas Series() function which actually converts the list or NumPy array into the size of the DataFrame column length by adding NaN if list or NumPy array has lesser length else if the list or NumPy has greater length then it takes the list or NumPy array with the length of columns of the pandas dataframe.
Syntax For list:
Consider list1 as a python list
df['new_column'] = pd.Series(list1)
Syntax For NumPy array:
Consider numarr as a numpy array
df['new_column'] = pd.Series(numarr)
Python3
# importing pandasimport pandas as pd  # importing numpyimport numpy as npsepal_length = [5.1, 4.9, 4.7, 4.6, 5.0, 5.4,                4.6, 5.0, 4.4, 4.9]sepal_width = [4.6, 5.0, 5.4, 4.6, 5.0, 4.4,               4.9, 5.1, 5.2, 5.3]petal_length = [3.3, 4.6, 4.7, 5.6, 6.7, 5.0, 4.8]  # numpy array of length 7petal_width = np.array([3.6, 5.6, 5.4, 4.6, 4.4,                         5.0, 4.9])  # DataFrame with 2 columns of length 10df = pd.DataFrame({'sepal_length(cm)': sepal_length,                   'sepal_width(cm)': sepal_width})  # Adding list to pandas DataFramedf['petal_length(cm)'] = pd.Series(petal_length)  # Adding numpy array to pandas DataFramedf['petal_width(cm)'] = pd.Series(petal_width)  print(df)
Output:
Picked
Python How-to-fix
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
Python | sympy.rewrite() method - GeeksforGeeks

07 Jul, 2019
With the help of sympy.rewrite() method, we can represent any mathematical function in terms of another function.
Syntax: expression.rewrite(function)
Parameters:expression – It is mathematical expression which is to be represented by another function.function – It is the mathematical function used to rewrite the given expression.
Returns: Returns a mathematical expression corresponding to the input in terms of specified function.
Example #1:
# import sympy from sympy import *   x = symbols('x')expr = tan(x)print("Expression = {}".format(expr))   # Use sympy.rewrite() method expr_in_terms_of_sin = expr.rewrite(sin)        print("Expression in terms of sin() : {}".format(expr_in_terms_of_sin))  
Output:
Expression = tan(x)
Expression in terms of sin() : 2*sin(x)**2/sin(2*x)

Example #2:
# import sympy from sympy import *   x = symbols('x')expr = factorial(x)print("Expression = {}".format(expr))   # Use sympy.rewrite() method expr_in_terms_of_gamma = expr.rewrite(gamma)        print("Expression in terms of gamma() : {}".format(expr_in_terms_of_gamma))  
Output:
Expression = factorial(x)
Expression in terms of gamma() : gamma(x + 1)

SymPy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Check if element exists in list in Python
sum() function in Python
How to create Emoji Picker in ReactJS ? - GeeksforGeeks

08 Nov, 2021
In this article, we are going to learn how we can create Emoji Picker in ReactJs. React is a free and open-source front-end JavaScript library for building user interfaces or UI components. It is maintained by Facebook and a community of individual developers and companies.
Approach: To create our Spreadsheet we are going to use the emoji-picker-react package because it is powerful, lightweight, and fully customizable. After that, we will add an emoji picker on our homepage using the installed package.
Create ReactJs Application: You can create a new ReactJs project using the below command:
npx create-react-app gfg
Module Installation: Install the emoji-picker-react package using the below command:
npm i emoji-picker-react
Project Structure: It will look like this.
Filename: App.js In this example, we are going to add the emoji picker on the homepage of our app using the package that we installed. For this, add the below content in the App.js file.
Javascript
import React, { useState } from 'react';import Picker from 'emoji-picker-react';  export default function Emoji(){  const [chosenEmoji, setChosenEmoji] = useState(null);    const onEmojiClick = (event, emojiObject) => {    setChosenEmoji(emojiObject);  };    return (    <div>      <h3>GeeksforGeeks Emoji Picker</h3>      {chosenEmoji ? (        <span>Your Emoji: {chosenEmoji.emoji}</span>      ) : (        <span>No Emoji</span>      )}      <Picker onEmojiClick={onEmojiClick} />    </div>  );};
Explanation: In the above example first, we are importing the Picker component from the emoji-picker-react package. After that, we are using our useState to add the initial data and update the emoji. Then we are adding our Emoji PIcker using the Picker component.
Steps to run the application: Run the below command in the terminal to run the app.
npm start
Output:
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ReactJS useNavigate() Hook
How to set background images in ReactJS ?
Axios in React: A Guide for Beginners
How to create a table in ReactJS ?
How to navigate on path by button click in react router ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
How to push data in a MongoDB document ? - GeeksforGeeks

12 Nov, 2021
The insertOne() and insertMany() are the two methods of the MongoDB module in node.js that are used to push the documents in the collections of the MongoDB database. The insertOne() method inserts one data at a time into the collection and insertMany() method inserts multiple data into the collection of the MongoDB database. In this article, we will discuss how to push data in MongoDB collection using MongoDB module methods.
Installing module: You can install mongodb module using the following command. 
node install mongodb
Project Structure: It will look like the following.
Running Server on Local IP: Data is the directory where MongoDB server is present.
mongod --dbpath=data --bind_ip 127.0.0.1
index.js
const MongoClient = require("mongodb");  // Server running const url = 'mongodb://localhost:27017/';  // Database nameconst databasename = "GFG";  MongoClient.connect(url).then((client) => {      // Connecting to the database    const connect = client.db(databasename);       // Database collection    const collection = connect        .collection("GFGcollections");      // Inserting single document    collection.insertOne({         "name": "aayush", "class": "GFG" });      // Inserting multiple document    collection.insertMany([        { "name": "saini", "class": "GFG" },         { "name": "GfGnew", "class": "GFGNEW" }    ]);      console.log("Insertion Successful")}).catch(err) => {          // If error occured show the error message    console.log(err.Message);}
Run index.js file using the following command:
node index.js
Output:
MongoDB Database:
clintra
MongoDB
Node.js-Methods
NodeJS-Questions
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to connect Node.js with React.js ?
Node.js Export Module
Difference between dependencies, devDependencies and peerDependencies
Mongoose Populate() Method
Mongoose find() Function
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
Powershell - Create CSV File

New-Item cmdlet is used to create a csv file and Set-Content cmdlet to put content into it.
In this example, we're creating a new csv file named test.csv
Type the following command in PowerShell ISE Console
New-Item D:\temp\test\test.csv -ItemType File
You can see the test.csv created in D:\temp\test directory.
In this example, we're adding content to test.csv.
Type the following command in PowerShell ISE Console
Set-Content D:\temp\test\test.csv 'Mahesh,Suresh,Ramesh'
In this example, we're reading content of test.csv.
Get-Content D:\temp\test\test.csv

You can see following output in PowerShell console.
Mahesh,Suresh,Ramesh


    15 Lectures 
     3.5 hours 

 Fabrice Chrzanowski

    35 Lectures 
     2.5 hours 

 Vijay Saini

    145 Lectures 
     12.5 hours 

 Fettah Ben
 Print
 Add Notes
 Bookmark this page
Tryit Editor v3.7

Tryit: Set border colors
How to aggregate two collections where a field from one collection is greater than the other in MongoDB?

For this, you can use $lookup. Let us create a collection with documents −
> db.demo446.insert([
...    { "ProductName": "Product1", "ProductPrice": 60 },
...    { "ProductName": "Product2", "ProductPrice": 90 }
... ])
BulkWriteResult({
   "writeErrors" : [ ],
   "writeConcernErrors" : [ ],
   "nInserted" : 2,
   "nUpserted" : 0,
   "nMatched" : 0,
   "nModified" : 0,
   "nRemoved" : 0,
   "upserted" : [ ]
})
Display all documents from a collection with the help of find() method −
> db.demo446.find();
This will produce the following output −
{ "_id" : ObjectId("5e790766bbc41e36cc3caec3"), "ProductName" : "Product1", "ProductPrice" : 60 }
{ "_id" : ObjectId("5e790766bbc41e36cc3caec4"), "ProductName" : "Product2", "ProductPrice" : 90 }
Following is the query to create second collection with documents −
> db.demo447.insert([
...
...    { "ProductName": "Product1", "ProductPrice": 40 },
...    { "ProductName": "Product2", "ProductPrice": 70 }
... ])
BulkWriteResult({
   "writeErrors" : [ ],
   "writeConcernErrors" : [ ],
   "nInserted" : 2,
   "nUpserted" : 0,
   "nMatched" : 0,
   "nModified" : 0,
   "nRemoved" : 0,
   "upserted" : [ ]
})
Display all documents from a collection with the help of find() method −
> db.demo447.find();
This will produce the following output −
{ "_id" : ObjectId("5e790789bbc41e36cc3caec5"), "ProductName" : "Product1", "ProductPrice" : 40 }
{ "_id" : ObjectId("5e790789bbc41e36cc3caec6"), "ProductName" : "Product2", "ProductPrice" : 70 }
Following is the query to aggregate two collections where a field from one collection is greater than the other −
> var rate = 1;
> db.demo446.aggregate([
... { "$match": { "ProductPrice": { "$exists": true }, "ProductName": { "$exists": true } } },
... {
...    "$lookup": {
...       "from": "demo447",
...       "localField": "ProductName",
...       "foreignField": "ProductName",
...       "as": "demo447"
...    }
... },
... { "$unwind": "$demo447" },
... {
...    "$redact": {
...       "$cond": [
...          {
...             "$gt": [
...                "$ProductPrice", {
...                   "$add": [
...                         { "$multiply": [ "$demo447.ProductPrice",rate ] },
...                         3
...                      ]
...                   }
...                ]
...             },
...             "$$KEEP",
...             "$$PRUNE"
...          ]
...       }
...    }
... ])
This will produce the following output −
{ "_id" : ObjectId("5e790766bbc41e36cc3caec3"), "ProductName" : "Product1", "ProductPrice" : 60, "demo447" : { "_id" : ObjectId("5e790789bbc41e36cc3caec5"), "ProductName" : "Product1", "ProductPrice" : 40 } }
{ "_id" : ObjectId("5e790766bbc41e36cc3caec4"), "ProductName" : "Product2", "ProductPrice" : 90, "demo447" : { "_id" : ObjectId("5e790789bbc41e36cc3caec6"), "ProductName" : "Product2", "ProductPrice" : 70 } }
VBA - Erase Function

The Erase Function is used to reset the values of fixed size arrays and free the memory of the dynamic arrays. It behaves depending upon the type of the arrays.
Erase ArrayName

Fixed numeric array, each element in an array is reset to Zero.
Fixed string array, each element in an array is reset to Zero length " ".
Array of objects, each element in an array is reset to special value Nothing.
Add a button and add the following function.
Private Sub Constant_demo_Click()
   Dim NumArray(3)
   NumArray(0) = "VBScript"
   NumArray(1) = 1.05
   NumArray(2) = 25
   NumArray(3) = #23/04/2013#
  
   Dim DynamicArray()
   ReDim DynamicArray(9)   ' Allocate storage space.
  
   Erase NumArray          ' Each element is reinitialized.
   Erase DynamicArray      ' Free memory used by array.
  
   ' All values would be erased.
   msgbox("The value at Zeroth index of NumArray is " & NumArray(0))
   msgbox("The value at First index of NumArray is " & NumArray(1))
   msgbox("The value at Second index of NumArray is " & NumArray(2))
   msgbox("The value at Third index of NumArray is " & NumArray(3))
End Sub
When you execute the above function, it produces the following output.
The value at Zeroth index of NumArray is 
The value at First index of NumArray is 
The value at Second index of NumArray is 
The value at Third index of NumArray is 


    101 Lectures 
     6 hours 

 Pavan Lalwani

    41 Lectures 
     3 hours 

 Arnold Higuit

    80 Lectures 
     5.5 hours 

 Prashant Panchal

    25 Lectures 
     2 hours 

 Prashant Panchal

    26 Lectures 
     2 hours 

 Arnold Higuit

    92 Lectures 
     10.5 hours 

 Vijay Kumar Parvatha Reddy
 Print
 Add Notes
 Bookmark this page
Min window substring in JavaScript

We are required to write a JavaScript function that takes in two strings let's call them str1 and str2.
The size of str1 is guaranteed to be greater than that of str2. We are required to find the smallest substring in str1 that contains all the characters contained in str2.
For example −
If the input strings are −
const str1 = 'abcdefgh';
const str2 = 'gedcf';
Then the output should be −
const output = 'cdefg';
because this the smallest consecutive substring of str1 that contains all characters of str2.
Following is the code −
const str1 = 'abcdefgh';
const str2 = 'gedcf';
const subIncludesAll = (str, str2) => {
   for (let i = 0; i < str.length; i++) {
      if (str2.indexOf(str[i]) !== -1) {
         str2 = str2.replace(str[i], '');
      };
   };
   return (str2.length === 0);
};
const minWindow = (str1 = '', str2 = '') => {
   let shortestString = null;
   for (let i = 0; i < str1.length; i++) {
      for (let j = i; j < str1.length; j++) {
         let testString = str1.substr(i, j-i+1);
         if (subIncludesAll(testString, str2)) {
            if (shortestString === null || testString.length < shortestString.length) {
               shortestString = testString;
            }
         }
      }
   }
   return shortestString;
};
console.log(minWindow(str1, str2));
Following is the output on console −
cdefg
Why interfaces don't have static initialization block when it can have static methods alone in java?

An interface in Java is similar to class but, it contains only abstract methods and fields which are final and static.
A static method is declared using the static keyword and it will be loaded into the memory along with the class. You can access static methods using class name without instantiation.
Since Java8 you can have static methods in an interface (with body). You need to call them using the name of the interface, just like static methods of a class.
In the following example, we are defining a static method in an interface and accessing it from a class implementing the interface.
interface MyInterface{
   public void demo();
   public static void display() {
      System.out.println("This is a static method");
   }
}
public class InterfaceExample{
   public void demo() {
      System.out.println("This is the implementation of the demo method");
   }
   public static void main(String args[]) {
      InterfaceExample obj = new InterfaceExample();
      obj.demo();
      MyInterface.display();
   }
}
This is the implementation of the demo method
This is a static method
A static block is a block of code with a static keyword. In general, these are used to initialize the static members. JVM executes static blocks before the main method at the time of class loading.
public class MyClass {
   static{
      System.out.println("Hello this is a static block");
   }
   public static void main(String args[]){
      System.out.println("This is main method");
   }
}
Hello this is a static block
This is main method
Mainly, static blocks are used to initialize the class/static variables if you have not initialized them at the time of declaration.
In case of interfaces when you declare a field in it. It is mandatory to assign value to it else, a compile time error is generated.
interface Test{
   public abstract void demo();
   public static final int num;
}
Test.java:3: error: = expected
   public static final int num;
                              ^
1 error
This will be resolved when you assign value to the static final variable in the interface.
interface Test{
   public abstract void demo();
   public static final int num = 400;
}
Therefore, it is not necessary to have static blocks in the interface.
Python Program to Form a New String Made of the First 2 and Last 2 characters From a Given String

When it is required to form a new string that is made from the first two and last two characters of a given string, a counter can be defined, and indexing can be used to access specific range of elements.
Below is the demonstration of the same −
 Live Demo
my_string = "Hi there how are you"

my_counter = 0

for i in my_string:
   my_counter = my_counter + 1
new_string = my_string[0:2] + my_string [my_counter - 2: my_counter ]

print("The string is ")
print(my_string)
print("The new string is ")
print(new_string)
The string is
Hi there how are you
The new string is
Hiou
A string is defined and is displayed on the console.
A string is defined and is displayed on the console.
A counter is initiated to 0.
A counter is initiated to 0.
The string is iterated over, and the first 2 and last two elements are accessed using indexing.
The string is iterated over, and the first 2 and last two elements are accessed using indexing.
This is assigned to a variable.
This is assigned to a variable.
It is the output that is displayed on the console.
It is the output that is displayed on the console.
java.util.regex.Matcher.group() Method 

The java.time.Matcher.group(int group) method returns the input subsequence captured by the given group during the previous match operation.
Following is the declaration for java.time.Matcher.group(int group) method.
public String group(int group)

group − The index of a capturing group in this matcher's pattern.
group − The index of a capturing group in this matcher's pattern.
The (possibly empty) subsequence captured by the group during the previous match, or null if the group failed to match part of the input.
IllegalStateException − If no match has yet been attempted, or if the previous match operation failed.
IllegalStateException − If no match has yet been attempted, or if the previous match operation failed.
IndexOutOfBoundsException − If there is no capturing group in the pattern with the given index.
IndexOutOfBoundsException − If there is no capturing group in the pattern with the given index.
The following example shows the usage of java.time.Matcher.group(int group) method.
package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MatcherDemo {
   private static String REGEX = "(a*b)(foo)";
   private static String INPUT = "aabfooaabfooabfoob";
   private static String REPLACE = "-";
   
   public static void main(String[] args) {
      Pattern pattern = Pattern.compile(REGEX);
      
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT);
      
      if(matcher.find()) {
         //Prints the offset after the last character matched.
         System.out.println("Second Capturing Group : "+matcher.group(1));
      }      
   }
}
Let us compile and run the above program, this will produce the following result −
Second Capturing Group : aab

 Print
 Add Notes
 Bookmark this page
How to create editText accepts Alphabets only in Android?

This example demonstrates how do I create edittext accepts alphabets only in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity">
   <EditText
      android:id="@+id/editText"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_centerInParent="true"
      android:hint="Enter text here" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.Spanned;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
   EditText editText;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      editText = findViewById(R.id.editText);
      editText.setFilters(new InputFilter[] new InputFilter() {
         @Override
         public CharSequence filter(CharSequence charSequence, int start, int end,
         Spanned dest, int etStart, int etEnd) {
            if (charSequence.equals("")) {
               return charSequence;
            }
            if (charSequence.toString().matches("[a-zA-Z ]+")) {
               return charSequence;
            }
            return "";
         }
      }
   });
}
Step 4 - Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="app.com.sample">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
Click here to download the project code.
Python | Insert list in another list - GeeksforGeeks

26 Jan, 2019
The problem of inserting a number at any index is a quite common one. But sometimes we require to insert the whole list into another list. These kinds of problems occur in Machine Learning while playing with data. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using insert() + loopIn this method, we insert one element by 1 at a time using the insert function. This way we add all the list elements at the specified index in other list.
# Python3 code to demonstrate # to insert one list in another# using insert() + loop  # initializing lists test_list = [4, 5, 6, 3, 9]insert_list = [2, 3]  # initializing positionpos = 2  # printing original listprint ("The original list is : " + str(test_list))  # printing insert list print ("The list to be inserted is : " + str(insert_list))  # using insert() + loop# to insert one list in anotherfor i in range(len(insert_list)):    test_list.insert(i + pos, insert_list[i])  # printing result print ("The list after insertion is : " +  str(test_list))
Output :
The original list is : [4, 5, 6, 3, 9]
The list to be inserted is : [2, 3]
The list after insertion is : [4, 5, 2, 3, 6, 3, 9]

 Method #2 : Using list slicingThis is the most pythonic and elegant way to perform this particular task. In this method, we just slice the list where we need to add the element and assign the list to be inserted.
# Python3 code to demonstrate # to insert one list in another# using list slicing  # initializing lists test_list = [4, 5, 6, 3, 9]insert_list = [2, 3]  # initializing positionpos = 2  # printing original listprint ("The original list is : " + str(test_list))  # printing insert list print ("The list to be inserted is : " + str(insert_list))  # using list slicing# to insert one list in anothertest_list[pos:pos] = insert_list  # printing result print ("The list after insertion is : " +  str(test_list))
Output :
The original list is : [4, 5, 6, 3, 9]
The list to be inserted is : [2, 3]
The list after insertion is : [4, 5, 2, 3, 6, 3, 9]

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
8085 program to convert ASCII code into HEX code - GeeksforGeeks

14 Jun, 2018
Problem – Write an assembly level language program to convert ASCII code to its respective HEX Code.
Examples:
Input: 
DATA: 31H in memory location 2050
Output:
DATA: 0BH in memory location 3050 
Assume that starting address of program, input memory location, and output memory locations are 2000, 2050, and 3050 respectively.
Algorithm –
Input the content of 2050 in accumulator.Subtract 30H from accumulator.Compare the content of accumulator with 0AH.If content of accumulator is less than 0A then goto step 6 else goto step 5.Subtract 07H from accumulator.Store content of accumulator to memory location 3050.Terminate the program.
Input the content of 2050 in accumulator.
Subtract 30H from accumulator.
Compare the content of accumulator with 0AH.
If content of accumulator is less than 0A then goto step 6 else goto step 5.
Subtract 07H from accumulator.
Store content of accumulator to memory location 3050.
Terminate the program.
Program –
Explanation –
LDA 2050 load the content of memory location 2050 to accumulator.SUI 30H subtracts 30H immediately from accumulator.CPI 0AH compare immediately 0AH with the data of accumulator.JC 200D check for carry if yes then go to address 200D.SUI 07H subtracts 07H immediately from accumulator.STA 3050 store the content of accumulator to memory location 3050.HLT stops the execution of program.
LDA 2050 load the content of memory location 2050 to accumulator.
SUI 30H subtracts 30H immediately from accumulator.
CPI 0AH compare immediately 0AH with the data of accumulator.
JC 200D check for carry if yes then go to address 200D.
SUI 07H subtracts 07H immediately from accumulator.
STA 3050 store the content of accumulator to memory location 3050.
HLT stops the execution of program.
microprocessor
system-programming
Computer Organization & Architecture
microprocessor
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Memory Hierarchy Design and its Characteristics
Computer Organization and Architecture | Pipelining | Set 1 (Execution, Stages and Throughput)
Flag register of 8086 microprocessor
Direct Access Media (DMA) Controller in Computer Architecture
Interrupts
I/O Interface (Interrupt and DMA Mode)
Flag register in 8085 microprocessor
Computer Organization and Architecture | Pipelining | Set 2 (Dependencies and Data Hazard)
Architecture of 8085 microprocessor
Addressing modes in 8086 microprocessor
C++ program to calculate GST from original and net prices

Given with the original cost and net price as an input and the task is to calculate the GST percentage and display the result
GST stands for Goods and Service task. It is always included in the Net price of the product and before calculating the GST percentage we need to calculate GST amount and for that there are formulas available
Netprice = originalcost + GSTAmount
GSTAmount = Netprice – original_cost
GST_Percentage = (GSTAmount * 100)/ originalcost
GST % formula = (GSTAmount*100) / originalcost
Input-: cost = 120.00
   price = 150.00
Output-: GST amount is = 25.00 %
Input-: price = 120.00
   cost = 100.00
Output-: GST amount is = 20.00 %
Approach used in the given program is as follows −
Take the input as net price and original cost
Apply the formula given to calculate GST percentage
Display the result
Start
Step 1-> declare function to calculate GST
   float GST(float cost, float price)
   return (((price - cost) * 100) / cost)
step 2-> In main()
   set float cost = 120
   set float price = 150
   call GST(cost, price)
Stop
 Live Demo
Using c++
#include <iostream>
using namespace std;
//function to calculate GST
float GST(float cost, float price) {
   return (((price - cost) * 100) / cost);
}
int main() {
   float cost = 120.00;
   float price = 150.00;
   cout << "GST amount is = "<<GST(cost, price)<<" % ";
   return 0;
}
IF WE RUN THE ABOVE CODE IT WILL GENERATE FOLLOWING OUTPUT
GST amount is = 25.00 %
 Live Demo
#include <stdio.h>
//function to calculate GST
float GST(float cost, float price) {
   return (((price - cost) * 100) / cost);
}
int main() {
   float cost = 120;
   float price = 150;
   float gst = GST(cost, price);
   printf("GST amount is : %.2f ",gst);
   return 0;
}
IF WE RUN THE ABOVE CODE IT WILL GENERATE FOLLOWING OUTPUT
GST amount is : 25.00
Disable a Bootstrap Button

When you disable a button, it will fade in color by 50%, and lose the gradient. Use disabled to disable any button.
To disable a button, you can try to run the following code −
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Example</title>
      <link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet">
      <script src = "/scripts/jquery.min.js"></script>
      <script src = "/bootstrap/js/bootstrap.min.js"></script>
   </head>
   <body>
      <p>The following are some buttons:</p>
      <button type = "button" class = "btn btn-default btn-lg ">
         Default Button
      </button>
      <button type = "button" class = "btn btn-default btn-lg active">
         Active Button
      </button>
      <button type = "button" class = "btn btn-default btn-lg" disabled = "disabled">
         Disabled Button
      </button>
   </body>
</html>
Firebase - Arrays

This chapter will explain the Firebase representation of arrays. We will use the same data from the previous chapter.
We could create this data by sending the following JSON tree to the player’s collection.
['john', 'amanda']

This is because Firebase does not support Arrays directly, but it creates a list of objects with integers as key names.
The reason for not using arrays is because Firebase acts as a real time database and if a couple of users were to manipulate arrays at the same time, the result could be problematic since array indexes are constantly changing.
The way Firebase handles it, the keys (indexes) will always stay the same. We could delete john and amanda would still have the key (index) 1.

    60 Lectures 
     5 hours 

 University Code

    28 Lectures 
     2.5 hours 

 Appeteria

    85 Lectures 
     14.5 hours 

 Appeteria

    46 Lectures 
     2.5 hours 

 Gautham Vijayan

    13 Lectures 
     1.5 hours 

 Nishant Kumar

    85 Lectures 
     16.5 hours 

 Rahul Agarwal
 Print
 Add Notes
 Bookmark this page
Python | Subtraction of dictionaries

27 Aug, 2021
Sometimes, while working with dictionaries, we might have a utility problem in which we need to perform elementary operations among the common keys of dictionaries. This can be extended to any operation to be performed. Let’s discuss subtraction of like key values and ways to solve it in this article. 
The combination of the above two can be used to perform this particular task. This is just a shorthand to the longer method of loops and can be used to perform this task in one line. 
Python3
# Python3 code to demonstrate working of# Subtraction of dictionaries# Using dictionary comprehension + keys() # Initialize dictionariestest_dict1 = {'gfg' : 6, 'is' : 4, 'best' : 7}test_dict2 = {'gfg' : 10, 'is' : 6, 'best' : 10} # printing original dictionariesprint("The original dictionary 1 : " +  str(test_dict1))print("The original dictionary 2 : " +  str(test_dict2)) # Using dictionary comprehension + keys()# Subtraction of dictionariesres = {key: test_dict2[key] - test_dict1.get(key, 0)                       for key in test_dict2.keys()} # printing resultprint("The difference dictionary is : " + str(res))
The original dictionary 1 : {'gfg': 6, 'is': 4, 'best': 7}
The original dictionary 2 : {'gfg': 10, 'is': 6, 'best': 10}
The difference dictionary is : {'gfg': 4, 'is': 2, 'best': 3}
 
The combination of the above methods can be used to perform this particular task. In this, the Counter function converts the dictionary in the form in which the minus operator can perform the task of subtraction. 
Python3
# Python3 code to demonstrate working of# Subtraction of dictionaries# Using Counter() + "-" operatorfrom collections import Counterfrom collections import subtract # Initialize dictionariestest_dict1 = {'gfg' : 6, 'is' : 4, 'best' : 7}test_dict2 = {'gfg' : 10, 'is' : 6, 'best' : 10} # printing original dictionariesprint("The original dictionary 1 : " +  str(test_dict1))print("The original dictionary 2 : " +  str(test_dict2)) # Using Counter() + "-" operator# Subtraction of dictionariestemp1 = Counter(test_dict1)temp2 = Counter(test_dict2)res = temp2 - temp1 # printing resultprint("The difference dictionary is : " + str(dict(res))) # Using the subtract method of test_dict2.subtract(test_dict1) # printing resultprint("The difference dictionary is : " + str(dict(test_dict2)))
                        The original dictionary 1 : {'gfg': 6, 'is': 4, 'best': 7}
                        The original dictionary 2 : {'gfg': 10, 'is': 6, 'best': 10}
                        The difference dictionary is : {'gfg': 4, 'is': 2, 'best': 3}
 
wvuq4qtrpgnnizfujqrdqfojlf6091nhax5bv35c
sweetyty
Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Java String indexOf() Method

❮ String Methods

Search a string for the first occurrence of "planet":
String myStr = "Hello planet earth, you are a great planet.";
System.out.println(myStr.indexOf("planet"));

Try it Yourself »

The indexOf() method returns the position of the first occurrence of specified character(s) in a string.
Tip: Use the lastIndexOf method to return the position of the last occurrence of specified character(s) in a string.
There are 4 indexOf() methods:
public int indexOf(String str)
public int indexOf(String str, int fromIndex)
public int indexOf(int char)
public int indexOf(int char, int fromIndex)

Find the first occurrence of the letter "e" in a string, starting the search at position 5:
public class Main {
  public static void main(String[] args) {
    String myStr = "Hello planet earth, you are a great planet.";
    System.out.println(myStr.indexOf("e", 5));
  }
}


Try it Yourself »

We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
C# | How to play Beep sound through Console - GeeksforGeeks

29 Jan, 2019
Given a normal Console in C#, the task is to play Beep sound through the Console.
Approach: This can be achieved with the help of Beep() method of Console Class in System package of C#.
The Beep() method of Console Class is used to play a Beep sound through the Console speaker.
Syntax: public static void Beep ();
Exceptions: This method throws HostProtectionException if this method was executed on a server, such as SQL Server, that does not permit access to a user interface.
Below programs show the use of Console.Beep() method:
Program 1:
// C# program to illustrate the// Console.Beep Methodusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading;using System.Threading.Tasks;  namespace GFG {  class Program {      static void Main(string[] args)    {        // Play beep sound once        Console.Beep();    }}}
Program 2: Play Beep sound n number of times.
// C# program to illustrate the// Console.Beep Methodusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading;using System.Threading.Tasks;  namespace GFG {  class Program {      static void Main(string[] args)    {        int n = 5;          // Play beep sound n times        for (int i = 1; i < n; i++)            Console.Beep();    }}}
Note: Please run the programs on offline Visual Studio to experience the output.
CSharp-Console-Class
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C# | Method Overriding
C# Dictionary with examples
Difference between Ref and Out keywords in C#
C# | Delegates
Top 50 C# Interview Questions & Answers
C# | Constructors
Extension Method in C#
Introduction to .NET Framework
C# | Abstract Classes
C# | Class and Object
Python – Split a String by Custom Lengths

11 Oct, 2020
Given a String, perform split of strings on the basis of custom lengths.
Input : test_str = ‘geeksforgeeks’, cus_lens = [4, 3, 2, 3, 1] Output : [‘geek’, ‘sfo’, ‘rg’, ‘eek’, ‘s’] Explanation : Strings separated by custom lengths.Input : test_str = ‘geeksforgeeks’, cus_lens = [10, 3] Output : [‘geeksforge’, ‘eks’] Explanation : Strings separated by custom lengths.  
Method #1 : Using slicing + loop
In this, we perform task of slicing to cater custom lengths and loop is used to iterate for all the lengths.
Python3
# Python3 code to demonstrate working of # Multilength String Split# Using loop + slicing  # initializing stringtest_str = 'geeksforgeeks'  # printing original stringprint("The original string is : " + str(test_str))  # initializing length listcus_lens = [5, 3, 2, 3]  res = []strt = 0for size in cus_lens:          # slicing for particular length    res.append(test_str[strt : strt + size])    strt += size      # printing result print("Strings after splitting : " + str(res)) 
The original string is : geeksforgeeks
Strings after splitting : ['geeks', 'for', 'ge', 'eks']

Method #2 : Using join() + list comprehension + next()
This is yet another way in which this task can be performed. In this, we perform task of getting character till length using next(),  iterator method, provides more efficient solution. Lastly, join() is used to convert each character list to string.
Python3
# Python3 code to demonstrate working of # Multilength String Split# Using join() + list comprehension + next()  # initializing stringtest_str = 'geeksforgeeks'  # printing original stringprint("The original string is : " + str(test_str))  # initializing length listcus_lens = [5, 3, 2, 3]  # join() performs characters to string conversion# list comprehension provides shorthand to solve problemstritr = iter(test_str)res = ["".join(next(stritr) for idx in range(size)) for size in cus_lens]      # printing result print("Strings after splitting : " + str(res)) 
The original string is : geeksforgeeks
Strings after splitting : ['geeks', 'for', 'ge', 'eks']

Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Calculate the Sum of Matrix or Array columns in R Programming – colSums() Function

03 Jun, 2020
colSums() function in R Language is used to compute the sums of matrix or array columns.
Syntax: colSums (x, na.rm = FALSE, dims = 1)
Parameters:x: matrix or arraydims: this is integer value whose dimensions are regarded as ‘columns’ to sum over. It is over dimensions 1:dims.
Example 1:
# R program to illustrate# colSums function  # Initializing a matrix with 3 # rows and 3 columnsx <- matrix(rep(1:9), 3, 3)  # Getting the matrix representationx  # Calling the colSums() functioncolSums(x)
Output:
     [, 1] [, 2] [, 3]
[1, ]    1    4    7
[2, ]    2    5    8
[3, ]    3    6    9

[1]  6 15 24

Example 2:
# R program to illustrate# colSums function  # Initializing a 3D arrayx <- array(1:12, c(2, 3, 3))  # Getting the array representationx  # Calling the colSums() functioncolSums(x, dims = 1)colSums(x, dims = 2)
Output:
,, 1

     [, 1] [, 2] [, 3]
[1, ]    1    3    5
[2, ]    2    4    6,, 2

     [, 1] [, 2] [, 3]
[1, ]    7    9   11
[2, ]    8   10   12,, 3

     [, 1] [, 2] [, 3]
[1, ]    1    3    5
[2, ]    2    4    6

     [, 1] [, 2] [, 3]
[1, ]    3   15    3
[2, ]    7   19    7
[3, ]   11   23   11

[1] 21 57 21

R Matrix-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Check whether a Numpy array contains a specified row

05 Sep, 2020
In this article we will learn about checking a specified row is in NumPy array or not. If the given list is present in a NumPy array as a row then the output is True else False. The list is present in a NumPy array means any row of that numpy array matches with the given list with all elements in given order. This can be done by using simple approach as checking for each row with the given list but this can be easily understood and implemented by using inbuilt library functions numpy.array.tolist().
Syntax: ndarray.tolist()
Parameters: none
Returns: The possibly nested list of array elements.
Examples :
Arr = [[1,2,3,4,5], [6,7,8,9,10], [11,12,13,14,15], [16,17,18,19,20]]
and the given lists are as follows :
lst  = [1,2,3,4,5]              True, as it matches with the row 0.      [16,17,20,19,18]         False, as it doesn’t match with any row.      [3,2,5,-4,5]             False, as it doesn’t match with any row.      [11,12,13,14,15]         True, as it matches with the row 2.
Below is the implementation with an example :
Python3
# importing packageimport numpy  # create numpy arrayarr = numpy.array([[1, 2, 3, 4, 5],                   [6, 7, 8, 9, 10],                   [11, 12, 13, 14, 15],                   [16, 17, 18, 19, 20]                   ])  # view arrayprint(arr)  # check for some listsprint([1, 2, 3, 4, 5] in arr.tolist())print([16, 17, 20, 19, 18] in arr.tolist())print([3, 2, 5, -4, 5] in arr.tolist())print([11, 12, 13, 14, 15] in arr.tolist())
Output :
[[ 1  2  3  4  5]
 [ 6  7  8  9 10]
 [11 12 13 14 15]
 [16 17 18 19 20]]
True
False
False
True

Python numpy-ndarray
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.