code-rag-bench/online-tutorials huggingface dataset:
C# | Adding an element into the Hashtable - GeeksforGeeks

01 Feb, 2019
The Hashtable class represents a collection of key-and-value pairs that are organized based on the hash code of the key. The key is used to access the items in the collection. Hashtable.Add(Object, Object) Method is used to adds an element with the specified key and value into the Hashtable.
Syntax:
public virtual void Add(object key, object value);

Parameters:
key: It is the specified key of the element to add of type System.Object.
value: It is the specified value of the element to add of type System.Object. The value can be null.
Exceptions:
ArgumentNullException : If the key is null.
ArgumentException : If an element with the same key already exists in the Hashtable.
NotSupportedException : Either Hashtable is read-only or Hashtable has a fixed size.
Below given are some examples to understand the implementation in a better way :
Example 1 :
// C# code for adding an element with the// specified key and value into the Hashtableusing System;using System.Collections;  class GFG {      // Driver code    public static void Main()    {          // Creating a Hashtable        Hashtable myTable = new Hashtable();          // Adding elements in Hashtable        myTable.Add("g", "geeks");        myTable.Add("c", "c++");        myTable.Add("d", "data structures");        myTable.Add("q", "quiz");          // Get a collection of the keys.        ICollection c = myTable.Keys;          // Displaying the contents        foreach(string str in c)            Console.WriteLine(str + ": " + myTable[str]);    }}
d: data structures
c: c++
q: quiz
g: geeks

Example 2:
// C# code for adding an element with the// specified key and value into the Hashtableusing System;using System.Collections;  class GFG {      // Driver code    public static void Main()    {          // Creating a Hashtable        Hashtable myTable = new Hashtable();          // Adding elements in Hashtable        myTable.Add("4", "Even");        myTable.Add("9", "Odd");        myTable.Add("5", "Odd and Prime");        myTable.Add("2", "Even and Prime");          // Get a collection of the keys.        ICollection c = myTable.Keys;          // Displaying the contents        foreach(string str in c)            Console.WriteLine(str + ": " + myTable[str]);    }}
5: Odd and Prime
9: Odd
2: Even and Prime
4: Even

Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.hashtable.add?view=netframework-4.7.2
CSharp-Collections-Hashtable
CSharp-Collections-Namespace
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
Difference between Ref and Out keywords in C#
C# | Delegates
Top 50 C# Interview Questions & Answers
Introduction to .NET Framework
C# | Constructors
Extension Method in C#
C# | Class and Object
C# | Abstract Classes
C# | String.IndexOf( ) Method | Set - 1
atexit() function in C/C++

The function atexit() is used to call the function after the normal exit of program. The program is called without any parameters. The function atexit() is called after exit(). The termination function can be called anywhere in the program. This function is declared in “stdlib.h” header file.
Here is the syntax of atexit() in C language,
int atexit(void (*function_name)(void))
Here,
function_name − The function is to be called at the time of termination of program.
Here is an example of atexit() in C language,
 Live Demo
#include <stdio.h>
#include <stdlib.h>
void func1 (void) {
   printf("\nExit of function 1");
}
void func2 (void) {
   printf("\nExit of function 2");
}
int main () {
   atexit (func1);
   printf("\nStarting of main()");
   atexit (func2);
   printf("\nEnding of main()");
   return 0;
}
Starting of main()
Ending of main()
Exit of function 2
Exit of function 1
In the above program, two functions func1 and func2 are defined before main() function. By using atexit(), defined functions are called. The main() function calls the functions before the exit of main() function. We called the two functions as shown below.
atexit (func1);
printf("\nStarting of main()");
atexit (func2);
printf("\nEnding of main()");
\vartheta - Tex Command

\vartheta - Used to create vartheta symbol.
{ \vartheta}
\vartheta command draws vartheta symbol.

\vartheta

θ



\vartheta

θ


\vartheta

    14 Lectures 
     52 mins

 Ashraf Said

    11 Lectures 
     1 hours 

 Ashraf Said

    9 Lectures 
     1 hours 

 Emenwa Global, Ejike IfeanyiChukwu

    29 Lectures 
     2.5 hours 

 Mohammad Nauman

    14 Lectures 
     1 hours 

 Daniel Stern

    15 Lectures 
     47 mins

 Nishant Kumar
 Print
 Add Notes
 Bookmark this page
Groovy - Nested Switch Statement

It is also possible to have a nested set of switch statements. The general form of the statement is shown below −
switch(expression) { 
   case expression #1: 
   statement #1 
   ... 
   case expression #2: 
   statement #2
   ... 
   case expression #N: 
   statement #N 
   ... 
   default: 
   statement #Default 
   ... 
}

Following is an example of the nested switch statement −
class Example { 
   static void main(String[] args) { 
      //Initializing 2 variables i and j 
      int i = 0; 
      int j = 1; 
		
      // First evaluating the value of variable i 
      switch(i) { 
         case 0: 
            // Next evaluating the value of variable j 
            switch(j) { 
               case 0: 
                  println("i is 0, j is 0"); 
                  break; 
               case 1: 
                  println("i is 0, j is 1"); 
                  break; 
               
               // The default condition for the inner switch statement 
               default: 
               println("nested default case!!"); 
            } 
         break; 
			
         // The default condition for the outer switch statement 
         default: 
            println("No matching case found!!"); 
      }
   }
}
In the above example, we are first initializing a variable to the a to a value of 2. We then have a switch statement which evaluates the value of the variable a. Based on the value of the variable it will execute the relevant case set of statements. The output of the above code would be −
i is 0, j is 1


    52 Lectures 
     8 hours 

 Krishna Sakinala

    49 Lectures 
     2.5 hours 

 Packt Publishing
 Print
 Add Notes
 Bookmark this page
Solidity - For Loop

The for loop is the most compact form of looping. It includes the following three important parts −
The loop initialization where we initialize our counter to a starting value. The initialization statement is executed before the loop begins.
The loop initialization where we initialize our counter to a starting value. The initialization statement is executed before the loop begins.
The test statement which will test if a given condition is true or not. If the condition is true, then the code given inside the loop will be executed, otherwise the control will come out of the loop.
The test statement which will test if a given condition is true or not. If the condition is true, then the code given inside the loop will be executed, otherwise the control will come out of the loop.
The iteration statement where you can increase or decrease your counter.
The iteration statement where you can increase or decrease your counter.
You can put all the three parts in a single line separated by semicolons.
The flow chart of a for loop in Solidity would be as follows −
The syntax of for loop is Solidity is as follows −
for (initialization; test condition; iteration statement) {
   Statement(s) to be executed if test condition is true
}

pragma solidity ^0.5.0;

contract SolidityTest {
   uint storedData; 
   constructor() public{
      storedData = 10;   
   }

   function getResult() public view returns(string memory){
      uint a = 10; 
      uint b = 2;
      uint result = a + b;
      return integerToString(result); 
   }

   function integerToString(uint _i) internal pure 
      returns (string memory) {
      if (_i == 0) {
         return "0";
      }
      uint j=0;
      uint len;
      for (j = _i; j != 0; j /= 10) {  //for loop example
         len++;         
      }
      bytes memory bstr = new bytes(len);
      uint k = len - 1;
      while (_i != 0) {
         bstr[k--] = byte(uint8(48 + _i % 10));
         _i /= 10;
      }
      return string(bstr);//access local variable
   }
}
Run the above program using steps provided in Solidity First Application chapter.
0: string: 12


    38 Lectures 
     4.5 hours 

 Abhilash Nelson

    62 Lectures 
     8.5 hours 

 Frahaan Hussain

    31 Lectures 
     3.5 hours 

 Swapnil Kole
 Print
 Add Notes
 Bookmark this page
Perl require Function

This function then it demands that the script requires the specified version of Perl in order to continue if EXPR is numeric. If EXPR or $_ are not numeric, it assumes that the name is the name of a library file to be included. You cannot include the same file with this function twice. The included file must return a true value as the last statement.
This differs from use in that included files effectively become additional text for the current script. Functions, variables, and other objects are not imported into the current name space, so if the specified file includes a package definition, then objects will require fully qualified names.
The specified module is searched for in the directories defined in @INC, looking for a file with the specified name and an extension of .pm.
Following is the simple syntax for this function −
require EXPR

require

This function does not return any value.
Following is the example code showing its basic usage −
#!/usr/bin/perl -w

# require to demand a particular perl version.
require 5.003;

# require to include amodule.
require Module;

..............

    46 Lectures 
     4.5 hours 

 Devi Killada

    11 Lectures 
     1.5 hours 

 Harshit Srivastava

    30 Lectures 
     6 hours 

 TELCOMA Global

    24 Lectures 
     2 hours 

 Mohammad Nauman

    68 Lectures 
     7 hours 

 Stone River ELearning

    58 Lectures 
     6.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
Python - Output Formatting

There are several ways to present the output of a program, data can be printed in a human-readable form, or written to a file for future use. Sometimes user often wants more control the formatting of output than simply printing space-separated values. There are several ways to format output.
To use formatted string literals, begin a string with f or F before the opening quotation mark or triple quotation mark.
The str.format()method of strings help a user to get a fancier Output
User can do all the string handling by using string slicing and concatenation operations to create any layout that user wants. The string type has some methods that perform useful operations for padding strings to a given column width.
The % operator can also be used for string formatting. It interprets the left argument much like a printf()-style format string to be applied to the right argument.
 Live Demo
# string modulo operator(%) to print
# print integer and float value
print("Vishesh : % 2d, Portal : % 5.2f" %(1, 05.333))
# print integer value
print("Total students : % 3d, Boys : % 2d" %(240, 120))
# print octal value
print("% 7.3o"% (25))
# print exponential value
print("% 10.3E"% (356.08977))
Vishesh : 1, Portal : 5.33
Total students : 240, Boys : 120
031
3.561E+02
The format() method was added in Python(2.6). Format method of strings requires more manual effort. User use {} to mark where a variable will be substituted and can provide detailed formatting directives, but user also needs to provide the information to be formatted.
# show format () is used in dictionary
tab = {'Vishesh': 4127, 'for': 4098, 'python': 8637678}
# using format() in dictionary
print('Vishesh: {0[vishesh]:d}; For: {0[for]:d}; '
'python: {0[python]:d}'.format(tab))
data = dict(fun ="VisheshforPython", adj ="Python")
# using format() in dictionary
print("I love {fun} computer {adj}".format(**data))
In this output is formatted by using string slicing and concatenation operations.
 Live Demo
# format a output using string() method
cstr = "I love python"
# Printing the center aligned
# string with fillchr
print ("Center aligned string with fillchr: ")
print (cstr.center(40, '$'))
# Printing the left aligned string with "-" padding
print ("The left aligned string is : ")
print (cstr.ljust(40, '-'))
# Printing the right aligned string with "-" padding
print ("The right aligned string is : ")
print (cstr.rjust(40, '-'))
Center aligned string with fillchr:
$$$$$$$$$$$$$I love python$$$$$$$$$$$$$$
The left aligned string is :
I love python---------------------------
The right aligned string is :
---------------------------I love python
How to sort a Python date string list?

To sort a Python date string list using the sort function, you'll have to convert the dates in objects and apply the sort on them. For this you can use the key named attribute of the sort function and provide it a lambda that creates a datetime object for each date and compares them based on this date object. 
from datetime import datetime
my_dates = ['5-Nov-18', '25-Mar-17', '1-Nov-18', '7-Mar-17']
my_dates.sort(key=lambda date: datetime.strptime(date, "%d-%b-%y"))
print(my_dates)
This will give the output −
['7-Mar-17', '25-Mar-17', '1-Nov-18', '5-Nov-18']
How to read the data from a CSV file in Java?


A CSV stands for Comma Separated Values. In a CSV file, each line contains words that are separated with a comma(,) and it is stored with a .csv extension.
We can read a CSV file line by line using the readLine() method of BufferedReader class. Split each line on comma character to get the words of the line into an array. Now we can easily print the contents of the array by iterating over it or by using an appropriate index.
import java.io.*;
public class CSVReaderTest {
   public static final String delimiter = ",";
   public static void read(String csvFile) {
      try {
         File file = new File(csvFile);
         FileReader fr = new FileReader(file);
         BufferedReader br = new BufferedReader(fr);
         String line = "";
         String[] tempArr;
         while((line = br.readLine()) != null) {
            tempArr = line.split(delimiter);
            for(String tempStr : tempArr) {
               System.out.print(tempStr + " ");
            }
            System.out.println();
         }
         br.close();
         } catch(IOException ioe) {
            ioe.printStackTrace();
         }
   }
   public static void main(String[] args) {
      // csv file to read
      String csvFile = "C:/Temp/Technology.csv";
       CSVReaderTest.read(csvFile);
   }
}
"JAVA" "PYTHON" "JAVASCRIPT" "SELENIUM" "SCALA"
quotactl() - Unix, Linux System Call

Unix - Home
Unix - Getting Started
Unix - File Management
Unix - Directories
Unix - File Permission
Unix - Environment
Unix - Basic Utilities
Unix - Pipes & Filters
Unix - Processes
Unix - Communication
Unix - The vi Editor
Unix - What is Shell?
Unix - Using Variables
Unix - Special Variables
Unix - Using Arrays
Unix - Basic Operators
Unix - Decision Making
Unix - Shell Loops
Unix - Loop Control
Unix - Shell Substitutions
Unix - Quoting Mechanisms
Unix - IO Redirections
Unix - Shell Functions
Unix - Manpage Help
Unix - Regular Expressions
Unix - File System Basics
Unix - User Administration
Unix - System Performance
Unix - System Logging
Unix - Signals and Traps
Unix - Useful Commands
Unix - Quick Guide
Unix - Builtin Functions
Unix - System Calls
Unix - Commands List
Unix Useful Resources
Computer Glossary
Who is Who
Copyright © 2014 by tutorialspoint
#include <sys/quota.h> 
#include <sys/types.h> 
#include <xfs/xqm.h> 
#include <linux/dqblk_v1.h> 
#include <linux/dqblk_v2.h> 

long quotactl(int cmd, char *special, qid_t id, caddr_t addr) 


long quotactl(int cmd, char *special, qid_t id, caddr_t addr) 







The
quotactl() call manipulates disk quotas.
cmd indicates a command to be applied to
UID id or
GID id. To set the type of quota use the
QCMD(cmd, type) macro.
special is a pointer to a null-terminated string containing the path
name of the block special device for the filesystem being manipulated.
addr is the address of an optional, command specific, data structure
which is copied in or out of the system.  The interpretation of
addr is given with each command below.


quotactl() returns:

quota (1)
quota (1)
getrlimit (2)
getrlimit (2)
quotacheck (8)
quotacheck (8)
quotaon (8)
quotaon (8)

Advertisements


    129 Lectures 
     23 hours 

 Eduonix Learning Solutions

    5 Lectures 
     4.5 hours 

 Frahaan Hussain

    35 Lectures 
     2 hours 

 Pradeep D

    41 Lectures 
     2.5 hours 

 Musab Zayadneh

    46 Lectures 
     4 hours 

 GUHARAJANM

    6 Lectures 
     4 hours 

 Uplatz
 Print
 Add Notes
 Bookmark this page
Linear Regression Using Least Squares | by Adarsh Menon | Towards Data Science

Linear Regression is the simplest form of machine learning out there. In this post, we will see how linear regression works and implement it in Python from scratch. This is the written version of the above video. Watch it if you prefer that.
In statistics, linear regression is a linear approach to modelling the relationship between a dependent variable and one or more independent variables. In the case of one independent variable it is called simple linear regression. For more than one independent variable, the process is called mulitple linear regression. We will be dealing with simple linear regression in this tutorial. Let X be the independent variable and Y be the dependent variable. We will define a linear relationship between these two variables as follows:
This is the equation for a line that you studied in high school. m is the slope of the line and c is the y intercept. Today we will use this equation to train our model with a given dataset and predict the value of Y for any given value of X.
Our challenege today is to determine the value of m and c, that gives the minimum error for the given dataset. We will be doing this by using the Least Squares method.
So to minimize the error we need a way to calculate the error in the first place. A loss function in machine learning is simply a measure of how different the predicted value is from the actual value. Today we will be using the Quadratic Loss Function to calculate the loss or error in our model. It can be defined as:
We are squaring it because, for the points below the regression line y — p will be negative and we don’t want negative values in our total error.
Now that we have determined the loss function, the only thing left to do is minimize it. This is done by finding the partial derivative of L, equating it to 0 and then finding an expression for m and c. After we do the math, we are left with these equations:
Here x̅ is the mean of all the values in the input X and ȳ is the mean of all the values in the desired output Y. This is the Least Squares method. Now we will implement this in python and make predictions.
1.287357370010931 9.908606190326509
There wont be much accuracy because we are simply taking a straight line and forcing it to fit into the given data in the best possible way. But you can use this to make simple predictions or get an idea about the magnitude/range of the real value. Also this is a good first step for beginners in Machine Learning.
Find the data set and code here: https://github.com/chasinginfinity/ml-from-scratch/tree/master/01%20Linear%20Regression%20using%20Least%20Squares
Got questions ? Need help ? Contact me!
How to check Leap Year in Java 8 How to get current timestamp in Java 8?

The java.time package of Java provides API’s for dates, times, instances and durations. It provides various classes like Clock, LocalDate, LocalDateTime, LocalTime, MonthDay,Year, YearMonth etc. Using classes of this package you can get details related to date and time in much simpler way compared to previous alternatives.
Java.time.LocalDate − This class represents a date object without time zone in ISO-8601 calendar system. The now() method of this class obtains the current date from the system clock.
The isLeapYear() method of java.time.LocalDate verifies if the year in the current object is a leap year according to the ISO proleptic calendar system rules, returns true if so, else returns false.
Following Java program gets the current date and finds out whether it is a leap year.
import java.time.LocalDate;
public class IsLeapYear {
   public static void main(String args[]) {
      //Getting the current date
      LocalDate currentDate = LocalDate.now();
      //Verifying if leap year
      boolean bool = currentDate.isLeapYear();
      //is after
      if(bool){
         System.out.println("Current year is a leap year ");
      }else{
         System.out.println("Current year is not a leap year ");
      }
   }
}
Current year is not a leap year
Following example accepts an year from user and displays whether it is a leap year.
import java.time.LocalDate;
import java.util.Scanner;
public class IsLeapYear {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the year: ");
      int year = sc.nextInt();
      //Getting the date of jan1st of the given date value
      LocalDate givenDate = LocalDate.of(year, 01, 01);
      //Verifying if leap year
      boolean bool = givenDate.isLeapYear();
      //is after
      if(bool){
         System.out.println("Given year is a leap year ");
      }else{
         System.out.println("Given year is not a leap year ");
      }
   }
}
Enter the year:
2004
Given year is a leap year
How to remove non-word characters in JavaScript?

To remove non-word characters we need to use regular expressions. The logic behind removing non-word characters is that just replace the non-word characters with nothing('').
In the following example there are many non-word characters and in between them there exists a text named "Tutorix is the best e-learning platform". So using regular expressions the non-word characters were replaced with nothing('') so as to get the word characters as the output.
Live Demo
<html>
<body>
<script type="text/javascript">
   function remNonWord (string) {
      if ((string===null) || (string===''))
      return false;
      else
      string = string.toString();
      var PATTERN = /[^\x20\x2D0-9A-Z\x5Fa-z\xC0-\xD6\xD8-\xF6\xF8-\xFF]/g;
      return string.replace(PATTERN, '');
   }
   document.write(remNonWord('Tutorix is the ~!@^&";\'/?>#$%*()+`={}[]|\\:<.,best e-learning            platform'));
</script>
</body>
</html>
Tutorix is the best e-learning platform
Keras - Flatten Layers

Flatten is used to flatten the input. For example, if flatten is applied to layer having input shape as (batch_size, 2,2), then the output shape of the layer will be (batch_size, 4)
Flatten has one argument as follows
keras.layers.Flatten(data_format = None)

data_format is an optional argument and it is used to preserve weight ordering when switching from one data format to another data format. It accepts either channels_last or channels_first as value. channels_last is the default one and it identifies the input shape as (batch_size, ..., channels) whereas channels_first identifies the input shape as (batch_size, channels, ...)
A simple example to use Flatten layers is as follows −
>>> from keras.models import Sequential 
>>> from keras.layers import Activation, Dense, Flatten 
>>> 
>>> 
>>> model = Sequential() 
>>> layer_1 = Dense(16, input_shape=(8,8)) 
>>> model.add(layer_1) 
>>> layer_2 = Flatten() 
>>> model.add(layer_2) 
>>> layer_2.input_shape (None, 8, 16) 
>>> layer_2.output_shape (None, 128) 
>>>
where, the second layer input shape is (None, 8, 16) and it gets flattened into (None, 128).

    87 Lectures 
     11 hours 

 Abhilash Nelson

    61 Lectures 
     9 hours 

 Abhishek And Pukhraj

    57 Lectures 
     7 hours 

 Abhishek And Pukhraj

    52 Lectures 
     7 hours 

 Abhishek And Pukhraj

    52 Lectures 
     6 hours 

 Abhishek And Pukhraj

    68 Lectures 
     2 hours 

 Mike West
 Print
 Add Notes
 Bookmark this page
Convert string to objectid in MongoDB?

To convert string to objectid in MongoDB, use $toObjectId. Let us create a collection with documents −
> db.demo95.insertOne({"Id":"5ab9cbe531c2ab715d42129a"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2d5ef5b8903cdd865577ac")
}
Display all documents from a collection with the help of find() method −
> db.demo95.find();
This will produce the following output −
{ "_id" : ObjectId("5e2d5ef5b8903cdd865577ac"), "Id" : "5ab9cbe531c2ab715d42129a" }
Following is the query to convert string to objectid in MongoDB −
> db.demo95.aggregate([ { "$addFields": { "d" : { "$toObjectId": "$Id" } }} ])
This will produce the following output −
{ "_id" : ObjectId("5e2d5ef5b8903cdd865577ac"), "Id" : "5ab9cbe531c2ab715d42129a", "d" : ObjectId("5ab9cbe531c2ab715d42129a") }
C++ Array Library - front() Function

The C++ function std::array::front() returns reference to the first element of the array container. If array size is zero then behavior of this method is undefined. Unlike begin()
method this method returns first element itself and not iterator.
Following is the declaration for std::array::front() function form std::array header.
reference front();
const_reference front() cont;
None
Returns the first element of an array. If array object is const-qualified
this method return const reference otherwise it returns reference.
This member function never throws exception. Calling this method on empty
array container will cause undefined behavior.
Constant i.e. O(1)
The following example shows the usage of std::array::front() function.
#include <iostream>
#include <array>

using namespace std;

int main(void) {

   array<int, 5> arr = {10, 20, 30, 40, 50};

   /* print first element */
   cout << "First element of array                    = " << arr.front() 
      << endl;

   /* modify value */
   arr.front() = 1;

   /* print modified value */
   cout << "After modification first element of array = " << arr.front() 
      << endl;

   return 0;
}
Let us compile and run the above program, this will produce the following result −
First element of array                    = 10
After modification first element of array = 1

 Print
 Add Notes
 Bookmark this page
Erlang - OTP

OTP stands for Open Telecom Platform. It’s an application operating system and a set of libraries and procedures used for building large-scale, fault-tolerant, distributed applications. If you want to program your own applications using OTP, then the central concept that you will find very useful is the OTP behavior. A behavior encapsulates common behavioral patterns — think of it as an application framework that is parameterized by a callback module.
The power of OTP comes from the properties such as fault tolerance, scalability, dynamic-code upgrade, and so on, can be provided by the behavior itself. So the first basic concept is to create a server component that mimics the basics of an OTP environment, let’s look at the following example for the same.
-module(server). 
-export([start/2, rpc/2]). 

start(Name, Mod) -> 
   register(Name, spawn(fun() -> loop(Name, Mod, Mod:init()) end)). 
rpc(Name, Request) -> 
   Name ! {self(), Request}, 
   receive 
      {Name, Response} -> Response 
   end. 
   
loop(Name, Mod, State) ->
   receive 
      {From, Request} ->
         {Response, State1} = Mod:handle(Request, State), 
         From ! {Name, Response}, 
         loop(Name, Mod, State1) 
   end.
The following things need to be noted about the above program −
The process if registered with the system using the register function.
The process if registered with the system using the register function.
The process spawns a loop function which handles the processing.
The process spawns a loop function which handles the processing.
Now let’s write a client program that will utilize the server program.
-module(name_server). 
-export([init/0, add/2, whereis/1, handle/2]). 
-import(server1, [rpc/2]). 

add(Name, Place) -> rpc(name_server, {add, Name, Place}). 
whereis(Name) -> rpc(name_server, {whereis, Name}). 

init() -> dict:new().
handle({add, Name, Place}, Dict) -> {ok, dict:store(Name, Place, Dict)}; 
handle({whereis, Name}, Dict) -> {dict:find(Name, Dict), Dict}.
This code actually performs two tasks. It serves as a callback module that is called from the server framework code, and at the same time, it contains the interfacing routines that will be called by the client. The usual OTP convention is to combine both functions in the same module.
So here is how the above program needs to be run −
In erl, first run the server program by running the following command.
server(name_server,name_server)

You will get the following output −
true

Then, run the following command
name_server.add(erlang,”Tutorialspoint”).

You will get the following output −
Ok

Then, run the following command −
name_server.whereis(erlang).

You will get the following output −
{ok,"Tutorialspoint"}

 Print
 Add Notes
 Bookmark this page
How to create a simple server in Node.js that display Hello World ? - GeeksforGeeks

01 Oct, 2021
A Server is a piece of computer hardware or software that provides functionality for other programs or devices, called clients. This architecture is called the client-server model. Node is an open-source, cross-platform runtime environment that allows developers to create all kinds of server-side tools and applications in JavaScript.
In the following example, we will create a simple server in Node.js that returns Hello World using an express server.
Create NodeJS Application: Initialize the NodeJS application using the following command:
npm init
Module Installation: Install the express module which is a web framework for NodeJS using the following command.
npm install express
Implementation: Create an app.js file and write down the following code in it.
app.js
// Require would make available the// express package to be used in// our codeconst express = require("express");  // Creates an express objectconst app = express();  // It listens to HTTP get request. // Here it listens to the root i.e '/'app.get("/", (req, res) => {    // Using send function we send  // response to the client  // Here we are sending html  res.send("<h1> Hello World </h1>");});  // It configures the system to listen// to port 3000. Any number can be // given instead of 3000, the only// condition is that no other server// should be running at that portapp.listen(3000, () => {    // Print in the console when the  // servers starts to listen on 3000  console.log("Listening to port 3000");});
Step to run the application: Run the app.js file using the following command.
node app.js
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
output
So this is how you can set up the server and achieve the task. If you want to return anything else then pass that argument in res.send() of the app.get() function instead of “Hello World”.
NodeJS-Questions
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Express.js express.Router() Function
Mongoose Populate() Method
Express.js req.params Property
Mongoose find() Function
How to connect Node.js with React.js ?
Express.js express.Router() Function
How to set input type date in dd-mm-yyyy format using HTML ?
Differences between Functional Components and Class Components in React
How to create footer to stay at the bottom of a Web page?
Convert a string to an integer in JavaScript
How to Install a Package in R ? - GeeksforGeeks

21 Apr, 2021
R programming language doesn’t come with all packages installed, and they need to be installed explicitly. In this article, we will discuss How to Install a Package in the R language.
Method 1: Using application options
1. Open R studio.
2. Select tools
3. After selecting the tools you need to press install packages.
4. Here you need to give the package name you need to install.
Here we used expm. This function computes the exponential of a square matrix.
1. Open RGui
2. Select packages
3. Select install packages.
4. Select required package and click ok.
 Package will be installed 
package 'expm' successfully unpacked and MD5 sums checked
Method 2: Using command 
In this method, simply pass the package to be installed as an argument to install.packages() function
Syntax:
install.packages(“package name”)
Example:
R
install.packages("ggplot2")
A package can be loaded once it has been installed using library() command.
Syntax;
library(“package_name”)
Example:
R
library("ggplot2")
Picked
R-Packages
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
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
Replace Specific Characters in String in R
How to filter R dataframe by multiple conditions?
R - if statement
How to import an Excel File into R ?
How to change the order of bars in bar chart in R ?
How to make a class thread-safe in Java?

A thread-safe class is a class that guarantees the internal state of the class as well as returned values from methods, are correct while invoked concurrently from multiple threads.
The HashMap is a non-synchronized collection class. If we need to perform thread-safe operations on it then we must need to synchronize it explicitly.
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.Iterator;

public class HashMapSyncExample {
   public static void main(String args[]) {

      HashMap hmap = new HashMap();
      hmap.put(2, "Raja");
      hmap.put(44, "Archana");
      hmap.put(1, "Krishna");
      hmap.put(4, "Vineet");
      hmap.put(88, "XYZ");

      Map map= Collections.synchronizedMap(hmap);
      Set set = map.entrySet();
      synchronized(map){
            Iterator i = set.iterator();
          // Display elements
         while(i.hasNext()) {
               Map.Entry me = (Map.Entry)i.next();
               System.out.print(me.getKey() + ": ");
               System.out.println(me.getValue());
         }
      }
   }
}
In the above example, we have a HashMap it is having integer keys and String type values. In order to synchronize it we are using Collections.synchronizedMap(hashmap). It returns a thread-safe map backed up by the specified HashMap.
1: Krishna
2: Raja
4: Vineet
88: XYZ
44: Archana
_Noreturn function specifier in C - GeeksforGeeks

29 Mar, 2019
After the removal of “noreturn” keyword, C11 standard (known as final draft) of C programming language introduce a new “_Noreturn” function specifier that specify that the function does not return to the function that it was called from. If the programmer try to return any value from that function which is declared as _Noreturn type, then the compiler automatically generates a compile time error.
// C program to show how _Noreturn type // function behave if it has return statement.#include <stdio.h>#include <stdlib.h>  // With return value_Noreturn void view(){    return 10;}int main(void){    printf("Ready to begin...\n");    view();      printf("NOT over till now\n");    return 0;}
Output:
Ready to begin...
After that abnormal termination of program.
compiler error:[Warning] function declared 'noreturn' has a 'return' statement

// C program to illustrate the working // of _Noreturn type function.#include <stdio.h>#include <stdlib.h>  // Nothing to return_Noreturn void show(){    printf("BYE BYE");}int main(void){    printf("Ready to begin...\n");    show();      printf("NOT over till now\n");    return 0;}
Output:
Ready to begin...
BYE BYE

Reference: http://en.cppreference.com/w/c/language/_Noreturn
This article is contributed by Bishal Kumar Dubey. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
AbhinavMadheshiya1
C-Library
C Language
Misc
Misc
Misc
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
Multithreading in C
Exception Handling in C++
'this' pointer in C++
Arrow operator -> in C/C++ with Examples
Top 10 algorithms in Interview Questions
vector::push_back() and vector::pop_back() in C++ STL
Overview of Data Structures | Set 1 (Linear Data Structures)
How to write Regular Expressions?
fgets() and gets() in C language
Bitcoin's Monetary Policy - GeeksforGeeks

03 Jan, 2020
Bitcoin‘s Monetary Policy consists of 2 main parts:
1. The Halving
2. Block Frequency 
The Monetary Policy is completely controlled by Software. It’s all preprogrammed.
1. The Halving:The number of Bitcoins released into the system every 10 minutes is halved after every 4 years. Actually, the halving takes place after every 210000 Blocks which takes approximately 4 years to generate (as on an average one block is generated every 10 minutes).
When bitcoin started (2009), the block reward was 50 Bitcoin every 10 minutes.In November 2012, Bitcoin’s 1st Halving took place and block reward(i.e reward for successfully mining one block into the Blockchain) reduced to half i.e., 25 Bitcoin from 50 Bitcoin.
In July 2016 Bitcoin’s 2nd halving took place(reward reduces to 12.5 Bitcoin) and the next halving which is Bitcoin’s 3rd will take place in May 2020. This is when the current block reward of 12.5 Bitcoin every 10 minutes will be cut into half to 6.25 Bitcoin.
This also means over time mining will become more difficult. As network difficulty increases over time & the reward rate drop, so the actual cost of mining each Bitcoin increases, which will then cause the trading price of each Bitcoin to increase as well. Also, the limited supply will cause Bitcoin prices to increase, as their scarcity also increases proportionally.
As total Bitcoin’s supply is set to be limited by Satoshi Nakamoto (who created Bitcoin). Only 21 million Bitcoins can be generated. Right now there is almost 18 million Bitcoin (85% of total supply) in circulation.
The supply limit of 21 million Bitcoins will be reached by 2140.
2. Block Frequency:Block Frequency is defined as, how often the blocks come in & break the reward which is now 12.5 Bitcoin per block for Bitcoin.The Average Block-Time or Block Frequency is different for different cryptocurrencies.For example, Average Block-Time for Bitcoin is 10 minutes. For Ethereum, it is 15 seconds. For Ripple, it is 3.5 seconds.
BlockChain
GBlog
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Roadmap to Become a Web Developer in 2022
DSA Sheet by Love Babbar
A Freshers Guide To Programming
Top 10 Angular Libraries For Web Developers
Top 5 Python Libraries For Big Data
Top 10 Programming Languages to Learn in 2022
ML | Underfitting and Overfitting
Virtualization In Cloud Computing and Types
What is web socket and how it is different from the HTTP?
Software Testing | Basics
gdbtui - Unix, Linux Command

GDB can do four main kinds of things (plus other things in support of
these) to help you catch bugs in the act:










You can use GDB to debug programs written in C, C++, and Modula-2.
Fortran support will be added when a GNU Fortran compiler is ready.


GDB is invoked with the shell command 
gdb .  Once started, it reads
commands from the terminal until you tell it to exit with the GDB
command 
quit .  You can get online help from 
gdb  itself
by using the command 
help .


You can run 
gdb  with no arguments or options; but the most
usual way to start GDB is with one argument or two, specifying an
executable program as the argument:


gdb program




You can also start with both an executable program and a core file specified:


gdb program core




You can, instead, specify a process ID as a second argument, if you want
to debug a running process:


gdb program 1234




would attach GDB to process 
1234  (unless you also have a file
named ‘
1234 ’; GDB does check for a core file first).


Here are some of the most frequently needed GDB commands:


All the options and command line arguments you give are processed
in sequential order.  The order makes a difference when the
‘
-x ’ option is used.


























Batch mode may be useful for running GDB as a filter, for example to
download and run a program on another computer; in order to make this
more useful, the message


Program exited normally.




(which is ordinarily issued whenever a program running under GDB control
terminates) is not issued when running in batch mode.









$ gdbtui gdb_example

$ gdb gdb_example -tui


    129 Lectures 
     23 hours 

 Eduonix Learning Solutions

    5 Lectures 
     4.5 hours 

 Frahaan Hussain

    35 Lectures 
     2 hours 

 Pradeep D

    41 Lectures 
     2.5 hours 

 Musab Zayadneh

    46 Lectures 
     4 hours 

 GUHARAJANM

    6 Lectures 
     4 hours 

 Uplatz
 Print
 Add Notes
 Bookmark this page
Creating a Cell at specific position in Excel file using Java - GeeksforGeeks

14 Apr, 2022
Apache POI is an open-source java library to create and manipulate various file formats based on Microsoft Office. Using POI, one should be able to perform create, modify and display/read operations on the following file formats/ it can be used to create a cell in a Given Excel file at a specific position. Apache POI is an API provided by the Apache foundation.
Create a maven project(Maven is a build automation tool used primarily for Java projects) in eclipse or a Java project with the POI library installedAdd the following maven dependency in the pom.xml fileWrite java code in javaresource folder
Create a maven project(Maven is a build automation tool used primarily for Java projects) in eclipse or a Java project with the POI library installed
Add the following maven dependency in the pom.xml file
Write java code in javaresource folder
Example
Java
// Java Program to Demonstrate Creation Of Cell// At Specific Position in Excel File // Importing required classesimport java.io.*;import org.apache.poi.hssf.usermodel.HSSFWorkbook;import org.apache.poi.ss.usermodel.Cell;import org.apache.poi.ss.usermodel.Row;import org.apache.poi.ss.usermodel.Sheet;import org.apache.poi.ss.usermodel.Workbook; // Class// CreateCellAtSpecificPositionpublic class GFG {     // Main driver method    public static void main(String[] args)        throws FileNotFoundException, IOException    {         // Creating a workbook instances        Workbook wb = new HSSFWorkbook();         // Creating output file        OutputStream os            = new FileOutputStream("Geeks.xlsx");         // Creating a sheet using predefined class        // provided by Apache POI        Sheet sheet = wb.createSheet("Company Preparation");         // Creating a row at specific position        // using predefined class provided by Apache POI         // Specific row number        Row row = sheet.createRow(1);         // Specific cell number        Cell cell = row.createCell(1);         // putting value at specific position        cell.setCellValue("Geeks");         // Finding index value of row and column of give        // cell        int rowIndex = cell.getRowIndex();        int columnIndex = cell.getColumnIndex();         // Writing the content to Workbook        wb.write(os);         // Printing the row and column index of cell created        System.out.println("Given cell is created at "                           + "(" + rowIndex + ","                           + columnIndex + ")");    }}
Output: On console 
Given cell is created at (1,1)
Output: Inside file named ‘Geeks.xlsx’  
akshaysingh98088
nandinigujral
GBlog
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Roadmap to Become a Web Developer in 2022
DSA Sheet by Love Babbar
GET and POST requests using Python
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Working with csv files in Python
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Arrays.sort() in Java with examples
Reverse a string in Java
How to show all the tables present in the database and server in MySQL using Python?

We may sometimes require to get the list of all the tables present in our database. This can be done by using the SHOW TABLES command.
The SHOW TABLES command is used to display the table names in a database as well as the server.
To show the tables present in a database −
SHOW TABLES
The above statement when executed using the cursor object returns the names of the tables present in our database.
To show the tables present in a server
SELECT table_name FROM information_schema.tables
import MySQL connector
import MySQL connector
establish connection with the connector using connect()
establish connection with the connector using connect()
create the cursor object using cursor() method
create the cursor object using cursor() method
create a query using the appropriate mysql statements
create a query using the appropriate mysql statements
execute the SQL query using execute() method
execute the SQL query using execute() method
close the connection
close the connection
Example
import mysql.connector

db=mysql.connector.connect(host="your host", user="your username", password="your_password",database="database_name")

cursor=db.cursor()

cursor.execute("SHOW TABLES")

for table_name in cursor:
   print(table_name)
Example
import mysql.connector

db=mysql.connector.connect(host="your host", user="your username", password="your_password",database="database_name")

cursor=db.cursor()

cursor.execute("SELECT table_name FROM information_schema.tables")

for table_name in cursor:
   print(table_name)
The above codes output the list of tables present in your database or the server .
Employees
Students
MyTable
Position of robot after given movements in C++

In this problem, we are given a robot that moves in all four directions but only one move. The directions are up(‘U’), down(‘D’), left(‘L’), right(‘R’). And we are given a string that contains initials of directions of the number. Our task is to print the final position of the robot, given the initial position of the robot is (0,0).
Let’s take an example to understand the problem
Input − input: ‘LDRRUL’
Output − (0, 0)
Explanation −
L (left) : (0,0) -> (-1,0)
D (down) : (-1,0) -> (-1, -1)
R (right) : (-1, -1) -> (0, -1)
R (right) : (0, -1) -> (1, -1)
U(up) : (1, -1) -> (1, 0)
L(left) : (1, 0) -> (0, 0)
To solve this problem, we will count the total moves in the x-axis and the y-axis direction. For x-coordinate, increase the count for Right move and decrease count for a left move. For y-coordinate, increase the count for the up move and down count for a left move.
Program to show the implementation of our solution
 Live Demo
#include <iostream>
#include <string.h>
using namespace std;
void robotMoved(string move) {
   int xAxis, yAxis;
   int l=move.size();
   for (int i = 0; i < l; i++) {
      if (move[i]=='U')
         yAxis++;
      else if (move[i]=='D')
         yAxis--;
      else if (move[i]=='L')
         xAxis--;
      else if (move[i]=='R')
         xAxis++;
   }
   cout<<"Final Position of the robot is : ("<<xAxis<<", "<<yAxis<<")"<<endl;
}
int main() {
   string move="URLLDDRRUDUDDRU";
   robotMoved(move);
   return 0;
}
Final Position of the robot is : (32744, -274873553)