text:
Q: Should I use std::function or a function pointer in C++? When implementing a callback function in C++, should I still use the C-style function pointer:
void (*callbackFunc)(int);

Or should I make use of std::function:
std::function< void(int) > callbackFunc;

A: void (*callbackFunc)(int); may be a C style callback function, but it is a horribly unusable one of poor design.
A well designed C style callback looks like void (*callbackFunc)(void*, int); -- it has a void* to allow the code that does the callback to maintain state beyond the function.  Not doing this forces the caller to store state globally, which is impolite.
std::function< int(int) > ends up being slightly more expensive than int(*)(void*, int) invocation in most implementations.  It is however harder for some compilers to inline.  There are std::function clone implementations that rival function pointer invocation overheads (see 'fastest possible delegates' etc) that may make their way into libraries.
Now, clients of a callback system often need to set up resources and dispose of them when the callback is created and removed, and to be aware of the lifetime of the callback.  void(*callback)(void*, int) does not provide this.
Sometimes this is available via code structure (the callback has limited lifetime) or through other mechanisms (unregister callbacks and the like).
std::function provides a means for limited lifetime management (the last copy of the object goes away when it is forgotten).
In general, I'd use a std::function unless performance concerns manifest.  If they did, I'd first look for structural changes (instead of a per-pixel callback, how about generating a scanline processor based off of the lambda you pass me?  which should be enough to reduce function-call overhead to trivial levels.).  Then, if it persists, I'd write a delegate based off fastest possible delegates, and see if the performance problem goes away.
I would mostly only use function pointers for legacy APIs, or for creating C interfaces for communicating between different compilers generated code.  I have also used them as internal implementation details when I am implementing jump tables, type erasure, etc: when I am both producing and consuming it, and am not exposing it externally for any client code to use, and function pointers do all I need.
Note that you can write wrappers that turn a std::function<int(int)> into a int(void*,int) style callback, assuming there are proper callback lifetime management infrastructure.  So as a smoke test for any C-style callback lifetime management system, I'd make sure that wrapping a std::function works reasonably well.

A: In short, use std::function unless you have a reason not to.
Function pointers have the disadvantage of not being able to capture some context. You won't be able to for example pass a lambda function as a callback which captures some context variables (but it will work if it doesn't capture any). Calling a member variable of an object (i.e. non-static) is thus also not possible, since the object (this-pointer) needs to be captured.(1)
std::function (since C++11) is primarily to store a function (passing it around doesn't require it to be stored). Hence if you want to store the callback for example in a member variable, it's probably your best choice. But also if you don't store it, it's a good "first choice" although it has the disadvantage of introducing some (very small) overhead when being called (so in a very performance-critical situation it might be a problem but in most it should not). It is very "universal": if you care a lot about consistent and readable code as well as don't want to think about every choice you make (i.e. want to keep it simple), use std::function for every function you pass around.
Think about a third option: If you're about to implement a small function which then reports something via the provided callback function, consider a template parameter, which can then be any callable object, i.e. a function pointer, a functor, a lambda, a std::function, ... Drawback here is that your (outer) function becomes a template and hence needs to be implemented in the header. On the other hand you get the advantage that the call to the callback can be inlined, as the client code of your (outer) function "sees" the call to the callback will the exact type information being available.
Example for the version with the template parameter (write & instead of && for pre-C++11):
template <typename CallbackFunction>
void myFunction(..., CallbackFunction && callback) {
    ...
    callback(...);
    ...
}

As you can see in the following table, all of them have their advantages and disadvantages:

function ptr
std::function
template param

can capture context variables
no1
yes
yes

no call overhead (see comments)
yes
no
yes

can be inlined (see comments)
no
no
yes

can be stored in a class member
yes
yes
no2

can be implemented outside of header
yes
yes
no

supported without C++11 standard
yes
no3
yes

nicely readable (my opinion)
no
yes
(yes)

(1) Workarounds exist to overcome this limitation, for example passing the additional data as further parameters to your (outer) function: myFunction(..., callback, data) will call callback(data). That's the C-style "callback with arguments", which is possible in C++ (and by the way heavily used in the WIN32 API) but should be avoided because we have better options in C++.
(2) Unless we're talking about a class template, i.e. the class in which you store the function is a template. But that would mean that on the client side the type of the function decides the type of the object which stores the callback, which is almost never an option for actual use cases.
(3) For pre-C++11, use boost::function

A: Use std::function to store arbitrary callable objects. It allows the user to provide whatever context is needed for the callback; a plain function pointer does not.
If you do need to use plain function pointers for some reason (perhaps because you want a C-compatible API), then you should add a void * user_context argument so it's at least possible (albeit inconvenient) for it to access state that's not directly passed to the function.

A: The only reason to avoid std::function is support of legacy compilers that lack support for this template, which has been introduced in C++11.
If supporting pre-C++11 language is not a requirement, using std::function gives your callers more choice in implementing the callback, making it a better option compared to "plain" function pointers. It offers the users of your API more choice, while abstracting out the specifics of their implementation for your code that performs the callback.

A: std::function may bring VMT to the code in some cases, which has some impact on performance.

A: The other answers answer based on technical merits.  I'll give you an answer based on experience.
As a very heavy X-Windows developer who always worked with function pointer callbacks with void* pvUserData arguments, I started using std::function with some trepidation.
But I find out that combined with the power of lambdas and the like, it has freed up my work considerably to be able to, at a whim, throw multiple arguments in, re-order them, ignore parameters the caller wants to supply but I don't need, etc.  It really makes development feel looser and more responsive, saves me time, and adds clarity.
On this basis I'd recommend anyone to try using std::function any time they'd normally have a callback.  Try it everywhere, for like six months, and you may find you hate the idea of going back.
Yes there's some slight performance penalty, but I write high-performance code and I'm willing to pay the price.  As an exercise, time it yourself and try to figure out whether the performance difference would ever matter, with your computers, compilers and application space.


text:
Q: How to find all unused and first missing number in an array (in Python)? I'm new to python and I need help in trying to find all unused and the first unused/missing number in an array (in python 2.7.3)?
The array is of length 20 and is used by an application. When the application is launched, the array is empty, but as users begin to populate it, I need to find all unused numbers and first unused number.
Think of it as a car-park with 20 spots numbered 1 to 20. As people begin to park their cars, the spaces get filled. People may not necessarily park cars in a sequence, two people may park in spots 1 and 16, so i need to find all the missing spots and the first unused parking spot.
Parking cars is given as an example to help you understand what I'm trying to convey. Array will always be integer, and will hold values from 1 to 20.
Below is what the code should do
On Launch, myArray is empty:
myarray = []

So the first missing number should be 1 (i.e. Park car in first spot)
missingNumbers = [1,2,3,.......20]
firstMissingNoInMyArray = 1

As spaces in the array are filled, the array will look like this
myarray = [1, 5, 15]

So first missing number and missing numbers are:
missingNumbers = [2,3,4,6,7,8,9,10,11,12,13,14,16,17,18,19,20].
firstMissingNoInMyArray = 2

I need to see both missing numbers list and the first missing number, can anyone help with Python code, I'm restricted to using Python 2.7.3; if you have a solution in Python 3, do write it, it may help Python 3 users.
Many thanks in advance.

A: I think this listcomprehension should do the trick for you
missingNumbers = [ i  for i in range(20) if i not in myarray ]

to get the first number you only need to take the first element
firstMissingNoInMyArray = missingNumbers[0]

A: You can use sets then you can simply subtract the sets.
In order to see the first missing number you can take the min in the resulting set:
all_nums = set(xrange(1, 21))
arr = set(xrange(5, 10))

print all_nums - arr
print min(all_nums - arr)
# note that sets are unordered
>>   {1, 2, 3, 4, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20}
     1

This should work on Python 2.7.3, but you should consider upgrading anyway. Python 2.7.3 is 7 years old.

A: You could use set operations.
limit = 20
myarray = [1, 5, 15]  # Example
missingNumbers = list(set(range(1, limit + 1)) - set(myarray))

print 'Missing numbers ->', missingNumbers
print 'First missing number ->', missingNumbers[0] # Access the first element.

Sample Output:
Missing numbers -> [2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 18, 19, 20]
First missing number -> 2

Although user @Magellan88's solution is quite pythonic, set operations are highly optimized for this class of calculations. Running some bench marks below, the list comprehension takes significantly longer to finish execution even for smaller data sets -> Search list: 100,000 items, list to subtract -> 100 items.
import timeit
print timeit.timeit("list(set(range(1,100000)) - set(range(1,100)))", number=100)
print timeit.timeit("[ i  for i in range(1,100000) if i not in myarray]", number=100, setup="myarray = range(1,100)")

Results (in seconds):

*

*1.43372607231  - Set operations.

*18.2217440605  - List comprehension.

Set difference is a relatively low costing operation with a time complexity of O(n), (python documentation on complexities). Sets in python are essentially implemented using a hash-table giving way to very fast operations (source code).
Meanwhile, in the list comprehension, there is an in operation which has an average case of O(n), this operation occurs within a for loop O(n), thus giving us an average time complexity of O(n2). The list comprehension follows a quadratic asymptotic growth pattern (far slower than the set operation).

A: If you know the upper limit of the range, then remove element, that came from user, from pre-populated list and return the first element. Like below:
prepop_list = [ i for i in xrange( 1, 20+1 ) ]

def new_user( item ):
    if item in prepop_list:
        prepop_list.remove( item )
    else:
        return "Item "+ str(item) +" not found"

    return prepop_list[0]

first_e_pos = new_user( 4 ) # some new user reserved 4th position
print( first_e_pos )

redpajama_set_name: RedPajamaStackExchange


text:
Q: Java - Cannot find HttpClient.executeMethod() I'm trying to upload a file with Apache's HTTP Client and MultipartRequests, but it gives me an error, here's my code:
PostMethod filePost = new PostMethod("http://host/some_path");
Part[] parts = {
  new StringPart("param_name", "value"),
  new FilePart(f.getName(), f)
 };
filePost.setRequestEntity(
  new CountingMultipartRequestEntity(parts, filePost.getParams())
  );
HttpClient client = new DefaultHttpClient();
int status = client.executeMethod(filePost);

It says "Cannot find symbol executeMethod()".
It's strange because I based my code on examples I found on Internet, and when I copy/paste their code, it shows me errors!

A: You are using HtppClient 4.x (see DefaultHttpClient) while the example code is based on HttpClient 3.x (see HttpClient). The API has been changed completely between these versions.
Just include HttpClient 4 on your CLASSPATH and get rid of version 3.

A: I presume you double-checked that you are using the same version these samples were written for? Maybe this will help.


text:
Q: Checkboxes selectable but not able to uncheck I have a DataGridView with check boxes.
What would cause the checkboxes to be selectable but not able to uncheck in .Net 4.0, but checkable and unchekable in .Net 2.0?

A: The problem was the width of the checkboxes. It was 18 and it worked ok for .Net 2.0, but not fo .Net 4.0. If it's 20, it works for both.


text:
Q: I want to make this table as Scrollable This is how it looks like Hii i want to make this screen scrollable there are certain tables i have created using linear layout but i have tried everything but cant find any solution.I used frame layout inside their is an linear layout so while running this on small screen it gets hide.I have tried add scroll view but its didnt work please help me to fix it out.
**<?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/white"
        android:orientation="vertical">

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="10dp"
                android:layout_marginRight="10dp"
                android:layout_marginBottom="100dp"
                android:background="@drawable/ic_down"
                android:orientation="vertical"
                android:weightSum="8.8">

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="0dp"
                    android:layout_weight="1.2"
                    android:orientation="horizontal"
                    android:weightSum="4">

                    <LinearLayout
                        android:layout_width="0dp"
                        android:layout_height="match_parent"
                        android:layout_weight="1.6">

                        <TextView
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:text=""
                            android:textColor="@android:color/black"
                            android:textSize="14dp" />

                    </LinearLayout>

                    <View
                        android:layout_width="1dp"
                        android:layout_height="wrap_content"
                        android:layout_marginLeft="5dp"
                        android:layout_marginRight="5dp"
                        android:background="@android:color/black" />

                    <LinearLayout
                        android:layout_width="0dp"
                        android:layout_height="match_parent"
                        android:layout_weight=".8"
                        android:gravity="center">

                        <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:gravity="center"
                            android:text="Quantity"
                            android:textColor="@android:color/black"
                            android:textSize="15sp" />

                    </LinearLayout>

                    <View
                        android:layout_width="1dp"
                        android:layout_height="wrap_content"
                        android:layout_marginLeft="5dp"
                        android:layout_marginRight="5dp"
                        android:background="@android:color/black" />

                    <LinearLayout
                        android:layout_width="0dp"
                        android:layout_height="match_parent"
                        android:layout_weight=".9"
                        android:gravity="center">

                        <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:gravity="center"
                            android:text="Hour Multiplier"
                            android:textColor="@android:color/black"
                            android:textSize="15sp" />

                    </LinearLayout>

                    <View
                        android:layout_width="1dp"
                        android:layout_height="wrap_content"
                        android:layout_marginLeft="5dp"
                        android:layout_marginRight="5dp"
                        android:background="@android:color/black" />

                    <LinearLayout
                        android:layout_width="0dp"
                        android:layout_height="match_parent"
                        android:layout_weight=".7"
                        android:gravity="center">

                        <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:gravity="center"
                            android:text="Shramanand Hours"
                            android:textColor="@android:color/black"
                            android:textSize="15sp" />

                    </LinearLayout>

                </LinearLayout>

                <View
                    android:layout_width="match_parent"
                    android:layout_height="1dp"
                    android:background="@android:color/black" />

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="0dp"
                    android:layout_weight=".7"
                    android:orientation="horizontal"
                    android:weightSum="4">

                    <LinearLayout
                        android:layout_width="0dp"
                        android:layout_height="match_parent"
                        android:layout_weight="1.6"
                        android:gravity="center">

                        <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:gravity="center"
                            android:text="Courses/Camps"
                            android:textColor="@android:color/black"
                            android:textSize="14sp" />

                    </LinearLayout>

                    <View
                        android:layout_width="1dp"
                        android:layout_height="wrap_content"
                        android:layout_marginLeft="5dp"
                        android:layout_marginRight="5dp"
                        android:background="@android:color/black" />

                    <LinearLayout
                        android:layout_width="0dp"
                        android:layout_height="match_parent"
                        android:layout_weight=".8"
                        android:gravity="center">

                        <EditText
                            android:id="@+id/edtCount1"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:inputType="number"
                            android:maxLength="3"
                            android:paddingLeft="8dp"
                            android:hint="__"
                            android:textColor="@android:color/black"
                            android:textCursorDrawable="@null"
                            android:textSize="15sp" />

                    </LinearLayout>

                    <View
                        android:layout_width="1dp"
                        android:layout_height="wrap_content"
                        android:layout_marginLeft="5dp"
                        android:layout_marginRight="5dp"
                        android:background="@android:color/black" />

                    <LinearLayout
                        android:layout_width="0dp"
                        android:layout_height="match_parent"
                        android:layout_weight=".9"
                        android:gravity="center">

                        <TextView
                            android:id="@+id/txtHours1"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:text=" x 10"
                            android:textColor="@android:color/black"
                            android:textSize="16sp" />

                    </LinearLayout>

                    <View
                        android:layout_width="1dp"
                        android:layout_height="wrap_content"
                        android:layout_marginLeft="5dp"
                        android:layout_marginRight="5dp"
                        android:background="@android:color/black" />

                    <LinearLayout
                        android:layout_width="0dp"
                        android:layout_height="match_parent"
                        android:layout_weight=".7"
                        android:gravity="center">

                        <TextView
                            android:id="@+id/txtTotalHours1"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:gravity="center"
                            android:text=""
                            android:textColor="@android:color/black"
                            android:textSize="16sp" />

                    </LinearLayout>

                </LinearLayout>

                <View
                    android:layout_width="match_parent"
                    android:layout_height="1dp"
                    android:background="@android:color/black" />

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="0dp"
                    android:layout_weight=".7"
                    android:orientation="horizontal"
                    android:weightSum="4">

                    <LinearLayout
                        android:layout_width="0dp"
                        android:layout_height="match_parent"
                        android:layout_weight="1.6"
                        android:gravity="center">

                        <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:gravity="center"
                            android:text="1 Day Test including Machine Test"
                            android:textColor="@android:color/black"
                            android:textSize="14sp" />

                    </LinearLayout>

                    <View
                        android:layout_width="1dp"
                        android:layout_height="wrap_content"
                        android:layout_marginLeft="5dp"
                        android:layout_marginRight="5dp"
                        android:background="@android:color/black" />

                    <LinearLayout
                        android:layout_width="0dp"
                        android:layout_height="match_parent"
                        android:layout_weight=".8"
                        android:gravity="center">

                        <EditText
                            android:id="@+id/edtCount2"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:inputType="number"
                            android:maxLength="3"
                            android:hint="__"
                            android:paddingLeft="8dp"
                            android:textColor="@android:color/black"
                            android:textCursorDrawable="@null"
                            android:textSize="15sp" />

                    </LinearLayout>

                    <View
                        android:layout_width="1dp"
                        android:layout_height="wrap_content"
                        android:layout_marginLeft="5dp"
                        android:layout_marginRight="5dp"
                        android:background="@android:color/black" />

                    <LinearLayout
                        android:layout_width="0dp"
                        android:layout_height="match_parent"
                        android:layout_weight=".9"
                        android:gravity="center">

                        <TextView
                            android:id="@+id/txtHours2"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:text="x 6"
                            android:textColor="@android:color/black"
                            android:textSize="16sp" />

                    </LinearLayout>

                    <View
                        android:layout_width="1dp"
                        android:layout_height="wrap_content"
                        android:layout_marginLeft="5dp"
                        android:layout_marginRight="5dp"
                        android:background="@android:color/black" />

                    <LinearLayout
                        android:layout_width="0dp"
                        android:layout_height="match_parent"
                        android:layout_weight=".7"
                        android:gravity="center">

                        <TextView
                            android:id="@+id/txtTotalHours2"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:gravity="center"
                            android:text=""
                            android:textColor="@android:color/black"
                            android:textSize="16sp" />

                    </LinearLayout>

                </LinearLayout>

                <View
                    android:layout_width="match_parent"
                    android:layout_height="1dp"
                    android:background="@android:color/black" />

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="0dp"
                    android:layout_weight=".7"
                    android:orientation="horizontal"
                    android:weightSum="4">

                    <LinearLayout
                        android:layout_width="0dp"
                        android:layout_height="match_parent"
                        android:layout_weight="1.6"
                        android:gravity="center">

                        <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:gravity="center"
                            android:text="Manashakti Varganidar"
                            android:textColor="@android:color/black"
                            android:textSize="14sp" />

                    </LinearLayout>

                    <View
                        android:layout_width="1dp"
                        android:layout_height="wrap_content"
                        android:layout_marginLeft="5dp"
                        android:layout_marginRight="5dp"
                        android:background="@android:color/black" />

                    <LinearLayout
                        android:layout_width="0dp"
                        android:layout_height="match_parent"
                        android:layout_weight=".8"
                        android:gravity="center">

                        <EditText
                            android:id="@+id/edtCount3"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:inputType="number"
                            android:maxLength="3"
                            android:paddingLeft="8dp"
                            android:hint="__"
                            android:textColor="@android:color/black"
                            android:textCursorDrawable="@null"
                            android:textSize="15sp" />

                    </LinearLayout>

                    <View
                        android:layout_width="1dp"
                        android:layout_height="wrap_content"
                        android:layout_marginLeft="5dp"
                        android:layout_marginRight="5dp"
                        android:background="@android:color/black" />

                    <LinearLayout
                        android:layout_width="0dp"
                        android:layout_height="match_parent"
                        android:layout_weight=".9"
                        android:gravity="center">

                        <TextView
                            android:id="@+id/txtHours3"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:text="x 5"
                            android:textColor="@android:color/black"
                            android:textSize="16dp" />

                    </LinearLayout>

                    <View
                        android:layout_width="1dp"
                        android:layout_height="wrap_content"
                        android:layout_marginLeft="5dp"
                        android:layout_marginRight="5dp"
                        android:background="@android:color/black" />

                    <LinearLayout
                        android:layout_width="0dp"
                        android:layout_height="match_parent"
                        android:layout_weight=".7"
                        android:gravity="center">

                        <TextView
                            android:id="@+id/txtTotalHours3"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:gravity="center"
                            android:text=""
                            android:textColor="@android:color/black"
                            android:textSize="16sp" />

                    </LinearLayout>

                </LinearLayout>

                <View
                    android:layout_width="match_parent"
                    android:layout_height="1dp"
                    android:background="@android:color/black" />

                <Button
                    android:id="@+id/btnSubmit"
                    android:layout_width="wrap_content"
                    android:layout_height="40dp"
                    android:layout_gravity="right|bottom"
                    android:textColor="#fff"
                    android:layout_marginLeft="30dp"
                    android:layout_marginRight="30dp"
                    android:layout_marginTop="10dp"
                    android:layout_marginBottom="20dp"
                    android:background="@drawable/rounded_corner_button_bg"
                    android:text="Next" />

            </LinearLayout>

        </FrameLayout>
    </LinearLayout>**

A: Add Scroll View with android:fillViewport="true" Attribute in Layout
And also add in menifest to resolve edittext shrink issue
<activity android:name=".MainActivity"
            android:windowSoftInputMode="adjustPan"/>

Try This Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/white"
android:orientation="vertical">

<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fillViewport="true">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="10dp"
            android:layout_marginRight="10dp"
            android:layout_marginBottom="100dp"
            android:orientation="vertical"
            android:weightSum="8.8">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="1.2"
                android:orientation="horizontal"
                android:weightSum="4">

                <LinearLayout
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight="1.6">

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text=""
                        android:textColor="@android:color/black"
                        android:textSize="14dp" />

                </LinearLayout>

                <View
                    android:layout_width="1dp"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="5dp"
                    android:layout_marginRight="5dp"
                    android:background="@android:color/black" />

                <LinearLayout
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight=".8"
                    android:gravity="center">

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:gravity="center"
                        android:text="Quantity"
                        android:textColor="@android:color/black"
                        android:textSize="15sp" />

                </LinearLayout>

                <View
                    android:layout_width="1dp"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="5dp"
                    android:layout_marginRight="5dp"
                    android:background="@android:color/black" />

                <LinearLayout
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight=".9"
                    android:gravity="center">

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:gravity="center"
                        android:text="Hour Multiplier"
                        android:textColor="@android:color/black"
                        android:textSize="15sp" />

                </LinearLayout>

                <View
                    android:layout_width="1dp"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="5dp"
                    android:layout_marginRight="5dp"
                    android:background="@android:color/black" />

                <LinearLayout
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight=".7"
                    android:gravity="center">

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:gravity="center"
                        android:text="Shramanand Hours"
                        android:textColor="@android:color/black"
                        android:textSize="15sp" />

                </LinearLayout>

            </LinearLayout>

            <View
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:background="@android:color/black" />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight=".7"
                android:orientation="horizontal"
                android:weightSum="4">

                <LinearLayout
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight="1.6"
                    android:gravity="center">

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:gravity="center"
                        android:text="Courses/Camps"
                        android:textColor="@android:color/black"
                        android:textSize="14sp" />

                </LinearLayout>

                <View
                    android:layout_width="1dp"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="5dp"
                    android:layout_marginRight="5dp"
                    android:background="@android:color/black" />

                <LinearLayout
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight=".8"
                    android:gravity="center">

                    <EditText
                        android:id="@+id/edtCount1"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:inputType="number"
                        android:maxLength="3"
                        android:paddingLeft="8dp"
                        android:hint="__"
                        android:textColor="@android:color/black"
                        android:textCursorDrawable="@null"
                        android:textSize="15sp" />

                </LinearLayout>

                <View
                    android:layout_width="1dp"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="5dp"
                    android:layout_marginRight="5dp"
                    android:background="@android:color/black" />

                <LinearLayout
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight=".9"
                    android:gravity="center">

                    <TextView
                        android:id="@+id/txtHours1"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text=" x 10"
                        android:textColor="@android:color/black"
                        android:textSize="16sp" />

                </LinearLayout>

                <View
                    android:layout_width="1dp"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="5dp"
                    android:layout_marginRight="5dp"
                    android:background="@android:color/black" />

                <LinearLayout
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight=".7"
                    android:gravity="center">

                    <TextView
                        android:id="@+id/txtTotalHours1"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:gravity="center"
                        android:text=""
                        android:textColor="@android:color/black"
                        android:textSize="16sp" />

                </LinearLayout>

            </LinearLayout>

            <View
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:background="@android:color/black" />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight=".7"
                android:orientation="horizontal"
                android:weightSum="4">

                <LinearLayout
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight="1.6"
                    android:gravity="center">

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:gravity="center"
                        android:text="1 Day Test including Machine Test"
                        android:textColor="@android:color/black"
                        android:textSize="14sp" />

                </LinearLayout>

                <View
                    android:layout_width="1dp"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="5dp"
                    android:layout_marginRight="5dp"
                    android:background="@android:color/black" />

                <LinearLayout
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight=".8"
                    android:gravity="center">

                    <EditText
                        android:id="@+id/edtCount2"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:inputType="number"
                        android:maxLength="3"
                        android:hint="__"
                        android:paddingLeft="8dp"
                        android:textColor="@android:color/black"
                        android:textCursorDrawable="@null"
                        android:textSize="15sp" />

                </LinearLayout>

                <View
                    android:layout_width="1dp"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="5dp"
                    android:layout_marginRight="5dp"
                    android:background="@android:color/black" />

                <LinearLayout
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight=".9"
                    android:gravity="center">

                    <TextView
                        android:id="@+id/txtHours2"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="x 6"
                        android:textColor="@android:color/black"
                        android:textSize="16sp" />

                </LinearLayout>

                <View
                    android:layout_width="1dp"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="5dp"
                    android:layout_marginRight="5dp"
                    android:background="@android:color/black" />

                <LinearLayout
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight=".7"
                    android:gravity="center">

                    <TextView
                        android:id="@+id/txtTotalHours2"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:gravity="center"
                        android:text=""
                        android:textColor="@android:color/black"
                        android:textSize="16sp" />

                </LinearLayout>

            </LinearLayout>

            <View
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:background="@android:color/black" />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight=".7"
                android:orientation="horizontal"
                android:weightSum="4">

                <LinearLayout
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight="1.6"
                    android:gravity="center">

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:gravity="center"
                        android:text="Manashakti Varganidar"
                        android:textColor="@android:color/black"
                        android:textSize="14sp" />

                </LinearLayout>

                <View
                    android:layout_width="1dp"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="5dp"
                    android:layout_marginRight="5dp"
                    android:background="@android:color/black" />

                <LinearLayout
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight=".8"
                    android:gravity="center">

                    <EditText
                        android:id="@+id/edtCount3"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:inputType="number"
                        android:maxLength="3"
                        android:paddingLeft="8dp"
                        android:hint="__"
                        android:textColor="@android:color/black"
                        android:textCursorDrawable="@null"
                        android:textSize="15sp" />

                </LinearLayout>

                <View
                    android:layout_width="1dp"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="5dp"
                    android:layout_marginRight="5dp"
                    android:background="@android:color/black" />

                <LinearLayout
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight=".9"
                    android:gravity="center">

                    <TextView
                        android:id="@+id/txtHours3"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="x 5"
                        android:textColor="@android:color/black"
                        android:textSize="16dp" />

                </LinearLayout>

                <View
                    android:layout_width="1dp"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="5dp"
                    android:layout_marginRight="5dp"
                    android:background="@android:color/black" />

                <LinearLayout
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight=".7"
                    android:gravity="center">

                    <TextView
                        android:id="@+id/txtTotalHours3"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:gravity="center"
                        android:text=""
                        android:textColor="@android:color/black"
                        android:textSize="16sp" />

                </LinearLayout>

            </LinearLayout>

            <View
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:background="@android:color/black" />

            <Button
                android:id="@+id/btnSubmit"
                android:layout_width="wrap_content"
                android:layout_height="40dp"
                android:layout_gravity="right|bottom"
                android:textColor="#fff"
                android:layout_marginLeft="30dp"
                android:layout_marginRight="30dp"
                android:layout_marginTop="10dp"
                android:layout_marginBottom="20dp"
                android:text="Next" />

        </LinearLayout>

    </ScrollView>

</FrameLayout>

Check text not null
 button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String text1=edtCount1.getText().toString();
            String text2=edtCount2.getText().toString();
            String text3=edtCount3.getText().toString();
          if(!isNullOrEmpty(text1)||!isNullOrEmpty(text2)||!isNullOrEmpty(text3)){
              //Add your executable code here
          }else {
              Toast.makeText(MainActivity.this, "Please Add All Data", Toast.LENGTH_SHORT).show();
          }

        }
    });

}

public  boolean isNullOrEmpty(String str){
    return str==null || str.isEmpty();
}


text:
Q: How to only fetch the document with changes made form firebase with snapshot listener in swift? I have a collection that I attach a snapshot listener to. Problem is when I change a document in this collection it refetch all the documents in the collection, not just the one that changed.
This is my code when I set the snapshot listener
let docRef = db.collection("users").document(userID).collection("Platser")
        docRef.addSnapshotListener { [weak self] snapshot, error in
            guard let data = snapshot, error == nil else {
                return
            }

Inside .collection("Platser") is the collection for each "Plats" That have an auto-generated id from firebase as name.
If I change one document I just want to refetch that specific document, else the reads will go up way to high on a real app with users.
Been trying different ways to solve this and tried to read the firebase docs for this but I'm new to firebase and I really can't solve this one right now.


text:
Q: How to create ArrayList of ArrayLists so that it fits the programe to interface principle I know this question has already been aksed, but I am looking at it from a different perspective.
An answer is provided on what the generic type for ArrayList of ArrayLists is. However, I am looking for best practices and to program to interface. I then came up with the three options below.
Questions:

*

*Why the option 1 is compilation error? Why the conversion cannot take place?

*Which one of the options 2 or 3 are preferred and where?

*In the option 3 why the interface "List" is appeared at the right hand side of the statement? Please provide an appropriate answer to this. I need to understand these nested generic definitions.
 1) List<List<Integer>> arList1 = new ArrayList<ArrayList<Integer>>();
 2) List<ArrayList<Integer>> arList2 = new ArrayList<ArrayList<Integer>>();
 3) List<List<Integer>> arList3 = new ArrayList<List<Integer>>();

A: *

*This code:
List<List<Integer>> arList1 = new ArrayList<ArrayList<Integer>>();

is a compilation error because List<List<Integer>> can legally hold a LinkedList<Integer>, but the right-hand side of the assignment cannot. Generics are not covariant. (See the excellent article on generics by Brian Goetz.)

*I prefer 3 unless I want to explicitly require that the lists added to arList2 must be instances of ArrayList. While such a requirement would be quite rare, it can arise.

*In Java 7, you don't need to do this. You can write:
List<List<Integer>> arList1 = new ArrayList<>();

and the compiler will fill in List<Integer> as the generic type argument on the right side. With Java 6 and earlier, you need to explicitly provide a generic argument to the constructor call that is compatible with the generic argument of the left side of the assignment.

A: Option 1 is a compilation error because the types are not compatible. Indeed, you can put a List which is not an ArrayList into List<List<Integer>>, but not into ArrayList<ArrayList<Integer>>. That's why List appears on the right hand side in option 3.
The option 3 is preferred because it refers to objects by their interfaces. See Joshua Bloch, Effective Java: Programming Language Guide, item 34.


text:
Q: RabbitMQ' pika handshaking fails when SSL is set I am setting up the SSL layer on RabbitMQ on both server and clients. But the clients are failing when creating the connection to the server. At this point I am running the RabbitMQ server on a docker locally and the client locally using a conda environment.
Once the RabbitMQ server is up I see that the secure connection is accepting incoming connections:
test-rabbitmq-1  | 2023-01-20 08:22:01.692731+00:00 [info] <0.726.0> started TCP listener on [::]:5672
test-rabbitmq-1  | 2023-01-20 08:22:01.694836+00:00 [info] <0.746.0> started TLS (SSL) listener on [::]:7575

But the client refuses to connect with:
(rabbitmq-test) ➜  RabbitMQ-TSL ✗ python3 test.py
Enter PEM pass phrase: ********
INFO:pika.adapters.utils.connection_workflow:Pika version 1.3.1 connecting to ('127.0.0.1', 7575)
INFO:pika.adapters.utils.io_services_utils:Socket connected: <socket.socket fd=6, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=6, laddr=('127.0.0.1', 43142), raddr=('127.0.0.1', 7575)>
ERROR:pika.adapters.utils.io_services_utils:SSL do_handshake failed: error=SSLZeroReturnError(6, 'TLS/SSL connection has been closed (EOF) (_ssl.c:997)'); <ssl.SSLSocket fd=6, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=6, laddr=('127.0.0.1', 43142), raddr=('127.0.0.1', 7575)>
Traceback (most recent call last):
  File "/.../.local/lib/python3.10/site-packages/pika/adapters/utils/io_services_utils.py", line 636, in _do_ssl_handshake
    self._sock.do_handshake()
  File "/usr/lib/python3.10/ssl.py", line 1342, in do_handshake
    self._sslobj.do_handshake()
ssl.SSLZeroReturnError: TLS/SSL connection has been closed (EOF) (_ssl.c:997)
ERROR:pika.adapters.utils.connection_workflow:Attempt to create the streaming transport failed: SSLZeroReturnError(6, 'TLS/SSL connection has been closed (EOF) (_ssl.c:997)'); 'localhost'/(<AddressFamily.AF_INET: 2>, <SocketKind.SOCK_STREAM: 1>, 6, '', ('127.0.0.1', 7575)); ssl=True
ERROR:pika.adapters.utils.connection_workflow:AMQPConnector - reporting failure: AMQPConnectorTransportSetupError: SSLZeroReturnError(6, 'TLS/SSL connection has been closed (EOF) (_ssl.c:997)')
ERROR:pika.adapters.utils.connection_workflow:AMQP connection workflow failed: AMQPConnectionWorkflowFailed: 1 exceptions in all; last exception - AMQPConnectorTransportSetupError: SSLZeroReturnError(6, 'TLS/SSL connection has been closed (EOF) (_ssl.c:997)'); first exception - None.
ERROR:pika.adapters.utils.connection_workflow:AMQPConnectionWorkflow - reporting failure: AMQPConnectionWorkflowFailed: 1 exceptions in all; last exception - AMQPConnectorTransportSetupError: SSLZeroReturnError(6, 'TLS/SSL connection has been closed (EOF) (_ssl.c:997)'); first exception - None
ERROR:pika.adapters.blocking_connection:Connection workflow failed: AMQPConnectionWorkflowFailed: 1 exceptions in all; last exception - AMQPConnectorTransportSetupError: SSLZeroReturnError(6, 'TLS/SSL connection has been closed (EOF) (_ssl.c:997)'); first exception - None
ERROR:pika.adapters.blocking_connection:Error in _create_connection().
Traceback (most recent call last):
  File "/.../.local/lib/python3.10/site-packages/pika/adapters/blocking_connection.py", line 451, in _create_connection
    raise self._reap_last_connection_workflow_error(error)
  File "/.../.local/lib/python3.10/site-packages/pika/adapters/utils/io_services_utils.py", line 636, in _do_ssl_handshake
    self._sock.do_handshake()
  File "/usr/lib/python3.10/ssl.py", line 1342, in do_handshake
    self._sslobj.do_handshake()
ssl.SSLZeroReturnError: TLS/SSL connection has been closed (EOF) (_ssl.c:997)
Traceback (most recent call last):
  File "/.../test.py", line 16, in <module>
    with pika.BlockingConnection(conn_params) as conn:
  File "/.../.local/lib/python3.10/site-packages/pika/adapters/blocking_connection.py", line 360, in __init__
    self._impl = self._create_connection(parameters, _impl_class)
  File "/.../.local/lib/python3.10/site-packages/pika/adapters/blocking_connection.py", line 451, in _create_connection
    raise self._reap_last_connection_workflow_error(error)
  File "/.../.local/lib/python3.10/site-packages/pika/adapters/utils/io_services_utils.py", line 636, in _do_ssl_handshake
    self._sock.do_handshake()
  File "/usr/lib/python3.10/ssl.py", line 1342, in do_handshake
    self._sslobj.do_handshake()
ssl.SSLZeroReturnError: TLS/SSL connection has been closed (EOF) (_ssl.c:997)

Any idea of what I am not setting properly on pika or at the RabbitMQ server?

On the server side I set the SSL layer at rabbitmq.conf as:
# Enable AMQPS
listeners.ssl.default = 7575
ssl_options.cacertfile = /etc/rabbitmq/cer/ca_certificate.pem
ssl_options.certfile = /etc/rabbitmq/cer/server_certificate.pem
ssl_options.keyfile = /etc/rabbitmq/cer/server_key.pem
ssl_options.verify = verify_peer
ssl_options.fail_if_no_peer_cert = true

# Enable HTTPS
management.listener.port = 15671
management.listener.ssl = true
management.listener.ssl_opts.cacertfile = /etc/rabbitmq/cer/ca_certificate.pem
management.listener.ssl_opts.certfile = /etc/rabbitmq/cer/server_certificate.pem
management.listener.ssl_opts.keyfile = /etc/rabbitmq/cer/server_key.pem

The docker compose file contains:
version: '3.8'

services:
  rabbitmq:
    image: rabbitmq:3-management
    hostname: rabbitmq-server
    volumes:
      - ./rabbitmq-config/rabbitmq-cert:/etc/rabbitmq/cer
      - ./rabbitmq-config/rabbitmq.conf:/etc/rabbitmq/rabbitmq.conf
      - ./rabbitmq/data:/var/lib/rabbitmq/mnesia/rabbit@my-rabbit
      - ./rabbitmq/logs:/var/log/rabbitmq/log
    ports:
      - 5672:5672
      - 7575:7575
      - 15672:15672

Then, and to simply, I am using the demo client from RabbitMQ's guide as:
import logging
import pika
import ssl
from pika.credentials import ExternalCredentials

logging.basicConfig(level=logging.INFO)
context = ssl.create_default_context(
    cafile = '/rabbitmq-config/rabbitmq-cert/ca_certificate.pem'
)
context.load_cert_chain(
    '/rabbitmq-config/rabbitmq-cert/client_certificate.pem',
    '/rabbitmq-config/rabbitmq-cert/client_key.pem'
)
ssl_options = pika.SSLOptions(context, "localhost")
conn_params = pika.ConnectionParameters(
    port        = 7575,
    ssl_options = ssl_options,
    credentials = ExternalCredentials()
)

with pika.BlockingConnection(conn_params) as conn:
    ch = conn.channel()
    ch.queue_declare("foobar")
    ch.basic_publish("", "foobar", "Hello, world!")
    print(ch.basic_get("foobar"))

A: Your Python code is set up to do X509 certificate authentication (you're not using username/password but are using ExternalCredentials). However, you have not configured RabbitMQ to accept X509 certificates for authentication (docs).
The Pika docs need to be updated, so I opened this issue - https://github.com/pika/pika/issues/1413
You would probably get a hint of this if you look at the RabbitMQ log file at the time your Python client tries to connect.
In order to enable X509 certificate authentication, do the following:

*

*rabbitmq-plugins enable rabbitmq_auth_mechanism_ssl (docs)

*Edit your rabbitmq.conf file and add the following section:
auth_mechanisms.1 = PLAIN
auth_mechanisms.1 = AMQPLAIN
auth_mechanisms.1 = EXTERNAL

*Restart RabbitMQ

*Add a password-less user that exactly matches the CN= value in your client certificate: rabbitmqctl add_user 'foobar, O=baz'. You can also get this value by attempting to connect after making the above changes. The failed auth attempt will be logged.

If you continue to have problems, I suggest asking on the mailing list as this is not a good forum for detailed analysis.

NOTE: the RabbitMQ team monitors the rabbitmq-users mailing list and only sometimes answers questions on StackOverflow.


text:
Q: sending message to contacts in telethon python telegram How can I see all my contacts and send them messages?
i use Telethon (API telegram python).
from telethon.tl.functions.contacts import ResolveUsernameRequest
from telethon.tl.types import InputChannelEmpty
from telethon import TelegramClient
from telethon.tl.types.messages import Messages
from telethon.tl.types.contacts import Contacts
api_id = 1****
api_hash = '5fbd2d************************'
client = TelegramClient('arta0', api_id, api_hash)
client.connect()

A: Just add this line to your code:
contacts = client.invoke(GetContactsRequest(""))
print(contacts)

And you should see the contacts in the result.
To send messages to contacts, you can use the send_message function defined in telegram_client.py and has an example in InteractiveTelegramClient.py.
for u in contacts.users:
    client.send_message(InputPeerUser(u.id, u.access_hash), "hi")

If you need more details comment below and I will try to reply.

A: Sending empty string didn't worked for me:
contacts = client.invoke(GetContactsRequest(""))
*** struct.error: required argument is not an integer

So I think you should use '0' instead:
contacts = client.invoke(GetContactsRequest(0))
print(contacts)

A: I think in new update client.invoke() is not defined.
I used following code and it worked for me.
from telethon.tl.functions.contacts import GetContactsRequest
contacts = client(GetContactsRequest(0))


text:
Q: Can't seem to add two numbers in shell I have been googling and trying different methods but nothing seems to work.
I have the following code
string=0 4 5 27 8 7 0 6

total=0

for n in "$string"; do
 total=$(($total + $n))
done

This way I want to count the total sum of all the numbers within that string.
I have also tried expr "$total" + "$n" but that gives me an error saying the operand is not an integer.
Any suggestion how I might make this work?

A: Don't quote the string in the in clause, quoted string is not split into words:
#! /bin/bash
total=0
string='0 4 5 27 8 7 0 6'
for n in $string ; do
    (( total += n ))
done
echo $total

A: string=0 4 5 27 8 7 0 6

This attempts to set the variable string to 0, then invoke the command 4 with arguments 5 27 8 7 0 6.
You need to quote the value:
string="0 4 5 27 8 7 0 6"

And you need to remove the quotes when you refer to it; change
for n in "$string"; do

to
for n in $string; do

A: You should use :
total=$(( total + n ))

no need for the $ before variables inside a $(( )) statement


text:
Q: java.lang.RuntimeException: Unable to start activity ComponentInfo: java.lang.NullPointerException: println needs a message I am new to Android. I am getting the above error and I am not aware what is causing this. Please do help me to debug the error. All suggestions are welcome. Thanks in advance.
My Main Activity method (I have named it as DetailsUsers.Java)
      package form.app.applicationform1;

        import form.app.applicationform1.DatabaseHandler;
        import form.app.applicationform1.R;
        import form.app.applicationform1.User;

        import android.app.Activity;
        import android.content.Intent;
        import android.os.Bundle;
        import android.util.Log;
        import android.view.View;
        import android.view.View.OnClickListener;
        import android.widget.Button;
        import android.widget.TextView;
        import android.widget.Toast;

        public class DetailsUsers  extends Activity implements OnClickListener{
            private static String position = null;

            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.main);

                Intent intent = getIntent();

                position = intent.getStringExtra("position");
                Log.d("value of position from intent", position);
                DatabaseHandler db = new DatabaseHandler(this);
                User user = db.getUser(position);
                TextView textViewDetailName = (TextView) findViewById(R.id.textView1);
                textViewDetailName.setText(user.getName());

                TextView textViewDetailAddress = (TextView) findViewById(R.id.textView4);
                textViewDetailAddress.setText(user.getAddress());

                TextView textViewDetailsPhone = (TextView) findViewById(R.id.textView2);
                textViewDetailsPhone.setText(user.getPhone());

                TextView textViewDetailsEmail = (TextView) findViewById(R.id.textView3);
                textViewDetailsEmail.setText(user.getEmail());

                TextView textViewDetailsComments = (TextView) findViewById(R.id.textView5);
                textViewDetailsComments.setText(user.getComments());

                Button backButton = (Button)findViewById(R.id.button2);
                backButton.setOnClickListener(this);

                Button editButton = (Button)findViewById(R.id.button1);
                editButton.setOnClickListener(this);

                Button saveButton = (Button)findViewById(R.id.button3);
                saveButton.setOnClickListener(this);
            }

            @Override
            public void onClick(View v) {
                if(v.getId() == R.id.button2) {
                    Intent intent = new Intent(getApplicationContext(), ListUsers.class);
                    startActivity(intent);
                }
                else if(v.getId() == R.id.button1) {
                    Intent intent = new Intent(getApplicationContext(), EditUsers.class);
                    intent.putExtra("position", position);
                    startActivity(intent);
                }
                else if (v.getId() == R.id.button3){
                    Intent intent = new Intent(getApplicationContext(), DetailsUsers.class);
                    Toast.makeText(this.getApplicationContext(), "User Has Been Saved", Toast.LENGTH_LONG ).show();
                    intent.putExtra("position", position);
                    startActivity(intent);
                }
            }
        }

Main.xml file:
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        tools:context="form.app.applicationform1.DetailsUsers" >

        <Button
            android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/back" />

        <ImageView
            android:id="@+id/imageView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="50dp"
            android:contentDescription="@string/form_icon"
            android:paddingLeft="100dp"
            android:src="@drawable/ic_launcher"
            android:tag="Edit Form" />

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="70dp"
            android:text="@string/full_name"
            android:textSize="16sp" />

        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/phone_no"
            android:textSize="16sp" />

        <TextView
            android:id="@+id/textView3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/email_id"
            android:textSize="16sp" />

        <TextView
            android:id="@+id/textView4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingLeft="50dp"
            android:text="@string/postal_address"
            android:textSize="16sp" />

        <TextView
            android:id="@+id/textView5"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/comments_feedback"
            android:textSize="16sp" />

        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/edit_form" />

        <Button
            android:id="@+id/button3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/save_form" />

    </LinearLayout>

Manifest file:
    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="form.app.applicationform1"
        android:versionCode="1"
        android:versionName="1.0" >

        <uses-sdk
            android:minSdkVersion="8"
            android:targetSdkVersion="21" />
        <uses-permission android:name="android.permission.WRITE_USER_DICTIONARY"/>

        <application
            android:allowBackup="true"
            android:icon="@drawable/ic_launcher"
            android:label="@string/app_name" >
            <activity
                android:name="form.app.applicationform1.DetailsUsers"
                android:label="@string/app_name" >
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />

                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
            <activity
                android:name=".EditUsers"
                android:label="@string/title_activity_edit_users" >
            </activity>
            <activity
                android:name=".ListUsers"
                android:label="@string/title_activity_list_users" >
            </activity>

             <activity android:name="form.app.applicationform1.DatabaseHandler"></activity>
            <activity android:name="form.app.applicationform1.User"></activity>
        </application>

    </manifest>

Logcat error trace:
        12-23 01:29:29.179: D/AndroidRuntime(2412): Shutting down VM
        12-23 01:29:29.219: W/dalvikvm(2412): threadid=1: thread exiting with uncaught exception (group=0xb0f5e648)
        12-23 01:29:29.229: E/AndroidRuntime(2412): FATAL EXCEPTION: main
        12-23 01:29:29.229: E/AndroidRuntime(2412): java.lang.RuntimeException: Unable to start activity ComponentInfo{form.app.applicationform1/form.app.applicationform1.DetailsUsers}: java.lang.NullPointerException: println needs a message
        12-23 01:29:29.229: E/AndroidRuntime(2412):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
        12-23 01:29:29.229: E/AndroidRuntime(2412):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
        12-23 01:29:29.229: E/AndroidRuntime(2412):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
        12-23 01:29:29.229: E/AndroidRuntime(2412):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
        12-23 01:29:29.229: E/AndroidRuntime(2412):     at android.os.Handler.dispatchMessage(Handler.java:99)
        12-23 01:29:29.229: E/AndroidRuntime(2412):     at android.os.Looper.loop(Looper.java:137)
        12-23 01:29:29.229: E/AndroidRuntime(2412):     at android.app.ActivityThread.main(ActivityThread.java:5103)
        12-23 01:29:29.229: E/AndroidRuntime(2412):     at java.lang.reflect.Method.invokeNative(Native Method)
        12-23 01:29:29.229: E/AndroidRuntime(2412):     at java.lang.reflect.Method.invoke(Method.java:525)
        12-23 01:29:29.229: E/AndroidRuntime(2412):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
        12-23 01:29:29.229: E/AndroidRuntime(2412):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
        12-23 01:29:29.229: E/AndroidRuntime(2412):     at dalvik.system.NativeStart.main(Native Method)
        12-23 01:29:29.229: E/AndroidRuntime(2412): Caused by: java.lang.NullPointerException: println needs a message
        12-23 01:29:29.229: E/AndroidRuntime(2412):     at android.util.Log.println_native(Native Method)
        12-23 01:29:29.229: E/AndroidRuntime(2412):     at android.util.Log.d(Log.java:138)
        12-23 01:29:29.229: E/AndroidRuntime(2412):     at form.app.applicationform1.DetailsUsers.onCreate(DetailsUsers.java:28)
        12-23 01:29:29.229: E/AndroidRuntime(2412):     at android.app.Activity.performCreate(Activity.java:5133)
        12-23 01:29:29.229: E/AndroidRuntime(2412):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
        12-23 01:29:29.229: E/AndroidRuntime(2412):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
        12-23 01:29:29.229: E/AndroidRuntime(2412):     ... 11 more

Database code is as below:
import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DatabaseHandler extends SQLiteOpenHelper{

    // Database Version
    private static final int DATABASE_VERSION = 1;
    // Database Name
    private static final String DATABASE_NAME = "userDB";
    // Employee table name
    private static final String TABLE_USERS = "users";

    private static String NAME = "name";
    private static String PHONE = "phone";
    private static String EMAIL  = "email";
    private static String ADDRESS = "address";
    private static String COMMENTS = "comments";
    public DatabaseHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_USER_TABLE = "CREATE TABLE " + TABLE_USERS + "("
                + NAME + " TEXT,"
                + PHONE + " TEXT,"
                + EMAIL + " TEXT,"
                + ADDRESS + " TEXT"
                + COMMENTS + " TEXT"
                + ")";
        db.execSQL(CREATE_USER_TABLE);
        //db.close();

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_USERS);
        // Create tables again
        onCreate(db);

    }

    // Adding new user
    public int addUser(User user)
    {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(NAME, user.getName());
        values.put(ADDRESS, user.getAddress());
        values.put(PHONE, user.getPhone());
        values.put(EMAIL, user.getEmail());
        values.put(COMMENTS, user.getComments());
        // Inserting Row
        int id = (int) db.insert(TABLE_USERS, null, values);
        db.close(); // Closing database connection
        return id;
    }

    //updating a existing user
    public int editUser(User user, String position) {
            SQLiteDatabase db = this.getWritableDatabase();
            ContentValues values = new ContentValues();
            values.put(NAME, user.getName());
            values.put(ADDRESS, user.getAddress());
            values.put(PHONE, user.getPhone());
            values.put(EMAIL, user.getEmail());
            values.put(COMMENTS, user.getComments());
            // updating row
            return db.update(TABLE_USERS, values, NAME + " = ?",
                    new String[] { String.valueOf(position) });
    }

    public User getUser(String id) {
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.query(TABLE_USERS, new String[] {
                NAME, ADDRESS, PHONE, EMAIL, COMMENTS }, NAME + "=?",
                new String[] {String.valueOf(id)}, null, null, null, null);
        if (cursor != null)
            cursor.moveToFirst();

        User user = new User(cursor.getString(1),
                cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5));
        db.close();
        // return user
        return user;

    }

        // LIst all users
        public String[] getAllUsers() {
            ArrayList<String> usersList = new ArrayList<String>();
            String selectQuery = "SELECT  * FROM " + TABLE_USERS;
            try {
                SQLiteDatabase db = this.getReadableDatabase();
                Cursor cursor = db.rawQuery(selectQuery, null);
                // looping through all rows and adding to list
                if (cursor.moveToFirst()) {
                    do {
                        String user = cursor.getString(1) + ", " + cursor.getString(2) +  ", " + cursor.getString(3) + ", " + cursor.getString(4) + ", " + cursor.getString(5);
                        usersList.add(user);
                    } while (cursor.moveToNext());
                }

                String[] users = new String[usersList.size()];
                db.close();
                return (usersList.toArray(users));
            }
            catch(Exception e) {
                Log.d("Error in getting users from DB", e.getMessage());
                return null;
            }
        }

}

Please let me know if more information is needed. Please help to solve this problem

A: a) Please add null result error handling for:
position = intent.getStringExtra("position");

b) Also, when you insert your Extras consider adding .toString()
c) Always use something like Log.d("value of position from intent", ""+position) if you don't check for position == null OR you could write your own Log.d wrapper which accepts and handles nulls.

A: Enter the query like this and then try. you are missing a comma after address text and put space after the comma ... :)
public void onCreate(SQLiteDatabase db) {
    String CREATE_USER_TABLE = "CREATE TABLE " + TABLE_USERS + "("
            + NAME + " TEXT, "
            + PHONE + " TEXT, "
            + EMAIL + " TEXT, "
            + ADDRESS + " TEXT, "
            + COMMENTS + " TEXT "
            + ")";
    db.execSQL(CREATE_USER_TABLE);

Hope it helps ...


text:
Q: jquery text highlight is ok but not in iPad/iPhone I found a demo that to highlight some text in html page using jquery.
Demo: http://development.michaelpstone.net/highlight-and-capture/
But it is not work on mobile (iPad/iPhone)
Already changed the event "click", "mouseup" to "touchend" but no luck.
Can anyone help? Thanks
Source Code from the demo site:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Highlight, capture, and designate keeywords</title>

Highlight and capture content

By Michael P. Stone - www.michaelpstone.net

In this demo, you're going to be able to highlight a piece of text and click it to decide whether it's a good piece of text or a bad piece of text

Instructions: Highlight a piece of text within the bordered container, click off of it, then you can click on that selection to either define as good or bad. You can continue to click that piece as it will just go back between good and bad. After you've selected all of the text you want, you can press the button that says "Extract Highlighted Text".

Jowl pig chuck pork, tri-tip salami jerky andouille ham ground round rump beef ribs filet mignon hamburger. Brisket filet mignon pork belly fatback. Ham ball tip prosciutto tail. Sausage fatback filet mignon kielbasa andouille beef pancetta cow, sirloin ham hock bresaola pork loin shoulder strip steak boudin. Turducken capicola cow short loin venison ball tip. Flank pork loin boudin, short loin salami ribeye beef bacon ham hock ball tip rump pork belly. Beef ribs bresaola pork ground round hamburger pancetta short ribs, t-bone shank capicola ham sausage.

Strip steak biltong ham hock, ham pig salami andouille prosciutto filet mignon cow. Chuck turkey jerky boudin, jowl cow drumstick ball tip short loin ham hock shankle venison sirloin tail t-bone. Spare ribs bacon venison, ribeye ham hock pork tail beef ribs capicola bresaola. Beef frankfurter salami, ham hock t-bone ball tip ground round shoulder short loin meatball filet mignon brisket chuck pastrami. Kielbasa filet mignon drumstick, ham ribeye chuck jerky beef ribs pork belly ball tip bresaola biltong.

<input type="button" id="extractText" value="Extract Highlighted Text" style="margin-left:10px" /> <input type="button" id="clearHighlights" value="Clear Highlights" style="margin-left:10px" />

Bad Text Results

Good Text Results

A: I found the solution. Now I can use my iPad to highlight the text
change the code:
1)
From
CurrentSelection.Selector.mouseup = function(){
To
CurrentSelection.Selector.touchend = function(){
2)
From
$("#"+parentContainerId).bind("mouseup",CurrentSelection.Selector.mouseup)
To
$("#"+parentContainerId).bind("touchstart",CurrentSelection.Selector.touchend)


text:
Q: renaming data in a dataframe using config json I have a situation where I need to change some junk data in json such as
 'a' need to be A
 'B' need to be B

I want to create a config json which shall have a dictionary where the key & value should look like
dict={'a':'A', 'b':'B'}
And then access the json in another python file which reads data from a dataframe where those junk values(keys of the dictionary) are there & change them to the correct ones(values of the dictionary). Can anyone help..?

A: So, given the following config.json file:
{
    "junk1": "John",
    "junk2": "Jack",
    "junk3": "Tom",
    "junk4": "Butch"
}

You could have the following python file in the same directory:
import pandas as pd
import json

with open("config.json", "r") as f:
    cfg = json.load(f)

df = pd.DataFrame(
    {
        "class": {
            0: "class1",
            1: "class2",
            2: "class3",
            3: "class4",
        },
        "firstname": {0: "junk1", 1: "junk2", 2: "junk3", 3: "junk4"},
    }
)
print(df)
# Outputs
    class firstname
0  class1     junk1
1  class2     junk2
2  class3     junk3
3  class4     junk4

And then do:
df["firstname"] = df["firstname"].replace(cfg)

print(df)
# Outputs
    class firstname
0  class1      John
1  class2      Jack
2  class3       Tom
3  class4     Butch


text:
Q: How can I view all elements of a structure of arrays without writing a FOR-loop? I am interested in seeing all the elements in the :
result(:,:).randMin(1:4,2:end)

in which the result(a=1:24, d=1:5).
In general is it possible to access them without a loop and cat ?

A: You cannot use the [] trick with multi-level indexing, but if all of randMin are 128 x 11 arrays:
out = [result(1:24,1:5).randMin];
out = reshape(out,[128 11, 24, 5]);
out = out(1:4,2:end,:,:);

Final result has size of 4 x 10 x 24 x 5 where the first two are your randMin(1:4,2:end), and last two dimensions are your a and d respectively.

A: It looks like you are looking for getfield:
getfield( result, {1:24, 1:5}, 'randMin', {1:4, 2:end} );

I'm a bit rusty with this command and you might need to play with it a bit to make it work.
Read its manual and good luck!

A: I don't think it is possible because randMin could be something else for every field in result. result(1,1).randMin could be a matrix, result(1,2).randMin could be a vector, result(2,1).randMin could be 4-dimensional...you see where I'm going with this.
So there is no way of knowing the dimensions or the size of each result's randMin without looping through all fields in result. If there is a function that does what you want, it will have to use a loop internally, so you might as well use a loop yourself.
Edit:
If it is constant you can try something like this:
%Generating matrix struct results(a,b).randMin(c,d)
dim1=24;
dim2=5;
dim3=128;
dim4=11;

% value=0;
% for i=1:dim1
%     for j=1:dim2
%         for k=1:dim3
%             for l=1:dim4
%                 results(i,j).randMin(k,l)=value;
%                 value=value+1;
%             end
%         end
%     end
% end

%Getting the values
range1=1:24;
range2=1:5;
range3=1:4;
range4=2:dim4;

myMat=[results(range1, range2).randMin];
myContainer=reshape(myMat, dim3, dim4, length(range1), length(range2));
desiredValues=myContainer(range3, range4,:,:);

In the end, desiredValues will have the values you want, but the indices switched sides, instead of results(a,b).randMin(c,d) it is now desiredValues(c,d,a,b).
As I didn't know exactly how your struct looks like, I defined dim1 to dim4 as maximum values for the indices a to d. You can use range1 to range4 to select your desired values.


text:
Q: R - web scraping dynamic form with inputs I'm trying to achieve the following task in R.
This website provides sub-district level statistics (in tables) on agricultural data in India: http://agcensus.dacnet.nic.in/tehsilsummarytype.aspx
My understanding is that this is called a dynamic form as the options change depending on the entries made. Specifically I would like to download tables for:

*

*State = Andhra Pradesh

*District = Adilabad, Anantapur, Kadapa, ... (8 total)

*Tahsil = Mancherial, Kasipet (those are just 2 examples  for District = Adilabad; total 158)

Then I want "Average Holdings by size" for all social groups, all genders and the Total.
Based on this post What if I want to web scrape with R for a page with parameters? I think the way to go is to use getHTMLFormDescription(). However, since my form is dynamic, I can't follow the route that was suggested in the other post. The createFunction() line returns an error:
 "*Error in writeFunction(formDescription, character(), url, con, verbose = verbose,  :  You should provide a form description here. See getFormDescription()."
In the RHTMLForms package that can be downloaded from  the omegahat webpage,
there is this function that (as the name suggests) should do what I need:
function function(desc, omit = character(), drop = TRUE, ..., verbose = FALSE) {
# Discard the elements that we are omitting.
 if(length(omit)) {
   idx = match(omit, names(desc$elements), 0)
  k = class(desc$elements)
 desc$elements <- desc$elements[-idx]
class(desc$elements) = k }

 # If no more elements left as a result of omitting them, just return the description
 # as there are definitely no more dynamic components left.
if(length(desc$elements) == 0)
 return(desc)

   # Now find the dynamic components.
 dyn = sapply(desc$elements, inherits, "DynamicHTMLFormElement")
if(!any(dyn))
return(desc)

pivot = desc$elements[[min(which(dyn))]]

 # We will need to submit the form for each value of this dynamic element, so
  # get the URI.  If the URI changes depending on the value, we are out of     luck!!
url = mergeURI(URI(desc$formAttributes["action"]), URI(desc$url))

 # Prepare the return value with the pivot information and we will build up
 # the branches by looping over the possible values.
 descriptions = list(elementName = pivot$name,
                 description = pivot,
                 values = list())

 omit = c(omit, pivot$name)

 for(i in names(pivot$options)) {
   # Create the arguments for the submission. We may need to include them all.
 args = list(i)
 names(args)[1] = pivot$name

 if(verbose)
   cat("Checking ", pivot$name, " - option", i, "\n")

  #XX we may need to provide all the arguments rather than just this one.
  # or perhaps cumulate them for the elements we have already deal with.
  # We have the defaults and the possible values from the original description.
 page = formQuery(args, toString(url), desc, .checkArgs = FALSE, ...)
  # Make certain that we turn the checkDynamic off here to avoid recursively.
 tmp = getHTMLFormDescription(page, asText = TRUE, handlers = multiFormElementHandlers(url, checkDynamic = FALSE))
 tmp = getDynamicHTMLFormDescription(tmp, omit = omit)

   # Now remove the elements that we are omitting. This leaves a subset of the form.
 if(drop) {
    idx = match(omit, names(tmp$elements), 0)

    if(any(is.na(idx))) {
      k = class(tmp$elements)
      tmp$elements = tmp$elements[is.na(idx)]
      class(tmp$elements) = k
    }

    class(tmp) <- c("HTMLFormSubset", class(tmp))
 }

 descriptions$values[[i]] = tmp
 }

class(descriptions) <- c("DynamicFormElementPath")

descriptions
}

However, I can't get this to work either - the call getDynamicHTMLFormDescription("http://agcensus.dacnet.nic.in/tehsilsummarytype.aspx") gives "Error in desc$elements : $ operator is invalid for atomic vectors".
Does anybody have advise on how to go about this? Once I have a way to fill out the form and access the table for each sub-district (tahsil), I know how to get the data in shape. It's really only about making R fill out this (particular) form.
Any help is welcome!
Michael Kaiser
(Staff Research Associate, UCSD)

A: Here is a solution using RSelenium for downloading data for

*

*State = Andhra Pradesh

*District = Adilabadt

*Tahsil = Mancherial

*Tables = Average Size of Operational Holding by Size Group

The remaining fields use the default input parameters.
library(RSelenium)
library(XML)
library(magrittr)

# Start Selenium Server --------------------------------------------------------

checkForServer()
startServer()
remDrv <- remoteDriver()
remDrv$open()

# Simulate browser session and fill out form -----------------------------------

remDrv$navigate('http://agcensus.dacnet.nic.in/tehsilsummarytype.aspx')
remDrv$findElement(using = "xpath",
                   "//select[@name = '_ctl0:ContentPlaceHolder1:DropDownList1']/option[@value = '1a']")$clickElement()
remDrv$findElement(using = "xpath",
                   "//select[@name = '_ctl0:ContentPlaceHolder1:DropDownList9']/option[@value = '19']")$clickElement()
remDrv$findElement(using = "xpath",
                   "//option[@value = '33']")$clickElement()
remDrv$findElement(using = "xpath",
                   "//select[@name = '_ctl0:ContentPlaceHolder1:DropDownList3']/option[@value = '4']")$clickElement()
# Click submit
remDrv$findElement(using = "xpath",
                   "//input[@value = 'Submit']")$clickElement()

# Retrieve and download results ------------------------------------------------

table <- remDrv$getPageSource()[[1]] %>%
  htmlParse %>%
  readHTMLTable %>%
  extract2(4)

remDrv$quit()
remDrv$closeServer()

head(table)

#      V1                      V2                     V3
# 1 SI No. Size of Holding(in ha.) Institutional Holdings
# 2    (1)                     (2)                    (3)
# 3      1                MARGINAL                      0
# 4      2                   SMALL                      0
# 5      3              SEMIMEDIUM                      0
# 6      4                  MEDIUM                      0

However, the static solution above only answers parts of your questions, namely how to fill out the web form using R.
The tricky thing on your web page is that the values in the different drop-down menus depend on each other.
Below, you will find a solution which takes into account those dependencies without the need that you know the respective district and tehsils IDs upfront.
The code below downloads data for

*

*State = GOA

*Tables = Average Size of Operational Holding by Size Group

including all districts and all tehsils. I used GOA as the primary anchor but you can easily select another state of your choice.
library(RSelenium)
library(XML)
library(dplyr)
library(magrittr)

# Start Selenium Server --------------------------------------------------------

checkForServer()
startServer()
remDrv <- remoteDriver()
remDrv$open()

# Simulate browser session and fill out form -----------------------------------

remDrv$navigate('http://agcensus.dacnet.nic.in/tehsilsummarytype.aspx')

# Select 27a == GOA as the anchor
remDrv$findElement(using = "xpath",
                   "//select[@name = '_ctl0:ContentPlaceHolder1:DropDownList1']/option[@value = '27a']")$clickElement()
# Select 4 == Average Size of Operational Holding by Size Group
remDrv$findElement(using = "xpath",
                   "//select[@name = '_ctl0:ContentPlaceHolder1:DropDownList3']/option[@value = '4']")$clickElement()

# Get all district IDs and the respective names belonging to GOA
district_IDs <- remDrv$findElements(using = "xpath",
                                "//select[@name = '_ctl0:ContentPlaceHolder1:DropDownList9']/option") %>%
  lapply(function(x){x$getElementAttribute('value')}) %>%
  unlist

district_names <- remDrv$findElements(using = "xpath",
                                    "//select[@name = '_ctl0:ContentPlaceHolder1:DropDownList9']/option") %>%
  lapply(function(x){x$getElementText()}) %>%
  unlist

# Retrieve and download results ------------------------------------------------

result <- data.frame(district = character(), teshil = character(),
                     V1 = character(), V2 = character(), V3 = character())

for (i in seq_along(district_IDs)) {

  remDrv$findElement(using = "xpath",
                     paste0("//select[@name = '_ctl0:ContentPlaceHolder1:DropDownList9']/option[@value = ",
                          "'", district_IDs[i], "']"))$clickElement()
  Sys.sleep(2)

  # Get all tehsil IDs and names from the currently selected district
  tehsil_IDs <- remDrv$findElements(using = "xpath",
                     "//div[@id = '_ctl0_ContentPlaceHolder1_Panel4']/select/option") %>%
    lapply(function(x){x$getElementAttribute('value')}) %>%
    unlist

  tehsil_names <- remDrv$findElements(using = "xpath",
                                                    "//div[@id = '_ctl0_ContentPlaceHolder1_Panel4']/select/option") %>%
    lapply(function(x){x$getElementText()}) %>%
    unlist

  for (j in seq_along(tehsil_IDs)) {

    remDrv$findElement(using = "xpath",
                        paste0("//div[@id = '_ctl0_ContentPlaceHolder1_Panel4']/select/option[@value = ",
                               "'", tehsil_IDs[j], "']"))$clickElement()
    Sys.sleep(2)

    # Click submit and download data of the selected tehsil
    remDrv$findElement(using = "xpath",
                       "//input[@value = 'Submit']")$clickElement()
    Sys.sleep(2)

    # Download data for current tehsil
    tehsil_data <- remDrv$getPageSource()[[1]] %>%
      htmlParse %>%
      readHTMLTable %>%
      extract2(4) %>%
      extract(c(-1, -2), )

    result <- data.frame(district = district_names[i], tehsil = tehsil_names[j],
                         tehsil_data) %>% rbind(result, .)

    remDrv$goBack()
    Sys.sleep(2)
  }
}

remDrv$quit()
remDrv$closeServer()

result %<>% as_data_frame %>%
  rename(
    si_no = V1,
    holding_size = V2,
    inst_holdings = V3
    ) %>%
  mutate(
    si_no = as.numeric(as.character(si_no)),
    inst_holdings = as.numeric(as.character(inst_holdings))
    )

dim(result)
# [1] 66  5

head(result)
# district tehsil si_no   holding_size inst_holdings
# 1 NORTH GOA  ponda     1       MARGINAL          0.34
# 2 NORTH GOA  ponda     2          SMALL          0.00
# 3 NORTH GOA  ponda     3     SEMIMEDIUM          2.50
# 4 NORTH GOA  ponda     4         MEDIUM          0.00
# 5 NORTH GOA  ponda     5          LARGE        182.64
# 6 NORTH GOA  ponda     6 ALL SIZE CLASS         41.09

tail(result)
# district tehsil si_no   holding_size inst_holdings
# 1 SOUTH GOA quepem     1       MARGINAL          0.30
# 2 SOUTH GOA quepem     2          SMALL          0.00
# 3 SOUTH GOA quepem     3     SEMIMEDIUM          0.00
# 4 SOUTH GOA quepem     4         MEDIUM          0.00
# 5 SOUTH GOA quepem     5          LARGE         23.50
# 6 SOUTH GOA quepem     6 ALL SIZE CLASS         15.77

RSelenium even supports headless browsing leveraging PhantomJS as described in this vignette.