问:
Submit form after successful ajax call using jQuery in asp.net mvc 5
I have a form in an Asp.net MVC 5 project which has a Submit button. When the Submit button is clicked, I want to do the following:

Perform client=side validation using jQuery on various fields (required fields have been filled, email format is valid, etc...). That part is working fine.

Make an Ajax call that will perform some server side validation by calling an action from the controller and return a JSON response. The response contains a Success property and Errors property which contains a list of errors.

The Success property will return true if no error are found and the Errors property will be null. If errors are found the Success property is returns false and the Errors property contains a list of relevant errors.

I'm calling '\ApplicationForm\Validate' action from my ApplicationForm controller and this part is working fine.

When no errors are found in part 2, I want my form to be submitted as normal and call the '\ApplicationForm\Index' action so that my data can then be added to my database. I cannot get this part to work!!

The Submit button is defined as follows:

```<code><div class="form-group">
  <div>
    <input type="button" id="btnApply" value="Apply" class="btn btn-primary" />
  </div>
</div>
</code>```

My JavaScript code is defined as follows:

```<code>$('#AppllicationForm').submit(function () {
    if (!$(this).attr('validated')) {
        if ($(this).valid()) {
            $.ajax({
                type: "POST",
                data: $(this).serialize(),
                url: "/ApplicationForm/ValidateForm",
                dataType: 'json',
                success: function (response) {
                    $('validationSummary').show();
                    if (response != null && response.success) {
                        console.log('No Validation errors detected');
                        $('#ApplicationForm').attr('validated', true);
                        $('#ApplicationForm').attr('action', '/ApplicationForm/Index')
                            .submit();
                        return true;
                    }
                    else if (response != null && !response.success) {
                        console.log('Validation errors detected');
                        var errors = response['errors'];
                        displayValidationErrors(errors);
                        window.scrollTo(0, 0);
                    }
                    return false;
                },
                error: function (response) {
                    $('validationSummary').hide();
                    console.log(response);
                    return false;
                }
            });
        }
    }
    return false;
});
</code>```

The above is using a regular button but I've also tried to define its type as Submit but to no avail.

I know similar questions have been posted in the past but I cannot find one that has actually helped me out to find a resolution to my problem, so please bear with me and do not mark this question as a duplicate unless there is an actual question/answer with an actual resolution to my problem. Much appreciated!

The closest scenario I found to what I'm trying to achieve is can be found from this article on SO: Submit a form from inside an ajax success function that checks the values

I've been trying so many different things at this stage but nothing is working out. I either don't get the Index action to be called after the ValidateForm action, or either one or the other action is called or the only Index action is called or my model gets messed up, and the list goes on.

I'm clearly not doing this correctly or missing something but I'm at a complete stand still for now. I'm hoping that it will be something silly that I've missed and hopefully someone will clarify this for me.

Any help would be greatly appreciated.

答:
Please try it out:

```<code>    $('#btnApply').on('click', function (e) {
    e.preventDefault();
    var form = $( "#AppllicationForm" );
    if (!form.attr('validated')) {
        if (form.valid()) {
            $.ajax({
                type: "POST",
                data: $(this).serialize(),
                url: "/ApplicationForm/ValidateForm",
                dataType: 'json',
                success: function (response) {
                    $('validationSummary').show();
                    if (response != null && response.success) {
                        console.log('No Validation errors detected');
                        form.attr('validated', true);
                        form.submit();
                        return true;
                    }
                    else if (response != null && !response.success) {
                        console.log('Validation errors detected');
                        var errors = response['errors'];
                        displayValidationErrors(errors);
                        window.scrollTo(0, 0);
                    }
                    return false;
                },
                error: function (response) {
                    $('validationSummary').hide();
                    console.log(response);
                    return false;
                }
            });
        }
    }
    return false;
});
</code>```

Your form action attribute will be '/ApplicationForm/Index'. When you click on the button, you make the validation and if everything is OK, then submit the form.

Body:
I have a form in an Asp.net MVC 5 project which has a Submit button. When the Submit button is clicked, I want to do the following:

Perform client=side validation using jQuery on various fields (required fields have been filled, email format is valid, etc...). That part is working fine.

Make an Ajax call that will perform some server side validation by calling an action from the controller and return a JSON response. The response contains a Success property and Errors property which contains a list of errors.

The Success property will return true if no error are found and the Errors property will be null. If errors are found the Success property is returns false and the Errors property contains a list of relevant errors.

I'm calling '\ApplicationForm\Validate' action from my ApplicationForm controller and this part is working fine.

When no errors are found in part 2, I want my form to be submitted as normal and call the '\ApplicationForm\Index' action so that my data can then be added to my database. I cannot get this part to work!!

The Submit button is defined as follows:

    <input type="button" id="btnApply" value="Apply" class="btn btn-primary" />

My JavaScript code is defined as follows:

$('#AppllicationForm').submit(function () {
    if (!$(this).attr('validated')) {
        if ($(this).valid()) {
            $.ajax({
                type: "POST",
                data: $(this).serialize(),
                url: "/ApplicationForm/ValidateForm",
                dataType: 'json',
                success: function (response) {
                    $('validationSummary').show();
                    if (response != null && response.success) {
                        console.log('No Validation errors detected');
                        $('#ApplicationForm').attr('validated', true);
                        $('#ApplicationForm').attr('action', '/ApplicationForm/Index')
                            .submit();
                        return true;
                    }
                    else if (response != null && !response.success) {
                        console.log('Validation errors detected');
                        var errors = response['errors'];
                        displayValidationErrors(errors);
                        window.scrollTo(0, 0);
                    }
                    return false;
                },
                error: function (response) {
                    $('validationSummary').hide();
                    console.log(response);
                    return false;
                }
            });
        }
    }
    return false;
});

The above is using a regular button but I've also tried to define its type as Submit but to no avail.

I know similar questions have been posted in the past but I cannot find one that has actually helped me out to find a resolution to my problem, so please bear with me and do not mark this question as a duplicate unless there is an actual question/answer with an actual resolution to my problem. Much appreciated!

The closest scenario I found to what I'm trying to achieve is can be found from this article on SO: Submit a form from inside an ajax success function that checks the values

I've been trying so many different things at this stage but nothing is working out. I either don't get the Index action to be called after the ValidateForm action, or either one or the other action is called or the only Index action is called or my model gets messed up, and the list goes on.

I'm clearly not doing this correctly or missing something but I'm at a complete stand still for now. I'm hoping that it will be something silly that I've missed and hopefully someone will clarify this for me.

Any help would be greatly appreciated.

Body:
Please try it out:

    $('#btnApply').on('click', function (e) {
    e.preventDefault();
    var form = $( "#AppllicationForm" );
    if (!form.attr('validated')) {
        if (form.valid()) {
            $.ajax({
                type: "POST",
                data: $(this).serialize(),
                url: "/ApplicationForm/ValidateForm",
                dataType: 'json',
                success: function (response) {
                    $('validationSummary').show();
                    if (response != null && response.success) {
                        console.log('No Validation errors detected');
                        form.attr('validated', true);
                        form.submit();
                        return true;
                    }
                    else if (response != null && !response.success) {
                        console.log('Validation errors detected');
                        var errors = response['errors'];
                        displayValidationErrors(errors);
                        window.scrollTo(0, 0);
                    }
                    return false;
                },
                error: function (response) {
                    $('validationSummary').hide();
                    console.log(response);
                    return false;
                }
            });
        }
    }
    return false;
});

Your form action attribute will be '/ApplicationForm/Index'. When you click on the button, you make the validation and if everything is OK, then submit the form.


来源: stackexchange

问:
c# division giving odd result on multiple calls
We have an class responsible for converting internal units to display units. So if our display units are m and internal units are mm it would divide the internal units by a conversionFactor of 1000. The user can add entities into the system at a varying x,y,z co-ordinates. We have an odd occurrence where a user is inputting units at 1000 mm so the display is showing 1m. the input is consistently 1000 mm but every now and again the division of 1000/1000 seems to be throwing up .9999999m instead of 1m. so in our grid we have 1m,1m,1m,1m,0.9999m,1m,1m etc. Sometimes the .9999m never appears some times it is straight away sometimes it is occurs after 20 to 100 inputs. We are investigating if something odd is happening on the input side, but I wondered if anyone else has come across something like this?

I should say we are converting it to a string to display.

答:
Thanks for all your help we have tracked it down to a weird side effect from inputing a different object.

The issue is that if a different object is inserted by any multiple of 3 times the error is triggered e.g. objectA is input 3 times at 1m all okay, then after this objectB is input at 1m 0.9999m appears however if objectA is input 1,2,4 or 5 times there is no problem. 6 times and the problem reappears, 9 times etc. What fun we have.

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
Binding OneWayToSource in C#
I'm currently trying to receive the DateTime from a Xamarin.Forms.TimePicker.
I just want to populate the model which is a DateTime pickerTime variable.
This variable will be populated by whatever is in the TimePicker view.

Therefore I need to do OneWayToSource data binding but I only ever find examples in XAML, where as I'm working in C# file because its an Android custom render of a abstract Xamarin.Forms Page.

Is there any way to OneWayToSource data bind in C#? If not I would try making the Forms View page type of my abstract sub-classed page so I have access to a XAML page and make the TimePicker view as well the data bound object in there that the Custom Renderer Pages inherit with OneWayToSource data binding.

Thanks for your help!

答:
Of course you can. Considering you have already set the BindingContext, this XAML:

```<code><TimePicker x:Name="myTimePicker" Time="{Binding Property, Mode=OneWayToSource}"/>
</code>```

is the same as this in C#:

```<code>TimePicker myTimePicker = new TimePicker();
myTimePicker.SetBinding(TimePicker.TimeProperty, new Binding("Property") { Mode = BindingMode.OneWayToSource });
</code>```

FYI, anything you can do in XAML can be done using C#!

Title: Binding OneWayToSource in C#

Body:
Of course you can. Considering you have already set the BindingContext, this XAML:

<TimePicker x:Name="myTimePicker" Time="{Binding Property, Mode=OneWayToSource}"/>

is the same as this in C#:

TimePicker myTimePicker = new TimePicker();
myTimePicker.SetBinding(TimePicker.TimeProperty, new Binding("Property") { Mode = BindingMode.OneWayToSource });

FYI, anything you can do in XAML can be done using C#!


问:
Optimize code to find the median of values of past 4 to 6 days for each row in a DataFrame
Given a dataframe of timestamp data, I would like to compute the median of certain variable of past 4-6 days.
Median of past 1-3 days can be computed by pd.pandas.DataFrame.rolling, but I couldn't find how to use rolling to compute the median of past 4-6 days.

```<code>import pandas as pd
import numpy as np
import datetime
df = pd.DataFrame()
df['timestamp'] = pd.date_range('1/1/2011', periods=100, freq='6H')
df['timestamp'] = df.timestamp.astype(pd.Timestamp)
np.random.seed(1)
df['var'] = pd.Series(np.random.randn(len(df['timestamp'])))
</code>```

Data looks like this. In my real data, there are gaps in time and maybe more data points in one day.

```<code>              timestamp       var
0   2011-01-01 00:00:00  1.624345
1   2011-01-01 06:00:00 -0.611756
2   2011-01-01 12:00:00 -0.528172
3   2011-01-01 18:00:00 -1.072969
4   2011-01-02 00:00:00  0.865408
5   2011-01-02 06:00:00 -2.301539
6   2011-01-02 12:00:00  1.744812
7   2011-01-02 18:00:00 -0.761207
8   2011-01-03 00:00:00  0.319039
9   2011-01-03 06:00:00 -0.249370
10  2011-01-03 12:00:00  1.462108
</code>```

Desired output:

```<code>              timestamp       var  past4d-6d_var_median
0   2011-01-01 00:00:00  1.624345                   NaN # no data in past 4-6 days
1   2011-01-01 06:00:00 -0.611756                   NaN # no data in past 4-6 days
2   2011-01-01 12:00:00 -0.528172                   NaN # no data in past 4-6 days
3   2011-01-01 18:00:00 -1.072969                   NaN # no data in past 4-6 days
4   2011-01-02 00:00:00  0.865408                   NaN # no data in past 4-6 days
5   2011-01-02 06:00:00 -2.301539                   NaN # no data in past 4-6 days
6   2011-01-02 12:00:00  1.744812                   NaN # no data in past 4-6 days
7   2011-01-02 18:00:00 -0.761207                   NaN # no data in past 4-6 days
8   2011-01-03 00:00:00  0.319039                   NaN # no data in past 4-6 days
9   2011-01-03 06:00:00 -0.249370                   NaN # no data in past 4-6 days
10  2011-01-03 12:00:00  1.462108                   NaN # no data in past 4-6 days
11  2011-01-03 18:00:00 -2.060141                   NaN # no data in past 4-6 days
12  2011-01-04 00:00:00 -0.322417                   NaN # no data in past 4-6 days
13  2011-01-04 06:00:00 -0.384054                   NaN # no data in past 4-6 days
14  2011-01-04 12:00:00  1.133769                   NaN # no data in past 4-6 days
15  2011-01-04 18:00:00 -1.099891                   NaN # no data in past 4-6 days
16  2011-01-05 00:00:00 -0.172428                   NaN # only 4 data in past 4-6 days
17  2011-01-05 06:00:00 -0.877858             -0.528172
18  2011-01-05 12:00:00  0.042214             -0.569964
19  2011-01-05 18:00:00  0.582815             -0.528172
20  2011-01-06 00:00:00 -1.100619             -0.569964
21  2011-01-06 06:00:00  1.144724             -0.528172
22  2011-01-06 12:00:00  0.901591             -0.388771
23  2011-01-06 18:00:00  0.502494             -0.249370
</code>```

My current code:

```<code>def findPastVar2(df, var='var' ,window=3, method='median'):
    # window= # of past days
    for i in xrange(len(df)):
        pastVar2 = df[var].loc[(df['timestamp'] - df['timestamp'].loc[i] < datetime.timedelta(days=-window)) & (df['timestamp'] - df['timestamp'].loc[i] >= datetime.timedelta(days=-window*2))]
        if pastVar2.shape[0]>=5: # At least 5 data points
            if method == 'median':
                df.loc[i,'past{}d-{}d_{}_median'.format(window+1,window*2,var)] = np.median(pastVar2.values)
    return(df)
</code>```

Current speed:

```<code>In [35]: %timeit df2 = findPastVar2(df)
1 loop, best of 3: 821 ms per loop
</code>```

I edited the post so that I can clearly show my expected output of at least 5 data points. I've set the random seed so that everyone should be able to get the same input and show the same output. As far as I know simple rolling and shift does not work for the case of multiple data in the same day.

Body:
Given a dataframe of timestamp data, I would like to compute the median of certain variable of past 4-6 days.
Median of past 1-3 days can be computed by pd.pandas.DataFrame.rolling, but I couldn't find how to use rolling to compute the median of past 4-6 days.

import pandas as pd
import numpy as np
import datetime
df = pd.DataFrame()
df['timestamp'] = pd.date_range('1/1/2011', periods=100, freq='6H')
df['timestamp'] = df.timestamp.astype(pd.Timestamp)
np.random.seed(1)
df['var'] = pd.Series(np.random.randn(len(df['timestamp'])))

Data looks like this. In my real data, there are gaps in time and maybe more data points in one day.

              timestamp       var
0   2011-01-01 00:00:00  1.624345
1   2011-01-01 06:00:00 -0.611756
2   2011-01-01 12:00:00 -0.528172
3   2011-01-01 18:00:00 -1.072969
4   2011-01-02 00:00:00  0.865408
5   2011-01-02 06:00:00 -2.301539
6   2011-01-02 12:00:00  1.744812
7   2011-01-02 18:00:00 -0.761207
8   2011-01-03 00:00:00  0.319039
9   2011-01-03 06:00:00 -0.249370
10  2011-01-03 12:00:00  1.462108

Desired output:

              timestamp       var  past4d-6d_var_median
0   2011-01-01 00:00:00  1.624345                   NaN # no data in past 4-6 days
1   2011-01-01 06:00:00 -0.611756                   NaN # no data in past 4-6 days
2   2011-01-01 12:00:00 -0.528172                   NaN # no data in past 4-6 days
3   2011-01-01 18:00:00 -1.072969                   NaN # no data in past 4-6 days
4   2011-01-02 00:00:00  0.865408                   NaN # no data in past 4-6 days
5   2011-01-02 06:00:00 -2.301539                   NaN # no data in past 4-6 days
6   2011-01-02 12:00:00  1.744812                   NaN # no data in past 4-6 days
7   2011-01-02 18:00:00 -0.761207                   NaN # no data in past 4-6 days
8   2011-01-03 00:00:00  0.319039                   NaN # no data in past 4-6 days
9   2011-01-03 06:00:00 -0.249370                   NaN # no data in past 4-6 days
10  2011-01-03 12:00:00  1.462108                   NaN # no data in past 4-6 days
11  2011-01-03 18:00:00 -2.060141                   NaN # no data in past 4-6 days
12  2011-01-04 00:00:00 -0.322417                   NaN # no data in past 4-6 days
13  2011-01-04 06:00:00 -0.384054                   NaN # no data in past 4-6 days
14  2011-01-04 12:00:00  1.133769                   NaN # no data in past 4-6 days
15  2011-01-04 18:00:00 -1.099891                   NaN # no data in past 4-6 days
16  2011-01-05 00:00:00 -0.172428                   NaN # only 4 data in past 4-6 days
17  2011-01-05 06:00:00 -0.877858             -0.528172
18  2011-01-05 12:00:00  0.042214             -0.569964
19  2011-01-05 18:00:00  0.582815             -0.528172
20  2011-01-06 00:00:00 -1.100619             -0.569964
21  2011-01-06 06:00:00  1.144724             -0.528172
22  2011-01-06 12:00:00  0.901591             -0.388771
23  2011-01-06 18:00:00  0.502494             -0.249370

My current code:

def findPastVar2(df, var='var' ,window=3, method='median'):
    # window= # of past days
    for i in xrange(len(df)):
        pastVar2 = df[var].loc[(df['timestamp'] - df['timestamp'].loc[i] < datetime.timedelta(days=-window)) & (df['timestamp'] - df['timestamp'].loc[i] >= datetime.timedelta(days=-window*2))]
        if pastVar2.shape[0]>=5: # At least 5 data points
            if method == 'median':
                df.loc[i,'past{}d-{}d_{}_median'.format(window+1,window*2,var)] = np.median(pastVar2.values)
    return(df)

Current speed:

In [35]: %timeit df2 = findPastVar2(df)
1 loop, best of 3: 821 ms per loop

I edited the post so that I can clearly show my expected output of at least 5 data points. I've set the random seed so that everyone should be able to get the same input and show the same output. As far as I know simple rolling and shift does not work for the case of multiple data in the same day.

Body:
here we go:

df.set_index('timestamp', inplace = True)
df['var'] =df['var'].rolling('3D', min_periods = 3).median().shift(freq = pd.Timedelta('4d')).shift(-1)

df['var']
Out[55]:
timestamp
2011-01-01 00:00:00         NaN
2011-01-01 06:00:00         NaN
2011-01-01 12:00:00         NaN
2011-01-01 18:00:00         NaN
2011-01-02 00:00:00         NaN
2011-01-02 06:00:00         NaN
2011-01-02 12:00:00         NaN
2011-01-02 18:00:00         NaN
2011-01-03 00:00:00         NaN
2011-01-03 06:00:00         NaN
2011-01-03 12:00:00         NaN
2011-01-03 18:00:00         NaN
2011-01-04 00:00:00         NaN
2011-01-04 06:00:00         NaN
2011-01-04 12:00:00         NaN
2011-01-04 18:00:00         NaN
2011-01-05 00:00:00         NaN
2011-01-05 06:00:00   -0.528172
2011-01-05 12:00:00   -0.569964
2011-01-05 18:00:00   -0.528172
2011-01-06 00:00:00   -0.569964
2011-01-06 06:00:00   -0.528172
2011-01-06 12:00:00   -0.569964
2011-01-06 18:00:00   -0.528172
2011-01-07 00:00:00   -0.388771
2011-01-07 06:00:00   -0.249370
2011-01-07 12:00:00   -0.388771


问:
Error with H20Context running PySparkling with Spark 2.1
I'm getting this error when trying to run a Pysparkling script on an AWS EMR cluster. I can get everything to work when downloading Sparkling water 2.1.8 and running it from a pysparkling shell. However, spark-submit does not seem to work.

Error:

```<code>NameError: name 'H2OContext' is not defined
</code>```

My spark-submit:

```<code>spark-submit --packages ai.h2o:sparkling-water-core_2.11:2.1.7,ai.h2o:sparkling-water-examples_2.11:2.1.7 --conf spark.dynamicAllocation.enabled=false spark.py
</code>```

Python file

```<code>from pysparkling import *

hc = H2OContext.getOrCreate(sc)
</code>```

Also, I've tried actually making a spark context but that just results in the same error, but takes longer.

Bootstrap file:

```<code>#!/usr/bin/env bash

# install conda (conda 4.2 defaults to pythone35)
wget --quiet http://repo.continuum.io/archive/Anaconda3-4.2.0-Linux-x86_64.sh -O ~/anaconda.sh \
    && /bin/bash ~/anaconda.sh -b -p $HOME/conda

echo -e '\nexport PATH=$HOME/conda/bin:$PATH' >> $HOME/.bashrc && source $HOME/.bashrc

# install packages
conda install -y ipython jupyter

# needed for PySparkling
conda install requests
conda install six
conda install future
conda install tabulate

# install pysparkling
pip install h2o
# pip install pysparkling
pip install h2o_pysparkling_2.1
</code>```

More detailed output:

```<code>[hadoop@ip-172-31-32-30 test]$ spark-submit --packages ai.h2o:sparkling-water-core_2.11:2.1.7,ai.h2o:sparkling-water-examples_2.11:2.1.7 --conf spark.dynamicAllocation.enabled=false spark.py
Ivy Default Cache set to: /home/hadoop/.ivy2/cache
The jars for the packages stored in: /home/hadoop/.ivy2/jars
:: loading settings :: url = jar:file:/usr/lib/spark/jars/ivy-2.4.0.jar!/org/apache/ivy/core/settings/ivysettings.xml
ai.h2o#sparkling-water-core_2.11 added as a dependency
ai.h2o#sparkling-water-examples_2.11 added as a dependency
:: resolving dependencies :: org.apache.spark#spark-submit-parent;1.0
        confs: [default]
        found ai.h2o#sparkling-water-core_2.11;2.1.7 in central
        found ai.h2o#h2o-genmodel;3.10.4.7 in central
        found net.sf.opencsv#opencsv;2.3 in central
        found ai.h2o#deepwater-backend-api;1.0.2 in central
        found com.google.guava#guava;19.0 in central
        found ai.h2o#h2o-core;3.10.4.7 in central
        found joda-time#joda-time;2.3 in central
        found gov.nist.math#jama;1.0.3 in central
        found org.javassist#javassist;3.18.2-GA in central
        found org.apache.commons#commons-math3;3.3 in central
        found commons-io#commons-io;2.4 in central
        found ai.h2o#google-analytics-java;1.1.2-H2O-CUSTOM in central
        found org.apache.httpcomponents#httpclient;4.1 in central
        found org.apache.httpcomponents#httpcore;4.1 in central
        found commons-logging#commons-logging;1.1.1 in central
        found commons-codec#commons-codec;1.4 in central
        found org.eclipse.jetty.aggregate#jetty-servlet;8.1.17.v20150415 in central
        found org.eclipse.jetty#jetty-plus;8.1.17.v20150415 in central
        found org.eclipse.jetty.orbit#javax.transaction;1.1.1.v201105210645 in central
        found org.eclipse.jetty#jetty-webapp;8.1.17.v20150415 in central
        found org.eclipse.jetty#jetty-xml;8.1.17.v20150415 in central
        found org.eclipse.jetty#jetty-util;8.1.17.v20150415 in central
        found org.eclipse.jetty#jetty-servlet;8.1.17.v20150415 in central
        found org.eclipse.jetty#jetty-security;8.1.17.v20150415 in central
        found org.eclipse.jetty#jetty-server;8.1.17.v20150415 in central
        found org.eclipse.jetty.orbit#javax.servlet;3.0.0.v201112011016 in central
        found org.eclipse.jetty#jetty-continuation;8.1.17.v20150415 in central
        found org.eclipse.jetty#jetty-http;8.1.17.v20150415 in central
        found org.eclipse.jetty#jetty-io;8.1.17.v20150415 in central
        found org.eclipse.jetty#jetty-jndi;8.1.17.v20150415 in central
        found org.eclipse.jetty.orbit#javax.mail.glassfish;1.4.1.v201005082020 in central
        found org.eclipse.jetty.orbit#javax.activation;1.1.0.v201105071233 in central
        found com.github.rwl#jtransforms;2.4.0 in central
        found ai.h2o#h2o-jaas-pam;3.10.4.7 in central
        found org.kohsuke#libpam4j;1.8 in central
        found net.java.dev.jna#jna;4.0.0 in central
        found log4j#log4j;1.2.15 in central
        found com.google.code.gson#gson;2.3.1 in central
        found commons-lang#commons-lang;2.6 in central
        found ai.h2o#reflections;0.9.11-h2o-custom in central
        found com.google.code.findbugs#jsr305;3.0.0 in central
        found ai.h2o#h2o-algos;3.10.4.7 in central
        found ai.h2o#h2o-web;3.10.4.7 in central
        found ai.h2o#h2o-avro-parser;3.10.4.7 in central
        found ai.h2o#h2o-parquet-parser;3.10.4.7 in central
        found ai.h2o#h2o-orc-parser;3.10.4.7 in central
        found ai.h2o#h2o-scala_2.11;3.10.4.7 in central
        found ai.h2o#h2o-persist-hdfs;3.10.4.7 in central
        found net.java.dev.jets3t#jets3t;0.6.1 in central
        found commons-httpclient#commons-httpclient;3.1 in central
        found ai.h2o#h2o-persist-s3;3.10.4.7 in central
        found com.amazonaws#aws-java-sdk-s3;1.10.47 in central
        found com.amazonaws#aws-java-sdk-kms;1.10.47 in central
        found com.amazonaws#aws-java-sdk-core;1.10.47 in central
        found commons-logging#commons-logging;1.1.3 in central
        found org.apache.httpcomponents#httpclient;4.3.6 in central
        found org.apache.httpcomponents#httpcore;4.3.3 in central
        found commons-codec#commons-codec;1.6 in central
        found joda-time#joda-time;2.8.1 in central
        found ai.h2o#sparkling-water-repl_2.11;2.1.7 in central
        found org.joda#joda-convert;1.7 in central
        found ai.h2o#sparkling-water-examples_2.11;2.1.7 in central
        found ai.h2o#sparkling-water-ml_2.11;2.1.7 in central
downloading https://repo1.maven.org/maven2/ai/h2o/sparkling-water-core_2.11/2.1.7/sparkling-water-core_2.11-2.1.7.jar ...
        [SUCCESSFUL ] ai.h2o#sparkling-water-core_2.11;2.1.7!sparkling-water-core_2.11.jar (56ms)
downloading https://repo1.maven.org/maven2/ai/h2o/sparkling-water-examples_2.11/2.1.7/sparkling-water-examples_2.11-2.1.7.jar ...
        [SUCCESSFUL ] ai.h2o#sparkling-water-examples_2.11;2.1.7!sparkling-water-examples_2.11.jar (15ms)
downloading https://repo1.maven.org/maven2/ai/h2o/h2o-genmodel/3.10.4.7/h2o-genmodel-3.10.4.7.jar ...
        [SUCCESSFUL ] ai.h2o#h2o-genmodel;3.10.4.7!h2o-genmodel.jar (7ms)
downloading https://repo1.maven.org/maven2/ai/h2o/h2o-core/3.10.4.7/h2o-core-3.10.4.7.jar ...
        [SUCCESSFUL ] ai.h2o#h2o-core;3.10.4.7!h2o-core.jar (129ms)
downloading https://repo1.maven.org/maven2/ai/h2o/h2o-algos/3.10.4.7/h2o-algos-3.10.4.7.jar ...
        [SUCCESSFUL ] ai.h2o#h2o-algos;3.10.4.7!h2o-algos.jar (35ms)
downloading https://repo1.maven.org/maven2/ai/h2o/h2o-web/3.10.4.7/h2o-web-3.10.4.7.jar ...
        [SUCCESSFUL ] ai.h2o#h2o-web;3.10.4.7!h2o-web.jar (512ms)
downloading https://repo1.maven.org/maven2/ai/h2o/h2o-scala_2.11/3.10.4.7/h2o-scala_2.11-3.10.4.7.jar ...
        [SUCCESSFUL ] ai.h2o#h2o-scala_2.11;3.10.4.7!h2o-scala_2.11.jar (4ms)
downloading https://repo1.maven.org/maven2/ai/h2o/h2o-persist-hdfs/3.10.4.7/h2o-persist-hdfs-3.10.4.7.jar ...
        [SUCCESSFUL ] ai.h2o#h2o-persist-hdfs;3.10.4.7!h2o-persist-hdfs.jar (2ms)
downloading https://repo1.maven.org/maven2/ai/h2o/h2o-persist-s3/3.10.4.7/h2o-persist-s3-3.10.4.7.jar ...
        [SUCCESSFUL ] ai.h2o#h2o-persist-s3;3.10.4.7!h2o-persist-s3.jar (2ms)
downloading https://repo1.maven.org/maven2/ai/h2o/sparkling-water-repl_2.11/2.1.7/sparkling-water-repl_2.11-2.1.7.jar ...
        [SUCCESSFUL ] ai.h2o#sparkling-water-repl_2.11;2.1.7!sparkling-water-repl_2.11.jar (4ms)
downloading https://repo1.maven.org/maven2/ai/h2o/h2o-jaas-pam/3.10.4.7/h2o-jaas-pam-3.10.4.7.jar ...
        [SUCCESSFUL ] ai.h2o#h2o-jaas-pam;3.10.4.7!h2o-jaas-pam.jar (2ms)
downloading https://repo1.maven.org/maven2/ai/h2o/sparkling-water-ml_2.11/2.1.7/sparkling-water-ml_2.11-2.1.7.jar ...
        [SUCCESSFUL ] ai.h2o#sparkling-water-ml_2.11;2.1.7!sparkling-water-ml_2.11.jar (10ms)
:: resolution report :: resolve 6024ms :: artifacts dl 802ms
        :: modules in use:
        ai.h2o#deepwater-backend-api;1.0.2 from central in [default]
        ai.h2o#google-analytics-java;1.1.2-H2O-CUSTOM from central in [default]
        ai.h2o#h2o-algos;3.10.4.7 from central in [default]
        ai.h2o#h2o-avro-parser;3.10.4.7 from central in [default]
        ai.h2o#h2o-core;3.10.4.7 from central in [default]
        ai.h2o#h2o-genmodel;3.10.4.7 from central in [default]
        ai.h2o#h2o-jaas-pam;3.10.4.7 from central in [default]
        ai.h2o#h2o-orc-parser;3.10.4.7 from central in [default]
        ai.h2o#h2o-parquet-parser;3.10.4.7 from central in [default]
        ai.h2o#h2o-persist-hdfs;3.10.4.7 from central in [default]
        ai.h2o#h2o-persist-s3;3.10.4.7 from central in [default]
        ai.h2o#h2o-scala_2.11;3.10.4.7 from central in [default]
        ai.h2o#h2o-web;3.10.4.7 from central in [default]
        ai.h2o#reflections;0.9.11-h2o-custom from central in [default]
        ai.h2o#sparkling-water-core_2.11;2.1.7 from central in [default]
        ai.h2o#sparkling-water-examples_2.11;2.1.7 from central in [default]
        ai.h2o#sparkling-water-ml_2.11;2.1.7 from central in [default]
        ai.h2o#sparkling-water-repl_2.11;2.1.7 from central in [default]
        com.amazonaws#aws-java-sdk-core;1.10.47 from central in [default]
        com.amazonaws#aws-java-sdk-kms;1.10.47 from central in [default]
        com.amazonaws#aws-java-sdk-s3;1.10.47 from central in [default]
        com.github.rwl#jtransforms;2.4.0 from central in [default]
        com.google.code.findbugs#jsr305;3.0.0 from central in [default]
        com.google.code.gson#gson;2.3.1 from central in [default]
        com.google.guava#guava;19.0 from central in [default]
        commons-codec#commons-codec;1.6 from central in [default]
        commons-httpclient#commons-httpclient;3.1 from central in [default]
        commons-io#commons-io;2.4 from central in [default]
        commons-lang#commons-lang;2.6 from central in [default]
        commons-logging#commons-logging;1.1.3 from central in [default]
        gov.nist.math#jama;1.0.3 from central in [default]
        joda-time#joda-time;2.8.1 from central in [default]
        log4j#log4j;1.2.15 from central in [default]
        net.java.dev.jets3t#jets3t;0.6.1 from central in [default]
        net.java.dev.jna#jna;4.0.0 from central in [default]
        net.sf.opencsv#opencsv;2.3 from central in [default]
        org.apache.commons#commons-math3;3.3 from central in [default]
        org.apache.httpcomponents#httpclient;4.3.6 from central in [default]
        org.apache.httpcomponents#httpcore;4.3.3 from central in [default]
        org.eclipse.jetty#jetty-continuation;8.1.17.v20150415 from central in [default]
        org.eclipse.jetty#jetty-http;8.1.17.v20150415 from central in [default]
        org.eclipse.jetty#jetty-io;8.1.17.v20150415 from central in [default]
        org.eclipse.jetty#jetty-jndi;8.1.17.v20150415 from central in [default]
        org.eclipse.jetty#jetty-plus;8.1.17.v20150415 from central in [default]
        org.eclipse.jetty#jetty-security;8.1.17.v20150415 from central in [default]
        org.eclipse.jetty#jetty-server;8.1.17.v20150415 from central in [default]
        org.eclipse.jetty#jetty-servlet;8.1.17.v20150415 from central in [default]
        org.eclipse.jetty#jetty-util;8.1.17.v20150415 from central in [default]
        org.eclipse.jetty#jetty-webapp;8.1.17.v20150415 from central in [default]
        org.eclipse.jetty#jetty-xml;8.1.17.v20150415 from central in [default]
        org.eclipse.jetty.aggregate#jetty-servlet;8.1.17.v20150415 from central in [default]
        org.eclipse.jetty.orbit#javax.activation;1.1.0.v201105071233 from central in [default]
        org.eclipse.jetty.orbit#javax.mail.glassfish;1.4.1.v201005082020 from central in [default]
        org.eclipse.jetty.orbit#javax.servlet;3.0.0.v201112011016 from central in [default]
        org.eclipse.jetty.orbit#javax.transaction;1.1.1.v201105210645 from central in [default]
        org.javassist#javassist;3.18.2-GA from central in [default]
        org.joda#joda-convert;1.7 from central in [default]
        org.kohsuke#libpam4j;1.8 from central in [default]
        :: evicted modules:
        joda-time#joda-time;2.3 by [joda-time#joda-time;2.8.1] in [default]
        org.apache.httpcomponents#httpclient;4.1 by [org.apache.httpcomponents#httpclient;4.3.6] in [default]
        org.apache.httpcomponents#httpcore;4.1 by [org.apache.httpcomponents#httpcore;4.3.3] in [default]
        commons-logging#commons-logging;1.1.1 by [commons-logging#commons-logging;1.1.3] in [default]
        commons-codec#commons-codec;1.4 by [commons-codec#commons-codec;1.6] in [default]
        com.google.guava#guava;16.0.1 by [com.google.guava#guava;19.0] in [default]
        com.google.guava#guava;18.0 by [com.google.guava#guava;19.0] in [default]
        commons-codec#commons-codec;1.3 by [commons-codec#commons-codec;1.4] in [default]
        commons-logging#commons-logging;1.0.4 by [commons-logging#commons-logging;1.1.1] in [default]
        commons-codec#commons-codec;1.2 by [commons-codec#commons-codec;1.4] in [default]
        ---------------------------------------------------------------------
        |                  |            modules            ||   artifacts   |
        |       conf       | number| search|dwnlded|evicted|| number|dwnlded|
        ---------------------------------------------------------------------
        |      default     |   68  |   15  |   15  |   10  ||   55  |   12  |
        ---------------------------------------------------------------------
:: retrieving :: org.apache.spark#spark-submit-parent
        confs: [default]
        12 artifacts copied, 43 already retrieved (23416kB/63ms)
Traceback (most recent call last):
  File "/home/hadoop/scripts/test/spark.py", line 3, in <module>
    hc = H2OContext.getOrCreate(sc)
NameError: name 'H2OContext' is not defined
</code>```

答:
You do not need to attach Sparkling Water packages (option --packages), but you need to provide pysparkling Python package (it contains all necessary binary dependencies internally).

The best way is to download binary distribution of Sparkling Water from http://h2o.ai/download and use bin/pysparkling script or use spark directly:

```<code>$SPARK_HOME/bin/pyspark --py-files h2o_pysparkling_2.1-2.1.8.zip
</code>```

Body:
I'm getting this error when trying to run a Pysparkling script on an AWS EMR cluster. I can get everything to work when downloading Sparkling water 2.1.8 and running it from a pysparkling shell. However, spark-submit does not seem to work.

Error:

NameError: name 'H2OContext' is not defined

My spark-submit:

spark-submit --packages ai.h2o:sparkling-water-core_2.11:2.1.7,ai.h2o:sparkling-water-examples_2.11:2.1.7 --conf spark.dynamicAllocation.enabled=false spark.py

Python file

from pysparkling import *

hc = H2OContext.getOrCreate(sc)

Also, I've tried actually making a spark context but that just results in the same error, but takes longer.

Bootstrap file:

#!/usr/bin/env bash

# install conda (conda 4.2 defaults to pythone35)
wget --quiet http://repo.continuum.io/archive/Anaconda3-4.2.0-Linux-x86_64.sh -O ~/anaconda.sh \
    && /bin/bash ~/anaconda.sh -b -p $HOME/conda

echo -e '\nexport PATH=$HOME/conda/bin:$PATH' >> $HOME/.bashrc && source $HOME/.bashrc

# install packages
conda install -y ipython jupyter

# needed for PySparkling
conda install requests
conda install six
conda install future
conda install tabulate

# install pysparkling
pip install h2o
# pip install pysparkling
pip install h2o_pysparkling_2.1

More detailed output:

[hadoop@ip-172-31-32-30 test]$ spark-submit --packages ai.h2o:sparkling-water-core_2.11:2.1.7,ai.h2o:sparkling-water-examples_2.11:2.1.7 --conf spark.dynamicAllocation.enabled=false spark.py
Ivy Default Cache set to: /home/hadoop/.ivy2/cache
The jars for the packages stored in: /home/hadoop/.ivy2/jars
:: loading settings :: url = jar:file:/usr/lib/spark/jars/ivy-2.4.0.jar!/org/apache/ivy/core/settings/ivysettings.xml
ai.h2o#sparkling-water-core_2.11 added as a dependency
ai.h2o#sparkling-water-examples_2.11 added as a dependency
:: resolving dependencies :: org.apache.spark#spark-submit-parent;1.0
        confs: [default]
        found ai.h2o#sparkling-water-core_2.11;2.1.7 in central
        found ai.h2o#h2o-genmodel;3.10.4.7 in central
        found net.sf.opencsv#opencsv;2.3 in central
        found ai.h2o#deepwater-backend-api;1.0.2 in central
        found com.google.guava#guava;19.0 in central
        found ai.h2o#h2o-core;3.10.4.7 in central
        found joda-time#joda-time;2.3 in central
        found gov.nist.math#jama;1.0.3 in central
        found org.javassist#javassist;3.18.2-GA in central
        found org.apache.commons#commons-math3;3.3 in central
        found commons-io#commons-io;2.4 in central
        found ai.h2o#google-analytics-java;1.1.2-H2O-CUSTOM in central
        found org.apache.httpcomponents#httpclient;4.1 in central
        found org.apache.httpcomponents#httpcore;4.1 in central
        found commons-logging#commons-logging;1.1.1 in central
        found commons-codec#commons-codec;1.4 in central
        found org.eclipse.jetty.aggregate#jetty-servlet;8.1.17.v20150415 in central
        found org.eclipse.jetty#jetty-plus;8.1.17.v20150415 in central
        found org.eclipse.jetty.orbit#javax.transaction;1.1.1.v201105210645 in central
        found org.eclipse.jetty#jetty-webapp;8.1.17.v20150415 in central
        found org.eclipse.jetty#jetty-xml;8.1.17.v20150415 in central
        found org.eclipse.jetty#jetty-util;8.1.17.v20150415 in central
        found org.eclipse.jetty#jetty-servlet;8.1.17.v20150415 in central
        found org.eclipse.jetty#jetty-security;8.1.17.v20150415 in central
        found org.eclipse.jetty#jetty-server;8.1.17.v20150415 in central
        found org.eclipse.jetty.orbit#javax.servlet;3.0.0.v201112011016 in central
        found org.eclipse.jetty#jetty-continuation;8.1.17.v20150415 in central
        found org.eclipse.jetty#jetty-http;8.1.17.v20150415 in central
        found org.eclipse.jetty#jetty-io;8.1.17.v20150415 in central
        found org.eclipse.jetty#jetty-jndi;8.1.17.v20150415 in central
        found org.eclipse.jetty.orbit#javax.mail.glassfish;1.4.1.v201005082020 in central
        found org.eclipse.jetty.orbit#javax.activation;1.1.0.v201105071233 in central
        found com.github.rwl#jtransforms;2.4.0 in central
        found ai.h2o#h2o-jaas-pam;3.10.4.7 in central
        found org.kohsuke#libpam4j;1.8 in central
        found net.java.dev.jna#jna;4.0.0 in central
        found log4j#log4j;1.2.15 in central
        found com.google.code.gson#gson;2.3.1 in central
        found commons-lang#commons-lang;2.6 in central
        found ai.h2o#reflections;0.9.11-h2o-custom in central
        found com.google.code.findbugs#jsr305;3.0.0 in central
        found ai.h2o#h2o-algos;3.10.4.7 in central
        found ai.h2o#h2o-web;3.10.4.7 in central
        found ai.h2o#h2o-avro-parser;3.10.4.7 in central
        found ai.h2o#h2o-parquet-parser;3.10.4.7 in central
        found ai.h2o#h2o-orc-parser;3.10.4.7 in central
        found ai.h2o#h2o-scala_2.11;3.10.4.7 in central
        found ai.h2o#h2o-persist-hdfs;3.10.4.7 in central
        found net.java.dev.jets3t#jets3t;0.6.1 in central
        found commons-httpclient#commons-httpclient;3.1 in central
        found ai.h2o#h2o-persist-s3;3.10.4.7 in central
        found com.amazonaws#aws-java-sdk-s3;1.10.47 in central
        found com.amazonaws#aws-java-sdk-kms;1.10.47 in central
        found com.amazonaws#aws-java-sdk-core;1.10.47 in central
        found commons-logging#commons-logging;1.1.3 in central
        found org.apache.httpcomponents#httpclient;4.3.6 in central
        found org.apache.httpcomponents#httpcore;4.3.3 in central
        found commons-codec#commons-codec;1.6 in central
        found joda-time#joda-time;2.8.1 in central
        found ai.h2o#sparkling-water-repl_2.11;2.1.7 in central
        found org.joda#joda-convert;1.7 in central
        found ai.h2o#sparkling-water-examples_2.11;2.1.7 in central
        found ai.h2o#sparkling-water-ml_2.11;2.1.7 in central
downloading https://repo1.maven.org/maven2/ai/h2o/sparkling-water-core_2.11/2.1.7/sparkling-water-core_2.11-2.1.7.jar ...
        [SUCCESSFUL ] ai.h2o#sparkling-water-core_2.11;2.1.7!sparkling-water-core_2.11.jar (56ms)
downloading https://repo1.maven.org/maven2/ai/h2o/sparkling-water-examples_2.11/2.1.7/sparkling-water-examples_2.11-2.1.7.jar ...
        [SUCCESSFUL ] ai.h2o#sparkling-water-examples_2.11;2.1.7!sparkling-water-examples_2.11.jar (15ms)
downloading https://repo1.maven.org/maven2/ai/h2o/h2o-genmodel/3.10.4.7/h2o-genmodel-3.10.4.7.jar ...
        [SUCCESSFUL ] ai.h2o#h2o-genmodel;3.10.4.7!h2o-genmodel.jar (7ms)
downloading https://repo1.maven.org/maven2/ai/h2o/h2o-core/3.10.4.7/h2o-core-3.10.4.7.jar ...
        [SUCCESSFUL ] ai.h2o#h2o-core;3.10.4.7!h2o-core.jar (129ms)
downloading https://repo1.maven.org/maven2/ai/h2o/h2o-algos/3.10.4.7/h2o-algos-3.10.4.7.jar ...
        [SUCCESSFUL ] ai.h2o#h2o-algos;3.10.4.7!h2o-algos.jar (35ms)
downloading https://repo1.maven.org/maven2/ai/h2o/h2o-web/3.10.4.7/h2o-web-3.10.4.7.jar ...
        [SUCCESSFUL ] ai.h2o#h2o-web;3.10.4.7!h2o-web.jar (512ms)
downloading https://repo1.maven.org/maven2/ai/h2o/h2o-scala_2.11/3.10.4.7/h2o-scala_2.11-3.10.4.7.jar ...
        [SUCCESSFUL ] ai.h2o#h2o-scala_2.11;3.10.4.7!h2o-scala_2.11.jar (4ms)
downloading https://repo1.maven.org/maven2/ai/h2o/h2o-persist-hdfs/3.10.4.7/h2o-persist-hdfs-3.10.4.7.jar ...
        [SUCCESSFUL ] ai.h2o#h2o-persist-hdfs;3.10.4.7!h2o-persist-hdfs.jar (2ms)
downloading https://repo1.maven.org/maven2/ai/h2o/h2o-persist-s3/3.10.4.7/h2o-persist-s3-3.10.4.7.jar ...
        [SUCCESSFUL ] ai.h2o#h2o-persist-s3;3.10.4.7!h2o-persist-s3.jar (2ms)
downloading https://repo1.maven.org/maven2/ai/h2o/sparkling-water-repl_2.11/2.1.7/sparkling-water-repl_2.11-2.1.7.jar ...
        [SUCCESSFUL ] ai.h2o#sparkling-water-repl_2.11;2.1.7!sparkling-water-repl_2.11.jar (4ms)
downloading https://repo1.maven.org/maven2/ai/h2o/h2o-jaas-pam/3.10.4.7/h2o-jaas-pam-3.10.4.7.jar ...
        [SUCCESSFUL ] ai.h2o#h2o-jaas-pam;3.10.4.7!h2o-jaas-pam.jar (2ms)
downloading https://repo1.maven.org/maven2/ai/h2o/sparkling-water-ml_2.11/2.1.7/sparkling-water-ml_2.11-2.1.7.jar ...
        [SUCCESSFUL ] ai.h2o#sparkling-water-ml_2.11;2.1.7!sparkling-water-ml_2.11.jar (10ms)
:: resolution report :: resolve 6024ms :: artifacts dl 802ms
        :: modules in use:
        ai.h2o#deepwater-backend-api;1.0.2 from central in [default]
        ai.h2o#google-analytics-java;1.1.2-H2O-CUSTOM from central in [default]
        ai.h2o#h2o-algos;3.10.4.7 from central in [default]
        ai.h2o#h2o-avro-parser;3.10.4.7 from central in [default]
        ai.h2o#h2o-core;3.10.4.7 from central in [default]
        ai.h2o#h2o-genmodel;3.10.4.7 from central in [default]
        ai.h2o#h2o-jaas-pam;3.10.4.7 from central in [default]
        ai.h2o#h2o-orc-parser;3.10.4.7 from central in [default]
        ai.h2o#h2o-parquet-parser;3.10.4.7 from central in [default]
        ai.h2o#h2o-persist-hdfs;3.10.4.7 from central in [default]
        ai.h2o#h2o-persist-s3;3.10.4.7 from central in [default]
        ai.h2o#h2o-scala_2.11;3.10.4.7 from central in [default]
        ai.h2o#h2o-web;3.10.4.7 from central in [default]
        ai.h2o#reflections;0.9.11-h2o-custom from central in [default]
        ai.h2o#sparkling-water-core_2.11;2.1.7 from central in [default]
        ai.h2o#sparkling-water-examples_2.11;2.1.7 from central in [default]
        ai.h2o#sparkling-water-ml_2.11;2.1.7 from central in [default]
        ai.h2o#sparkling-water-repl_2.11;2.1.7 from central in [default]
        com.amazonaws#aws-java-sdk-core;1.10.47 from central in [default]
        com.amazonaws#aws-java-sdk-kms;1.10.47 from central in [default]
        com.amazonaws#aws-java-sdk-s3;1.10.47 from central in [default]
        com.github.rwl#jtransforms;2.4.0 from central in [default]
        com.google.code.findbugs#jsr305;3.0.0 from central in [default]
        com.google.code.gson#gson;2.3.1 from central in [default]
        com.google.guava#guava;19.0 from central in [default]
        commons-codec#commons-codec;1.6 from central in [default]
        commons-httpclient#commons-httpclient;3.1 from central in [default]
        commons-io#commons-io;2.4 from central in [default]
        commons-lang#commons-lang;2.6 from central in [default]
        commons-logging#commons-logging;1.1.3 from central in [default]
        gov.nist.math#jama;1.0.3 from central in [default]
        joda-time#joda-time;2.8.1 from central in [default]
        log4j#log4j;1.2.15 from central in [default]
        net.java.dev.jets3t#jets3t;0.6.1 from central in [default]
        net.java.dev.jna#jna;4.0.0 from central in [default]
        net.sf.opencsv#opencsv;2.3 from central in [default]
        org.apache.commons#commons-math3;3.3 from central in [default]
        org.apache.httpcomponents#httpclient;4.3.6 from central in [default]
        org.apache.httpcomponents#httpcore;4.3.3 from central in [default]
        org.eclipse.jetty#jetty-continuation;8.1.17.v20150415 from central in [default]
        org.eclipse.jetty#jetty-http;8.1.17.v20150415 from central in [default]
        org.eclipse.jetty#jetty-io;8.1.17.v20150415 from central in [default]
        org.eclipse.jetty#jetty-jndi;8.1.17.v20150415 from central in [default]
        org.eclipse.jetty#jetty-plus;8.1.17.v20150415 from central in [default]
        org.eclipse.jetty#jetty-security;8.1.17.v20150415 from central in [default]
        org.eclipse.jetty#jetty-server;8.1.17.v20150415 from central in [default]
        org.eclipse.jetty#jetty-servlet;8.1.17.v20150415 from central in [default]
        org.eclipse.jetty#jetty-util;8.1.17.v20150415 from central in [default]
        org.eclipse.jetty#jetty-webapp;8.1.17.v20150415 from central in [default]
        org.eclipse.jetty#jetty-xml;8.1.17.v20150415 from central in [default]
        org.eclipse.jetty.aggregate#jetty-servlet;8.1.17.v20150415 from central in [default]
        org.eclipse.jetty.orbit#javax.activation;1.1.0.v201105071233 from central in [default]
        org.eclipse.jetty.orbit#javax.mail.glassfish;1.4.1.v201005082020 from central in [default]
        org.eclipse.jetty.orbit#javax.servlet;3.0.0.v201112011016 from central in [default]
        org.eclipse.jetty.orbit#javax.transaction;1.1.1.v201105210645 from central in [default]
        org.javassist#javassist;3.18.2-GA from central in [default]
        org.joda#joda-convert;1.7 from central in [default]
        org.kohsuke#libpam4j;1.8 from central in [default]
        :: evicted modules:
        joda-time#joda-time;2.3 by [joda-time#joda-time;2.8.1] in [default]
        org.apache.httpcomponents#httpclient;4.1 by [org.apache.httpcomponents#httpclient;4.3.6] in [default]
        org.apache.httpcomponents#httpcore;4.1 by [org.apache.httpcomponents#httpcore;4.3.3] in [default]
        commons-logging#commons-logging;1.1.1 by [commons-logging#commons-logging;1.1.3] in [default]
        commons-codec#commons-codec;1.4 by [commons-codec#commons-codec;1.6] in [default]
        com.google.guava#guava;16.0.1 by [com.google.guava#guava;19.0] in [default]
        com.google.guava#guava;18.0 by [com.google.guava#guava;19.0] in [default]
        commons-codec#commons-codec;1.3 by [commons-codec#commons-codec;1.4] in [default]
        commons-logging#commons-logging;1.0.4 by [commons-logging#commons-logging;1.1.1] in [default]
        commons-codec#commons-codec;1.2 by [commons-codec#commons-codec;1.4] in [default]
        ---------------------------------------------------------------------
        |                  |            modules            ||   artifacts   |
        |       conf       | number| search|dwnlded|evicted|| number|dwnlded|
        ---------------------------------------------------------------------
        |      default     |   68  |   15  |   15  |   10  ||   55  |   12  |
        ---------------------------------------------------------------------
:: retrieving :: org.apache.spark#spark-submit-parent
        confs: [default]
        12 artifacts copied, 43 already retrieved (23416kB/63ms)
Traceback (most recent call last):
  File "/home/hadoop/scripts/test/spark.py", line 3, in <module>
    hc = H2OContext.getOrCreate(sc)
NameError: name 'H2OContext' is not defined

Body:
You do not need to attach Sparkling Water packages (option --packages), but you need to provide pysparkling Python package (it contains all necessary binary dependencies internally).

The best way is to download binary distribution of Sparkling Water from http://h2o.ai/download and use bin/pysparkling script or use spark directly:

$SPARK_HOME/bin/pyspark --py-files h2o_pysparkling_2.1-2.1.8.zip


问:
DB2 SQL Error: SQLCODE=-204, SQLSTATE=42704, SQLERRMC=DB2ADMIN.STAFF, DRIVER=4.22.29
I have database DB2 SAMPLE in server 10.74.44.65:51020
I'm trying connect to staff table in database but i got an exception.
I use db2jcc4 of IBM.

```<code>Connection successfully
Test 1
com.ibm.db2.jcc.am.SqlSyntaxErrorException: DB2 SQL Error: SQLCODE=-204, SQLSTATE=42704, SQLERRMC=DB2ADMIN.STAFF, DRIVER=4.22.29
    at com.ibm.db2.jcc.am.ld.a(ld.java:810)
    at com.ibm.db2.jcc.am.ld.a(ld.java:66)
    at com.ibm.db2.jcc.am.ld.a(ld.java:140)
    at com.ibm.db2.jcc.am.up.c(up.java:2796)
    at com.ibm.db2.jcc.am.up.d(up.java:2784)
    at com.ibm.db2.jcc.am.up.a(up.java:2212)
    at com.ibm.db2.jcc.t4.bb.i(bb.java:148)
    at com.ibm.db2.jcc.t4.bb.b(bb.java:41)
    at com.ibm.db2.jcc.t4.p.a(p.java:32)
    at com.ibm.db2.jcc.t4.vb.i(vb.java:145)
    at com.ibm.db2.jcc.am.up.lb(up.java:2181)
    at com.ibm.db2.jcc.am.up.a(up.java:3300)
    at com.ibm.db2.jcc.am.up.a(up.java:717)
    at com.ibm.db2.jcc.am.up.executeQuery(up.java:696)
    at Main.main(Main.java:24)
</code>```

My Java Code. 10.74.44.65 is location ip of server .
Database connected but i cannot execute sql query.

```<code>import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Main {
    public static void main(String[] argv) {
        try {
            Class.forName("com.ibm.db2.jcc.DB2Driver");
        }
        catch (ClassNotFoundException e) {
            e.printStackTrace();
            return;
        }
        Connection conn;
        Statement  stmt;
        ResultSet rs;
        try {
            conn = DriverManager.getConnection("jdbc:db2://10.74.44.65:51020/SAMPLE","db2admin","Us3admin");
            System.out.println("Connection successfully");
            stmt=conn.createStatement();
            System.out.println("Test 1");
            rs=stmt.executeQuery("select * from staff");
            System.out.println("Test 2");
            while (rs.next()) {
                System.out.println("Employee number = " + rs.getString(1));
              }
        } catch (SQLException e) {
            e.printStackTrace();
            return;
        }
    }

}
</code>```

答:
"SQLCODE=-204, SQLSTATE=42704" is a DB2 error code indicating 'object does not exist'

(source: http://www-01.ibm.com/support/docview.wss?uid=swg21613531).

SQLERRMC=DB2ADMIN.STAFF then means that table STAFF does not exist in fro user DB2ADMIN, or the user is not authorized for that table.

Body:
I have database DB2 SAMPLE in server 10.74.44.65:51020
I'm trying connect to staff table in database but i got an exception.
I use db2jcc4 of IBM.

Connection successfully
Test 1
com.ibm.db2.jcc.am.SqlSyntaxErrorException: DB2 SQL Error: SQLCODE=-204, SQLSTATE=42704, SQLERRMC=DB2ADMIN.STAFF, DRIVER=4.22.29
    at com.ibm.db2.jcc.am.ld.a(ld.java:810)
    at com.ibm.db2.jcc.am.ld.a(ld.java:66)
    at com.ibm.db2.jcc.am.ld.a(ld.java:140)
    at com.ibm.db2.jcc.am.up.c(up.java:2796)
    at com.ibm.db2.jcc.am.up.d(up.java:2784)
    at com.ibm.db2.jcc.am.up.a(up.java:2212)
    at com.ibm.db2.jcc.t4.bb.i(bb.java:148)
    at com.ibm.db2.jcc.t4.bb.b(bb.java:41)
    at com.ibm.db2.jcc.t4.p.a(p.java:32)
    at com.ibm.db2.jcc.t4.vb.i(vb.java:145)
    at com.ibm.db2.jcc.am.up.lb(up.java:2181)
    at com.ibm.db2.jcc.am.up.a(up.java:3300)
    at com.ibm.db2.jcc.am.up.a(up.java:717)
    at com.ibm.db2.jcc.am.up.executeQuery(up.java:696)
    at Main.main(Main.java:24)

My Java Code. 10.74.44.65 is location ip of server .
Database connected but i cannot execute sql query.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Main {
    public static void main(String[] argv) {
        try {
            Class.forName("com.ibm.db2.jcc.DB2Driver");
        }
        catch (ClassNotFoundException e) {
            e.printStackTrace();
            return;
        }
        Connection conn;
        Statement  stmt;
        ResultSet rs;
        try {
            conn = DriverManager.getConnection("jdbc:db2://10.74.44.65:51020/SAMPLE","db2admin","Us3admin");
            System.out.println("Connection successfully");
            stmt=conn.createStatement();
            System.out.println("Test 1");
            rs=stmt.executeQuery("select * from staff");
            System.out.println("Test 2");
            while (rs.next()) {
                System.out.println("Employee number = " + rs.getString(1));
              }
        } catch (SQLException e) {
            e.printStackTrace();
            return;
        }
    }

}


问:
Could not find phantomjs at the specified path
I'm trying to get started with Mermaid CLI but when I try to run it against my source file it says it can't find phantomjs.  (I'm running Win 7 64.)

```<code>C:\Users\Chris\Documents>mermaid test.mermaid

You had errors in your syntax. Use --help for further information.
Could not find phantomjs at the specified path.
</code>```

However phantomjs is in my path and I have no problems running it from the command prompt.

```<code>C:\Users\Chris\Documents>phantomjs
phantomjs>
</code>```

I also tried putting the phantomjs path in directly.  This didn't help.

```<code>C:\Users\Chris\Documents>mermaid -e "C:\Users\Chris\AppData\Roaming\npm" test.mermaid

You had errors in your syntax. Use --help for further information.
Could not find phantomjs at the specified path.
</code>```

Curiously, if I ask for verbose feedback it also tells me it needs a source file

```<code>C:\Users\Chris\Documents>mermaid -v test.mermaid

You had errors in your syntax. Use --help for further information.
You must specify at least one source file.
Could not find phantomjs at the specified path.
</code>```

So, I'm wondering if there is something wrong with my source.  Which, I had just copied from the readme.  The source file looks like:

```<code>A[Hard edge] -->|Link text| B(Round edge)
B --> C{Decision}
C -->|One| D[Result one]
C -->|Two| E[Result two]
</code>```

Any thoughts would be much appreciated.

答:
I solve this problem.
I noticed that， if you install phantomjs by this npm -g install phantomjs, actually it is wrong, and I don't know why.

```<code>phantomjs --help
internal/child_process.js:294
var err = this._handle.spawn(options);
                     ^

TypeError: Bad argument
at ChildProcess.spawn (internal/child_process.js:294:26)
at exports.spawn (child_process.js:386:9)
at Object.<anonymous> (/usr/local/lib/node_modules/phantomjs-prebuilt/bin/phantomjs:22:10)
at Module._compile (module.js:571:32)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.runMain (module.js:605:10)
at run (bootstrap_node.js:425:7)
</code>```

So I download from this,

and npm remove mermaid

and npm install -g mermaid, done.

finally :

```<code>mermaid

You had errors in your syntax. Use --help for further information.
You must specify at least one source file.
</code>```

Body:
I'm trying to get started with Mermaid CLI but when I try to run it against my source file it says it can't find phantomjs.  (I'm running Win 7 64.)

C:\Users\Chris\Documents>mermaid test.mermaid

You had errors in your syntax. Use --help for further information.
Could not find phantomjs at the specified path.

However phantomjs is in my path and I have no problems running it from the command prompt.

C:\Users\Chris\Documents>phantomjs
phantomjs>

I also tried putting the phantomjs path in directly.  This didn't help.

C:\Users\Chris\Documents>mermaid -e "C:\Users\Chris\AppData\Roaming\npm" test.mermaid

You had errors in your syntax. Use --help for further information.
Could not find phantomjs at the specified path.

Curiously, if I ask for verbose feedback it also tells me it needs a source file

C:\Users\Chris\Documents>mermaid -v test.mermaid

You had errors in your syntax. Use --help for further information.
You must specify at least one source file.
Could not find phantomjs at the specified path.

So, I'm wondering if there is something wrong with my source.  Which, I had just copied from the readme.  The source file looks like:

A[Hard edge] -->|Link text| B(Round edge)
B --> C{Decision}
C -->|One| D[Result one]
C -->|Two| E[Result two]

Any thoughts would be much appreciated.

Body:
I solve this problem.
I noticed that， if you install phantomjs by this npm -g install phantomjs, actually it is wrong, and I don't know why.

phantomjs --help
internal/child_process.js:294
var err = this._handle.spawn(options);
                     ^

TypeError: Bad argument
at ChildProcess.spawn (internal/child_process.js:294:26)
at exports.spawn (child_process.js:386:9)
at Object.<anonymous> (/usr/local/lib/node_modules/phantomjs-prebuilt/bin/phantomjs:22:10)
at Module._compile (module.js:571:32)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.runMain (module.js:605:10)
at run (bootstrap_node.js:425:7)

So I download from this,

and npm remove mermaid

and npm install -g mermaid, done.

finally :

mermaid

You had errors in your syntax. Use --help for further information.
You must specify at least one source file.


问:
How to get user's non-command answer in PHP Telegram Bot?
I am writing a new Bot for Telegram for the first time using PHP Telegram Bot.

Imagine I want to show What is your name? for /start command and wait for user's answer, wait for user's answer and then show Hello USER_NAME to him.

I could implement /start commands. But how can I get user's reply that is not in form of /command? Actually I need a listener to a non-command message.

Is there anyone who can help me?

答:
Mohammad Jan,

You should do it yourself. I suggest you to store the chats in a database table and then store the next command in a column for each chat.

Lets say after /start you're looking for the name of user so you will store /name into the next_command column and whenever you receive a normal message without any /command, then you can check the next_command column and consider the message received as an answer to "What's your name?" question.

You can continue this process to get the full data from the user. For example after getting the name you can ask "How old are you?" and change next_command to /old and then consider the next message as an answer for the previous question.

BTW, It's just a suggestion. You should be able to find the way that is suitable for you. But what is obvious, you should do it yourself since telegram only provide messages to your bot and it's your bot that manage them.

Hope it helps.


问:
UIDynamicAnimator + custom UICollectionViewLayout resulting in perpetual circular motion
I've been replicating the 2013 WWDC Session 217 "Exploring Scroll Views on iOS 7". I'm using Xcode 7 beta 2 and my project is iOS 9 only.

I’m trying to use a UIDynamicAnimator with my UICollectionViewLayout in a way similar to the one presented in session 217 to imitate Messages.app feel. My UICollectionViewLayout is a custom one and for some reason my cells seem to bounce in circular motion in my project.

This is my custom layout code.

```<code>// Didn't write this code myself, but should be pretty simple to follow. @Goles

#import "VVSpringCollectionViewFlowLayout.h"

@interface VVSpringCollectionViewFlowLayout()
@property (nonatomic, strong) UIDynamicAnimator *animator;
@end

@implementation VVSpringCollectionViewFlowLayout

-(id)init {
    if (self = [super init]) {
        _springDamping = 0.5;
        _springFrequency = 0.8;
        _resistanceFactor = 500;
    }
    return self;
}

- (id)initWithCoder:(nonnull NSCoder *)aDecoder {
  self = [super initWithCoder:aDecoder];
  if (self) {
        _springDamping = 0.5;
        _springFrequency = 0.8;
        _resistanceFactor = 500;
  }
  return self;
}

-(void)prepareLayout {
    [super prepareLayout];

    if (!_animator) {
        _animator = [[UIDynamicAnimator alloc] initWithCollectionViewLayout:self];
        CGSize contentSize = [self collectionViewContentSize];
        NSArray *items = [super layoutAttributesForElementsInRect:CGRectMake(0, 0, contentSize.width, contentSize.height)];

        for (UICollectionViewLayoutAttributes *item in items) {
            UIAttachmentBehavior *spring = [[UIAttachmentBehavior alloc] initWithItem:item attachedToAnchor:item.center];

            spring.length = 0;
            spring.damping = self.springDamping;
            spring.frequency = self.springFrequency;

            [_animator addBehavior:spring];
        }
    }
}

-(NSArray *)layoutAttributesForElementsInRect:(CGRect)rect {
    return [_animator itemsInRect:rect];
}

- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath {
    return [_animator layoutAttributesForCellAtIndexPath:indexPath];
}

-(BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds {
    UIScrollView *scrollView = self.collectionView;
    CGFloat scrollDelta = newBounds.origin.y - scrollView.bounds.origin.y;
    CGPoint touchLocation = [scrollView.panGestureRecognizer locationInView:scrollView];

    for (UIAttachmentBehavior *spring in _animator.behaviors) {
       CGPoint anchorPoint = spring.anchorPoint;
       CGFloat distanceFromTouch = fabs(touchLocation.y - anchorPoint.y);
       CGFloat scrollResistance = distanceFromTouch / self.resistanceFactor;

       id<UIDynamicItem> item = [spring.items firstObject];
       CGPoint center = item.center;

       if (scrollDelta > 0) {
            center.y += MIN(scrollDelta, scrollDelta * scrollResistance);
       }

       item.center = center;
       [_animator updateItemUsingCurrentState:item];
    }
    return NO;
}

@end
</code>```

What could be going on here that's causing this circular motion? I'm only changing the Y axis property of my UIAttachmentAttributes center.

```<code>center.y += MIN(scrollDelta, scrollDelta * scrollResistance);
</code>```

What am I missing here? (tried this exact layout in other project and seems to work).

EDIT:

I uploaded a sample project(removed), the Custom Collection View Layout Class is called VVSpringCollectionViewFlowLayout.m, haven't had much time to look into this too much myself since I've had a lot to do at work lately.

When the sample project runs (Xcode 7 beta or up), you'll be prompted with a slider, drag all the way to the right to visualized the Collection View Cells.

答:
Well the accepted answer is mostly correct.  It actually can fail again with same symptoms on iPhone + with the screen scale of 3.  Pulling the center with the center at some irrational number with 1/3 or 2/3 point will again cause perpetual circular motion.

Round to an even number
2.0 * floorf((number/2.0) + 0.5) - modified from another post.
This will make sure the center is whole number and not irrational.
Then by pulling the center in only one dimension will make bug be gone.

ContentLicense: CC BY-SA 4.0

Body:
I've been replicating the 2013 WWDC Session 217 "Exploring Scroll Views on iOS 7". I'm using Xcode 7 beta 2 and my project is iOS 9 only.

I’m trying to use a UIDynamicAnimator with my UICollectionViewLayout in a way similar to the one presented in session 217 to imitate Messages.app feel. My UICollectionViewLayout is a custom one and for some reason my cells seem to bounce in circular motion in my project.

This is my custom layout code.

// Didn't write this code myself, but should be pretty simple to follow. @Goles

#import "VVSpringCollectionViewFlowLayout.h"

@interface VVSpringCollectionViewFlowLayout()
@property (nonatomic, strong) UIDynamicAnimator *animator;
@end

@implementation VVSpringCollectionViewFlowLayout

-(id)init {
    if (self = [super init]) {
        _springDamping = 0.5;
        _springFrequency = 0.8;
        _resistanceFactor = 500;
    }
    return self;
}

- (id)initWithCoder:(nonnull NSCoder *)aDecoder {
  self = [super initWithCoder:aDecoder];
  if (self) {
        _springDamping = 0.5;
        _springFrequency = 0.8;
        _resistanceFactor = 500;
  }
  return self;
}

-(void)prepareLayout {
    [super prepareLayout];

    if (!_animator) {
        _animator = [[UIDynamicAnimator alloc] initWithCollectionViewLayout:self];
        CGSize contentSize = [self collectionViewContentSize];
        NSArray *items = [super layoutAttributesForElementsInRect:CGRectMake(0, 0, contentSize.width, contentSize.height)];

        for (UICollectionViewLayoutAttributes *item in items) {
            UIAttachmentBehavior *spring = [[UIAttachmentBehavior alloc] initWithItem:item attachedToAnchor:item.center];

            spring.length = 0;
            spring.damping = self.springDamping;
            spring.frequency = self.springFrequency;

            [_animator addBehavior:spring];
        }
    }
}

-(NSArray *)layoutAttributesForElementsInRect:(CGRect)rect {
    return [_animator itemsInRect:rect];
}

- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath {
    return [_animator layoutAttributesForCellAtIndexPath:indexPath];
}

-(BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds {
    UIScrollView *scrollView = self.collectionView;
    CGFloat scrollDelta = newBounds.origin.y - scrollView.bounds.origin.y;
    CGPoint touchLocation = [scrollView.panGestureRecognizer locationInView:scrollView];

    for (UIAttachmentBehavior *spring in _animator.behaviors) {
       CGPoint anchorPoint = spring.anchorPoint;
       CGFloat distanceFromTouch = fabs(touchLocation.y - anchorPoint.y);
       CGFloat scrollResistance = distanceFromTouch / self.resistanceFactor;

       id<UIDynamicItem> item = [spring.items firstObject];
       CGPoint center = item.center;

       if (scrollDelta > 0) {
            center.y += MIN(scrollDelta, scrollDelta * scrollResistance);
       }

       item.center = center;
       [_animator updateItemUsingCurrentState:item];
    }
    return NO;
}

@end

What could be going on here that's causing this circular motion? I'm only changing the Y axis property of my UIAttachmentAttributes center.

center.y += MIN(scrollDelta, scrollDelta * scrollResistance);

What am I missing here? (tried this exact layout in other project and seems to work).

EDIT:

I uploaded a sample project(removed), the Custom Collection View Layout Class is called VVSpringCollectionViewFlowLayout.m, haven't had much time to look into this too much myself since I've had a lot to do at work lately.

When the sample project runs (Xcode 7 beta or up), you'll be prompted with a slider, drag all the way to the right to visualized the Collection View Cells.


问:
ASP.NET MVC Authorize attribute behaves different in IE and FireFox
First things first: this is only a sample. This is not a question as to whether or not this is a valid way of doing authentication.

Basically, I'm getting odd behaviour which is dependant on the browser being used. Everything works as expected in Firefox, but on IE the controller actions in question still fire even when authorisation fails.

I have an ASP.NET MVC test site set up where a SecureController class inherits from the standard Controller class with the following relevant code:

```<code>[AuthorizeByToken]
public class SecureController : Contrller
 protected override void OnAuthorization(AuthorizationContext filterContext)
 {
     // Check for presence of encoded session string
     if (filterContext == null) throw new ArgumentNullException("filterContext null");
     if (filterContext.HttpContext == null) throw new ArgumentNullException("httpContext null");
     if (filterContext.HttpContext.Request["TestToken"] == null) return;

     // Complete authorization
     FormsAuthentication.SetAuthCookie(csmSession.CSMUser.userName, true);
     base.OnAuthorization(filterContext);
 }
</code>```

There's also an AuthorizeByTokenAttribute attribute based on AuthorizeAttribute like so:

```<code>public class AuthorizeByTokenAttribute : AuthorizeAttribute
{
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        filterContext.Result = new RedirectResult("/");
        filterContext.ActionDescriptor = null;
        base.HandleUnauthorizedRequest(filterContext);
    }

}
</code>```

Now when for example you visit http://testsite/TestSecureController/Index it works as expected in Firefox. It goes into the authorize code, fails, and redirects to the root. In IE it goes into the authorize code, still fails, and the next step is TestSecureController's Index() action running.

Can anyone offer some insight into why something like this would be browser dependant?

答:
I tested your Uri routing scheme using a few different methods and eliminated that as an issue. That works equivalently across both browsers. I'm ultra-paranoid about that sort of thing.

Therefore I'm inclined to think that it's cookie-ing behavior or state that differs across your two browser instances. Try the following:

Try to authorize against your form using an InPrivate session in IE8 / IE9 - this is a cookieless session and should fail with normal post-fail routing behavior. What we're trying to eliminate with this test is the possibility that you have dirty cookies in your IE session and clean ones in Firefox. If this test succeeds, proceed to step 2. If it fails, see step 3.

Try to authorize against your controller using your standard IE instance; if it fails, wipe all of your cookies and try again. If it fails, see step 3.

If both of these tests have failed, then we need to check if the cookies in Firefox and IE are equivalent. You can try using something like http://ncookiereader.sourceforge.net/ to compare the cookies your site issues in Firefox and IE, but it might be simpler just to open up the cookies collection and diff them in Notepad++. The contents of your cookie are going to be encrypted and they might include different authentication tickets presumably because you're running on two different IIS sessions, so to make life easier for debugging purposes only I recommend enabling decryption as an option so you can view your cookies in plaintext using this snippet in your Web.config: <authentication mode="Forms">
  <forms loginUrl="~/Account/LogOn" timeout="2880" protection="None" />
</authentication> - if the contents of your cookies differ significantly other than just the auth ticket, go to http://aaronstannard.com/ and send me an email via the contact form. If the contents of your cookie are equivalent, proceed to step 4.

At this point, I'd start looking for unhandlded exceptions in your authorization filter and I'd use Wireshark to see if the HTTP requests being sent by IE and Firefox differ in any major way. Let us know if you find anything.

Body:
First things first: this is only a sample. This is not a question as to whether or not this is a valid way of doing authentication.

Basically, I'm getting odd behaviour which is dependant on the browser being used. Everything works as expected in Firefox, but on IE the controller actions in question still fire even when authorisation fails.

I have an ASP.NET MVC test site set up where a SecureController class inherits from the standard Controller class with the following relevant code:

[AuthorizeByToken]
public class SecureController : Contrller
 protected override void OnAuthorization(AuthorizationContext filterContext)
 {
     // Check for presence of encoded session string
     if (filterContext == null) throw new ArgumentNullException("filterContext null");
     if (filterContext.HttpContext == null) throw new ArgumentNullException("httpContext null");
     if (filterContext.HttpContext.Request["TestToken"] == null) return;

     // Complete authorization
     FormsAuthentication.SetAuthCookie(csmSession.CSMUser.userName, true);
     base.OnAuthorization(filterContext);
 }

There's also an AuthorizeByTokenAttribute attribute based on AuthorizeAttribute like so:

public class AuthorizeByTokenAttribute : AuthorizeAttribute
{
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        filterContext.Result = new RedirectResult("/");
        filterContext.ActionDescriptor = null;
        base.HandleUnauthorizedRequest(filterContext);
    }

}

Now when for example you visit http://testsite/TestSecureController/Index it works as expected in Firefox. It goes into the authorize code, fails, and redirects to the root. In IE it goes into the authorize code, still fails, and the next step is TestSecureController's Index() action running.

Can anyone offer some insight into why something like this would be browser dependant?


问:
By declaring character type T, online judge shows Runtime Error(SIGSEGV)
```<code>#include<stdio.h>
#include<math.h>
int main(void)
{
    //variable declaration
    char T;
    int N, i;
    double f;

    scanf("%d",&T);

    //for loop for T times iteration
    for(i=1;i<=T;i++){
        //input number  for checking its square root
        scanf("%d", &N);
        //sqrt() library function for square root
        f= sqrt(N);

        //checking if N has int type square root
        if(f - (int)f == 0)
            printf("YES\n");

        else
            printf("NO\n");
    }//for loop ends

    return 0;
}
</code>```

Output in Code Blocks:

3

16

YES

15

NO

14

No

Online judge shows:
Result: runtime error (SIGSEGV)

The program will take input for number of lines to be printed. And in each line it will take an integer type number and checks whether the number is square root or not. If yes, then it will print 'YES'. Otherwise 'No'.

In my code, Range of T should be T<=100. So, I declared T as character data
type. And I know the range of char is -128 to 127 or 0 to 255. I think it
should work. I compiled this program in Code Blocks without any error. It
gives right output. But when I compiled in online judge it gives runtime
error (SIGSEGV).

Can anyone please help me why does it happen?
Thank you.

答:
```<code>scanf("%d",&T);
</code>```

Here scanf will try to store input into 4 bytes starting from address of T which will lead to segment fault as T is char so is allocated only one byte

Body:
#include<stdio.h>
#include<math.h>
int main(void)
{
    //variable declaration
    char T;
    int N, i;
    double f;

    scanf("%d",&T);

    //for loop for T times iteration
    for(i=1;i<=T;i++){
        //input number  for checking its square root
        scanf("%d", &N);
        //sqrt() library function for square root
        f= sqrt(N);

        //checking if N has int type square root
        if(f - (int)f == 0)
            printf("YES\n");

        else
            printf("NO\n");
    }//for loop ends

    return 0;
}

Output in Code Blocks:

3

16

YES

15

NO

14

No

Online judge shows:
Result: runtime error (SIGSEGV)

The program will take input for number of lines to be printed. And in each line it will take an integer type number and checks whether the number is square root or not. If yes, then it will print 'YES'. Otherwise 'No'.

In my code, Range of T should be T<=100. So, I declared T as character data
type. And I know the range of char is -128 to 127 or 0 to 255. I think it
should work. I compiled this program in Code Blocks without any error. It
gives right output. But when I compiled in online judge it gives runtime
error (SIGSEGV).

Can anyone please help me why does it happen?
Thank you.

Body:
scanf("%d",&T);

Here scanf will try to store input into 4 bytes starting from address of T which will lead to segment fault as T is char so is allocated only one byte


问:
How can i refresh data table after updating the data and retain on the pagination page
I used ajax.reload(), but it is not working.

I try the other method to refresh the data but how can i stay on the current pagination table after data been edited.

```<code>$.ajax({
            type: 'GET',
            url: '/test',
            dataType: 'HTML',
            success: function (html) {
                $('#group').html(html);
            },
            error: function (data) {
                console.log('Error:', data);
            }
        });
</code>```

I able to refresh the page if using above method but it will always return back to first pagination table. Anyone got idea how to make it how can i stay on the current pagination table after data been edited?

答:
Im using this for stay on Page (before reload). "bStateSave" : true,
  I hope this will answer your reload page.

```<code>$(document).ready(function () {
    $('#users').DataTable({
        "bStateSave" : true,
        // "searching" : false,
        "columns": [
            {"data": "id"},
            {"data": "name"},
            {"data": "phone"},
            {"data": "fax"},
        ],
        "processing": true,
        "serverSide": true,
        "ajax": {
            url: 'demo.php',
            type: 'POST'
        }
    });
});
</code>```

Body:
I used ajax.reload(), but it is not working.

I try the other method to refresh the data but how can i stay on the current pagination table after data been edited.

$.ajax({
            type: 'GET',
            url: '/test',
            dataType: 'HTML',
            success: function (html) {
                $('#group').html(html);
            },
            error: function (data) {
                console.log('Error:', data);
            }
        });

I able to refresh the page if using above method but it will always return back to first pagination table. Anyone got idea how to make it how can i stay on the current pagination table after data been edited?

Body:
Im using this for stay on Page (before reload). "bStateSave" : true,
  I hope this will answer your reload page.

$(document).ready(function () {
    $('#users').DataTable({
        "bStateSave" : true,
        // "searching" : false,
        "columns": [
            {"data": "id"},
            {"data": "name"},
            {"data": "phone"},
            {"data": "fax"},
        ],
        "processing": true,
        "serverSide": true,
        "ajax": {
            url: 'demo.php',
            type: 'POST'
        }
    });
});


问:
Can't see multiple markers on google map
In PostExecute i have this array name : locations

I print Log for more details like that:

```<code>[lat/lng: (18.5159983333333,-72.2916166666667), lat/lng: (18.5363383333333,-72.3231866666667), lat/lng: (18.5076266666667,-72.3164933333333), lat/lng: (18.54138,-72.2920766666667)]
</code>```

And i try to show all coordinates like that

```<code>protected void onPostExecute(Boolean result) {
            dialog.dismiss();

            for (int i = 0; i < locations.size(); i++)
            {

            Double latitude = Double.valueOf(locations.get(i).latitude);
            Double longitude = Double.valueOf(locations.get(i).longitude);

            LatLng lng = new LatLng(latitude,longitude);
            map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
            map.addMarker(new MarkerOptions()
            .position(lng)
            .title("Test")
            .icon(BitmapDescriptorFactory.fromResource(getResources().getIdentifier("Title", "drawable", getPackageName()))));
            }

        }
</code>```

Google map shows blank. How may i resolve it please??

答:
You can only add markers when your map is ready to receive them and   that is true when

```<code>public void onMapReady(GoogleMap googleMap)
</code>```

is called.

I will try to get you started with this:

You need to setup some variables:

```<code>private GoogleMap mMap;
private boolean isMapReady = false;
private ArrayList<LatLng> myLocations = null;
</code>```

the ArrayList will contain your locations you get from your AsyncTask

Then you need to get the mapOnReady setup in your onCreate() Methode:

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_map);

    // What ever else you need

    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.mapViewRidesFoundMap);
    mapFragment.getMapAsync(this);
}
</code>```

Now you need to override the onMapReady method:

```<code>@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    // Set a boolean flag to let other parts of you code
    // know that the map is ready
    isMapReady = true;

    // If you need to get info from your marker Implement this
    //mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
    //    @Override
    //    public boolean onMarkerClick(Marker marker) {

    //        showMarkerInfo(marker);
    //        return false;
    //    }
    //});

    //If you need a click listener add this
    // Add implement the method 'onMapClickLocation'
    //mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
    //    @Override
    //    public void onMapClick(LatLng latLng) {
    //        onMapClickLocation(latLng);
    //    }
    //});

    // call a function to update your locations
    updateMapLocations();
}
</code>```

Within your(!) protected void onPostExecute(Boolean result)  add code to fill the myLocations ArrayList

```<code>protected void onPostExecute(Boolean result) {
        dialog.dismiss();
        myLocations = new ArrayList<LatLng>();

        for (int i = 0; i < locations.size(); i++)
        {

            Double latitude = Double.valueOf(locations.get(i).latitude);
            Double longitude = Double.valueOf(locations.get(i).longitude);

            LatLng lng = new LatLng(latitude,longitude);
            myLocations.put(lng);
        }

        // calls the update method when data is available
        this.updateMapLocations();
    }
</code>```

and add a call to updateMapLocations() which could look like this:

```<code>private void updateMapLocations(){
    // update locations won't continue unless the map is ready
    if(!isMapReady) return;

    // Zoom into your location !! if you need too
    // with a destinationLocation of your choice
    // perhaps your first location in you ArrayList
    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(destinationLocation, zoomFactor));

    // PseudoCode!!
    // Add your for Loop
    // !!! Check to see if your myLocations ArrayList is null  before you continue !!!
    // !!! or just add another boolean to you onPostExcecute method
    // And add the Markers

    //Loop Start
    //float hue = BitmapDescriptorFactory.HUE_MAGENTA;
    //MarkerOptions markerOptions = setMarker(latLng, hue)

    // !!! You need to add your destination loop !!!
    //mMap.addMarker(markerOptions);
    //Loop end!

}

    private MarkerOptions setMarker(LatLng latLng, float hue){
    MarkerOptions markerOptions = null;
    try {
        float markerAlpha = 0.7f;

        markerOptions = new MarkerOptions();
        markerOptions.icon(BitmapDescriptorFactory.defaultMarker(hue));
        markerOptions.position(latLng);
        markerOptions.alpha(markerAlpha);
        markerOptions.flat(false);
        markerOptions.title("What Ever");
        markerOptions.snippet("MySnippet");
        markerOptions.draggable(false);
        markerOptions.zIndex(0.0f);
    }
    catch (Exception ex){
        Log.e(TAG, "  setMarker --- " + ex.getMessage());
    }
    return markerOptions;
}
</code>```

Notice that updateMapLocations() is called in both your onPostExecute() and the onMapReady() methods. The onPostExecute() might be finished before the onMapReady() is called. So that first when the map is ready the updateMapLocations() will run to completion when data and map are ready.

I wrote this in a text editor - so there will probably be a couple of syntax errors.

Body:
In PostExecute i have this array name : locations

I print Log for more details like that:

[lat/lng: (18.5159983333333,-72.2916166666667), lat/lng: (18.5363383333333,-72.3231866666667), lat/lng: (18.5076266666667,-72.3164933333333), lat/lng: (18.54138,-72.2920766666667)]

And i try to show all coordinates like that

protected void onPostExecute(Boolean result) {
            dialog.dismiss();

            for (int i = 0; i < locations.size(); i++)
            {

            Double latitude = Double.valueOf(locations.get(i).latitude);
            Double longitude = Double.valueOf(locations.get(i).longitude);

            LatLng lng = new LatLng(latitude,longitude);
            map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
            map.addMarker(new MarkerOptions()
            .position(lng)
            .title("Test")
            .icon(BitmapDescriptorFactory.fromResource(getResources().getIdentifier("Title", "drawable", getPackageName()))));
            }

        }

Google map shows blank. How may i resolve it please??

Body:
You can only add markers when your map is ready to receive them and   that is true when

public void onMapReady(GoogleMap googleMap)

is called.

I will try to get you started with this:

You need to setup some variables:

private GoogleMap mMap;
private boolean isMapReady = false;
private ArrayList<LatLng> myLocations = null;

the ArrayList will contain your locations you get from your AsyncTask

Then you need to get the mapOnReady setup in your onCreate() Methode:

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

    // What ever else you need

    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.mapViewRidesFoundMap);
    mapFragment.getMapAsync(this);
}

Now you need to override the onMapReady method:

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    // Set a boolean flag to let other parts of you code
    // know that the map is ready
    isMapReady = true;

    // If you need to get info from your marker Implement this
    //mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
    //    @Override
    //    public boolean onMarkerClick(Marker marker) {

    //        showMarkerInfo(marker);
    //        return false;
    //    }
    //});

    //If you need a click listener add this
    // Add implement the method 'onMapClickLocation'
    //mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
    //    @Override
    //    public void onMapClick(LatLng latLng) {
    //        onMapClickLocation(latLng);
    //    }
    //});

    // call a function to update your locations
    updateMapLocations();
}

Within your(!) protected void onPostExecute(Boolean result)  add code to fill the myLocations ArrayList

protected void onPostExecute(Boolean result) {
        dialog.dismiss();
        myLocations = new ArrayList<LatLng>();

        for (int i = 0; i < locations.size(); i++)
        {

            Double latitude = Double.valueOf(locations.get(i).latitude);
            Double longitude = Double.valueOf(locations.get(i).longitude);

            LatLng lng = new LatLng(latitude,longitude);
            myLocations.put(lng);
        }

        // calls the update method when data is available
        this.updateMapLocations();
    }

and add a call to updateMapLocations() which could look like this:

private void updateMapLocations(){
    // update locations won't continue unless the map is ready
    if(!isMapReady) return;

    // Zoom into your location !! if you need too
    // with a destinationLocation of your choice
    // perhaps your first location in you ArrayList
    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(destinationLocation, zoomFactor));

    // PseudoCode!!
    // Add your for Loop
    // !!! Check to see if your myLocations ArrayList is null  before you continue !!!
    // !!! or just add another boolean to you onPostExcecute method
    // And add the Markers

    //Loop Start
    //float hue = BitmapDescriptorFactory.HUE_MAGENTA;
    //MarkerOptions markerOptions = setMarker(latLng, hue)

    // !!! You need to add your destination loop !!!
    //mMap.addMarker(markerOptions);
    //Loop end!

}

    private MarkerOptions setMarker(LatLng latLng, float hue){
    MarkerOptions markerOptions = null;
    try {
        float markerAlpha = 0.7f;

        markerOptions = new MarkerOptions();
        markerOptions.icon(BitmapDescriptorFactory.defaultMarker(hue));
        markerOptions.position(latLng);
        markerOptions.alpha(markerAlpha);
        markerOptions.flat(false);
        markerOptions.title("What Ever");
        markerOptions.snippet("MySnippet");
        markerOptions.draggable(false);
        markerOptions.zIndex(0.0f);
    }
    catch (Exception ex){
        Log.e(TAG, "  setMarker --- " + ex.getMessage());
    }
    return markerOptions;
}

Notice that updateMapLocations() is called in both your onPostExecute() and the onMapReady() methods. The onPostExecute() might be finished before the onMapReady() is called. So that first when the map is ready the updateMapLocations() will run to completion when data and map are ready.

I wrote this in a text editor - so there will probably be a couple of syntax errors.


问:
How to get Average Rating using SQL
I have a table:

How can I calculate average rating for a tutor using T-SQL in SQL Server 2008?

答:
Try Query to find avg as:

```<code>SELECT        tutorid, (rated1 + rated2 + rated3 + rated4 + rated5) / 5.0 AS Average
FROM            tutor
</code>```

Result for your demo data:

Title: How to get Average Rating using SQL

Body:
Try Query to find avg as:

SELECT        tutorid, (rated1 + rated2 + rated3 + rated4 + rated5) / 5.0 AS Average
FROM            tutor

Result for your demo data:


问:
Subversion, renaming, Wha?
So i have a funny problem.

Subversion, you are not allowed to rename items with the same name if the only difference is capitalization.  Netbeans has subversion.  Netbeans allows you to rename files if the capitalization changes.

I renamed something called eventCreator.php to EventCreator.php in subversion and uploaded (it is a class).  Everything went fine in Netbeans.  In fact, I made about 10 more commits. I tried to download it on another computer, and this is the error that happens

"Can't open file
C:\xampp\htdocs\MyProject\scripts.svn\tmp\text-base\eventCreator.php.svn-base':
The system cannot find the file specified."

My repository is located at DreamHost.  So i go to dreamhost and i am able to go into the scripts folder and see both eventCreator.php and EventCreator.php in the repository, yet i cannot download it with either netbeans or tortoiseSVN.
Any Help?

答:
Delete not necessary file with

```<code>svn del http://domain/path/to/eventCreator.php
</code>```

Or you can even open repo browser (from subversion context menu) and delete the file there, without using boring console commands ;-)

Title: Subversion, renaming, Wha?

Body:
Delete not necessary file with

svn del http://domain/path/to/eventCreator.php

Or you can even open repo browser (from subversion context menu) and delete the file there, without using boring console commands ;-)


问:
How to connect to an Oracle database Connection from .Net Core
Within a .netCore library I want to connect to an Oracle database.  Is there any way I can do that yet?

I have tried the suggestions on another SO post, but it doesn't work, perhaps removed since?  As you can see in my project.json, I'm trying to use "net461".

I'm currently trying using Oracle.ManagedDataAccess.Client via old fashioned ADO.Net.  I also know that Oracle haven't bought out a .netCore connector yet.  But even there I can't get it to work, it struggles to get the System.Data included, it errors whenever I try to add it.

My project.json looks like this:

```<code>{
  "version": "1.0.0-*",

  "dependencies": {
    "NETStandard.Library": "1.6.0",
    "Oracle.ManagedDataAccess": "12.1.24160719",
  },

  "frameworks": {
    "netstandard1.6": {
      "imports": [
        "dnxcore50",
        "net461"
      ]
    }
  }
}
</code>```

This is how I was trying to do it at the moment.

```<code>using Oracle.ManagedDataAccess.Client;

public class MyRepository
{
    public string GetServerVersion()
    {
        var _db = new OracleConnection("User Id=myUser;Password=myPassword;Data Source=MyOracleConnection");

        var serverVersion = _db.ServerVersion;
        return serverVersion;
    }
}
</code>```

However the above doesn't compile as it doesn't have System.Data, which I'm struggling to import.

I'm not entrenched on any particular way of doing it, I just want the best reasonable option at this point in time.

答: finally devart's dotConnect for Oracle support .net core since version "9.4.280". </p>

Body:
Within a .netCore library I want to connect to an Oracle database.  Is there any way I can do that yet?

I have tried the suggestions on another SO post, but it doesn't work, perhaps removed since?  As you can see in my project.json, I'm trying to use "net461".

I'm currently trying using Oracle.ManagedDataAccess.Client via old fashioned ADO.Net.  I also know that Oracle haven't bought out a .netCore connector yet.  But even there I can't get it to work, it struggles to get the System.Data included, it errors whenever I try to add it.

My project.json looks like this:

{
  "version": "1.0.0-*",

  "dependencies": {
    "NETStandard.Library": "1.6.0",
    "Oracle.ManagedDataAccess": "12.1.24160719",
  },

  "frameworks": {
    "netstandard1.6": {
      "imports": [
        "dnxcore50",
        "net461"
      ]
    }
  }
}

This is how I was trying to do it at the moment.

using Oracle.ManagedDataAccess.Client;

public class MyRepository
{
    public string GetServerVersion()
    {
        var _db = new OracleConnection("User Id=myUser;Password=myPassword;Data Source=MyOracleConnection");

        var serverVersion = _db.ServerVersion;
        return serverVersion;
    }
}

However the above doesn't compile as it doesn't have System.Data, which I'm struggling to import.

I'm not entrenched on any particular way of doing it, I just want the best reasonable option at this point in time.


问:
Can there be only one Distribution Certificate per App Developer?
I experience big trouble with the iOS provisioning / certification.

Recently I submitted an app to App Store with a normal App Store Distribution Certificate. And then I wanted to create a AdHoc Beta Test for another app, and I am not sure what happened next but now the Provisioning Portal doesn't list my App Store Distribution Certificate anymore. Instead it only lists my AdHoc BetaTest Certificate.

Also, the Provisioning Portal has no way to create a new Certificate.
Recently I renewed my developer account so maybe everything expired causing the trouble?

My Keychain has an entry "iPhone Distribution: Mikhalo Ivanokov", with green checkmark "This certificate is valid", expiring in Nov 10, 2012.

But Provisioning Portal doesn't list this Distribution Certificate. Only the AdHoc BetaTest certificate.

How can I fix this? Does anyone know what might have happened? Did Xcode replace my App Store Distribution Certificate with my AdHoc Distribution Certificate? Can I have two, or must I somehow delete the AdHoc Distribution Certificate first?

答: IOS distribution certificate personal account can only apply for three</p>