问:
issue cycling through forms with different names in django views
I am working on a project and i am having an issue with djago form templates and it only returning one part of the form.

So what is happening is:
I have a ModelForm that contains two fields which are amount and description. Within the view I cycle through a list of users. for every user in the loop it creates a form with the users username prefix and then passes the list of forms into the html template.

The issue that i am having is that all of the forms and their prefixes are passing to the html tempalte, but when it is submitted, only the last form is passed back to be proccessed. I have an example below and the file info that is related to this issue.

Please look at the updated section at the bottom of the question

Here are the passed in forms that were created in the view before html template is displayed:

```<code>omarform
<tr><th><label for="id_omar-amount">Amount:</label></th><td><input id="id_omar-amount" name="omar-amount" step="0.01" type="number" value="0.0" /></td></tr>
<tr><th><label for="id_omar-description">Description:</label></th><td><input id="id_omar-description" maxlength="250" name="omar-description" type="text" /></td></tr>
haniform
<tr><th><label for="id_hani-amount">Amount:</label></th><td><input id="id_hani-amount" name="hani-amount" step="0.01" type="number" value="0.0" /></td></tr>
<tr><th><label for="id_hani-description">Description:</label></th><td><input id="id_hani-description" maxlength="250" name="hani-description" type="text" /></td></tr>
ranaform
<tr><th><label for="id_rana-amount">Amount:</label></th><td><input id="id_rana-amount" name="rana-amount" step="0.01" type="number" value="0.0" /></td></tr>
<tr><th><label for="id_rana-description">Description:</label></th><td><input id="id_rana-description" maxlength="250" name="rana-description" type="text" /></td></tr>
</code>```

Here is what is displayed correctly:

```<code>fill out the form below
Amount:
0.0
Description:
Amount:
0.0
Description:
Amount:
0.0
Description:
Tax:
Tip:
submit
</code>```

but here is what is returned when i try to submit the form:

```<code>Request information

GET
No GET data
POST
Variable    Value
rana-amount '0.0'
rana-description    ''
tax ''
tip ''
submit  'submit'
</code>```

Here is the code:

html:

```<code>{% extends "base.html" %}

{% block content %}
  <h1>Add members to {{record.name}}</h1>
  {% if message %}
    <p>{{message}}</p>
  {% endif %}
  <form action="." method="POST">
    {% csrf_token %}
    {{ form.as_p }}
    <p>Tax: <input type="text" name="tax" value=""></p>
    <p>Tip: <input type="text" name="tip" value=""></p>
    <input type="submit" name="submit" value="submit">
  </form>
{% endblock %}
</code>```

views:

```<code>def addTransaction(request, groupId, recordId):
    user = User.objects.get(username='omar')
    group = Group.objects.get(id=groupId)
    record = Record.objects.get(id=recordId)
    transactions = Transaction.objects.all()
    if request.method == 'POST':
        if record.split == 1:
            form = EvenSplitTransactionForm(request.POST)
            if form.is_valid():
                cd = form.cleaned_data
                amount = cd['amount']
                description = cd['description']
                split_amount = SplitEven(record, amount)
                for trans in transactions:
                    if trans.record.id == record.id:
                        trans.description = description
                        trans.amount = split_amount
                        trans.save()
                return redirect('accounts')
        if record.split == 2:
            form = IndividualSplitTransactionForm(requesst.POST)
            if form.is_valid():
                cd = form.cleaned_data
                for trans in transactions:
                    if trans.record.id == record.id:
                        amount = 'desiatnace'

        # even_form = EvenSplitTransactionForm(request.POST)
        # if even_form.is_valid():
        #     even_cd = even_form.cleaned_data
        #     amount = even_cd['amount']
        #     description = even_cd['description']
        #     if record.split == 1:
        #         split_amount = SplitEven(record, amount)
        #         for trans in transactions:
        #             if trans.record.id == record.id:
        #                 trans.description = description
        #                 trans.amount = split_amount
        #                 trans.save()
        #     if record.split == 2:
        #         splits = amount
        return redirect('accounts')
    else:
        if record.split == 1:
            form = EvenSplitTransactionForm()
            message = 'fill out the form below'
            parameters = {
                'record':record,
                'form':form,
                'message':message,
                'transactions':transactions,
            }
            return render(request, 'tabs/add_even_transactions.html', parameters)
        if record.split == 2:
            for trans in transactions:
                if trans.record.id == record.id:
                    formName = trans.user.username + 'form'
                    print(formName)
                    form = IndividualSplitTransactionForm(prefix=trans.user.username)
                    print(form)
            message = 'fill out the form below'
            parameters = {
                'record':record,
                'form':form,
                'message':message,
                'transactions':transactions,
            }
            return render(request, 'tabs/add_individual_transaction.html', parameters)
</code>```

form:

```<code>class IndividualSplitTransactionForm(forms.ModelForm):
    class Meta:
        model = Transaction
        fields = ['amount', 'description']
</code>```

UPDATED

I was in the template file and i deleted some of the commented code and i found out that only the last form of the three that i am passing into the template is beign displayed and bragged by the template. So the real issue that I realized that i am having is that i need to pas three forms and only one is being passed. i need to figure out how to combine all three of the forms into one and pass it or pass all three forms individually with different names within the for loop.

This is what i with the form before it is being passed through...

```<code>if record.split == 2:
            for trans in transactions:
                if trans.record.id == record.id:
                    formName = trans.user.username + 'form'
                    form = IndividualSplitTransactionForm(prefix=trans.user.username)
                    print(form)
            message = 'fill out the form below'
            parameters = {
                'record':record,
                'form':form,
                'message':message,
                'transactions':transactions,
            }
            return render(request, 'tabs/add_individual_transaction.html', parameters)
</code>```

答:
I understood that you have multiple 'amount', 'description' fields in one form.

for example, you have Sarah, Pill, Kelly. You have three each fields in your form like below.

```<code><form action="." method="post">{% csrf_token %}
## Sarah section
<input type="text" name="amount">
<input type="text" name="description">
## Pill section
<input type="text" name="amount">
<input type="text" name="description">
## Kelly section
<input type="text" name="amount">
<input type="text" name="description">
<button name="submit">Submit</button>
</form>
</code>```

I assume that you use same name 'amount' and 'desciption'. So if you get data from request.POST.get('amount', None), you will get only last data. Try with request.POST.getlist('amount').

You can check in your console screen with print(request.POST);

Body:
I am working on a project and i am having an issue with djago form templates and it only returning one part of the form.

So what is happening is:
I have a ModelForm that contains two fields which are amount and description. Within the view I cycle through a list of users. for every user in the loop it creates a form with the users username prefix and then passes the list of forms into the html template.

The issue that i am having is that all of the forms and their prefixes are passing to the html tempalte, but when it is submitted, only the last form is passed back to be proccessed. I have an example below and the file info that is related to this issue.

Please look at the updated section at the bottom of the question

Here are the passed in forms that were created in the view before html template is displayed:

omarform

Amount:	<input id="id_omar-amount" name="omar-amount" step="0.01" type="number" value="0.0" />

Description:	<input id="id_omar-description" maxlength="250" name="omar-description" type="text" />

haniform

Amount:	<input id="id_hani-amount" name="hani-amount" step="0.01" type="number" value="0.0" />

Description:	<input id="id_hani-description" maxlength="250" name="hani-description" type="text" />

ranaform

Amount:	<input id="id_rana-amount" name="rana-amount" step="0.01" type="number" value="0.0" />

Description:	<input id="id_rana-description" maxlength="250" name="rana-description" type="text" />

Here is what is displayed correctly:

fill out the form below
Amount:
0.0
Description:
Amount:
0.0
Description:
Amount:
0.0
Description:
Tax:
Tip:
submit

but here is what is returned when i try to submit the form:

Request information

GET
No GET data
POST
Variable    Value
rana-amount '0.0'
rana-description    ''
tax ''
tip ''
submit  'submit'

Here is the code:

html:

{% extends "base.html" %}

{% block content %}

Add members to {{record.name}}

  {% if message %}

{{message}}

  {% endif %}
  <form action="." method="POST">
    {% csrf_token %}
    {{ form.as_p }}

Tax: <input type="text" name="tax" value="">

Tip: <input type="text" name="tip" value="">

    <input type="submit" name="submit" value="submit">
  </form>
{% endblock %}

views:

def addTransaction(request, groupId, recordId):
    user = User.objects.get(username='omar')
    group = Group.objects.get(id=groupId)
    record = Record.objects.get(id=recordId)
    transactions = Transaction.objects.all()
    if request.method == 'POST':
        if record.split == 1:
            form = EvenSplitTransactionForm(request.POST)
            if form.is_valid():
                cd = form.cleaned_data
                amount = cd['amount']
                description = cd['description']
                split_amount = SplitEven(record, amount)
                for trans in transactions:
                    if trans.record.id == record.id:
                        trans.description = description
                        trans.amount = split_amount
                        trans.save()
                return redirect('accounts')
        if record.split == 2:
            form = IndividualSplitTransactionForm(requesst.POST)
            if form.is_valid():
                cd = form.cleaned_data
                for trans in transactions:
                    if trans.record.id == record.id:
                        amount = 'desiatnace'

        # even_form = EvenSplitTransactionForm(request.POST)
        # if even_form.is_valid():
        #     even_cd = even_form.cleaned_data
        #     amount = even_cd['amount']
        #     description = even_cd['description']
        #     if record.split == 1:
        #         split_amount = SplitEven(record, amount)
        #         for trans in transactions:
        #             if trans.record.id == record.id:
        #                 trans.description = description
        #                 trans.amount = split_amount
        #                 trans.save()
        #     if record.split == 2:
        #         splits = amount
        return redirect('accounts')
    else:
        if record.split == 1:
            form = EvenSplitTransactionForm()
            message = 'fill out the form below'
            parameters = {
                'record':record,
                'form':form,
                'message':message,
                'transactions':transactions,
            }
            return render(request, 'tabs/add_even_transactions.html', parameters)
        if record.split == 2:
            for trans in transactions:
                if trans.record.id == record.id:
                    formName = trans.user.username + 'form'
                    print(formName)
                    form = IndividualSplitTransactionForm(prefix=trans.user.username)
                    print(form)
            message = 'fill out the form below'
            parameters = {
                'record':record,
                'form':form,
                'message':message,
                'transactions':transactions,
            }
            return render(request, 'tabs/add_individual_transaction.html', parameters)

form:

class IndividualSplitTransactionForm(forms.ModelForm):
    class Meta:
        model = Transaction
        fields = ['amount', 'description']

UPDATED

I was in the template file and i deleted some of the commented code and i found out that only the last form of the three that i am passing into the template is beign displayed and bragged by the template. So the real issue that I realized that i am having is that i need to pas three forms and only one is being passed. i need to figure out how to combine all three of the forms into one and pass it or pass all three forms individually with different names within the for loop.

This is what i with the form before it is being passed through...

if record.split == 2:
            for trans in transactions:
                if trans.record.id == record.id:
                    formName = trans.user.username + 'form'
                    form = IndividualSplitTransactionForm(prefix=trans.user.username)
                    print(form)
            message = 'fill out the form below'
            parameters = {
                'record':record,
                'form':form,
                'message':message,
                'transactions':transactions,
            }
            return render(request, 'tabs/add_individual_transaction.html', parameters)

Body:
I understood that you have multiple 'amount', 'description' fields in one form.

for example, you have Sarah, Pill, Kelly. You have three each fields in your form like below.

<form action="." method="post">{% csrf_token %}
## Sarah section
<input type="text" name="amount">
<input type="text" name="description">
## Pill section
<input type="text" name="amount">
<input type="text" name="description">
## Kelly section
<input type="text" name="amount">
<input type="text" name="description">
<button name="submit">Submit</button>
</form>

I assume that you use same name 'amount' and 'desciption'. So if you get data from request.POST.get('amount', None), you will get only last data. Try with request.POST.getlist('amount').

You can check in your console screen with print(request.POST);


来源: stackexchange

问:
Load Xamarin Forms page from android notification
I am trying to load a Xamarin Forms page from an Android Notification. I am really lost on the android side of this, and most of my code has been pieced together from tutorials and blog posts. However nothing really seems to cover exactly this scenario.

I have implemented a very simple interface with dependency service to create the notification with an intent...

```<code>[assembly: Xamarin.Forms.Dependency(typeof(QuoteNotification))]

namespace QuoteApp.Droid
{

    class QuoteNotification : IQuoteNotification
    {

        public void Notify(string title, string message)
        {

            //type needs to be derived from java, not xamarin.forms
            Intent LoadPostPage = new Intent(Forms.Context, typeof(DroidToForms));
            const int pendingIntentId = 0;
            PendingIntent pendingIntent =
                PendingIntent.GetActivity(Forms.Context, pendingIntentId, LoadPostPage, PendingIntentFlags.OneShot);

            Notification.Builder builder = new Notification.Builder(Forms.Context)
                .SetContentIntent(pendingIntent)
                .SetAutoCancel(true)

                     .SetContentTitle(title)
                     .SetContentText(message)
                     .SetSmallIcon(Resource.Drawable.icon);

            // Build the notification:
            Notification notification = builder.Build();

            // Get the notification manager:
            NotificationManager notificationManager =
                Forms.Context.GetSystemService(Context.NotificationService) as NotificationManager;

            // Publish the notification:
            const int notificationId = 0;
            notificationManager.Notify(notificationId, notification);
        }
    }
}
</code>```

this calls an activity -

```<code>namespace QuoteApp.Droid
{
    [Activity(Label = "QuoteApp", MainLauncher = true)]
    class DroidToForms : Activity
    {
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            StartActivity(typeof(XFPostPage));
            //Xamarin.Forms.Application.Current.MainPage.Navigation.PushAsync(new QuoteApp.PostPage());

        }
    }
}
</code>```

which in turn calls this forms page, all the code here has been in Xamarin.Android project

```<code>namespace QuoteApp.Droid
{

        /// <summary>
        /// This is a Xamarin.Forms screen. It MUST:
        /// * inherit from ANdroidActivity
        /// * call Forms.Init()
        /// * use LoadApplication()
        /// </summary>
        [Activity(Label = "XFPostPage", MainLauncher = true) ]
        public class XFPostPage : Xamarin.Forms.Platform.Android.FormsApplicationActivity
        {
            protected override void OnCreate(Bundle bundle)
            {
                base.OnCreate(bundle);

                Xamarin.Forms.Forms.Init(this, bundle);

            //LoadApplication( new App() ); //how do i send to PostPage.xaml ??

            Xamarin.Forms.Application.Current.MainPage.Navigation.PushAsync(new QuoteApp.PostPage());
        }
        }
    }
</code>```

this gives the following error in logcat

```<code>07-04 17:51:44.494  7668  7668 E AndroidRuntime: Caused by: android.runtime.JavaProxyThrowable: System.NullReferenceException: Object reference not set to an instance of an object
07-04 17:51:44.494  7668  7668 E AndroidRuntime:   at QuoteApp.Droid.XFPostPage.OnCreate (Android.OS.Bundle bundle) [0x00016] in <ab64801c0fb24acb8457c1d1202cc143>:0
07-04 17:51:44.494  7668  7668 E AndroidRuntime:   at Android.App.Activity.n_OnCreate_Landroid_os_Bundle_ (System.IntPtr jnienv, System.IntPtr native__this, System.IntPtr native_savedInstanceState) [0x0000f] in <d855bac285f44dda8a0d8510b679b1e2>:0
07-04 17:51:44.494  7668  7668 E AndroidRuntime:   at (wrapper dynamic-method) System.Object:2780fa42-5931-40d3-8d14-a642f1a3025c (intptr,intptr,intptr)
07-04 17:51:44.494  7668  7668 E AndroidRuntime:        at md543d03747be5a5b03a21a2a23b8ba191a.XFPostPage.n_onCreate(Native Method)
07-04 17:51:44.494  7668  7668 E AndroidRuntime:        at md543d03747be5a5b03a21a2a23b8ba191a.XFPostPage.onCreate(XFPostPage.java:29)
07-04 17:51:44.494  7668  7668 E AndroidRuntime:        at android.app.Activity.performCreate(Activity.java:6237)
07-04 17:51:44.494  7668  7668 E AndroidRuntime:        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
07-04 17:51:44.494  7668  7668 E AndroidRuntime:        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
07-04 17:51:44.494  7668  7668 E AndroidRuntime:        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
07-04 17:51:44.494  7668  7668 E AndroidRuntime:        at android.app.ActivityThread.-wrap11(ActivityThread.java)
07-04 17:51:44.494  7668  7668 E AndroidRuntime:        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
07-04 17:51:44.494  7668  7668 E AndroidRuntime:        at android.os.Handler.dispatchMessage(Handler.java:102)
07-04 17:51:44.494  7668  7668 E AndroidRuntime:        at android.os.Looper.loop(Looper.java:148)
07-04 17:51:44.494  7668  7668 E AndroidRuntime:        at android.app.ActivityThread.main(ActivityThread.java:5417)
07-04 17:51:44.494  7668  7668 E AndroidRuntime:        ... 3 more
</code>```

I have tried a bunch of different ideas all with different runtime errors, my understanding of the Xamarin.Android workings are very limited. eventually i will be using the notification with AlarmManager and further information will be sent to PostPage.Xaml. At the moment i'm just lost at exactly where this is going wrong though?!

Any Help would be hugely appreciated, thanks in advance.

答:
Problem is with your code Intent LoadPostPage = new Intent(Forms.Context, typeof(DroidToForms));.

For Android platform of XF project, it only has one Activity, which is MainActivity, or pages of XF are rendered based on this MainActivity.

So you may change you code like this:

```<code>Intent intent = new Intent(context, typeof(MainActivity));
intent.PutExtras(valuesForActivity);

PendingIntent resultPendingIntent = PendingIntent.GetActivity(Xamarin.Forms.Forms.Context, 0, intent, PendingIntentFlags.OneShot);
</code>```

Then in your OnCreate method of MainActivity:

```<code>//navigate to the page of PCL
Xamarin.Forms.Application.Current.MainPage.Navigation.PushAsync(new PostPage());
</code>```

At last, as @Pratik suggested, if you want to create a native page/ view for Android platform, use PageRenderer or ViewRenderer to do so.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to load a Xamarin Forms page from an Android Notification. I am really lost on the android side of this, and most of my code has been pieced together from tutorials and blog posts. However nothing really seems to cover exactly this scenario.

I have implemented a very simple interface with dependency service to create the notification with an intent...

[assembly: Xamarin.Forms.Dependency(typeof(QuoteNotification))]

namespace QuoteApp.Droid
{

    class QuoteNotification : IQuoteNotification
    {

        public void Notify(string title, string message)
        {

            //type needs to be derived from java, not xamarin.forms
            Intent LoadPostPage = new Intent(Forms.Context, typeof(DroidToForms));
            const int pendingIntentId = 0;
            PendingIntent pendingIntent =
                PendingIntent.GetActivity(Forms.Context, pendingIntentId, LoadPostPage, PendingIntentFlags.OneShot);

            Notification.Builder builder = new Notification.Builder(Forms.Context)
                .SetContentIntent(pendingIntent)
                .SetAutoCancel(true)

                     .SetContentTitle(title)
                     .SetContentText(message)
                     .SetSmallIcon(Resource.Drawable.icon);

            // Build the notification:
            Notification notification = builder.Build();

            // Get the notification manager:
            NotificationManager notificationManager =
                Forms.Context.GetSystemService(Context.NotificationService) as NotificationManager;

            // Publish the notification:
            const int notificationId = 0;
            notificationManager.Notify(notificationId, notification);
        }
    }
}

this calls an activity -

namespace QuoteApp.Droid
{
    [Activity(Label = "QuoteApp", MainLauncher = true)]
    class DroidToForms : Activity
    {
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            StartActivity(typeof(XFPostPage));
            //Xamarin.Forms.Application.Current.MainPage.Navigation.PushAsync(new QuoteApp.PostPage());

        }
    }
}

which in turn calls this forms page, all the code here has been in Xamarin.Android project

namespace QuoteApp.Droid
{

        ///
        /// This is a Xamarin.Forms screen. It MUST:
        /// * inherit from ANdroidActivity
        /// * call Forms.Init()
        /// * use LoadApplication()
        ///
        [Activity(Label = "XFPostPage", MainLauncher = true) ]
        public class XFPostPage : Xamarin.Forms.Platform.Android.FormsApplicationActivity
        {
            protected override void OnCreate(Bundle bundle)
            {
                base.OnCreate(bundle);

                Xamarin.Forms.Forms.Init(this, bundle);

            //LoadApplication( new App() ); //how do i send to PostPage.xaml ??

            Xamarin.Forms.Application.Current.MainPage.Navigation.PushAsync(new QuoteApp.PostPage());
        }
        }
    }

this gives the following error in logcat

07-04 17:51:44.494  7668  7668 E AndroidRuntime: Caused by: android.runtime.JavaProxyThrowable: System.NullReferenceException: Object reference not set to an instance of an object
07-04 17:51:44.494  7668  7668 E AndroidRuntime:   at QuoteApp.Droid.XFPostPage.OnCreate (Android.OS.Bundle bundle) [0x00016] in <ab64801c0fb24acb8457c1d1202cc143>:0
07-04 17:51:44.494  7668  7668 E AndroidRuntime:   at Android.App.Activity.n_OnCreate_Landroid_os_Bundle_ (System.IntPtr jnienv, System.IntPtr native__this, System.IntPtr native_savedInstanceState) [0x0000f] in <d855bac285f44dda8a0d8510b679b1e2>:0
07-04 17:51:44.494  7668  7668 E AndroidRuntime:   at (wrapper dynamic-method) System.Object:2780fa42-5931-40d3-8d14-a642f1a3025c (intptr,intptr,intptr)
07-04 17:51:44.494  7668  7668 E AndroidRuntime:        at md543d03747be5a5b03a21a2a23b8ba191a.XFPostPage.n_onCreate(Native Method)
07-04 17:51:44.494  7668  7668 E AndroidRuntime:        at md543d03747be5a5b03a21a2a23b8ba191a.XFPostPage.onCreate(XFPostPage.java:29)
07-04 17:51:44.494  7668  7668 E AndroidRuntime:        at android.app.Activity.performCreate(Activity.java:6237)
07-04 17:51:44.494  7668  7668 E AndroidRuntime:        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
07-04 17:51:44.494  7668  7668 E AndroidRuntime:        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
07-04 17:51:44.494  7668  7668 E AndroidRuntime:        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
07-04 17:51:44.494  7668  7668 E AndroidRuntime:        at android.app.ActivityThread.-wrap11(ActivityThread.java)
07-04 17:51:44.494  7668  7668 E AndroidRuntime:        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
07-04 17:51:44.494  7668  7668 E AndroidRuntime:        at android.os.Handler.dispatchMessage(Handler.java:102)
07-04 17:51:44.494  7668  7668 E AndroidRuntime:        at android.os.Looper.loop(Looper.java:148)
07-04 17:51:44.494  7668  7668 E AndroidRuntime:        at android.app.ActivityThread.main(ActivityThread.java:5417)
07-04 17:51:44.494  7668  7668 E AndroidRuntime:        ... 3 more

I have tried a bunch of different ideas all with different runtime errors, my understanding of the Xamarin.Android workings are very limited. eventually i will be using the notification with AlarmManager and further information will be sent to PostPage.Xaml. At the moment i'm just lost at exactly where this is going wrong though?!

Any Help would be hugely appreciated, thanks in advance.

Body:
Problem is with your code Intent LoadPostPage = new Intent(Forms.Context, typeof(DroidToForms));.

For Android platform of XF project, it only has one Activity, which is MainActivity, or pages of XF are rendered based on this MainActivity.

So you may change you code like this:

Intent intent = new Intent(context, typeof(MainActivity));
intent.PutExtras(valuesForActivity);

PendingIntent resultPendingIntent = PendingIntent.GetActivity(Xamarin.Forms.Forms.Context, 0, intent, PendingIntentFlags.OneShot);

Then in your OnCreate method of MainActivity:

//navigate to the page of PCL
Xamarin.Forms.Application.Current.MainPage.Navigation.PushAsync(new PostPage());

At last, as @Pratik suggested, if you want to create a native page/ view for Android platform, use PageRenderer or ViewRenderer to do so.


问:
path works from root only
I read through all I could find on the topic, but nothing worked for me. I run PHP 5.3.29.

I have this PHP code, that works from root, but not from folders:

```<code>  // Fetch latest poster
  $base_url = 'posters';
  $newest_mtime = 0;
  if ($handle = opendir($base_url)) {
  while (false !== ($latestFile = readdir($handle))) {
      if (($latestFile != '.') && ($latestFile != '..')) {
         $mtime = filemtime("$base_url/$latestFile");
         if ($mtime > $newest_mtime) {
            $newest_mtime = $mtime;
            $show_file = "$base_url/$latestFile";
         }
      }
    }
  }
  // Show latest poster
  $show_name = basename(trim($show_file, ".jpg"));
  echo '
  <a href="/' . $show_file . '">
  <img src="' . $show_file . '" class="jpg" width="150" alt="latest poster" title="' . $show_name . '">
  </a>';
</code>```

I'd love to just add a slash to get root-relative paths, but that doesn't work in PHP.

This is the site with this issue:

http://flamencopeko.net (here there is no issue)

http://flamencopeko.net/disco_pages/sundays.php (this one has the issue)

答:
Big thanks again.

From root that resulted in:

Warning: opendir(/home/flamenco/public_htmlposters) [function.opendir]: failed to open dir: No such file or directory in /home/flamenco/public_html/left_test.php on line 40

so I changed

```<code>base_url = getcwd() . 'posters';
</code>```

to

```<code>base_url = getcwd() . '/posters';
</code>```

This shows the poster, but it links to:

http://flamencopeko.net/http://flamencopeko.net/posters/08-05-2017_01.jpg

From sub-folder it results in:

Warning: opendir(/home/flamenco/public_html/disco_pages/posters) [function.opendir]: failed to open dir: No such file or directory in /home/flamenco/public_html/disco_pages/left_test2.php on line 12

I was able to write a messy work-around, that works, just now:

```<code>$path = getcwd();
if ($path == '/home/flamenco/public_html') {
  $base_url = 'posters';
  $newest_mtime = 0;
  if ($handle = opendir($base_url)) {
  while (false !== ($latestFile = readdir($handle))) {
      if (($latestFile != '.') && ($latestFile != '..')) {
         $mtime = filemtime("$base_url/$latestFile");
         if ($mtime > $newest_mtime) {
            $newest_mtime = $mtime;
            $show_file = "$base_url/$latestFile";
         }
      }
    }
  }
  // Show latest poster
  $show_name = basename(trim($show_file, ".jpg"));
  echo '
  <a href="/' . $show_file . '">
  <img src="' . $show_file . '" class="jpg" width="150" alt="latest poster" title="' . $show_name . '">
  </a>';
  }
  else
  {
  $base_url = '../posters';
  $newest_mtime = 0;
  if ($handle = opendir($base_url)) {
  while (false !== ($latestFile = readdir($handle))) {
      if (($latestFile != '.') && ($latestFile != '..')) {
         $mtime = filemtime("$base_url/$latestFile");
         if ($mtime > $newest_mtime) {
            $newest_mtime = $mtime;
            $show_file = "$base_url/$latestFile";
         }
      }
    }
  }
  // Show latest poster
  $show_name = basename(trim($show_file, ".jpg"));
  echo '
  <a href="/' . $show_file . '">
  <img src="' . $show_file . '" class="jpg" width="150" alt="latest poster" title="' . $show_name . '">
  </a>';
  }
</code>```

Title: path works from root only

Body:
I read through all I could find on the topic, but nothing worked for me. I run PHP 5.3.29.

I have this PHP code, that works from root, but not from folders:

  // Fetch latest poster
  $base_url = 'posters';
  $newest_mtime = 0;
  if ($handle = opendir($base_url)) {
  while (false !== ($latestFile = readdir($handle))) {
      if (($latestFile != '.') && ($latestFile != '..')) {
         $mtime = filemtime("$base_url/$latestFile");
         if ($mtime > $newest_mtime) {
            $newest_mtime = $mtime;
            $show_file = "$base_url/$latestFile";
         }
      }
    }
  }
  // Show latest poster
  $show_name = basename(trim($show_file, ".jpg"));
  echo '

  ';

I'd love to just add a slash to get root-relative paths, but that doesn't work in PHP.

This is the site with this issue:

http://flamencopeko.net (here there is no issue)

http://flamencopeko.net/disco_pages/sundays.php (this one has the issue)

Body:
Big thanks again.

From root that resulted in:

Warning: opendir(/home/flamenco/public_htmlposters) [function.opendir]: failed to open dir: No such file or directory in /home/flamenco/public_html/left_test.php on line 40

so I changed

base_url = getcwd() . 'posters';

to

base_url = getcwd() . '/posters';

This shows the poster, but it links to:

http://flamencopeko.net/http://flamencopeko.net/posters/08-05-2017_01.jpg

From sub-folder it results in:

Warning: opendir(/home/flamenco/public_html/disco_pages/posters) [function.opendir]: failed to open dir: No such file or directory in /home/flamenco/public_html/disco_pages/left_test2.php on line 12

I was able to write a messy work-around, that works, just now:

$path = getcwd();
if ($path == '/home/flamenco/public_html') {
  $base_url = 'posters';
  $newest_mtime = 0;
  if ($handle = opendir($base_url)) {
  while (false !== ($latestFile = readdir($handle))) {
      if (($latestFile != '.') && ($latestFile != '..')) {
         $mtime = filemtime("$base_url/$latestFile");
         if ($mtime > $newest_mtime) {
            $newest_mtime = $mtime;
            $show_file = "$base_url/$latestFile";
         }
      }
    }
  }
  // Show latest poster
  $show_name = basename(trim($show_file, ".jpg"));
  echo '
  <a href="/' . $show_file . '">
  <img src="' . $show_file . '" class="jpg" width="150" alt="latest poster" title="' . $show_name . '">
  </a>';
  }
  else
  {
  $base_url = '../posters';
  $newest_mtime = 0;
  if ($handle = opendir($base_url)) {
  while (false !== ($latestFile = readdir($handle))) {
      if (($latestFile != '.') && ($latestFile != '..')) {
         $mtime = filemtime("$base_url/$latestFile");
         if ($mtime > $newest_mtime) {
            $newest_mtime = $mtime;
            $show_file = "$base_url/$latestFile";
         }
      }
    }
  }
  // Show latest poster
  $show_name = basename(trim($show_file, ".jpg"));
  echo '
  <a href="/' . $show_file . '">
  <img src="' . $show_file . '" class="jpg" width="150" alt="latest poster" title="' . $show_name . '">
  </a>';
  }


问:
Nothing Happens after Clicking the Submit Button
With the generated code, one of my entities can not be saved. On the 8080 port, the form remains the same and nothing shows up on the console after I click the submit button. On the 9000 port, however, a log message shows fetching for related entities from the database after I click the button. There isn't an error message on any console, including the browser's console. In the dialog.html file, the first line is as follows:

```<code>    <form name="editForm" role="form" novalidate ng-submit="vm.save()"
 show-validation>
</code>```

so I insert the log in the first line of the Javascript function of the dialog.controller.js:

```<code>function save () {
    console.log("Saving ...");
...
</code>```

How should I resolve it?

The structure of the controller is the followings:

```<code>(function() {
'use strict';

angular
    .module('myApp')
    .controller('MyDialogController', MyDialogController);

SkuSDialogController.$inject = ['$timeout', '$scope', '$stateParams', '$uibModalInstance', 'DataUtils', 'entity', 'MyEntity', 'MyRelatedEntity'];

function SkuSDialogController ($timeout, $scope, $stateParams, $uibModalInstance, DataUtils, entity, MyEntity, MyRelatedEntity) {
    var vm = this;

    ...
    vm.clear = clear;
    vm.datePickerOpenStatus = {};
    vm.openCalendar = openCalendar;
    vm.byteSize = DataUtils.byteSize;
    vm.openFile = DataUtils.openFile;
    vm.save = save;
    ...

    $timeout(function (){
        angular.element('.form-group:eq(1)>input').focus();
    });

    function clear () {
        $uibModalInstance.dismiss('cancel');
    }

    function save () {
    console.log("Saving ...");
        vm.isSaving = true;
        if (vm.myEntity.id !== null) {
            MyEntity.update(vm.myEntity, onSaveSuccess, onSaveError);
        } else {
            MyEntity.save(vm.myEntity, onSaveSuccess, onSaveError);
        }
    }

    function onSaveSuccess (result) {
        $scope.$emit('myApp:myEntityUpdate', result);
        $uibModalInstance.close(result);
        vm.isSaving = false;
    }

    function onSaveError () {
        vm.isSaving = false;
    }

    vm.datePickerOpenStatus.activeStartDate = false;
    vm.datePickerOpenStatus.activeEndDate = false;

    function openCalendar (date) {
        vm.datePickerOpenStatus[date] = true;
    }
  }
})();
</code>```

答:
Try this in your controller,</p>

```<code> vm.save = function() {
console.log("Saving ...");
    vm.isSaving = true;
    if (vm.myEntity.id !== null) {
        MyEntity.update(vm.myEntity, onSaveSuccess, onSaveError);
    } else {
        MyEntity.save(vm.myEntity, onSaveSuccess, onSaveError);
    }
}
</code>```

Body:
With the generated code, one of my entities can not be saved. On the 8080 port, the form remains the same and nothing shows up on the console after I click the submit button. On the 9000 port, however, a log message shows fetching for related entities from the database after I click the button. There isn't an error message on any console, including the browser's console. In the dialog.html file, the first line is as follows:

    <form name="editForm" role="form" novalidate ng-submit="vm.save()"
 show-validation>

so I insert the log in the first line of the Javascript function of the dialog.controller.js:

function save () {
    console.log("Saving ...");
...

How should I resolve it?

The structure of the controller is the followings:

(function() {
'use strict';

angular
    .module('myApp')
    .controller('MyDialogController', MyDialogController);

SkuSDialogController.$inject = ['$timeout', '$scope', '$stateParams', '$uibModalInstance', 'DataUtils', 'entity', 'MyEntity', 'MyRelatedEntity'];

function SkuSDialogController ($timeout, $scope, $stateParams, $uibModalInstance, DataUtils, entity, MyEntity, MyRelatedEntity) {
    var vm = this;

    ...
    vm.clear = clear;
    vm.datePickerOpenStatus = {};
    vm.openCalendar = openCalendar;
    vm.byteSize = DataUtils.byteSize;
    vm.openFile = DataUtils.openFile;
    vm.save = save;
    ...

    $timeout(function (){
        angular.element('.form-group:eq(1)>input').focus();
    });

    function clear () {
        $uibModalInstance.dismiss('cancel');
    }

    function save () {
    console.log("Saving ...");
        vm.isSaving = true;
        if (vm.myEntity.id !== null) {
            MyEntity.update(vm.myEntity, onSaveSuccess, onSaveError);
        } else {
            MyEntity.save(vm.myEntity, onSaveSuccess, onSaveError);
        }
    }

    function onSaveSuccess (result) {
        $scope.$emit('myApp:myEntityUpdate', result);
        $uibModalInstance.close(result);
        vm.isSaving = false;
    }

    function onSaveError () {
        vm.isSaving = false;
    }

    vm.datePickerOpenStatus.activeStartDate = false;
    vm.datePickerOpenStatus.activeEndDate = false;

    function openCalendar (date) {
        vm.datePickerOpenStatus[date] = true;
    }
  }
})();

Body:
Try this in your controller,

 vm.save = function() {
console.log("Saving ...");
    vm.isSaving = true;
    if (vm.myEntity.id !== null) {
        MyEntity.update(vm.myEntity, onSaveSuccess, onSaveError);
    } else {
        MyEntity.save(vm.myEntity, onSaveSuccess, onSaveError);
    }
}


问:
How to iterate through members of a class
This:

```<code>class Loan
    def initialize(amount, interest)
        @amount = amount
        @interest = interest
    end
end

loan1 = Loan.new(100, 0.1)

Loan.each do |amount, interest|
    debt = debt + amount + (amount*interest)
end
</code>```

won't work because it's attempting to iterate over a class rather than an array or hash. Is there a away to iterate over all of the instances of a class?

答:
Ruby doesn't automatically keep references to objects you create, it's your responsibility to write code that does. For example, when creating a new Loan instance you get an object. If you want an each method at the class level you'll need to track these by writing code that captures them:

```<code>class Loan
  def self.all
    # Lazy-initialize the collection to an empty array
    @all ||= [ ]
  end

  def self.each(&proc)
    @all.each(&proc)
  end

  def initialize(amount, interest)
    @amount = amount
    @interest = interest

    # Force-add this loan to the collection
    Loan.all << self
  end
end
</code>```

You must manually retain these because otherwise the garbage collector will pick up and destroy any un-referenced objects when they fall out of scope.

Body:
This:

class Loan
    def initialize(amount, interest)
        @amount = amount
        @interest = interest
    end
end

loan1 = Loan.new(100, 0.1)

Loan.each do |amount, interest|
    debt = debt + amount + (amount*interest)
end

won't work because it's attempting to iterate over a class rather than an array or hash. Is there a away to iterate over all of the instances of a class?

Body:
Ruby doesn't automatically keep references to objects you create, it's your responsibility to write code that does. For example, when creating a new Loan instance you get an object. If you want an each method at the class level you'll need to track these by writing code that captures them:

class Loan
  def self.all
    # Lazy-initialize the collection to an empty array
    @all ||= [ ]
  end

  def self.each(&proc)
    @all.each(&proc)
  end

  def initialize(amount, interest)
    @amount = amount
    @interest = interest

    # Force-add this loan to the collection
    Loan.all << self
  end
end

You must manually retain these because otherwise the garbage collector will pick up and destroy any un-referenced objects when they fall out of scope.


问:
SSIS Error - The AcquireConnection method call to the connection manager failed with error code 0xC0202009
I have scoured high and low for a solution but nothing has helped. To be clear, I am not developing a SSIS package, I am simply trying to run one that has already proven to work. This issue is server specific.

We have an ETL Job that builds a repository from a production database for reporting purposes. I built a new VM server with bigger resources to ease the burden of this process on our larger databases.

Server is Windows Server 2012R2. Running SQL Server 2014 SP2 CU05 with integration services and really not much else. This job runs through the agent on 15 minute intervals. The first few times it runs, it does actually start building some of the data in the destination database, but this error persists with every new batch that is executed, whether manually or on schedule, and after a while it just stops moving data.

Here is the base error:

SSIS Error Code DTS_E_CANNOTACQVIRECONNECTIONFROMCONNECTIONMANAGER. The AcquireConnection method call to the connection manager "ETL_Framework" failed with error code 0xCO202009.
  There may be error messages posted before this with more information on why the AcquireConnection method call failed.

Said error messages before the AcquireConnection call:

SSIS Error Code DTS_E OLEDBERROR. An OLE DB error has occurred. Error code: 0x80004005.
  Source: "Microsoft SQL Server Native Client 11.0" Description: "Login timeout expired".
  Source. "Microsoft SQL Server Native Client 11.0" Description: "A network-related or instance-specific error has occurred while establishing a connection to SQL Server. Server is not found or not accessible. Check if instance name is correct and if SQL Server is configured to allow remote connections. For more information see SQL Server Books Online."
  Source. "Microsoft SQL Server Native Client 11.0" Description: "Named Pipes Provider: Could not open a connection to SQL Server [2]. ".

One important thing to bear in mind is that both the source and destination databases are on this same server that the job is running from, meaning everything is localized and the domain service account is a local admin on the server and a sysadmin on SQL.

I have Named Pipes and TCP/IP protocols enabled on SQL. The service account running the job is a domain user that I have used hundreds of times on other servers setup for this same kind of work with never having a problem. I can connect via SSMS to this server from other VMs using the FQDN of the instance (i.e. SZDB.somewhere.com\SQL2014), and vice-versa.

So, open to suggestions here. There has to be something I am missing in the setup of my server.

答: We found that the solution in this case was to install a default instance of SQL Server. I previously only had a named instance running. As soon as I went through SQL setup and installed the default instance (i.e. MSSQLSERVER), the error on our ETL job went away and our data warehouse continued to build without any further issues. Proved to be the solution on two other servers as well that were exhibiting the same issue. </p>

ContentLicense: CC BY-SA 4.0


问:
Store data from HTML radio buttons into Javascript Array
Could anyone please provide a JSFiddle Demo for me with an implementation?
I have the following HTML code below. I want to record in an array in javascript the the radio button I clicked. Say if I choose the first radio button id="white1", the array should store the integer '1'. I am a beginner in javascript so any help would be appreciated!

```<code><body>
    <div id="container">
      <div id="overlay">
        <form action="">
          <input type="radio" name="white" value="1" id="radio1"/>
          <input type="radio" name="white" value="2" id="radio2"/>
          <input type="radio" name="white" value="3" id="radio3"/>
          <input type="radio" name="white" value="4" id="radio4"/>
          <input type="button" id="continue" value="Continue"/>
        </form>
      </div>
      <div id="base">
        <video controls>
          <source src="videos/event_0_Junli_Standing_20150322_181647_00_0.6.mp4" type="video/mp4">
          Your browser does not support the video tag.
        </video>
      </div>
    </div>
    <script>
      var arr = []
      document.getElementById("continue").addEventListener("click", function() {
          var cbChecked = document.querySelectorAll('[name="white"]:checked')
          if (cbChecked != null) {
            arr.push(cbChecked.value)
          }
          console.log(arr)
      })
    </script>
  </body>
</code>```

答:
You can use document.querySelector() to directly select whichever radio button is currently :checked:

var arr = []

document.getElementById("continue").addEventListener("click", function() {
  var cbChecked = document.querySelector('[name="white"]:checked')

  if (cbChecked != null) {
    arr.push(cbChecked.value)
  }

  console.log(arr)
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form action="">
  <input type="radio" name="white" value="1" />
  <input type="radio" name="white" value="2" />
  <input type="radio" name="white" value="3" />
  <input type="radio" name="white" value="4" />
  <input type="button" id="continue" value="Continue"/>
</form></code>```

.querySelector() returns null if no elements match the supplied selector, otherwise it returns the first element that matches (in your case there would be only one). Note that according to MDN, the :checked selector won't work in browsers older than IE9, in which case you might have to use document.querySelectorAll('[name="white"]') or some other element selection method to get a list of all of the radios and then loop through them till you find the one that is checked.

Note also that I've changed your HTML to a more "normal" implementation of radio buttons, that is, giving them all the same name attribute so that they work as a group, and giving them a value attribute to distinguish between them. They don't need id attributes - at least, not for this.

Body:
Could anyone please provide a JSFiddle Demo for me with an implementation?
I have the following HTML code below. I want to record in an array in javascript the the radio button I clicked. Say if I choose the first radio button id="white1", the array should store the integer '1'. I am a beginner in javascript so any help would be appreciated!

        <form action="">
          <input type="radio" name="white" value="1" id="radio1"/>
          <input type="radio" name="white" value="2" id="radio2"/>
          <input type="radio" name="white" value="3" id="radio3"/>
          <input type="radio" name="white" value="4" id="radio4"/>
          <input type="button" id="continue" value="Continue"/>
        </form>

        <video controls>
          <source src="videos/event_0_Junli_Standing_20150322_181647_00_0.6.mp4" type="video/mp4">
          Your browser does not support the video tag.
        </video>

Body:
You can use document.querySelector() to directly select whichever radio button is currently :checked:

var arr = []

document.getElementById("continue").addEventListener("click", function() {
  var cbChecked = document.querySelector('[name="white"]:checked')

  if (cbChecked != null) {
    arr.push(cbChecked.value)
  }

  console.log(arr)
})

<form action="">
  <input type="radio" name="white" value="1" />
  <input type="radio" name="white" value="2" />
  <input type="radio" name="white" value="3" />
  <input type="radio" name="white" value="4" />
  <input type="button" id="continue" value="Continue"/>
</form>

.querySelector() returns null if no elements match the supplied selector, otherwise it returns the first element that matches (in your case there would be only one). Note that according to MDN, the :checked selector won't work in browsers older than IE9, in which case you might have to use document.querySelectorAll('[name="white"]') or some other element selection method to get a list of all of the radios and then loop through them till you find the one that is checked.

Note also that I've changed your HTML to a more "normal" implementation of radio buttons, that is, giving them all the same name attribute so that they work as a group, and giving them a value attribute to distinguish between them. They don't need id attributes - at least, not for this.


问:
How do you disable animations at the system level for an android device/emulator using adb with API 23?
Based on reading, the values window_animation_scale, transition_animation_scale and animator_duration_scale need to be set to 0

The following works for API 22 but not for API 23:

```<code>adb shell settings put global window_animation_scale 0.0
</code>```

Even the below command did not work for API 23

```<code>adb shell content update --uri content://settings/system --bind value:s:0.0 --where 'name="window_animation_scale"'
</code>```

We want to disable animations to prevent flaky visual test failures only.
We do not want to introduce this logic in the application and hence want to apply it at the system level rather than through the application.

答:
You can execute the following adb commands to disable the animations:

```<code>adb shell settings put global window_animation_scale 0
adb shell settings put global transition_animation_scale 0
adb shell settings put global animator_duration_scale 0
</code>```

Also, you could take a look at this repo

Build the project and download the generated .apk file and follow the instructions mentioned in that project to disable the animations and you should have a smooth sailing afterwards. You could also download the same .apk file from a lot of other sources (go google!).

Once you have the .apk file then issue the following commands:

```<code> adb install -r android_emulator_hacks.apk
 adb shell pm grant no.finn.android_emulator_hacks android.permission.SET_ANIMATION_SCALE
 adb shell am start -n no.finn.android_emulator_hacks/no.finn.android_emulator_hacks.HackActivity
</code>```

Body:
Based on reading, the values window_animation_scale, transition_animation_scale and animator_duration_scale need to be set to 0

The following works for API 22 but not for API 23:

adb shell settings put global window_animation_scale 0.0

Even the below command did not work for API 23

adb shell content update --uri content://settings/system --bind value:s:0.0 --where 'name="window_animation_scale"'

We want to disable animations to prevent flaky visual test failures only.
We do not want to introduce this logic in the application and hence want to apply it at the system level rather than through the application.

Body:
You can execute the following adb commands to disable the animations:

adb shell settings put global window_animation_scale 0
adb shell settings put global transition_animation_scale 0
adb shell settings put global animator_duration_scale 0

Also, you could take a look at this repo

Build the project and download the generated .apk file and follow the instructions mentioned in that project to disable the animations and you should have a smooth sailing afterwards. You could also download the same .apk file from a lot of other sources (go google!).

Once you have the .apk file then issue the following commands:

 adb install -r android_emulator_hacks.apk
 adb shell pm grant no.finn.android_emulator_hacks android.permission.SET_ANIMATION_SCALE
 adb shell am start -n no.finn.android_emulator_hacks/no.finn.android_emulator_hacks.HackActivity


问:
Is it possible to declare a scanner variable inside a method in Java to read keyboard input?
```<code>final int MAX_ROUNDS = 5;
String name1,name1;

Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter player1 name: ");
name1 = keyboard.nextLine();
System.out.println("Please enter player2 name: ");
name2 = keyboard.nextLine();
Player player1 = new Player(name1);
Player player2 = new Player(name2);

Dealer dealer = new Dealer();

    for(int count = 1; count <=MAX_ROUNDS; count++)
    {
        System.out.println("------------------");
        System.out.ptintf("Round : %d",count);
        dealer.rollDice();
        player1.makeGuess();
        player2.makeGuess();
        roundResults();
</code>```

excerpt from the makeGuess method which belongs to the  Player class.

```<code>public void makeGuess()
{
Scanner keyboard = new Scanner(System.in)

System.out.printf("Please guess 'even' or 'odd' "+
        "%s.", name);
String answer = keyboard.nextLine();

        if(answer.equalsIgnoreCase("even")
            guess = "Cho (even)";
        else
            guess = "Han (odd);
  }
</code>```

I am not being prompted anything when the method executes I cannot understand why I did not include everything for the program. was just wondering if anyone eye balling this code could see something obvious otherwise, i will just take out the guess submission.

答: While I cannot find anything wrong with your code, If I had to take an educated guess, the dealer.dice() method probably has an infinite loop, which is causing your whole program to malfunction</p>

Body:
final int MAX_ROUNDS = 5;
String name1,name1;

Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter player1 name: ");
name1 = keyboard.nextLine();
System.out.println("Please enter player2 name: ");
name2 = keyboard.nextLine();
Player player1 = new Player(name1);
Player player2 = new Player(name2);

Dealer dealer = new Dealer();

    for(int count = 1; count <=MAX_ROUNDS; count++)
    {
        System.out.println("------------------");
        System.out.ptintf("Round : %d",count);
        dealer.rollDice();
        player1.makeGuess();
        player2.makeGuess();
        roundResults();

excerpt from the makeGuess method which belongs to the  Player class.

public void makeGuess()
{
Scanner keyboard = new Scanner(System.in)

System.out.printf("Please guess 'even' or 'odd' "+
        "%s.", name);
String answer = keyboard.nextLine();

        if(answer.equalsIgnoreCase("even")
            guess = "Cho (even)";
        else
            guess = "Han (odd);
  }

I am not being prompted anything when the method executes I cannot understand why I did not include everything for the program. was just wondering if anyone eye balling this code could see something obvious otherwise, i will just take out the guess submission.


问:
Change order np.argmax index is taken from
I have three matrixes as such:

```<code>one = np.empty((5,5))
one[:] = 10

two = np.empty((5,5))
two[:] = 10

three = np.empty((5,5))
three[:] = 2
</code>```

I then stack them:

```<code>stacked = np.dstack([one, two, three])
</code>```

and finally determine the index with the maximum values:

```<code>t_max = np.argmax(stacked, axis=2)
</code>```

I now want to determine the maximum value, but with a caveat.  If there are multiple depths with identical max values (as in my example) I want to return the index from the largest depth.

As it is now t_max returns:

```<code>[[0 0 0 0 0]
 [0 0 0 0 0]
 [0 0 0 0 0]
 [0 0 0 0 0]
 [0 0 0 0 0]]
</code>```

but I would like to return:

```<code>[[1 1 1 1 1]
 [1 1 1 1 1]
 [1 1 1 1 1]
 [1 1 1 1 1]
 [1 1 1 1 1]]
</code>```

since the second depth has identical maximum values as the first, but has a larger depth as well.

EDIT:

I think I can just do np.flip(stacked, axis=2) first, but maybe this isn't the best way.

答:
For efficiency purposes, I would suggest using a flipped view and then getting the indices after subtracting from the last axis length, like so -

```<code>stacked.shape[-1] - stacked[...,::-1].argmax(-1) - 1
</code>```

Another approach without flipping and a bit longer one, would be with comparison against the maximum value, using cumulative summation and then using argmax to catch the last ones of those matches, like so -

```<code>(stacked == stacked.max(-1,keepdims=1)).cumsum(-1).argmax(-1)
</code>```

Sample run -

```<code>In [29]: stacked = np.random.randint(0,3,(2,5,3))

In [30]: stacked
Out[30]:
array([[[2, 1, 2],
        [1, 1, 1],
        [1, 1, 1],
        [1, 1, 0],
        [1, 2, 2]],

       [[2, 1, 1],
        [1, 1, 1],
        [1, 2, 2],
        [1, 1, 0],
        [1, 0, 0]]])

In [31]: stacked.shape[-1] - stacked[...,::-1].argmax(-1) - 1
Out[31]:
array([[2, 2, 2, 1, 2],
       [0, 2, 2, 1, 0]])

In [32]: (stacked == stacked.max(-1,keepdims=1)).cumsum(-1).argmax(-1)
Out[32]:
array([[2, 2, 2, 1, 2],
       [0, 2, 2, 1, 0]])
</code>```

Runtime test -

```<code>In [33]: stacked = np.random.randint(0,10,(1000,1000,100))

In [34]: %timeit stacked.shape[-1] - stacked[...,::-1].argmax(-1) - 1
1 loop, best of 3: 281 ms per loop

In [35]: %timeit (stacked == stacked.max(-1,keepdims=1)).cumsum(-1).argmax(-1)
1 loop, best of 3: 659 ms per loop
</code>```

Body:
I have three matrixes as such:

one = np.empty((5,5))
one[:] = 10

two = np.empty((5,5))
two[:] = 10

three = np.empty((5,5))
three[:] = 2

I then stack them:

stacked = np.dstack([one, two, three])

and finally determine the index with the maximum values:

t_max = np.argmax(stacked, axis=2)

I now want to determine the maximum value, but with a caveat.  If there are multiple depths with identical max values (as in my example) I want to return the index from the largest depth.

As it is now t_max returns:

[[0 0 0 0 0]
 [0 0 0 0 0]
 [0 0 0 0 0]
 [0 0 0 0 0]
 [0 0 0 0 0]]

but I would like to return:

[[1 1 1 1 1]
 [1 1 1 1 1]
 [1 1 1 1 1]
 [1 1 1 1 1]
 [1 1 1 1 1]]

since the second depth has identical maximum values as the first, but has a larger depth as well.

EDIT:

I think I can just do np.flip(stacked, axis=2) first, but maybe this isn't the best way.

Body:
For efficiency purposes, I would suggest using a flipped view and then getting the indices after subtracting from the last axis length, like so -

stacked.shape[-1] - stacked[...,::-1].argmax(-1) - 1

Another approach without flipping and a bit longer one, would be with comparison against the maximum value, using cumulative summation and then using argmax to catch the last ones of those matches, like so -

(stacked == stacked.max(-1,keepdims=1)).cumsum(-1).argmax(-1)

Sample run -

In [29]: stacked = np.random.randint(0,3,(2,5,3))

In [30]: stacked
Out[30]:
array([[[2, 1, 2],
        [1, 1, 1],
        [1, 1, 1],
        [1, 1, 0],
        [1, 2, 2]],

       [[2, 1, 1],
        [1, 1, 1],
        [1, 2, 2],
        [1, 1, 0],
        [1, 0, 0]]])

In [31]: stacked.shape[-1] - stacked[...,::-1].argmax(-1) - 1
Out[31]:
array([[2, 2, 2, 1, 2],
       [0, 2, 2, 1, 0]])

In [32]: (stacked == stacked.max(-1,keepdims=1)).cumsum(-1).argmax(-1)
Out[32]:
array([[2, 2, 2, 1, 2],
       [0, 2, 2, 1, 0]])

Runtime test -

In [33]: stacked = np.random.randint(0,10,(1000,1000,100))

In [34]: %timeit stacked.shape[-1] - stacked[...,::-1].argmax(-1) - 1
1 loop, best of 3: 281 ms per loop

In [35]: %timeit (stacked == stacked.max(-1,keepdims=1)).cumsum(-1).argmax(-1)
1 loop, best of 3: 659 ms per loop


问:
Why do I get a segmentation fault when calling a CUDA kernel directly from a shared library?
The way I tried it (see question title) it compiled, but I get a segmentation fault. So is it me, CMake or CUDA which doesn't support direct kernel calls from a shared library? The solution doesn't have to be with CMake

Further details:

I have the following file structure:

testKernel.hpp

```<code>__global__ void kernelTest( float x );
void callKernel( float x );
</code>```

testKernel.cu

```<code>#include "testKernel.hpp"

__global__ void kernelTest( float x ) {}
void callKernel( float x ) { kernelTest<<<1,1>>>( x ); }
</code>```

useKernel.cu

```<code>#include <cstdio>
#include "testKernel.hpp"

int main( void )
{
    kernelTest<<<1,1>>>( 3.0f );
    //callKernel( 3.0f );
    printf("OK\n");
    return 0;
}
</code>```

CMakeLists.txt

```<code>cmake_minimum_required(VERSION 3.3.1)
project(testKernelCall)
find_package(CUDA REQUIRED)

cuda_add_library( ${PROJECT_NAME} SHARED testKernel.cu testKernel.hpp )
target_link_libraries( ${PROJECT_NAME} ${CUDA_LIBRARIES} )

cuda_add_executable("useKernel" useKernel.cu)
target_link_libraries("useKernel" ${PROJECT_NAME})
</code>```

Compiling and running this with:

```<code>cmake .; make && ./useKernel
</code>```

results in a segmentation fault. The backtrace with gdb is:

```<code>Program received signal SIGSEGV, Segmentation fault.
0x00007ffff75726bd in cudart::configData::addArgument(void const*, unsigned long, unsigned long) ()
   from ./libtestKernelCall.so
(gdb) bt
#0  0x00007ffff75726bd in cudart::configData::addArgument(void const*, unsigned long, unsigned long) ()
   from ./libtestKernelCall.so
#1  0x00007ffff7562eb7 in cudart::cudaApiSetupArgument(void const*, unsigned long, unsigned long) ()
   from ./libtestKernelCall.so
#2  0x00007ffff7591ca2 in cudaSetupArgument ()
   from ./libtestKernelCall.so
#3  0x00007ffff7556125 in __device_stub__Z10kernelTestf (__par0=3)
    at /tmp/tmpxft_00003900_00000000-4_testKernel.cudafe1.stub.c:7
#4  0x00007ffff755616c in kernelTest (__cuda_0=3) at ./testKernel.cu:2
#5  0x000000000040280e in main () at ./useKernel.cu:6
</code>```

Tested with (which means the segfault appears in those setups):

Setup 1

cmake 3.4.1

CUDA 7.0.27

g++ 4.9.2

Debian

Setup 2

cmake 3.3.1

CUDA 6.5.14

g++ 4.7.1

There are two ways to solve this error:

change SHARED to STATIC in CMakeList.txt

use the wrapper function callKernel instead of calling the kernel directly

I don't really know how to build a CUDA shared library without CMake. I know how to build a CUDA static library, but that case seems to work with CMake, so I didn't test it without CMake.

Here are the relevant CMake commands I got with make VERBOSE=1. I changed absolute paths to relative paths, where possible, but I wasn't sure about all these library paths. Putting these commands in a file and sourcing that file compiles the shared library and the program correctly and "correctly" leads to the segmentation fault. I also added command because for me nvcc is aliased with the `-ccbin`` option.

make.sh

```<code>command nvcc "./testKernel.cu" -c -o "./testKernel.cu.o" -ccbin /usr/bin/cc -m64 -DtestKernelCall_EXPORTS -Xcompiler ,\"-fPIC\",\"-g\" -DNVCC -I/opt/cuda-7.0/include -I/opt/cuda-7.0/include
/usr/bin/c++  -fPIC   -shared -Wl,-soname,libtestKernelCall.so -o libtestKernelCall.so ./testKernel.cu.o /opt/cuda-7.0/lib64/libcudart_static.a -lpthread /usr/lib/x86_64-linux-gnu/librt.so /usr/lib/x86_64-linux-gnu/libdl.so /opt/cuda-7.0/lib64/libcudart_static.a -lpthread /usr/lib/x86_64-linux-gnu/librt.so /usr/lib/x86_64-linux-gnu/libdl.so
command nvcc "./useKernel.cu" -c -o "./useKernel.cu.o" -ccbin /usr/bin/cc -m64 -Xcompiler ,\"-g\" -DNVCC -I/opt/cuda-7.0/include -I/opt/cuda-7.0/include
/usr/bin/c++ ./useKernel.cu.o  -o useKernel -rdynamic /opt/cuda-7.0/lib64/libcudart_static.a -lpthread /usr/lib/x86_64-linux-gnu/librt.so /usr/lib/x86_64-linux-gnu/libdl.so libtestKernelCall.so /opt/cuda-7.0/lib64/libcudart_static.a -lpthread /usr/lib/x86_64-linux-gnu/librt.so /usr/lib/x86_64-linux-gnu/libdl.so -Wl,-rpath,"."
</code>```

答: put set(CUDA_USE_STATIC_CUDA_RUNTIME OFF) before find_package(CUDA REQUIRED) will do the job equivalent to set(CUDA_LIBRARIES "${CUDA_TOOLKIT_ROOT_DIR}/lib64/libcudart.so")

Body:
The way I tried it (see question title) it compiled, but I get a segmentation fault. So is it me, CMake or CUDA which doesn't support direct kernel calls from a shared library? The solution doesn't have to be with CMake

Further details:

I have the following file structure:

testKernel.hpp

__global__ void kernelTest( float x );
void callKernel( float x );

testKernel.cu

#include "testKernel.hpp"

__global__ void kernelTest( float x ) {}
void callKernel( float x ) { kernelTest<<<1,1>>>( x ); }

useKernel.cu

#include <cstdio>
#include "testKernel.hpp"

int main( void )
{
    kernelTest<<<1,1>>>( 3.0f );
    //callKernel( 3.0f );
    printf("OK\n");
    return 0;
}

CMakeLists.txt

cmake_minimum_required(VERSION 3.3.1)
project(testKernelCall)
find_package(CUDA REQUIRED)

cuda_add_library( ${PROJECT_NAME} SHARED testKernel.cu testKernel.hpp )
target_link_libraries( ${PROJECT_NAME} ${CUDA_LIBRARIES} )

cuda_add_executable("useKernel" useKernel.cu)
target_link_libraries("useKernel" ${PROJECT_NAME})

Compiling and running this with:

cmake .; make && ./useKernel

results in a segmentation fault. The backtrace with gdb is:

Program received signal SIGSEGV, Segmentation fault.
0x00007ffff75726bd in cudart::configData::addArgument(void const*, unsigned long, unsigned long) ()
   from ./libtestKernelCall.so
(gdb) bt
#0  0x00007ffff75726bd in cudart::configData::addArgument(void const*, unsigned long, unsigned long) ()
   from ./libtestKernelCall.so
#1  0x00007ffff7562eb7 in cudart::cudaApiSetupArgument(void const*, unsigned long, unsigned long) ()
   from ./libtestKernelCall.so
#2  0x00007ffff7591ca2 in cudaSetupArgument ()
   from ./libtestKernelCall.so
#3  0x00007ffff7556125 in __device_stub__Z10kernelTestf (__par0=3)
    at /tmp/tmpxft_00003900_00000000-4_testKernel.cudafe1.stub.c:7
#4  0x00007ffff755616c in kernelTest (__cuda_0=3) at ./testKernel.cu:2
#5  0x000000000040280e in main () at ./useKernel.cu:6

Tested with (which means the segfault appears in those setups):

Setup 1

cmake 3.4.1

CUDA 7.0.27

g++ 4.9.2

Debian

Setup 2

cmake 3.3.1

CUDA 6.5.14

g++ 4.7.1

There are two ways to solve this error:

change SHARED to STATIC in CMakeList.txt

use the wrapper function callKernel instead of calling the kernel directly

I don't really know how to build a CUDA shared library without CMake. I know how to build a CUDA static library, but that case seems to work with CMake, so I didn't test it without CMake.

Here are the relevant CMake commands I got with make VERBOSE=1. I changed absolute paths to relative paths, where possible, but I wasn't sure about all these library paths. Putting these commands in a file and sourcing that file compiles the shared library and the program correctly and "correctly" leads to the segmentation fault. I also added command because for me nvcc is aliased with the `-ccbin`` option.

make.sh

command nvcc "./testKernel.cu" -c -o "./testKernel.cu.o" -ccbin /usr/bin/cc -m64 -DtestKernelCall_EXPORTS -Xcompiler ,\"-fPIC\",\"-g\" -DNVCC -I/opt/cuda-7.0/include -I/opt/cuda-7.0/include
/usr/bin/c++  -fPIC   -shared -Wl,-soname,libtestKernelCall.so -o libtestKernelCall.so ./testKernel.cu.o /opt/cuda-7.0/lib64/libcudart_static.a -lpthread /usr/lib/x86_64-linux-gnu/librt.so /usr/lib/x86_64-linux-gnu/libdl.so /opt/cuda-7.0/lib64/libcudart_static.a -lpthread /usr/lib/x86_64-linux-gnu/librt.so /usr/lib/x86_64-linux-gnu/libdl.so
command nvcc "./useKernel.cu" -c -o "./useKernel.cu.o" -ccbin /usr/bin/cc -m64 -Xcompiler ,\"-g\" -DNVCC -I/opt/cuda-7.0/include -I/opt/cuda-7.0/include
/usr/bin/c++ ./useKernel.cu.o  -o useKernel -rdynamic /opt/cuda-7.0/lib64/libcudart_static.a -lpthread /usr/lib/x86_64-linux-gnu/librt.so /usr/lib/x86_64-linux-gnu/libdl.so libtestKernelCall.so /opt/cuda-7.0/lib64/libcudart_static.a -lpthread /usr/lib/x86_64-linux-gnu/librt.so /usr/lib/x86_64-linux-gnu/libdl.so -Wl,-rpath,"."


问:
Likens the background color of the label and the sheet column
How to write code for the background color of a label with the color source of the color cells. for example:</p>

```<code>Cmb.backcolor=sheets("sheet1").cells(2,2)
</code>```

答:
Use this:</p>

```<code>Label1.BackColor = sheets("sheet1").cells(2,2).DisplayFormat.Interior.Color
</code>```

Body:
How to write code for the background color of a label with the color source of the color cells. for example:

Cmb.backcolor=sheets("sheet1").cells(2,2)

Body:
Use this:

Label1.BackColor = sheets("sheet1").cells(2,2).DisplayFormat.Interior.Color


问:
if grep value greater than 1000 then
I want to grep "priority=" in a file where the value of "priority=" is greater than 1000.

I tried something like this:

```<code>if grep -q "priority=[ >1000 ]" file; then
    echo "[!] Unnatural priority"
fi
</code>```

e.g. <intent-filter android:priority="2147483647">

答:
awk will make this easy:

```<code>$ cat file | awk -F '=' '$2 > 1000 {print $0}'
</code>```

Assuming that there's only one = on each line of course.

Title: if grep value greater than 1000 then

Body:
I want to grep "priority=" in a file where the value of "priority=" is greater than 1000.

I tried something like this:

if grep -q "priority=[ >1000 ]" file; then
    echo "[!] Unnatural priority"
fi

e.g. <intent-filter android:priority="2147483647">

Body:
awk will make this easy:

$ cat file | awk -F '=' '$2 > 1000 {print $0}'

Assuming that there's only one = on each line of course.


问:
Login Form freezes when SQL Server is not running
I have a Login Form that checks AutoLogInStatus in database. If the AutoLogInStatus is set to true the main form will show if false the login form will show.

This the code in my Form_Load events:

```<code> if (Convert.ToBoolean(UserAutoLogon()) == true)
    {
          this.Hide();
          frmMain.Show();
    }
 else
    {
          this.Show();
    }
</code>```

All works good, except if the SQL server is not running. The login forms shows with all white  and it freezes.

How will I handle this?

Thanks.

答:
Consider using async-await so that your UI thread is not blocked while the SQL connection is being established:

```<code>  private async void Form_Load(object sender, EventArgs e)
    {
        var frmMain = new frmMain();

        var result = await UserAutoLogon();

        if (result == true)
        {
            this.Hide();
            frmMain.Show();
        }
        else
        {
            this.Show();
        }
    }

 private Task<bool> UserAutoLogon()
    {
        return Task.Run(() =>
        {
            Thread.Sleep(10000); // Db connection delay
            return true;
        });
    }
</code>```

UPDATE

The UserAutoLogon() method's implementation was given so that it simulates the delay - you may use await connection.OpenAsync() as suggested by Scott Chamberlain in the comments.

Body:
I have a Login Form that checks AutoLogInStatus in database. If the AutoLogInStatus is set to true the main form will show if false the login form will show.

This the code in my Form_Load events:

 if (Convert.ToBoolean(UserAutoLogon()) == true)
    {
          this.Hide();
          frmMain.Show();
    }
 else
    {
          this.Show();
    }

All works good, except if the SQL server is not running. The login forms shows with all white  and it freezes.

How will I handle this?

Thanks.

Body:
Consider using async-await so that your UI thread is not blocked while the SQL connection is being established:

  private async void Form_Load(object sender, EventArgs e)
    {
        var frmMain = new frmMain();

        var result = await UserAutoLogon();

        if (result == true)
        {
            this.Hide();
            frmMain.Show();
        }
        else
        {
            this.Show();
        }
    }

 private Task<bool> UserAutoLogon()
    {
        return Task.Run(() =>
        {
            Thread.Sleep(10000); // Db connection delay
            return true;
        });
    }

UPDATE

The UserAutoLogon() method's implementation was given so that it simulates the delay - you may use await connection.OpenAsync() as suggested by Scott Chamberlain in the comments.


问:
sql case statement in where?
```<code>select t1.customer_code as doc_num, CONVERT(VARCHAR,t2.created_on,103) as doc_date,
t2.sap_cardcode as sap_doc_num ,t2.void_flg,t2.status_ind,t2.err_msg
from customer t1
inner join sap_customer t2 on t1.id = t2.customer_id
where t2.status_ind = case when @test = 'todo' then t2.status_ind='1' else t2.status_ind='0' END
</code>```

Above is the select statement that i need to do, based on the where statement i need to pass a param to determine which want should it execute.
Status Ind = 1 or Status Ind = 0

答:
I have modified the Case part a little in your query. Hope this helps:

```<code>select t1.customer_code as doc_num, CONVERT(VARCHAR,t2.created_on,103) as doc_date,t2.sap_cardcode as sap_doc_num ,t2.void_flg,t2.status_ind,t2.err_msg
from customer t1
inner join sap_customer t2 on t1.id = t2.customer_id
where t2.status_ind = case when @test = 'todo' then '1' else '0' END
</code>```

OR you can use case like below:

```<code>where t2.status_ind = case @test when 'todo' then '1' else '0' END
</code>```

Title: sql case statement in where?

Body:
select t1.customer_code as doc_num, CONVERT(VARCHAR,t2.created_on,103) as doc_date,
t2.sap_cardcode as sap_doc_num ,t2.void_flg,t2.status_ind,t2.err_msg
from customer t1
inner join sap_customer t2 on t1.id = t2.customer_id
where t2.status_ind = case when @test = 'todo' then t2.status_ind='1' else t2.status_ind='0' END

Above is the select statement that i need to do, based on the where statement i need to pass a param to determine which want should it execute.
Status Ind = 1 or Status Ind = 0

Body:
I have modified the Case part a little in your query. Hope this helps:

select t1.customer_code as doc_num, CONVERT(VARCHAR,t2.created_on,103) as doc_date,t2.sap_cardcode as sap_doc_num ,t2.void_flg,t2.status_ind,t2.err_msg
from customer t1
inner join sap_customer t2 on t1.id = t2.customer_id
where t2.status_ind = case when @test = 'todo' then '1' else '0' END

OR you can use case like below:

where t2.status_ind = case @test when 'todo' then '1' else '0' END


问:
Remove any leading Blankspace inside an Input
<input type='text'>

for an input like this, How can i dynamically delete any whitespace leading in it for example if someone typed '_______' __ as spaces, it won't read and act like an empty value '' How can i prevent that and check it in both JQuery and PHP.

I've tried

if($_POST['input'] != ' ' && !empty($_POST['input'])){run query}

But if i used two spaces instead of one the query will work

答:
In PHP you should apply trim() and empty() function:

```<code>if(!empty(trim($_POST['name']))){
//run
}
</code>```

In JQuery apply $.trim().

Body:
In PHP you should apply trim() and empty() function:

if(!empty(trim($_POST['name']))){
//run
}

In JQuery apply $.trim().


问:
Pay with Debit or Credit Card - The button is not displayed
Here is a tutorial: https://www.codexworld.com/paypal-standard-payment-gateway-integration-php/
Below is a button. If I click the paypal gate will appear. There is also a button: "Pay with Debit or Credit Card"
When I write a code according to the tutorial, I do not have a paypal button on the sandbox: "Pay with Debit or Credit Card"
I only have the button: "Create an Account"
Where is the problem?</p>

答:
Kindly check if your PayPal account is Business/Premier.

```<code>Then check for the PayPal account optional setting is "on or off". It should be on.

Login to PayPal
Go to your Account Profile.
Select: My Selling Tools
Under: Selling Online
Locate: Website Preferences
Click on: Update
Locate: PayPal Account Optional
Click:  On
Click: Save
</code>```

Please contact PayPal customer care support and check your country is supported with guest checkout or not.

Body:
Kindly check if your PayPal account is Business/Premier.

Then check for the PayPal account optional setting is "on or off". It should be on.

Login to PayPal
Go to your Account Profile.
Select: My Selling Tools
Under: Selling Online
Locate: Website Preferences
Click on: Update
Locate: PayPal Account Optional
Click:  On
Click: Save

Please contact PayPal customer care support and check your country is supported with guest checkout or not.


问:
UIApplicationExitsOnSuspend anything else I'm missing?
So I know this has been beaten to death but I still can't figure out a solution.

I have my UIApplicationExitsOnSuspend set to <true/> in the Info.plist and still both in the simulator as well as on an iPhone 4 device, the app goes into standby instead of terminating?

Any ideas of what else could one do to get it to terminate?  Perhaps are there methods that I need to remove from the app delegate? Any ideas?

答: I had the same problem, when you add the key UIApplicationExitsOnSuspend, make sure you right click on it and select value type > Boolean. Otherwise Xcode will ignore it. Hope it helps</p>

ContentLicense: CC BY-SA 2.5


问:
Creating a SWT.MOZILLA browser on Windows 64 bit and SWT 4.3
I'm trying to create an SWT Browser widget of the SWT.MOZILLA type under windows 8 64Bit with SWT 4.3 64Bit.

According to this, SWT 4.3 should support 64 Bit version on XULRunner 10.x or 24.x

So, I have downloaded both the 10.x and 24.x 64 versions from here and unzipped under c:\xulrunner10 and c:\xulrunner24 respectively.

If I start my java app pointing to xulrunner10 (using the VM argument -Dorg.eclipse.swt.browser.XULRunnerPath=C:\xulrunner10) it works, however if I try with xulrunner24 (using the VM argument -Dorg.eclipse.swt.browser.XULRunnerPath=C:\xulrunner24) I get the follwoing error:

```<code>Exception in thread "main" org.eclipse.swt.SWTError: XPCOM error 0x80004005
    at org.eclipse.swt.browser.Mozilla.error(Unknown Source)
    at org.eclipse.swt.browser.Mozilla.initXULRunner(Unknown Source)
    at org.eclipse.swt.browser.Mozilla.create(Unknown Source)
    at org.eclipse.swt.browser.Browser.<init>(Unknown Source)
</code>```

I also noticed that I get the same error if pointing to unexisting directory, however the folder c:\xulrunner24 exists and contains all the files as well as xulrunner.exe.

How can I make xulrunner 24.x 64bit embeddable in my swt 4.3 app?

答:
I realize that this question is old and already has an accepted answer, but the download location mentioned in the question is no longer valid (http://wiki.mozilla-x86-64.com/Download), and the same issue has been posted about several times.

With 64-bit 4.3 SWT I was able to fix this exception by using XULRunner version 1.9.2.25 runtimes. Originally I found the download from here: https://osdn.net/projects/sfnet_runawfe/downloads/SRC%20and%20BIN%20files/extras/xulrunner-1.9.2.25-win64.zip/

However, I have also re-hosted it as xulrunner-1.9.2.25.en-US.win64.zip.

Full explanation posted in my answer here: https://stackoverflow.com/a/44848877/3300205

Body:
I'm trying to create an SWT Browser widget of the SWT.MOZILLA type under windows 8 64Bit with SWT 4.3 64Bit.

According to this, SWT 4.3 should support 64 Bit version on XULRunner 10.x or 24.x

So, I have downloaded both the 10.x and 24.x 64 versions from here and unzipped under c:\xulrunner10 and c:\xulrunner24 respectively.

If I start my java app pointing to xulrunner10 (using the VM argument -Dorg.eclipse.swt.browser.XULRunnerPath=C:\xulrunner10) it works, however if I try with xulrunner24 (using the VM argument -Dorg.eclipse.swt.browser.XULRunnerPath=C:\xulrunner24) I get the follwoing error:

Exception in thread "main" org.eclipse.swt.SWTError: XPCOM error 0x80004005
    at org.eclipse.swt.browser.Mozilla.error(Unknown Source)
    at org.eclipse.swt.browser.Mozilla.initXULRunner(Unknown Source)
    at org.eclipse.swt.browser.Mozilla.create(Unknown Source)
    at org.eclipse.swt.browser.Browser.<init>(Unknown Source)

I also noticed that I get the same error if pointing to unexisting directory, however the folder c:\xulrunner24 exists and contains all the files as well as xulrunner.exe.

How can I make xulrunner 24.x 64bit embeddable in my swt 4.3 app?


问:
How to add or subtract very large numbers without bigint in C#?
So let me start by saying that I'm a newbie with little to moderate knowledge about C#.

Coming to the topic: I need to make a program that is able to add/subtract very large integers. Initially, used BigInt only to find out it's not allowed. There should be a logical workaround for this? I have an idea which is using "elementary school method" where you add each digit starting from right to left.

I made a string which I split into char array and added each digit from right to left(GetUpperBound-i). But it doesn't seem to work.

My Code:

```<code>string s, s2;
char[] c_arr, c_arr2;
int i, erg;

s = "1234";
s2 = "5678";
c_arr = s.ToCharArray();
c_arr2 = s2.ToCharArray();
for (i = 0; i <= c_arr.GetUpperBound(0); i++)
{
    erg = c_arr[c_arr.GetUpperBound(0)-i]+c_arr2[c_arr2.GetUpperBound(0)-i];
    Console.Write(erg);
}

Console.ReadKey();
</code>```

答:
```<code>    public static int[] addTwoNumbers(string s1, string s2)
    {

        char[] num1 = s1.ToCharArray();
        char[] num2 = s2.ToCharArray();
        int sum = 0;
        int carry = 0;
        int size = (s1.Length > s2.Length) ? s1.Length + 1 : s2.Length + 1;
        int[] result = new int[size];
        int index = size - 1;
        int num1index = num1.Length - 1;
        int num2index = num2.Length - 1;

        while (true)
        {
            if (num1index >= 0 && num2index >= 0)
            {
                sum = (num1[num1index]-'0') + (num2[num2index]-'0') + carry;
            }
            else if(num1index< 0 && num2index >= 0)
            {
                sum = (num2[num2index]-'0') + carry;
            }
            else if (num1index >= 0 && num2index < 0)
            {
                sum = (num1[num1index]-'0') + carry;
            }
            else { break; }

            carry = sum /10;
            result[index] = sum % 10;
            index--;
            num1index--;
            num2index--;
        }

            if(carry>0)
            {
                result[index] = carry;
            }

        return result;
    }
</code>```

Body:
So let me start by saying that I'm a newbie with little to moderate knowledge about C#.

Coming to the topic: I need to make a program that is able to add/subtract very large integers. Initially, used BigInt only to find out it's not allowed. There should be a logical workaround for this? I have an idea which is using "elementary school method" where you add each digit starting from right to left.

I made a string which I split into char array and added each digit from right to left(GetUpperBound-i). But it doesn't seem to work.

My Code:

string s, s2;
char[] c_arr, c_arr2;
int i, erg;

s = "1234";
s2 = "5678";
c_arr = s.ToCharArray();
c_arr2 = s2.ToCharArray();
for (i = 0; i <= c_arr.GetUpperBound(0); i++)
{
    erg = c_arr[c_arr.GetUpperBound(0)-i]+c_arr2[c_arr2.GetUpperBound(0)-i];
    Console.Write(erg);
}

Console.ReadKey();


问:
Codeigniter db_where in 3 joined tables
So this code is a combination of 3 table joined, now i want to filter the query where only the request that a user can have is his/her own request and not from other user.. the problem is in where clause i have duplicated.</p>

```<code>$this->db->order_by('loanrequest.ApplicationNo', 'DESC');
        $query = $this->db->get('loanrequest','loanapplication','user');
        $this->db->join('loanapplication','loanrequest.ApplicationNo = loanapplication.ApplicationNo');
        $this->db->join('user', 'user.userId = loanapplication.userId');
        $this->db->where('loanapplication.userId', $this->session->userdata('userId'));
        $this->db->where('loanapplication.ApplicationNo', 'loanrequest.ApplicationNo');
        return $query->result_array();
</code>```

答:
```<code>$query = $this->db->select('*')
            ->from('loanapplication')
            ->join('loanrequest', 'loanrequest.ApplicationNo  = loanapplication.ApplicationNo', 'left')
            ->join('user', 'user.userId  = loanapplication.userId', 'left')
            ->where_in('loanapplication.userId',$this->session->userdata('userId'))
            ->order_by('loanrequest.ApplicationNo', 'DESC');
            $result = $query->get();

           echo $this->db->last_query();exit; //use this to print your query so that you can get the actual issue
           if ($result->num_rows() > 0) {
            return $result->result_array();
          } else
            return '';
</code>```

Title: Codeigniter db_where in 3 joined tables

Body:
So this code is a combination of 3 table joined, now i want to filter the query where only the request that a user can have is his/her own request and not from other user.. the problem is in where clause i have duplicated.

$this->db->order_by('loanrequest.ApplicationNo', 'DESC');
        $query = $this->db->get('loanrequest','loanapplication','user');
        $this->db->join('loanapplication','loanrequest.ApplicationNo = loanapplication.ApplicationNo');
        $this->db->join('user', 'user.userId = loanapplication.userId');
        $this->db->where('loanapplication.userId', $this->session->userdata('userId'));
        $this->db->where('loanapplication.ApplicationNo', 'loanrequest.ApplicationNo');
        return $query->result_array();


答:
Your CASE statement needs to be modified

```<code>case when @test = 'todo' then '1' else '0' END
</code>```

Since, you are going to compare where t2.status_ind. So, you need to return some value from CASE instead of setting it.

Title: sql case statement in where?

Body:
Your CASE statement needs to be modified

case when @test = 'todo' then '1' else '0' END

Since, you are going to compare where t2.status_ind. So, you need to return some value from CASE instead of setting it.


问:
IBM Watson Knowledge Studio - Annotating negative / negated mentions
When annotating mentions using Watson Knowledge Studio, one often has examples such as:

"I received no feedback from in response to ..." or "I have never received any feedback".

If I were to annotate the mention "feedback" in the above, it is an "negative" example, i.e. it refers to something that did not happen.  There are two possibilities when creating a custom entity type system:

(a) Include the negator in the mention, i.e. "no feedback" is the mention.  This clearly does not work in the second example, since there is no negator before the work feedback.

(b) Do not include the negator in the mention, but add an attribute to the mention using the mention class NEG (https://www.ibm.com/watson/developercloud/doc/wks/wks_t_ts_intro.shtml)

Clearly option (b) is the more general approach.  However, once a model is trained one needs to be able to extract entities unseen examples.  For this you have to use the Natural Language Understanding API (https://www.ibm.com/watson/developercloud/doc/natural-language-understanding/#entities).

When one uses this API, there doesn't seem to be a way to extract the mention attributes, i.e. when I do entity extraction, how do I see that a mention is negated or not, since using approach (b) you do not include the negator as part of the mention?

答: as I mentioned here IBM Watson Knowledge Studio - Entities with Role attribute and extracting it from NLU api currently mention attributes such as negation are not extractable in NLU. </p>


问:
Getting 403 error in AngularJS project using IIS Express
In AngularJS, I am trying to set up a home page which lists the events (json files) in my app/data/event folder.  The controller, EventListController, looks like this:

```<code>'use strict';

eventsApp.controller('EventListController',
    function EventListController($scope, $location, eventData) {
        $scope.events = eventData.getAllEvents();
})
</code>```

The EventData service looks like this:

```<code>eventsApp.factory('eventData', function ($resource) {
    var resource = $resource('/app/data/event/:id', { id: '@id' }, { "getAll": { method: "GET", isArray: true, params: { something: "foo" } } });
    return {
        getEvent: function (eventId) {
            return resource.get({
                id: eventId
            });
        },
        typeOf: function (obj) {
            return {}.toString.call(obj).split(' ')[1].slice(0, -1).toLowerCase();
        },
        getAllEvents: function () {
            return resource.query();
        },
        save: function (event) {
            return resource.save(event);
        }
    };
</code>```

EventList.html looks like this:

```<code><div>
    <h1>Events</h1>
    <hr/>
    <hr/>
    <ul class="thumbnails">
        <li ng-repeat="event in events|orderBy:sortorder" class="span5">
            <event-thumbnail/>
        </li>
    </ul>

</div>
</code>```

My routes look like this:

```<code>'use strict';

var eventsApp = angular.module('eventsApp', ['ngResource', 'ngRoute'])
    .config(function ($routeProvider) {
        $routeProvider.when('/newEvent',
            {
                templateUrl: '/app/templates/NewEvent.html',
                controller: 'EditEventController'
            });
        $routeProvider.when('/eventDetails/:eventId',
           {
               templateUrl: '/app/templates/EventDetails.html',
               controller: 'EventController'
           });
        $routeProvider.when('/profile',
            {
                templateUrl: '/app/templates/EditProfile.html',
                controller: 'EditProfileController'
            });
        $routeProvider.when('/events',
            {
                templateUrl: '/app/templates/EventList.html',
                controller: 'EventListController'
            });
        $routeProvider.otherwise({ redirectTo: '/events' });
    });
</code>```

The WebAPI controller (in a separate WebAPI project), EventController.cs, looks like this:

```<code>public class EventController : ApiController
    {
       public JToken Get(string id = null)
        {
            if (id==null)
            {
                return GetAllJsonEventsAsArray();
            }
            return GetSingleJsonFile(id);
        }
private JArray GetAllJsonEventsAsArray()
        {
            var path = System.Web.Hosting.HostingEnvironment.MapPath("/");
            var contents = "";
            foreach (var file in System.IO.Directory.GetFiles(path + "..app/data/event/"))
            {
                contents += System.IO.File.ReadAllText(file) + ",";
            }

            return JArray.Parse("[" + contents.Substring(0, contents.Length - 1) + "]");
        }
</code>```

Finally, the WebApiConfig.cs looks like this:

```<code>public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            // Configure Web API to use only bearer token authentication.
            config.SuppressDefaultHostAuthentication();
            config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
</code>```

When I attempt to access http://localhost:49403/app/#/events I get the error:  GET http://localhost:49403/app/data/event/ 403 (Forbidden)

Can anyone help with this?  Any help will be much appreciated.

答: The configuration/system.webServer/directoryBrowse@enabled in the IIS web site was set to False by default.  Setting it to True enabled my app to browse the directory.</p>

Body:
In AngularJS, I am trying to set up a home page which lists the events (json files) in my app/data/event folder.  The controller, EventListController, looks like this:

'use strict';

eventsApp.controller('EventListController',
    function EventListController($scope, $location, eventData) {
        $scope.events = eventData.getAllEvents();
})

The EventData service looks like this:

eventsApp.factory('eventData', function ($resource) {
    var resource = $resource('/app/data/event/:id', { id: '@id' }, { "getAll": { method: "GET", isArray: true, params: { something: "foo" } } });
    return {
        getEvent: function (eventId) {
            return resource.get({
                id: eventId
            });
        },
        typeOf: function (obj) {
            return {}.toString.call(obj).split(' ')[1].slice(0, -1).toLowerCase();
        },
        getAllEvents: function () {
            return resource.query();
        },
        save: function (event) {
            return resource.save(event);
        }
    };

EventList.html looks like this:

Events

            <event-thumbnail/>

My routes look like this:

'use strict';

var eventsApp = angular.module('eventsApp', ['ngResource', 'ngRoute'])
    .config(function ($routeProvider) {
        $routeProvider.when('/newEvent',
            {
                templateUrl: '/app/templates/NewEvent.html',
                controller: 'EditEventController'
            });
        $routeProvider.when('/eventDetails/:eventId',
           {
               templateUrl: '/app/templates/EventDetails.html',
               controller: 'EventController'
           });
        $routeProvider.when('/profile',
            {
                templateUrl: '/app/templates/EditProfile.html',
                controller: 'EditProfileController'
            });
        $routeProvider.when('/events',
            {
                templateUrl: '/app/templates/EventList.html',
                controller: 'EventListController'
            });
        $routeProvider.otherwise({ redirectTo: '/events' });
    });

The WebAPI controller (in a separate WebAPI project), EventController.cs, looks like this:

public class EventController : ApiController
    {
       public JToken Get(string id = null)
        {
            if (id==null)
            {
                return GetAllJsonEventsAsArray();
            }
            return GetSingleJsonFile(id);
        }
private JArray GetAllJsonEventsAsArray()
        {
            var path = System.Web.Hosting.HostingEnvironment.MapPath("/");
            var contents = "";
            foreach (var file in System.IO.Directory.GetFiles(path + "..app/data/event/"))
            {
                contents += System.IO.File.ReadAllText(file) + ",";
            }

            return JArray.Parse("[" + contents.Substring(0, contents.Length - 1) + "]");
        }

Finally, the WebApiConfig.cs looks like this:

public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            // Configure Web API to use only bearer token authentication.
            config.SuppressDefaultHostAuthentication();
            config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }

When I attempt to access http://localhost:49403/app/#/events I get the error:  GET http://localhost:49403/app/data/event/ 403 (Forbidden)

Can anyone help with this?  Any help will be much appreciated.


问:
Wordpress: After login in the backend I am getting redirected to the frontend
I have a problem login to the backend. If I enter the user and the pw in the backend, I am getting redirected to the frontend instead of the backend (dashboard). There, on the frontend, I see my login credentials like name and so on.

I am using the wp lockout plugin.

When the website was running on my local computer, it worked.
Then I installed the website on a host server and the site is now online. Everything works but just not the login.

Why I am not getting redirected to the dasbhoard backend?

答: The Problem Was Something Was Blocking You And Redirecting You To Front-End So Just Do One Thing Go To File Manager In C panel And Select Your Directory Of Wordpress And Go To Plug-ins Folder And Check How Many Plug-ins Do You Have And Firstly Delete which You Have Said Then See Weather Its Allowing Or Not And If Yes Then Try Installing That Plug-in That Suites Your Needs (FULL BACKUP IS HIGHLY RECOMMENDED )</p>