code-rag-bench/online-tutorials huggingface dataset:
How to invert key value in JavaScript object ?

03 Dec, 2020
JavaScript is a high level, interpreted and dynamically typed client-side scripting language. JavaScript is used to add dynamic features to the static HTML. Everything is an object in JavaScript. Objects in JavaScript can be declared using figure brackets {..} and the objects may comprise certain properties. These properties are basically key-value pairs. The key is an identifier which is used to store and retrieve values. Inverting key-value pairs is tedious using conventional methods. But with the advent of “underscore.js”, inversion of key values can be performed using the inbuilt method _.invert(). In this article, we shall discuss both the methods of inverting key value pairs of JavaScript objects. 
First Approach: In this example, we will demonstrate the conventional method of inverting key-value pairs. At first, a student object is created with properties “name”, “age”, “std” and “fees”. An inverse() function is defined which takes the student object as a parameter and loops through each key of the object. A new object retobj is defined which stores the inverted key value pairs.
Code Implementation:
Javascript
function inverse(obj){  var retobj = {};  for(var key in obj){    retobj[obj[key]] = key;  }  return retobj;}  var student = {    name : "Jack",    age: 18,    std : 12,    fees : 5000}console.log("Object before inversion");console.log(student);student = inverse(student);console.log("Object after inversion");console.log(student);
Output:
Second Approach: In this example, we use the _.invert() method of “underscore.js” to invert the key value pairs of the object. The method takes the object as a parameter and returns a copy of the object with the keys as values and values as keys. The “student” object is passed to the _.invert() method. The method returns the inverted copy of the “student” object. The program imports the external “underscore.js” library to use inbuilt methods. The results are displayed on the webpage.
Syntax:
_.invert(object)
Code Implementation:
HTML
<!DOCTYPE html><html>  <head>     <script        src="https://cdn.jsdelivr.net/npm/underscore@1.12.0/underscore-min.js">    </script></head>  <body>    <script type="text/javascript">        var student = {            name : "Jack",            age: 18,            std : 12,            fees : 5000        }          document.write("<h1>Object before inversion</h1>");        document.write("<br>");        document.write(JSON.stringify(student));        document.write("<br>");        student = JSON.stringify(_.invert(student));        document.write("<h1>Object after inversion</h1>");        document.write("<br>");        document.write(student);    </script></body>  </html>
Output:
HTML-Misc
JavaScript-Misc
Picked
Technical Scripter 2020
HTML
JavaScript
Technical Scripter
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Map entrySet() method in Java with Examples

20 Jan, 2022
The java.util.Map.entrySet() method in Java is used to create a set out of the same elements contained in the map. It basically returns a set view of the map or we can create a new set and store the map elements into them.
Syntax:
map.entrySet()
Parameters: The method does not take any parameter.
Return Value: The method returns a set having same elements as the hash map.
Below programs illustrate the java.util.Map.entrySet() Method:
Program 1: Mapping String Values to Integer Keys.
// Java code to illustrate the entrySet() method  import java.util.*;  public class Map_Demo {    public static void main(String[] args)    {        // Creating an empty Map        Map<Integer, String> map = new HashMap<Integer, String>();          // Mapping string values to int keys        map.put(10, "Geeks");        map.put(15, "4");        map.put(20, "Geeks");        map.put(25, "Welcomes");        map.put(30, "You");          // Displaying the Map        System.out.println("Initial Mappings are: " + map);          // Using entrySet() to get the set view        System.out.println("The set is: " + map.entrySet());    }}
Initial Mappings are: {20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=4}
The set is: [20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=4]

Program 2: Mapping Integer Values to String Keys.
// Java code to illustrate the entrySet() methodimport java.util.*;  public class Map_Demo {    public static void main(String[] args)    {        // Creating an empty Map        Map<String, Integer> map = new HashMap<String, Integer>();          // Mapping int values to string keys        map.put("Geeks", 10);        map.put("4", 15);        map.put("Geeks", 20);        map.put("Welcomes", 25);        map.put("You", 30);          // Displaying the Map        System.out.println("Initial Mappings are: " + map);          // Using entrySet() to get the set view        System.out.println("The set is: " + map.entrySet());    }}
Initial Mappings are: {4=15, Geeks=20, You=30, Welcomes=25}
The set is: [4=15, Geeks=20, You=30, Welcomes=25]

Note: The same operation can be performed with any type of Mappings with variation and combination of different data types.
Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Map.html#entrySet()
simmytarika5
Java-Collections
Java-Functions
java-map
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
Stream In Java
ArrayList in Java
Collections in Java
Singleton Class in Java
Multidimensional Arrays in Java
Stack Class in Java
Initialize an ArrayList in Java
Initializing a List in Java
Introduction to Java
Python eval()

The eval() method parses the expression passed on to this method and runs the expression within the program. In other words, it interprets a string as code inside a python program.
The Syntax for eval is as below −
eval(expression, globals=None, locals=None)
Where
Expression − It is the python expression passed onto the method.
Expression − It is the python expression passed onto the method.
globals − A dictionary of available global methods and variables.
globals − A dictionary of available global methods and variables.
locals − A dictionary of available local methods and variables.
locals − A dictionary of available local methods and variables.
In the below example we allow the user to cerate an expression and run a python program to evaluate that expression. So it helps in create dynamic code.
 Live Demo
# expression to be evaluated
user_expr = raw_input("Enter an expression in terms of variable a):")
#nter the value of variable
a = int(raw_input("Enter the value of a:"))
# evaluate the expression
result = eval(user_expr)
# printing evaluated result
print("Result = {}".format(result))
Running the above code gives us the following result −
Enter an expression in terms of variable a):a*(a-3)+a^2
Enter the value of a:7
Result = 33
For programs involving web applications or desktop programs there is a chance that the use of such eval() method will create security vulnerabilities because the use running the program may supply expressions which are system commands to delete files or get sensitive data out of the system. As a step to prevent this we can restrict the eval() function to some selected functions or variables.
The steps to prevent these vulnerabilities are as below −
In this way it will be evaluated only in the current scope and not find other variables outside this scope.
On omitting the local variable, all the variables are scoped as global variable. Next we pass on an empty dictionary as the global variable and that allows only the built-in variables to be available even when we have imported other libraries to the program.
 Live Demo
from time import *
print(eval('dir()', {}))
Running the above code gives us the following result −
['__builtins__']
Next we can also allow only certain methods from the imported library to be available to the program.
 Live Demo
from time import *
print(eval('dir()', {'sleeptime': sleep, 'Localtime': localtime}))
Running the above code gives us the following result −
['Localtime', '__builtins__', 'sleeptime']
We can also restrict the availability of function in both local and global scope by allowing none of the built ins and only a few from the locally imported libraries. In the below example we have made only the gmtime method available from time library.
 Live Demo
from time import *
a = 1445945763
print(eval('gmtime(a)', {'__builtins__': None}, {'a': a, 'gmtime': gmtime}))
Running the above code gives us the following result −
time.struct_time(tm_year=2015, tm_mon=10, tm_mday=27, tm_hour=11, tm_min=36, tm_sec=3, tm_wday=1, tm_yday=300, tm_isdst=0)
Bottom Up Testing

Each component at lower hierarchy is tested individually and then the components that rely upon these components are tested.
The order of Integration by Bottom-down approach will be:
4,2
5,2
6,3
7,3
2,1
3,1

+ Firstly, Test 4,5,6,7 individually using drivers.
+ Test 2 such that it calls 4 and 5 separately. If an error occurs we know that the problem is in one of the modules.
+ Test 1 such that it calls 3 and If an error occurs we know that the problem is in 3 or in the interface between 1 and 3
Though Top level components are the most important, yet tested last using this strategy. In Bottom-up approach, the Components 2 and 3 are replaced by drivers while testing components 4,5,6,7. They are generally more complex than stubs.
What does the if __name__ == "__main__": do in Python?

When the Python interpreter reads a source file, it executes all of the code found in it.
Before executing the code, it will define a few special variables. For example, if the python interpreter is running that module (the source file) as the main program, it sets the special __name__ variable to have a value "__main__". If this file is being imported from another module, __name__ will be set to the module's name.
One reason for doing this is that sometimes you write a module (a .py file) where it can be executed directly. Alternatively, it can also be imported and used in another module. By doing the main check, you can have that code only execute when you want to run the module as a program and not have it execute when someone just wants to import your module and call your functions themselves.
For example, if you have 2 files one.py and two.py with the following code:
one.py:
def func():
    print("func() in one.py")
print("Root of one.py")
if __name__ == "__main__":
    print("one.py is being run directly")
else:
    print("one.py is being imported")
Two.py:
import one
print("Root of two.py")
one.func()
if __name__ == "__main__":
    print("two.py is being run directly")
else:
    print("two.py is being imported")
Now if you run,
$ python one.py
You will get the output:
Root of one.py
one.py is being run directly
But if you run,
$ python two.py
You will get the output:
Root of in one.py
one.py is being imported
Root of in two.py
func() in one.py
two.py is being run directly
What is the purpose of the testng.xml file?

The testng.xml file has the numerous uses as listed below −
Test cases are executed in groups.
Test cases are executed in groups.
Test methods can be included or excluded in the execution.
Test methods can be included or excluded in the execution.
The execution of multiple test cases from multiple java class files can be
triggered.
The execution of multiple test cases from multiple java class files can be
triggered.
Comprises names of the folder, class, method.
Comprises names of the folder, class, method.
Capable of triggering parallel execution.
Capable of triggering parallel execution.
Test methods belonging to groups can be included or excluded in the
execution.
Test methods belonging to groups can be included or excluded in the
execution.
TestNG.xml file
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name = "Cycle1">
   <test name = "Tutorialspoint">
   <classes>
      <class name = "Test1" />
         <methods>
            <exclude name= “Login.*”/>
         </methods>
      </classes>
   </test>
</suite>
Here as per the xml file, all the test methods with starting name Login will be
excluded from test execution.
@Test
public void VerifyPay(){
   System.out.println("Verify payment is successful”);
}
@Test
public void LoginAdmin(){
   System.out.println("Login is successful in admin”);
}
@Test
public void LoginSystem(){
   System.out.println("Login is successful”);
}
Here as per the java class file, only VerifyPay() will be executed since all methods starting with name Login will be excluded from test execution.
Python MongoDB - Create Database

Unlike other databases, MongoDB does not provide separate command to create a database.
In general, the use command is used to select/switch to the specific database. This command initially verifies whether the database we specify exists, if so, it connects to it. If the database, we specify with the use command doesn’t exist a new database will be created.
Therefore, you can create a database in MongoDB using the Use command.
Basic syntax of use DATABASE statement is as follows −
use DATABASE_NAME

Following command creates a database named in mydb.
>use mydb
switched to db mydb

You can verify your creation by using the db command, this displays the current database.
>db
mydb

To connect to MongoDB using pymongo, you need to import and create a MongoClient, then you can directly access the database you need to create in attribute passion.
Following example creates a database in MangoDB.
from pymongo import MongoClient

#Creating a pymongo client
client = MongoClient('localhost', 27017)

#Getting the database instance
db = client['mydb']
print("Database created........")

#Verification
print("List of databases after creating new one")
print(client.list_database_names())
Database created........
List of databases after creating new one:
['admin', 'config', 'local', 'mydb']

You can also specify the port and host names while creating a MongoClient and can access the databases in dictionary style.
from pymongo import MongoClient

#Creating a pymongo client
client = MongoClient('localhost', 27017)

#Getting the database instance
db = client['mydb']
print("Database created........")
Database created........


    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 do I remove a particular element from an array in JavaScript

To remove an element from an array, use the splice() method. JavaScript array splice() method changes the content of an array, adding new elements while removing old elements.
The following are the parameters −
index − Index at which to start changing the array.
index − Index at which to start changing the array.
howMany − An integer indicating the number of old array elements to remove. If howMany is a 0, then no elements are removed.
howMany − An integer indicating the number of old array elements to remove. If howMany is a 0, then no elements are removed.
element1, ..., elementN − The elements adds to the array. If you don't specify any elements, splice simply removes the elements from the array.
element1, ..., elementN − The elements adds to the array. If you don't specify any elements, splice simply removes the elements from the array.
You can try to run the following code to learn how to add and remove individual elements in a JavaScript array −
<html>
   <head>
      <title>JavaScript Array splice Method</title>
   </head>
   
   <body>
      <script>
         var arr = ["orange", "mango", "banana", "sugar", "tea"];

         var removed = arr.splice(2, 0, "water");
         document.write("After adding 1: " + arr );
         document.write("<br />removed is: " + removed);

         removed = arr.splice(3, 1);
         document.write("<br />After adding 1: " + arr );
         document.write("<br />removed is: " + removed);
      </script>
   </body>
   
</html>
After adding 1: orange,mango,water,banana,sugar,tea
removed is: 
After adding 1: orange,mango,water,sugar,tea
removed is: banana
Describe about net income approach in capital structure.

Capital structure plays an important role in value of a company. Different companies have different
capital structures like some have capital based on debt, some have based on equity and some have a
mixed or combination of both in their financial mix.
Durand proposed net income approach and he states that change in cost of capital and valuation of
company will change, if there a change in financial leverage. Capital structure is relevant to valuation of a firm. Increase in financial leverage leads to increase in weighted average cost of capital (WACC) and value of firm will increase.
Market value of equity shares depends on amount available after paying interest on debt. This approach prepositions that market value depends on the amount available for equity shareholders. Net income and cost of capital depends on use of Debt in capital structure, which had an impact on equity shares and market value.
NI = NOI – I
Where, NI = net income, NOI = net operating income and I = interest on debt.
Assumptions related to net income are as follows −
No taxes
No taxes
Cost of equity > cost of debt.
Cost of equity > cost of debt.
Both debt and equity capitalisations are constant.
Both debt and equity capitalisations are constant.
Debt proportion is independent of investors risk.
Debt proportion is independent of investors risk.
Dividend pay-out ratio is 1.
Dividend pay-out ratio is 1.
V = E + D
Where, V = market value (firm), E = market value (Equity) + Market value (Debt)
E = equity shareholder’s income/ cost of equity
D = interest rate on debt/ cost of Debt
Cost of capital = NOI/V
Degree of financial leverage = D/V
Where, NOI = Net operating income.
Disadvantages of net income are as follows −
Corporate taxes are not considered.
Corporate taxes are not considered.
It has constant cost of debt (interest rate depends on fund providers).
It has constant cost of debt (interest rate depends on fund providers).
Financial risk increases with increase debt.
Financial risk increases with increase debt.
Financial leverage increases with increase in equity capitalisation.
Financial leverage increases with increase in equity capitalisation.
Batch Script - TYPE

This batch command prints the content of a file or files to the output.
TYPE [filename]

Where filename is the file whose contents need to be displayed.
@echo off 
TYPE C:\tp\lists.txt
The contents of the file lists.txt will be displayed to the command prompt.
 Print
 Add Notes
 Bookmark this page
How to convert date YYYYMMDD to YY-MM-DD in MySQL query?

To convert date YYYYMMDD to YY-MM-DD in MySQL, use the below syntax −
select date_format(str_to_date(yourColumnName, '%Y%m%d'),'%Y-%m-%d') from yourTableName;
Let us first create a table −
mysql> create table DemoTable
(
   ClientId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   ClientProjectDeadline varchar(200)
);
Query OK, 0 rows affected (0.57 sec)
Insert some records in the table using insert command. We have inserted dates in the YYYYMMDD format −
mysql> insert into DemoTable(ClientProjectDeadline) values('20121221');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable(ClientProjectDeadline) values('20190416');
Query OK, 1 row affected (0.53 sec)
mysql> insert into DemoTable(ClientProjectDeadline) values('20160624');
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable(ClientProjectDeadline) values('20170131');
Query OK, 1 row affected (0.20 sec)
Following is the query to display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+----------+-----------------------+
| ClientId | ClientProjectDeadline |
+----------+-----------------------+
| 1        | 20121221              |
| 2        | 20190416              |
| 3        | 20160624              |
| 4        | 20170131              |
+----------+-----------------------+
4 rows in set (0.00 sec)
Following is the query to convert date YYYYMMDD to YY-MM-DD in MySQL −
mysql> select date_format(str_to_date(ClientProjectDeadline, '%Y%m%d'),'%Y-%m-%d') from DemoTable;
This will produce the following output −
+----------------------------------------------------------------------+
| date_format(str_to_date(ClientProjectDeadline, '%Y%m%d'),'%Y-%m-%d') |
+----------------------------------------------------------------------+
| 2012-12-21                                                           |
| 2019-04-16                                                           |
| 2016-06-24                                                           |
| 2017-01-31                                                           |
+----------------------------------------------------------------------+
4 rows in set (0.05 sec)
Swift - Deinitialization

Before a class instance needs to be deallocated 'deinitializer' has to be called to deallocate the memory space. The keyword 'deinit' is used to deallocate the memory spaces occupied by the system resources. Deinitialization is available only on class types.
Swift 4 automatically deallocates your instances when they are no longer needed, to free up resources. Swift 4 handles the memory management of instances through automatic reference counting (ARC), as described in Automatic Reference Counting. Typically you don't need to perform manual clean-up when your instances are deallocated. However, when you are working with your own resources, you might need to perform some additional clean-up yourself. For example, if you create a custom class to open a file and write some data to it, you might need to close the file before the class instance is deallocated.
var counter = 0; // for reference counting
class baseclass {
   init() {
      counter++;
   }
   deinit {
      counter--;
   }
}
var print: baseclass? = baseclass()

print(counter)
print = nil
print(counter)
When we run the above program using playground, we get the following result −
1
0

When print = nil statement is omitted the values of the counter retains the same since it is not deinitialized.
var counter = 0; // for reference counting

class baseclass {
   init() {
      counter++;
   }
   deinit {
      counter--;
   }
}
var print: baseclass? = baseclass()
print(counter)
print(counter)
When we run the above program using playground, we get the following result −
1
1


    38 Lectures 
     1 hours 

 Ashish Sharma

    13 Lectures 
     2 hours 

 Three Millennials

    7 Lectures 
     1 hours 

 Three Millennials

    22 Lectures 
     1 hours 

 Frahaan Hussain

    12 Lectures 
     39 mins

 Devasena Rajendran

    40 Lectures 
     2.5 hours 

 Grant Klimaytys
 Print
 Add Notes
 Bookmark this page
Android - Emulator

The Android SDK includes a virtual mobile device emulator that runs on your computer. The emulator lets you prototype, develop and test Android applications without using a physical device.
In this chapter we are going to explore different functionalities in the emulator that are present in the real android device.
If you want to emulate a real device, first crate an AVD with the same device configurations as real device, then launch this AVD from AVD manager.
Usually by default when you launch the emulator, its orientation is vertical, but you can change it orientation by pressing Ctrl+F11 key from keyboard.
First launch the emulator. It is shown in the picture below −
Once it is launched, press Ctrl+F11 key to change its orientation. It is shown below −
Apart from just orientation commands, there are other very useful commands of emulator that you should keep in mind while using emulator. They are listed below −
Home
Shifts to main screen
F2
Toggles context sensitive menu
F3
Bring out call log
F4
End call
F5
Search
F6
Toggle trackball mode
F7
Power button
F8
Toggle data network
Ctrl+F5
Ring Volume up
Ctrl+F6
Ring Volume down
You can emulate sending SMS to your emulator. There are two ways to do that. You can do that from DDMS which can be found in Android studio, or from Telnet.(Network utility found in windows).
Telnet is not enabled by default in windows. You have to enable it to use it. Once enabled you can go to command prompt and start telnet by typing telnet.
In order to send SMS , note down the AVD number which can be found on the title bar of the emulator. It could be like this 5554 e.t.c. Once noted , type this command in command prompt.
telnet localhost 5554

Press enter when you type the command. It is shown below in the figure.
You will see that you are now connected to your emulator. Now type this command to send message.
sms send 1234 "hello"

Once you type this command , hit enter. Now look at the AVD. You will receive a notification displaying that you got a new text message. It is shown below −
You can easily make phone calls to your emulator using telent client. You need to connect to your emulator from telnet. It is discussed in the sending sms topic above.
After that you will type this command in the telent window to make a call. Its syntax is given below −
gsm call 1234

Once you type this command , hit enter. Now look at the AVD. You will receive a call from the number your put in the command. It is shown below −
You can easily transfer files into the emulator and vice versa. In order to do that, you need to select the DDMS utility in Android studio. After that select the file explorer tab. It is shown below −
Browse through the explorer and make new folder , view existing contents e.t.c.

    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
Get and Set Working Directory in R - GeeksforGeeks

30 Jun, 2021
In this article, we are going to see how to get and set a working directory in R Programming Language.
getwd(): The getwd() method is used to gather information about the current working pathname or default working directory. This function has no arguments. It returns an absolute pathname. It returns NULL in case there is not any working directory. 
getwd()
Code:
R
# getting the working directorygetwd()
Output
[1] "/Users/mallikagupta/Desktop"
setwd(): This method is used to set the specified pathname as the current working space directory of the R console. 
Syntax: setwd(dir) 
Where, dir is specify a working directory. 
The setwd() function allows us to move a hierarchy level up in the folder domain using the “..” argument in this method. 
Code:
R
# getting the working directoryprint ("Current working directory")getwd()  # set working directory to its parents directorysetwd("..")print ("Modified working directory")getwd()
Output
[1] "Current working directory"
[1] "/Users/mallikagupta/Desktop" 
[1] "Modified working directory" 
[1] "/Users/mallikagupta"
The subfolders can be easily accessed once the root directory has been set or is available by further specifying the character name of the sub-directory as a character string in the function arguments. 
R
# setting parent directorysetwd("/Users/mallikagupta/Desktop")  # adding sub directorysetwd("GFG")print ("Current working directory")  # getting the working directorygetwd()
Output
[1] "Current working directory" 
[1] "/Users/mallikagupta/Desktop/GFG"
Picked
R directory-programs
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Change Color of Bars in Barchart using ggplot2 in R
Data Visualization in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
Logistic Regression in R Programming
How to Split Column Into Multiple Columns in R DataFrame?
Control Statements in R Programming
How to import an Excel File into R ?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
How to update only one property in MongoDB?

To update only one property, use $addToSet in MongoDB. Let us create a collection with documents −
> db.demo336.insertOne({"Name":"Chris","Score":[45,67,78]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e522cb1f8647eb59e562097")
}
> db.demo336.insertOne({"Name":"David","Score":[89,93,47]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e522cb2f8647eb59e562098")
}
Display all documents from a collection with the help of find() method −
> db.demo336.find();
This will produce the following output −
{ "_id" : ObjectId("5e522cb1f8647eb59e562097"), "Name" : "Chris", "Score" : [ 45, 67, 78 ] }
{ "_id" : ObjectId("5e522cb2f8647eb59e562098"), "Name" : "David", "Score" : [ 89, 93, 47 ] }
Following is the query to update only one property in MongoDB −
> db.demo336.update({Name:"David"},{ $addToSet: {Score: [56,34,71] }});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo336.find();
This will produce the following output −
{ "_id" : ObjectId("5e522cb1f8647eb59e562097"), "Name" : "Chris", "Score" : [ 45, 67, 78 ] }
{ "_id" : ObjectId("5e522cb2f8647eb59e562098"), "Name" : "David", "Score" : [ 89, 93, 47, [ 56, 34, 71 ] ] }
Parse and format a number to decimal in Java

To parse and format a number to decimal, try the following code.
 Live Demo
public class Demo {
   public static void main( String args[] ) {
      int val = Integer.parseInt("5");
      String str = Integer.toString(val);
      System.out.println(str);
   }
}
5
In the above program, we have used the Integer.parseInt() and Integer.toString() method to convert a number to decimal.
int val = Integer.parseInt("5");
String str = Integer.toString(val);
The toString() method above represents a value in string and formats.
Java Examples - Spliting a String

How to split a string into a number of substrings ?
Following example splits a string into a number of substrings with the help of str split(string) method and then prints the substrings.
public class JavaStringSplitEmp{
   public static void main(String args[]) {
      String str = "jan-feb-march";
      String[] temp;
      String delimeter = "-";
      temp = str.split(delimeter);
      
      for(int i = 0; i < temp.length; i++) {
         System.out.println(temp[i]);
         System.out.println("");
         str = "jan.feb.march";
         delimeter = "\\.";
         temp = str.split(delimeter);
      }
      for(int i = 0; i < temp.length; i++) {
         System.out.println(temp[i]);
         System.out.println("");
         temp = str.split(delimeter,2);
         
         for(int j = 0; j < temp.length; j++){
            System.out.println(temp[j]);
         }
      }
   }
}
The above code sample will produce the following result.
jan

feb

march

jan

jan
feb.march
feb.march

jan
feb.march

This is another example of string split
public class HelloWorld {
   public static void main(String args[]) {
      String s1 = "t u t o r i a l s"; 
      String[] words = s1.split("\\s"); 
      for(String w:words) {
         System.out.println(w);  
      }  
   }
}
The above code sample will produce the following result.
t 
u 
t 
o 
r 
i 
a 
l 
s 

 Print
 Add Notes
 Bookmark this page
Address Binding and its Types - GeeksforGeeks

23 Oct, 2020
In this article, We are going to cover address binding with the help of an example and Its types like compile time, load time, and execution time address binding. Let’s discuss one by one.
Address Binding :The Association of program instruction and data to the actual physical memory locations is called the Address Binding. Let’s consider the following example given below for better understanding.
Consider a program P1 has the set of instruction such that I1, I2, I3, I4, and program counter value is 10, 20, 30, 40 respectively.
Program P1
I1 --> 10 
I2 --> 20 
I3 --> 30 
I4 --> 40

Program Counter = 10, 20, 30, 40

Types of Address Binding :
Address Binding divided into three types as follows.
Compile-time Address BindingLoad time Address BindingExecution time Address Binding
Compile-time Address Binding
Load time Address Binding
Execution time Address Binding
Compile-time Address Binding :
If the compiler is responsible for performing address binding then it is called compile-time address binding.
It will be done before loading the program into memory.
The compiler requires interacts with an OS memory manager to perform compile-time address binding.
Load time Address Binding :
It will be done after loading the program into memory.
This type of address binding will be done by the OS memory manager i.e loader.
Execution time or dynamic Address Binding :
It will be postponed even after loading the program into memory.
The program will be kept on changing the locations in memory until the time of program execution.
The dynamic type of address binding done by the processor at the time of program execution.
Note :The majority of the Operating System practically implement dynamic loading, dynamic linking, dynamic address binding. For example – Windows, Linux, Unix all popular OS.
Compiler Design
GATE CS
Operating Systems
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Directed Acyclic graph in Compiler Design (with examples)
Difference between Top down parsing and Bottom up parsing
Loop Optimization in Compiler Design
S - attributed and L - attributed SDTs in Syntax directed translation
Why FIRST and FOLLOW in Compiler Design?
Layers of OSI Model
ACID Properties in DBMS
TCP/IP Model
Page Replacement Algorithms in Operating Systems
Types of Operating Systems
How do I get the 'state' of a Tkinter Checkbutton?

Tkinter provides a variety of input widgets such as entry widget, text widget, listbox, combobox, spinbox, checkbox, etc. Checkboxes are used for taking validity input and the state gets active whenever the user clicks on the checkbutton. In terms of a particular application, we can check the state of the tkinter CheckButtons by using the state() method. It prints the actual state of the tkinter checkbuttons.
#Import the required library
from tkinter import*
from tkinter import ttk
#Create an instance of tkinter frame
win= Tk()
#Set the geometry
win.geometry("750x250")
#Define geometry of the window
win.geometry("750x250")
#Create CheckButtons
chk= ttk.Checkbutton(win, text="Python")
chk.pack()
chk.config(state=NORMAL)
print(chk.state())
win.mainloop()
Running the example code will display a window with a check button that is initially defined as normal state.
Now, remove the line "win.mainloop()" from the program to print the state of the checkbox on the console.
('alternate',)
How to set Row Header View for JScrollPane in Java?

Set Row Header View using the setRowHeaderView() method. Let us first create a KScrollPane and set a list −
List<String> myList = new ArrayList<>(10);
for (int index = 0; index < 20; index++) {
   myList.add("List Item " + index);
}
final JList<String> list = new JList<String>(myList.toArray(new String[myList.size()]));
JScrollPane scrollPane = new JScrollPane();
scrollPane.setViewportView(list);
Now, set the row header view −
scrollPane.setRowHeaderView(new JLabel("All List Items "));
The following is an example to set row header view for JScrollPane in Java −
package my;
import java.awt.BorderLayout;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
public class SwingDemo {
   public static void main(String[] args) {
      JPanel panel = new JPanel(new BorderLayout());
      List<String> myList = new ArrayListlt;>(10);
      for (int index = 0; index lt; 20; index++) {
         myList.add("List Item " + index);
      }
      final JListlt;String> list = new JListlt;String>(myList.toArray(new String[myList.size()]));
      JScrollPane scrollPane = new JScrollPane();
      scrollPane.setViewportView(list);
      scrollPane.setRowHeaderView(new JLabel("All List Items "));
      list.setLayoutOrientation(JList.VERTICAL);
      panel.add(scrollPane);
      JFrame frame = new JFrame("Demo");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.add(panel);
      frame.setSize(500, 250);
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }
}
An array of streams in C#

Set the string array for the values −
string[] names = new string[] {"Jack", "Tom"};
Now using foreach array, write the content in the file −
using (StreamWriter sw = new StreamWriter("names.txt")) {

   foreach (string s in names) {
      sw.WriteLine(s);
   }
}
The following is an example showing an array of streams to write text to a file −
using System;
using System.IO;

namespace FileApplication {
   class Program {
      static void Main(string[] args) {
         string[] names = new string[] {"Jack", "Tom"};

         using (StreamWriter sw = new StreamWriter("names.txt")) {

            foreach (string s in names) {
               sw.WriteLine(s);
            }
         }

         // Read and show each line from the file.
         string line = "";
         using (StreamReader sr = new StreamReader("names.txt")) {
            while ((line = sr.ReadLine()) != null) {
               Console.WriteLine(line);
            }
         }
         Console.ReadKey();
      }
   }
}
How to assign int value to char variable in Java

To assign int value to a char variable in Java would consider the ASCII value and display the associated character/ digit.
Here, we have a char.
char val;
Now assign int value to it.
val = 77;
Now, when you will print the value of “val”, it would display the character associate with the value (ASCII) 77.
The following is the complete example.
 Live Demo
public class Demo {
   public static void main(String []args) {
      char val;
      val = 77;
      System.out.print("Value: ");
      System.out.println(val);
   }
}
Value: M
Center links in a Navigation Bar with CSS

To center links in a navigation bar, you need to add ‘text-align: center’ to <li>
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <style>
         ul {
            list-style-type: none;
            margin: 0;
            padding: 0;
            width: 200px;
         }
         li a {
            display: block;
            background-color: #F0E7E7;
         }
         .active {
            background-color: #4CAF50;
            color: white;
         }
         li {
            text-align: center;
            border-bottom: 1px solid #555;
         }
      </style>
   </head>
   <body>
      <ul>
         <li><a href = "#home">Home</a></li>
         <li><a href = "#company" class = "active">Company</a></li>
         <li><a href = "#product">Product</a></li>
         <li><a href = "#services">Services</a></li>
         <li><a href = "#contact">Contact</a></li>
      </ul>
   </body>
</html>
Initialization of a multidimensional arrays in C/C++

In multidimensional array, the array should have dimension more that 1. The following diagram shows the memory allocation strategy for a multidimensional array with dimension 3 x 3 x 3.
This is a C++ program to initialize a multidimensional array.
Begin
   Initialize the elements of a multidimensional array.
   Print the size of the array.
   Display the content of the array.
End
#include<iostream>
using namespace std;
int main()
{
   int r, c;
   int a[][2] = {{3,1},{7,6}};
   cout<< "Size of the Array:"<<sizeof(a)<<"\n";
   cout<< "Content of the Array:"<<sizeof(a)<<"\n";
   for(r=0; r<2; r++) {
      for(c=0; c<2; c++) {
         cout << " " << a[r][c];
      }
      cout << "\n";
   }
   return 0;
}
Size of the Array:16
Content of the Array:16
3 1
7 6
How to make phone call in iOS 10 using Swift?

In this post we will be seeing how to make phone in iOS programmatically.
So let’s get started.
Step 1 − Open Xcode → New Project → Single View Application → Let’s name it “MakeCall”
Step 2 − Open Main.storyboard and add one text field and one button as shown below
Step 3 − Create @IBOutlet for the text field, name it phoneNumberTextfield.
Step 4 − Create @IBAction method callButtonClicked for call button
Step 5 − To make a call we can use iOS openURL. In callButtonClicked add following lines
if let url = URL(string: "tel://\(phoneNumberTextfield.text!)"),
UIApplication.shared.canOpenURL(url) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
Step 6 − Run the app and enter the number you want to make call to as shown in the pic below
Step 7 − Click on the call button, you will be shown an alert with ‘Call’ and ‘Cancel’ options
Step 8 − Click on the call button, the call will be made to the number, as shown below
rev command in Linux with Examples - GeeksforGeeks

24 May, 2019
rev command in Linux is used to reverse the lines characterwise. This utility basically reverses the order of the characters in each line by copying the specified files to the standard output. If no files are specified, then the standard input will read.
Syntax:
rev [option] [file...]

Example 1: Taking input from standard input
Example 2: Suppose we have a text file named as sample.txt
Using rev command on sample file. It will display the result on the terminal as follows:
Options:
rev -V: This option display the version information and exit.rev -V
rev -V
rev -h: This option will show the help message and exit.rev -h
rev -h
linux-command
Linux-text-processing-commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
scp command in Linux with Examples
nohup Command in Linux with Examples
mv command in Linux with examples
Thread functions in C/C++
Docker - COPY Instruction
chown command in Linux with Examples
nslookup command in Linux with Examples
SED command in Linux | Set 2
Named Pipe or FIFO with example C program
uniq Command in LINUX with examples
Multiple COUNT() for multiple conditions in a single MySQL query?

You can count multiple COUNT() for multiple conditions in a single query using GROUP BY.
The syntax is as follows -
SELECT yourColumnName,COUNT(*) from yourTableName group by yourColumnName;
To understand the above syntax, let us first create a table. The query to create a table is as follows.
mysql> create table MultipleCountDemo
-> (
-> Id int,
-> Name varchar(100),
-> Age int
-> );
Query OK, 0 rows affected (2.17 sec)
Insert records in the table using insert command. The query is as follows.
mysql> insert into MultipleCountDemo values(1,'Carol',21);
Query OK, 1 row affected (0.27 sec)

mysql> insert into MultipleCountDemo values(2,'Sam',21);
Query OK, 1 row affected (0.29 sec)

mysql> insert into MultipleCountDemo values(3,'Bob',22);
Query OK, 1 row affected (0.10 sec)

mysql> insert into MultipleCountDemo values(4,'John',23);
Query OK, 1 row affected (0.24 sec)

mysql> insert into MultipleCountDemo values(5,'David',22);
Query OK, 1 row affected (0.12 sec)

mysql> insert into MultipleCountDemo values(6,'Adam',22);
Query OK, 1 row affected (0.21 sec)

mysql> insert into MultipleCountDemo values(7,'Johnson',23);
Query OK, 1 row affected (0.14 sec)

mysql> insert into MultipleCountDemo values(8,'Elizabeth',23);
Query OK, 1 row affected (0.25 sec)
Display all records from the table using select statement. The query is as follows -
mysql> select *from MultipleCountDemo;
The following is the output.
+------+-----------+------+
| Id | Name | Age |
+------+-----------+------+
| 1 | Carol | 21 |
| 2 | Sam | 21 |
| 3 | Bob | 22 |
| 4 | John | 23 |
| 5 | David | 22 |
| 6 | Adam | 22 |
| 7 | Johnson | 23 |
| 8 | Elizabeth | 23 |
+------+-----------+------+
8 rows in set (0.00 sec)
Now here is the query for multiple count() for multiple conditions in a single query.
mysql> select Age,count(*)as AllSingleCount from MultipleCountDemo group by Age;
The following is the output.
+------+----------------+
| Age | AllSingleCount |
+------+----------------+
| 21 | 2 |
| 22 | 3 |
| 23 | 3 |
+------+----------------+
3 rows in set (0.00 sec)
Maximum sum of hour glass in matrix in C++

In this problem, we are given a matrix. Our task is to create a program that finds the maximum sum of the hourglass in a matrix in C++.
Program description − Here, we will find the maximum sum of all hourglasses that can be created for the given matrix elements.
Hour glass is a 7 element shape made in the matrix in the following form,
X X X
  X
X X X
Let’s take an example to understand the problem,
Input −
array ={
   {2 4 0 0}
   {0 1 1 0}
   {4 2 1 0}
   {0 3 0 1}}
Output −
Explanation −
Hour glass are :
2    4    0       0    1    1
     1                 2
4    2    1       0    3    0
4    0    0       1    1    0
     1                 1
2    1    0       3    0    1
So, an hourglass can be created using the following indexes,
matrix[i][j]    matrix[i][j+1]    matrix[i][j+2]
               matrix[i+1][j+1]
matrix[i+2][j] matrix[i+2][j+1]   matrix[i+2][j+2]
We will find the sum of all these elements of the array from [0][0] to [R2][C-2] starting points. And the find the maxSum for all these hourglasses created from array elements.
Program to illustrate the working of our solution,
 Live Demo
#include<iostream>
using namespace std;
const int row = 4;
const int col = 4;
int findHourGlassSum(int mat[row][col]){
   if (row<3 || col<3)
      return -1;
   int maxSum = 0;
   for (int i=0; i<row-2; i++){
      for (int j=0; j<col-2; j++){
         int hrSum = (mat[i][j]+mat[i][j+1]+mat[i][j+2])+ (mat[i+1][j+1])+ (mat[i+2][j]+mat[i+2][j+1]+mat[i+2][j+2]);
         maxSum = max(maxSum, hrSum);
      }
   }
   return maxSum;
}
int main() {
   int mat[row][col] = {
      {2, 4, 0, 0},
      {0, 1, 1, 0},
      {4, 2, 1, 0},
      {0, 3, 0, 1}};
      int maxSum = findHourGlassSum(mat);
      if (maxSum == -1)
         cout<<"Not possible";
      else
         cout<<"Maximum sum of hour glass created is "<<maxSum;
      return 0;
}
Maximum sum of hour glass created is 14