问:
activity switching not working without finish() method
My code is as shown below:

TableActivity.java

```<code>public class TableActivity extends AppCompatActivity {

 @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_table_selection);
        itemName = (TextView) findViewById(R.id.itemName);
        foodMenuLayout = (LinearLayout) findViewById(R.id.foodMenuLayout);
        drinkMenuLayout = (LinearLayout) findViewById(R.id.drinksMenuLayout);
        tableNo = (TextView) findViewById(R.id.tableNo);
        foodMenu = (TextView) findViewById(R.id.foodMenu);
        drinksMenu = (TextView) findViewById(R.id.drinksMenu);
        tapLayout = (LinearLayout) findViewById(R.id.tapLayout);
        foodImage = (ImageView) findViewById(R.id.foodImage);
        drinkImage = (ImageView) findViewById(R.id.drinkImage);

        getFoodTruckInfo();

        tapLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tableList = TableList.getInstance(MyCart.getInstance().getTableNo());
                tableList.setItemListener(TableActivity.this);
                tableList.setCancelable(false);
                tableList.show(getSupportFragmentManager(), null);
            }
        });

        setFontStyle();

        foodMenuLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(tableNo.getText().toString().trim())) {
                    Toast.makeText(TableActivity.this, "Please select table", Toast.LENGTH_SHORT).show();
                } else {
                    lauchItemActivity();
                }
            }
        });

        drinkMenuLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(tableNo.getText().toString().trim())) {
                    Toast.makeText(TableActivity.this, "Please select table", Toast.LENGTH_SHORT).show();
                } else {
                    lauchDrinksActivity();
                }
            }
        });
    }

    private void lauchItemActivity() {
        FoodtruckInfo foodtruckInfo = new FoodtruckInfo();
        foodtruckInfo.setFoodTruckName(foodTruck.getFoodTruckName());
        foodtruckInfo.setFoodTruckImage(foodTruck.getFoodTruckLogo());
        foodtruckInfo.setFoodTruckId(foodTruck.getFoodTruckId());
        foodtruckInfo.setOrderStatus(foodTruck.getFoodTruckOpenStatus());
        Intent intent = new Intent(TableActivity.this, FoodTruckItemsActivity.class);
        intent.putExtra(Consts.FOODTRUCK_INFO, foodtruckInfo);
        intent.putExtra(Consts.IS_SEARCH, false);
        intent.putExtra(Consts.IS_DRINKS, false);
        intent.putParcelableArrayListExtra(Consts.FOODTRUCK_ITEM, (ArrayList<? extends Parcelable>) foodTruck.getFoodTruckItemList());

        startActivityForResult(intent, Consts.ITEMS_ACTIVITY);
    }

    private void lauchDrinksActivity() {
        FoodtruckInfo foodtruckInfo = new FoodtruckInfo();
        foodtruckInfo.setFoodTruckName(foodTruck.getFoodTruckName());
        foodtruckInfo.setFoodTruckImage(foodTruck.getFoodTruckLogo());
        foodtruckInfo.setFoodTruckId(foodTruck.getFoodTruckId());
        foodtruckInfo.setOrderStatus(foodTruck.getFoodTruckOpenStatus());
        Intent intent = new Intent(TableActivity.this, FoodTruckDrinksActivity.class);
        intent.putExtra(Consts.FOODTRUCK_INFO, foodtruckInfo);
        intent.putExtra(Consts.IS_SEARCH, false);
        intent.putExtra(Consts.IS_DRINKS, true);
        intent.putParcelableArrayListExtra(Consts.FOODTRUCK_ITEM, (ArrayList<? extends Parcelable>) foodTruck.getFoodTruckDrinkList());
        startActivityForResult(intent, Consts.DRINKS_ACTIVITY);
    }
@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == Consts.ITEMS_ACTIVITY) {
                lauchDrinksActivity();
            } else if (requestCode == Consts.DRINKS_ACTIVITY) {
                lauchItemActivity();
            }
        }
    }
}
</code>```

FoodTruckItemsActivity.java

```<code>public class FoodTruckItemsActivity extends AppCompatActivity implements
        FoodTruckItemsAdapter.OnItemClickListener, FoodTruckItemFragment.FoodTruckItemListener,
        ViewPager.OnPageChangeListener, View.OnClickListener {

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

 routeView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                routeToAnotherMenu();
            }
        });
    }

 private void routeToAnotherMenu() {
        setResult(Activity.RESULT_OK);

    }
}
</code>```

FoodTruckItemsActivity.java and FoodTruckDrinksActivity.java are identical. So what I want here is if I press routeView, it should switch from FoodTruckItemsActivity.java to FoodTruckDrinksActivity.java and vice-versa.
  For that I have written routeToAnotherMenu() method. Now problem here is if I do not write finish() inside routeToAnotherMenu, it does not load another activity. But if I write finish after setResult() then it works perfectly.

The main  reason why I do not prefer finish() inside that method because it will erase the data . So is there any way through which I can do it without writing finish() method?

答:
The setResult() should be used before starting another activity, or if you want the activity that launched this activity to collect the result after you exit (calling finish).Here is a link to docs

I could imagine 2 ways for the result you want to achieve:

1)Decouple the "data" you want to mantain after the finish() (for example, into a singleton) from the current activity.
If FoodTruckItemsActivity.java and FoodTruckDrinksActivity.java are almost identical, they should inherite from a common parent, so you will ease the job.
It's better also because "TableActivity" starts always a new intent every time, so it is useless to not call the finish.

2)You could also change approach converting FoodTruckItemsActivity and FoodTruckDrinksActivity to Fragments, swapping them into a fragment container of "TableActivity" and sharing the data into the activity.

Body:
My code is as shown below:

TableActivity.java

public class TableActivity extends AppCompatActivity {

 @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_table_selection);
        itemName = (TextView) findViewById(R.id.itemName);
        foodMenuLayout = (LinearLayout) findViewById(R.id.foodMenuLayout);
        drinkMenuLayout = (LinearLayout) findViewById(R.id.drinksMenuLayout);
        tableNo = (TextView) findViewById(R.id.tableNo);
        foodMenu = (TextView) findViewById(R.id.foodMenu);
        drinksMenu = (TextView) findViewById(R.id.drinksMenu);
        tapLayout = (LinearLayout) findViewById(R.id.tapLayout);
        foodImage = (ImageView) findViewById(R.id.foodImage);
        drinkImage = (ImageView) findViewById(R.id.drinkImage);

        getFoodTruckInfo();

        tapLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tableList = TableList.getInstance(MyCart.getInstance().getTableNo());
                tableList.setItemListener(TableActivity.this);
                tableList.setCancelable(false);
                tableList.show(getSupportFragmentManager(), null);
            }
        });

        setFontStyle();

        foodMenuLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(tableNo.getText().toString().trim())) {
                    Toast.makeText(TableActivity.this, "Please select table", Toast.LENGTH_SHORT).show();
                } else {
                    lauchItemActivity();
                }
            }
        });

        drinkMenuLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(tableNo.getText().toString().trim())) {
                    Toast.makeText(TableActivity.this, "Please select table", Toast.LENGTH_SHORT).show();
                } else {
                    lauchDrinksActivity();
                }
            }
        });
    }

    private void lauchItemActivity() {
        FoodtruckInfo foodtruckInfo = new FoodtruckInfo();
        foodtruckInfo.setFoodTruckName(foodTruck.getFoodTruckName());
        foodtruckInfo.setFoodTruckImage(foodTruck.getFoodTruckLogo());
        foodtruckInfo.setFoodTruckId(foodTruck.getFoodTruckId());
        foodtruckInfo.setOrderStatus(foodTruck.getFoodTruckOpenStatus());
        Intent intent = new Intent(TableActivity.this, FoodTruckItemsActivity.class);
        intent.putExtra(Consts.FOODTRUCK_INFO, foodtruckInfo);
        intent.putExtra(Consts.IS_SEARCH, false);
        intent.putExtra(Consts.IS_DRINKS, false);
        intent.putParcelableArrayListExtra(Consts.FOODTRUCK_ITEM, (ArrayList<? extends Parcelable>) foodTruck.getFoodTruckItemList());

        startActivityForResult(intent, Consts.ITEMS_ACTIVITY);
    }

    private void lauchDrinksActivity() {
        FoodtruckInfo foodtruckInfo = new FoodtruckInfo();
        foodtruckInfo.setFoodTruckName(foodTruck.getFoodTruckName());
        foodtruckInfo.setFoodTruckImage(foodTruck.getFoodTruckLogo());
        foodtruckInfo.setFoodTruckId(foodTruck.getFoodTruckId());
        foodtruckInfo.setOrderStatus(foodTruck.getFoodTruckOpenStatus());
        Intent intent = new Intent(TableActivity.this, FoodTruckDrinksActivity.class);
        intent.putExtra(Consts.FOODTRUCK_INFO, foodtruckInfo);
        intent.putExtra(Consts.IS_SEARCH, false);
        intent.putExtra(Consts.IS_DRINKS, true);
        intent.putParcelableArrayListExtra(Consts.FOODTRUCK_ITEM, (ArrayList<? extends Parcelable>) foodTruck.getFoodTruckDrinkList());
        startActivityForResult(intent, Consts.DRINKS_ACTIVITY);
    }
@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == Consts.ITEMS_ACTIVITY) {
                lauchDrinksActivity();
            } else if (requestCode == Consts.DRINKS_ACTIVITY) {
                lauchItemActivity();
            }
        }
    }
}

FoodTruckItemsActivity.java

public class FoodTruckItemsActivity extends AppCompatActivity implements
        FoodTruckItemsAdapter.OnItemClickListener, FoodTruckItemFragment.FoodTruckItemListener,
        ViewPager.OnPageChangeListener, View.OnClickListener {

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

 routeView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                routeToAnotherMenu();
            }
        });
    }

 private void routeToAnotherMenu() {
        setResult(Activity.RESULT_OK);

    }
}

FoodTruckItemsActivity.java and FoodTruckDrinksActivity.java are identical. So what I want here is if I press routeView, it should switch from FoodTruckItemsActivity.java to FoodTruckDrinksActivity.java and vice-versa.
  For that I have written routeToAnotherMenu() method. Now problem here is if I do not write finish() inside routeToAnotherMenu, it does not load another activity. But if I write finish after setResult() then it works perfectly.

The main  reason why I do not prefer finish() inside that method because it will erase the data . So is there any way through which I can do it without writing finish() method?


来源: stackexchange

问:
Button color change when untouched

<!DOCTYPE html>

 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Dummy form

<form name="myForm">
<input name="myInput" ng-model="myInput" required />

<input  type="button" ng-click="deleteRow($event,name)" value="Remove" class="btn" >

<input type="button"  ng-click="deleteRow($event,name)" value="Remove" class="btn btn-primary" >
</form>

```

When the inputs are touched I'm trying the change the remove button color.I tried with if else,it was not working.So, used ng-show where I'm getting two buttons and the one button with changed color is working only when I click outside the form.Can anyone help?

答:
Use ng-class to determine the colour of the button:

```<code><input type="button" class="btn btn-untouched"
  ng-class="{'coloured': myForm.myInput.$touched }" />
</code>```

Then only when the myInput field is 'touched', will the colour of that particular button change. I know this seems opposite of what you wanted, but, by default all fields are untouched. So if you make that the default (.btn-untouched) it will be there all ready and change colour when it becomes touched. Then you'll only need one button because you can stack the ng-class options, for example:

```<code><form name="myForm">
  <input name="myInput" ng-model="myInput" required />
  <input name="myInput" ng-model="myInput1" required />

  <input type="button" class="btn btn-untouched"
    ng-click="deleteRow($event, name)"
    ng-class="{'coloured': myForm.myInput.$touched, 'complete': myForm.myInput.$valid }"
    value="Remove"
    id="removeButton" />
</form>
</code>```

ContentLicense: CC BY-SA 3.0

Title: Button color change when untouched

Body:
<!DOCTYPE html>

 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Dummy form

<form name="myForm">
<input name="myInput" ng-model="myInput" required />

<input  type="button" ng-click="deleteRow($event,name)" value="Remove" class="btn" >

<input type="button"  ng-click="deleteRow($event,name)" value="Remove" class="btn btn-primary" >
</form>

When the inputs are touched I'm trying the change the remove button color.I tried with if else,it was not working.So, used ng-show where I'm getting two buttons and the one button with changed color is working only when I click outside the form.Can anyone help?

Body:
Use ng-class to determine the colour of the button:

<input type="button" class="btn btn-untouched"
  ng-class="{'coloured': myForm.myInput.$touched }" />

Then only when the myInput field is 'touched', will the colour of that particular button change. I know this seems opposite of what you wanted, but, by default all fields are untouched. So if you make that the default (.btn-untouched) it will be there all ready and change colour when it becomes touched. Then you'll only need one button because you can stack the ng-class options, for example:

<form name="myForm">
  <input name="myInput" ng-model="myInput" required />
  <input name="myInput" ng-model="myInput1" required />

  <input type="button" class="btn btn-untouched"
    ng-click="deleteRow($event, name)"
    ng-class="{'coloured': myForm.myInput.$touched, 'complete': myForm.myInput.$valid }"
    value="Remove"
    id="removeButton" />
</form>


问:
VS C# Button with Mailto function - it needs to open Outlook's new mail window
What I am trying to do:

A user clicks a button on a ASP.net page and it opens a Outlook 'new mail' window.
That's all.

My Problem:

With this -->

```<code>     using Outlook = Outlook = Microsoft.Office.Interop.Outlook;

    OutlookApp outlookApp = new OutlookApp();
    MailItem mailItem = (MailItem)outlookApp.CreateItem(OlItemType.olMailItem);

    mailItem.Subject = "Test";
    mailItem.HTMLBody = "<html><body>This is the message body</body></html>";

    mailItem.Display(false);
</code>```

And several other code I've tried, I am getting security errors on my IIS web server - Access is denied. But on localhost Outlook opens fine.

I looked all over, and everyone suggests that NETWORKSERVICE should be the user that has full security rights. Did that. And after reading a bit more, People are suggesting to not try and open Outlook over a web server for several reasons. So I decided to leave Interops.Outlook.

Then I also tried the following, which again works on my localhost, but when published to the web server does not respond when the button is clicked. It literally does nothing.

```<code>    string subject = "Test subject";
    string emailTag = string.Format("mailto:someone@test.com?subject={0}", subject);
    System.Diagnostics.Process.Start(emailTag);
</code>```

Thanks

答:
so I initially wanted to code inside an ASP button. And the following code to do that is :

```<code>               ClientScript.RegisterStartupScript(this.GetType(), "FormLoading", "window.open('mailto:someone@test.test', 'email');", true);
</code>```

This opens my outlook without issues plus I can add additional methods to the button as well.

Body:
What I am trying to do:

A user clicks a button on a ASP.net page and it opens a Outlook 'new mail' window.
That's all.

My Problem:

With this -->

     using Outlook = Outlook = Microsoft.Office.Interop.Outlook;

    OutlookApp outlookApp = new OutlookApp();
    MailItem mailItem = (MailItem)outlookApp.CreateItem(OlItemType.olMailItem);

    mailItem.Subject = "Test";
    mailItem.HTMLBody = "This is the message body";

    mailItem.Display(false);

And several other code I've tried, I am getting security errors on my IIS web server - Access is denied. But on localhost Outlook opens fine.

I looked all over, and everyone suggests that NETWORKSERVICE should be the user that has full security rights. Did that. And after reading a bit more, People are suggesting to not try and open Outlook over a web server for several reasons. So I decided to leave Interops.Outlook.

Then I also tried the following, which again works on my localhost, but when published to the web server does not respond when the button is clicked. It literally does nothing.

    string subject = "Test subject";
    string emailTag = string.Format("mailto:someone@test.com?subject={0}", subject);
    System.Diagnostics.Process.Start(emailTag);

Thanks

Body:
so I initially wanted to code inside an ASP button. And the following code to do that is :

               ClientScript.RegisterStartupScript(this.GetType(), "FormLoading", "window.open('mailto:someone@test.test', 'email');", true);

This opens my outlook without issues plus I can add additional methods to the button as well.


问:
get the hostname(Base URL) using javascript
I get too many ways to get the hostname like code below:

```<code>window.location.host // you'll get sub.domain.com:8080 or sub.domain.com:80
window.location.hostname // you'll get sub.domain.com
window.location.protocol // you'll get http:
window.location.port // you'll get 8080 or 80
window.location.pathname // you'll get /virtualPath
</code>```

In my case I want something different. For example:

My QA site name is example.com/testsite/index.html

My PROD site name is example.com/index.html

The problem here using the above methods to get the hostname it is returning me only the hostname like this: example.com

However for QA I need to return example.com/testsite

For PROD i need to return example.com

Is it possible with the single code? Thanks in advance.

答:
To achieve what you require you'll need to check the window.location.hostname, and also the first folder in the window.location.pathname. Something like this:

```<code>function getPath() {
  var folder = (window.location.pathname.split('/')[0] || '').toLowerCase() == 'testsite' ? '/testsite' : '';
  return window.location.hostname + folder;
}
</code>```

Body:
I get too many ways to get the hostname like code below:

window.location.host // you'll get sub.domain.com:8080 or sub.domain.com:80
window.location.hostname // you'll get sub.domain.com
window.location.protocol // you'll get http:
window.location.port // you'll get 8080 or 80
window.location.pathname // you'll get /virtualPath

In my case I want something different. For example:

My QA site name is example.com/testsite/index.html

My PROD site name is example.com/index.html

The problem here using the above methods to get the hostname it is returning me only the hostname like this: example.com

However for QA I need to return example.com/testsite

For PROD i need to return example.com

Is it possible with the single code? Thanks in advance.

Body:
To achieve what you require you'll need to check the window.location.hostname, and also the first folder in the window.location.pathname. Something like this:

function getPath() {
  var folder = (window.location.pathname.split('/')[0] || '').toLowerCase() == 'testsite' ? '/testsite' : '';
  return window.location.hostname + folder;
}


问:
When calling the activity in the external sdk , the Action Bar is not Hiding
I have an external SDK that is imported to my Project. SDK Contains certain activities and corresponding xmls. When i tried to call the activity in that SDK the action bar is not hidden. I tried all the possible solutions. So please help me to find out the problem.</p>

答:
The problem is with this theme

```<code> <style name="Theme.AppCompat.Light.NoActionBar" parent="@style/Theme.AppCompat.Light">
    <item name="android:windowNoTitle">false</item>
</style>
</code>```

When i removed this theme , its work fine.!

Body:
The problem is with this theme

 <style name="Theme.AppCompat.Light.NoActionBar" parent="@style/Theme.AppCompat.Light">
    <item name="android:windowNoTitle">false</item>
</style>

When i removed this theme , its work fine.!


问:
Element like a PageView in android
I'm creating an app for both Androids and iOS. In a view, I'm using a pageView as a subview (I mean it doesn't fill all the viewController) in the iOS app.

I need to implement the same thing in Android and I don't know what element I should use.

Here you have an example of a page view.

Thanks for the help.

答:
you can achieve this using view pager

ViewPager Layout manager that allows the user to flip left and right through pages of data. You supply an implementation of a PagerAdapter to generate the pages that the view shows.

follow this link to implement view pager

link 1

link 2

link 3

link 5

Title: Element like a PageView in android


问:
Django : 'unicode' object has no attribute 'get'
I had a problem with my Django program. I'm a beginner in Django, I was looking for an answer with different posts with the same error than mine but no success ...

```<code>Here's my traceback :

Environment:

Request Method: POST
Request URL: http://127.0.0.1:8000/pod

Django Version: 1.11.2
Python Version: 2.7.13
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'labinit',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']

Traceback:

File "C:\Python27\lib\site-packages\django\core\handlers\exception.py" in inner
  41.             response = get_response(request)

File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\Users\admin\Desktop\django_learneo3\Learneo\labinit\views.py" in groupe_pod
  121.      if form.is_valid():

File "C:\Python27\lib\site-packages\django\forms\forms.py" in is_valid
  183.         return self.is_bound and not self.errors

File "C:\Python27\lib\site-packages\django\forms\forms.py" in errors
  175.             self.full_clean()

File "C:\Python27\lib\site-packages\django\forms\forms.py" in full_clean
  384.         self._clean_fields()

File "C:\Python27\lib\site-packages\django\forms\forms.py" in _clean_fields
  396.                 value = field.widget.value_from_datadict(self.data, self.files, self.add_prefix(name))

File "C:\Python27\lib\site-packages\django\forms\widgets.py" in

 value_from_datadict
  639.         getter = data.get

Exception Type: AttributeError at /pod
Exception Value: 'unicode' object has no attribute 'get'
</code>```

This issue appears since I have changed my init fonction, for the form that I use in my view :

Forms:

```<code>class Groupe_Form(forms.ModelForm) :
    def __init__(self, nom_groupe, *args, **kwargs):
        super(Groupe_Form,self).__init__(*args, **kwargs)
        self.fields['pod'].widget = forms.Select()
        pod1 = Groupe.objects.filter(nom_groupe = nom_groupe).values_list('pod', flat = True)
        pods = list(pod1)
        self.fields['pod'].queryset = Pod.objects.filter(id__in=pods)
    class Meta:
        model = Groupe
        fields = ['pod']
</code>```

Views :

```<code>def groupe_pod(request):

    global new_groupe
    grp = new_groupe
    form = forms.Groupe_Form(request.POST, grp)
    if request.method == 'POST':
        if form.is_valid():
            print "form was valid"
            data_groupe_pod = request.POST.get('grp_pod')
            print "data_groupe :", data_groupe_pod

            global new_cours
            print new_cours

            if new_cours == "ICND1":
                return redirect('http://127.0.0.1:8000/icnd_1')
            elif new_cours == "ICND2":
                return redirect('http://127.0.0.1:8000/icnd_2')
    else :
        form = forms.Groupe_Form(new_groupe)
    return render(request, 'pod.html', locals())
</code>```

I've tried many things, I really don't know where is the problem in my Django code.

答:
Your form's __init__ method is:

```<code>def __init__(self, nom_groupe, *args, **kwargs):
</code>```

Therefore you should instantiate it with:

```<code>form = forms.Groupe_Form(grp, request.POST)
</code>```

You currently have the arguments the other way round.

Body:
I had a problem with my Django program. I'm a beginner in Django, I was looking for an answer with different posts with the same error than mine but no success ...

Here's my traceback :

Environment:

Request Method: POST
Request URL: http://127.0.0.1:8000/pod

Django Version: 1.11.2
Python Version: 2.7.13
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'labinit',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']

Traceback:

File "C:\Python27\lib\site-packages\django\core\handlers\exception.py" in inner
  41.             response = get_response(request)

File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\Users\admin\Desktop\django_learneo3\Learneo\labinit\views.py" in groupe_pod
  121.      if form.is_valid():

File "C:\Python27\lib\site-packages\django\forms\forms.py" in is_valid
  183.         return self.is_bound and not self.errors

File "C:\Python27\lib\site-packages\django\forms\forms.py" in errors
  175.             self.full_clean()

File "C:\Python27\lib\site-packages\django\forms\forms.py" in full_clean
  384.         self._clean_fields()

File "C:\Python27\lib\site-packages\django\forms\forms.py" in _clean_fields
  396.                 value = field.widget.value_from_datadict(self.data, self.files, self.add_prefix(name))

File "C:\Python27\lib\site-packages\django\forms\widgets.py" in

 value_from_datadict
  639.         getter = data.get

Exception Type: AttributeError at /pod
Exception Value: 'unicode' object has no attribute 'get'

This issue appears since I have changed my init fonction, for the form that I use in my view :

Forms:

class Groupe_Form(forms.ModelForm) :
    def __init__(self, nom_groupe, *args, **kwargs):
        super(Groupe_Form,self).__init__(*args, **kwargs)
        self.fields['pod'].widget = forms.Select()
        pod1 = Groupe.objects.filter(nom_groupe = nom_groupe).values_list('pod', flat = True)
        pods = list(pod1)
        self.fields['pod'].queryset = Pod.objects.filter(id__in=pods)
    class Meta:
        model = Groupe
        fields = ['pod']

Views :

def groupe_pod(request):

    global new_groupe
    grp = new_groupe
    form = forms.Groupe_Form(request.POST, grp)
    if request.method == 'POST':
        if form.is_valid():
            print "form was valid"
            data_groupe_pod = request.POST.get('grp_pod')
            print "data_groupe :", data_groupe_pod

            global new_cours
            print new_cours

            if new_cours == "ICND1":
                return redirect('http://127.0.0.1:8000/icnd_1')
            elif new_cours == "ICND2":
                return redirect('http://127.0.0.1:8000/icnd_2')
    else :
        form = forms.Groupe_Form(new_groupe)
    return render(request, 'pod.html', locals())

I've tried many things, I really don't know where is the problem in my Django code.

Body:
Your form's __init__ method is:

def __init__(self, nom_groupe, *args, **kwargs):

Therefore you should instantiate it with:

form = forms.Groupe_Form(grp, request.POST)

You currently have the arguments the other way round.


问:
compilererror, matrix expected vba
Im working on a vba program. When I want to use an array I get the compileerror: matrix expected.

In a for loop Im using this code

```<code> N = ThisWorkbook.Sheets("AS").Range("$O$2")
 ReDim Powerarray(0 To N) As Double
 Powerarray(0) = 7
 ...
 Watt = Powerarray(w)
</code>```

and somewhere else i fill up the array with this code:

```<code> Dim Watt As Double
 Dim Powerarray As Double
 Watt = ThisWorkbook.Sheets("AS").Range("O6").value  'w is an integer
 w = ThisWorkbook.Sheets("AS").Range("O2").value - 3
 ...

 Powerarray(w) = Watt
</code>```

Any idea what is causing the problem?

答:
Dim Powerarray As Double is not array, but  variable.

If you want to use array in seperate sub. use Public variable.

```<code>Public Powerarray() As Double
Sub test1()
 N = ThisWorkbook.Sheets("AS").Range("$O$2")
 ReDim Powerarray(0 To N) As Double
 Powerarray(0) = 7
 ...
 Watt = Powerarray(w)

End Sub
Sub test2()
Dim Watt As Double
'Dim Powerarray As Double '<~~ this is not needed.
 Watt = ThisWorkbook.Sheets("AS").Range("O6").Value  'w is an integer
 w = ThisWorkbook.Sheets("AS").Range("O2").Value - 3
 ...

 Powerarray(w) = Watt
End Sub
</code>```

Title: compilererror, matrix expected vba

Body:
Im working on a vba program. When I want to use an array I get the compileerror: matrix expected.

In a for loop Im using this code

 N = ThisWorkbook.Sheets("AS").Range("$O$2")
 ReDim Powerarray(0 To N) As Double
 Powerarray(0) = 7
 ...
 Watt = Powerarray(w)

and somewhere else i fill up the array with this code:

 Dim Watt As Double
 Dim Powerarray As Double
 Watt = ThisWorkbook.Sheets("AS").Range("O6").value  'w is an integer
 w = ThisWorkbook.Sheets("AS").Range("O2").value - 3
 ...

 Powerarray(w) = Watt

Any idea what is causing the problem?

Body:
Dim Powerarray As Double is not array, but  variable.

If you want to use array in seperate sub. use Public variable.

Public Powerarray() As Double
Sub test1()
 N = ThisWorkbook.Sheets("AS").Range("$O$2")
 ReDim Powerarray(0 To N) As Double
 Powerarray(0) = 7
 ...
 Watt = Powerarray(w)

End Sub
Sub test2()
Dim Watt As Double
'Dim Powerarray As Double '<~~ this is not needed.
 Watt = ThisWorkbook.Sheets("AS").Range("O6").Value  'w is an integer
 w = ThisWorkbook.Sheets("AS").Range("O2").Value - 3
 ...

 Powerarray(w) = Watt
End Sub


问:
iOS: How to stream (live sending) data over HTTP?
I know, this topic's title is pretty general and I thought this problem was easy to solve (I made it on Android very easily). But on iOS... Well, this question exists so....

I have a device and I want to stream data (audio data to be precise) on it. The protocol I have to use is HTTP. Actually, I have to build ans send a single HTTP request containing some data in its body, then, as and when my "producer" (here, a process that resample/encode audio data) gives new data to transmit, send it through this request body. It sounds weird for HTTP, but it's like HTTP multipart without boundary (data are just sent one behind the others).

For example, in Java I initialize a HttpUrlConnection with URL and headers, I precise the Content-Length header to "9999999" (as it is wrote in the targeted device's documentation) with /*my connection*/.setFixedLengthStreamingMode(9999999);. I don't call connect()method but I get the output stream (getOutputStream()) and when my producer gives new data, I just call /*my output stream*/.write(/*my data*/); then /*my output stream*/.flush();

So, I tried with NSURLSession and with low-level APIs NSInputStreamand NSOutputStream. But in each case, I can't achieve that:

With NSURLSession I called uploadTaskWithStreamedRequest: but the callback needNewBodyStream: is only called once (or twice in case of new auth). So I only send one data packet in the input stream.

With NSInputStreamand NSOutputStream connection is close by targeted device without error before I can send any data with standard TCP ending on input stream (except HTTP headers).

I think this is something a lot of people did and they is a way I didn't see, no? Please help me by give me examples (this'll be perfect) or avises about what API I have to choose or a specific parameter to apply?

Thanks!

EDIT

My problem is similar to this but it's an other (shorter) way to explain it.

EDIT 2

Here is my code when I use NSURLSession (I prefer keep using that if possible):

```<code>NSURLSessionConfiguration* defaultConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSOperationQueue* operationQueue = [NSOperationQueue mainQueue];
NSURLSession* session = [NSURLSession sessionWithConfiguration:defaultConfiguration delegate:self delegateQueue:operationQueue];

NSInputStream* inputStream = [NSInputStream inputStreamWithData:/*data*/];

NSURL* url = /*init from string*/
NSMutableRequest* request : [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"POST";
request.HTTPBodyStream = inputStream;
/*Add some headers to request*/

NSURLSessionUploadTask* uploadTask = [session uploadTaskWithStreamedRequest:request];
[uploadTask resume];
</code>```

To be precise, I didn't put auth information in URL. Delegates's methods are called in this order : didSendBodyData -> didReceiveChallenge (this is where I perform authentication and it works because I received just before a 401 and nothing after) -> needNewBodyStream (this is where I put my data in the input stream for the completion handler) -> didSendBodyData -> didFinishCollectingMetrics -> didCompleteWithError (with code -1005 : kCFErrorDomainCFNetwork). Strange thing is that data is transmited well (the first data packet) because I can heard sound in the target device for some instants.

To be more precise again, here is the network traffic during connection:

Send TCP SYN, ECN, CWR

Rcv TCP SYN, ACK, ECN

Send TCP ACK

Send TCP segment of reassembled PDU (my HTTP request and data without auth) (x7, each followed by an ACK response)

Rcv HTTP 401 (because required digest)

... TCP Succession of ACK, FIN/ACK, SYN/ECN/CWR...

Send TCP segment of reassembled PDU (my HTTP request and data with auth) (x7, each followed by an ACK response)

And then (I don't know why):

Rcv TCP END, ACK

Send TCP ACK

Send TCP END, ACK

Rcv TCP ACK

答:
Ok guys, I've got the answer and I think it's a good idea to share it. Actually it's very easy: the trick was just not explicit at all. The callback needNewBodyStream: is called once (or more, see doc) and we just have to bind the NSInputStream object with a NSOutputStream one. Then, data is wrote in the NSOutputStream's callback as and when the "producer" gives new data. Previously, my connection was closed because after the needNewBodyStream call there was nothing to send.

Part of the NSURLSessionTaskDelegate implementation:

```<code>-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
    needNewBodyStream:(void (^)(NSInputStream * bodyStream))completionHandler
{
    NSInputStream* inputStream = nil;
    NSOutputStream* outputStream = nil;

    // Bind inputStream and outputStream

    self.inputStream = inputStream;
    self.outputStream = outputStream;
    [self.outputStream setDelegate:/*NSStreamDelegate implementation*/];
    [self.outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [self.outputStream open];

    completionHandler(self.inputStream);
}
</code>```

Part of the NSStreamDelegate implementation:

```<code>- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode
{
    switch (eventCode) {
        case NSStreamEventOpenCompleted:
            // to handle...
            break;
        case NSStreamEventHasSpaceAvailable:
            // Producer/Consumer's consumer here, and when data is available:
            [self.outputStream write:/*data*/ maxLength:/*data length*/];
            break;
        case NSStreamEventErrorOccurred:
            // to handle...
            break;
        case NSStreamEventEndEncountered:
            // to handle...
            break;
        default:
            break;
    }
}
</code>```

Now you can stream "in live" over HTTP, enjoy :)

Body:
I know, this topic's title is pretty general and I thought this problem was easy to solve (I made it on Android very easily). But on iOS... Well, this question exists so....

I have a device and I want to stream data (audio data to be precise) on it. The protocol I have to use is HTTP. Actually, I have to build ans send a single HTTP request containing some data in its body, then, as and when my "producer" (here, a process that resample/encode audio data) gives new data to transmit, send it through this request body. It sounds weird for HTTP, but it's like HTTP multipart without boundary (data are just sent one behind the others).

For example, in Java I initialize a HttpUrlConnection with URL and headers, I precise the Content-Length header to "9999999" (as it is wrote in the targeted device's documentation) with /*my connection*/.setFixedLengthStreamingMode(9999999);. I don't call connect()method but I get the output stream (getOutputStream()) and when my producer gives new data, I just call /*my output stream*/.write(/*my data*/); then /*my output stream*/.flush();

So, I tried with NSURLSession and with low-level APIs NSInputStreamand NSOutputStream. But in each case, I can't achieve that:

With NSURLSession I called uploadTaskWithStreamedRequest: but the callback needNewBodyStream: is only called once (or twice in case of new auth). So I only send one data packet in the input stream.

With NSInputStreamand NSOutputStream connection is close by targeted device without error before I can send any data with standard TCP ending on input stream (except HTTP headers).

I think this is something a lot of people did and they is a way I didn't see, no? Please help me by give me examples (this'll be perfect) or avises about what API I have to choose or a specific parameter to apply?

Thanks!

EDIT

My problem is similar to this but it's an other (shorter) way to explain it.

EDIT 2

Here is my code when I use NSURLSession (I prefer keep using that if possible):

NSURLSessionConfiguration* defaultConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSOperationQueue* operationQueue = [NSOperationQueue mainQueue];
NSURLSession* session = [NSURLSession sessionWithConfiguration:defaultConfiguration delegate:self delegateQueue:operationQueue];

NSInputStream* inputStream = [NSInputStream inputStreamWithData:/*data*/];

NSURL* url = /*init from string*/
NSMutableRequest* request : [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"POST";
request.HTTPBodyStream = inputStream;
/*Add some headers to request*/

NSURLSessionUploadTask* uploadTask = [session uploadTaskWithStreamedRequest:request];
[uploadTask resume];

To be precise, I didn't put auth information in URL. Delegates's methods are called in this order : didSendBodyData -> didReceiveChallenge (this is where I perform authentication and it works because I received just before a 401 and nothing after) -> needNewBodyStream (this is where I put my data in the input stream for the completion handler) -> didSendBodyData -> didFinishCollectingMetrics -> didCompleteWithError (with code -1005 : kCFErrorDomainCFNetwork). Strange thing is that data is transmited well (the first data packet) because I can heard sound in the target device for some instants.

To be more precise again, here is the network traffic during connection:

Send TCP SYN, ECN, CWR

Rcv TCP SYN, ACK, ECN

Send TCP ACK

Send TCP segment of reassembled PDU (my HTTP request and data without auth) (x7, each followed by an ACK response)

Rcv HTTP 401 (because required digest)

... TCP Succession of ACK, FIN/ACK, SYN/ECN/CWR...

Send TCP segment of reassembled PDU (my HTTP request and data with auth) (x7, each followed by an ACK response)

And then (I don't know why):

Rcv TCP END, ACK

Send TCP ACK

Send TCP END, ACK

Rcv TCP ACK

Body:
Ok guys, I've got the answer and I think it's a good idea to share it. Actually it's very easy: the trick was just not explicit at all. The callback needNewBodyStream: is called once (or more, see doc) and we just have to bind the NSInputStream object with a NSOutputStream one. Then, data is wrote in the NSOutputStream's callback as and when the "producer" gives new data. Previously, my connection was closed because after the needNewBodyStream call there was nothing to send.

Part of the NSURLSessionTaskDelegate implementation:

-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
    needNewBodyStream:(void (^)(NSInputStream * bodyStream))completionHandler
{
    NSInputStream* inputStream = nil;
    NSOutputStream* outputStream = nil;

    // Bind inputStream and outputStream

    self.inputStream = inputStream;
    self.outputStream = outputStream;
    [self.outputStream setDelegate:/*NSStreamDelegate implementation*/];
    [self.outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [self.outputStream open];

    completionHandler(self.inputStream);
}

Part of the NSStreamDelegate implementation:

- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode
{
    switch (eventCode) {
        case NSStreamEventOpenCompleted:
            // to handle...
            break;
        case NSStreamEventHasSpaceAvailable:
            // Producer/Consumer's consumer here, and when data is available:
            [self.outputStream write:/*data*/ maxLength:/*data length*/];
            break;
        case NSStreamEventErrorOccurred:
            // to handle...
            break;
        case NSStreamEventEndEncountered:
            // to handle...
            break;
        default:
            break;
    }
}

Now you can stream "in live" over HTTP, enjoy :)


问:
nhibernate subclass mapping when both subclasses can be materialized
I have the following classes

```<code>public class Person
{
     public virtual int Id { get; set; }
}
public class Employee : Person
{
     public virtual int EmployeeProperty { get; set; }
}
public class Customer : Person
{
     public virtual int CustomerProperty { get; set; }
}
</code>```

Conceptually a the same Person can be both an Employee and a Customer. Also a Person can exist without either an Employee or Customer record. Using Table Per Subclass how can I get this to work.

As it stands now I don't see a way to get NHibernate to work this way. If I create a Person, and then try to create an Employee using an existing Person Id, NHibernate still tries to insert into Person. Is there a way to get NHibernate to realize that I already have a Person and just want to add the Employee record?

I would prefer to not go to Table Per Class or Table Per Hierarchy if possible.

答: You model is not correct. If a Person can be both a Customer and an Employee, then you should not use inheritance (An Employee is-a Person), but composition (An Employee has-a [corresponding] Person or A Person has-a Employee [role])

ContentLicense: CC BY-SA 2.5

Body:
I have the following classes

public class Person
{
     public virtual int Id { get; set; }
}
public class Employee : Person
{
     public virtual int EmployeeProperty { get; set; }
}
public class Customer : Person
{
     public virtual int CustomerProperty { get; set; }
}

Conceptually a the same Person can be both an Employee and a Customer. Also a Person can exist without either an Employee or Customer record. Using Table Per Subclass how can I get this to work.

As it stands now I don't see a way to get NHibernate to work this way. If I create a Person, and then try to create an Employee using an existing Person Id, NHibernate still tries to insert into Person. Is there a way to get NHibernate to realize that I already have a Person and just want to add the Employee record?

I would prefer to not go to Table Per Class or Table Per Hierarchy if possible.


问:
How to use a timer in C++ to force input within a given time?
I want to implement a time out feature in C++.

If the user does not input the value within 2 seconds then the program must display the time-out statement and ask the input again

EX(OUTPUT SCREEN):

```<code>Timer=0;
Please enter the input:       //if input is not given within 2 seconds then
Time-out: 2 seconds
Timer again set to 0
Please enter the input:  //if input is not given within 2 seconds then
Time-out: 2 seconds
Timer again set to 0
Please enter the input:22
Data accepted
Terminate the program`
</code>```

Code:

```<code>#include<iostream>
 #include<time.h>
 using namespace std;
 int main()
{
    clock_t endwait;
    endwait =  2000 ;
   cout<<endwait;
   while (clock() < endwait)
  {
         cout<<"Please enter the input:";
  }
   return 0;
}
</code>```

I have worked on the above code. But this happens only while entering the WHILE loop. How shall i do it in a way so that, I get the required output.

答:
I have used kbhit() function to solve your problem. The code is as follows:-</p>

```<code>    #include <conio.h>
    #include <iostream>
    #include <windows.h>

    using namespace std;

    int main()
    {
        int i;
        DWORD start_time, check_time;
        start_time=GetTickCount();
        check_time=start_time+2000;
        while(!kbhit())
        {
            cout<<"Please enter the input:"<<endl;
            while((check_time>GetTickCount()))
            {
                if (kbhit())
                {
                    i=getch();
                    cout<<"Data accepted"<<endl;
                    return 0;
                }
            }
            cout<<"Time-out: 2 seconds"<<endl;
            cout<<"Timer again set to 0"<<endl;
            start_time=GetTickCount();
            check_time=start_time+2000;
        }
    return 0;

    }
</code>```

Body:
I want to implement a time out feature in C++.

If the user does not input the value within 2 seconds then the program must display the time-out statement and ask the input again

EX(OUTPUT SCREEN):

Timer=0;
Please enter the input:       //if input is not given within 2 seconds then
Time-out: 2 seconds
Timer again set to 0
Please enter the input:  //if input is not given within 2 seconds then
Time-out: 2 seconds
Timer again set to 0
Please enter the input:22
Data accepted
Terminate the program`

Code:

#include<iostream>
 #include<time.h>
 using namespace std;
 int main()
{
    clock_t endwait;
    endwait =  2000 ;
   cout<<endwait;
   while (clock() < endwait)
  {
         cout<<"Please enter the input:";
  }
   return 0;
}

I have worked on the above code. But this happens only while entering the WHILE loop. How shall i do it in a way so that, I get the required output.

Body:
I have used kbhit() function to solve your problem. The code is as follows:-

    #include <conio.h>
    #include <iostream>
    #include <windows.h>

    using namespace std;

    int main()
    {
        int i;
        DWORD start_time, check_time;
        start_time=GetTickCount();
        check_time=start_time+2000;
        while(!kbhit())
        {
            cout<<"Please enter the input:"<<endl;
            while((check_time>GetTickCount()))
            {
                if (kbhit())
                {
                    i=getch();
                    cout<<"Data accepted"<<endl;
                    return 0;
                }
            }
            cout<<"Time-out: 2 seconds"<<endl;
            cout<<"Timer again set to 0"<<endl;
            start_time=GetTickCount();
            check_time=start_time+2000;
        }
    return 0;

    }


问:
Need to configure serverless resource output to get api gateway api id
I have a serverless project that is creating an API Gateway API amongst other things. One of the functions in the project needs to generate a URL for an API endpoint.

My plan is to get the API ID using a resource output in serverless.yml then create the URL and pass it through to the lambda function as an env parameter.

My problem/question is how to get the API ID as a cloud formation output in serverless.yml?

I've tried:

```<code>resources:
  Outputs:
    RESTApiId:
      Description: The id of the API created in the API gateway
      Value:
        Ref: name-of-api
</code>```

but this give the error:

```<code>The CloudFormation template is invalid: Unresolved resource dependencies [name-of-api] in the Outputs block of the template
</code>```

答:
The serverless framework has a documentation page on how they generate names for resources.

See. AWS CloudFormation Resource Reference

So the generated RestAPI resource is called ApiGatewayRestApi.

Body:
I have a serverless project that is creating an API Gateway API amongst other things. One of the functions in the project needs to generate a URL for an API endpoint.

My plan is to get the API ID using a resource output in serverless.yml then create the URL and pass it through to the lambda function as an env parameter.

My problem/question is how to get the API ID as a cloud formation output in serverless.yml?

I've tried:

resources:
  Outputs:
    RESTApiId:
      Description: The id of the API created in the API gateway
      Value:
        Ref: name-of-api

but this give the error:

The CloudFormation template is invalid: Unresolved resource dependencies [name-of-api] in the Outputs block of the template


答:
From the docs for onActivityResult():

Called when an activity you launched exits (...)

Just setting the result won't cause the method to be called.

If you want to switch freely between screens, maybe you should consider using Fragments?

Title: activity switching not working without finish() method

Body:
My code is as shown below:

TableActivity.java

public class TableActivity extends AppCompatActivity {

 @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_table_selection);
        itemName = (TextView) findViewById(R.id.itemName);
        foodMenuLayout = (LinearLayout) findViewById(R.id.foodMenuLayout);
        drinkMenuLayout = (LinearLayout) findViewById(R.id.drinksMenuLayout);
        tableNo = (TextView) findViewById(R.id.tableNo);
        foodMenu = (TextView) findViewById(R.id.foodMenu);
        drinksMenu = (TextView) findViewById(R.id.drinksMenu);
        tapLayout = (LinearLayout) findViewById(R.id.tapLayout);
        foodImage = (ImageView) findViewById(R.id.foodImage);
        drinkImage = (ImageView) findViewById(R.id.drinkImage);

        getFoodTruckInfo();

        tapLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tableList = TableList.getInstance(MyCart.getInstance().getTableNo());
                tableList.setItemListener(TableActivity.this);
                tableList.setCancelable(false);
                tableList.show(getSupportFragmentManager(), null);
            }
        });

        setFontStyle();

        foodMenuLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(tableNo.getText().toString().trim())) {
                    Toast.makeText(TableActivity.this, "Please select table", Toast.LENGTH_SHORT).show();
                } else {
                    lauchItemActivity();
                }
            }
        });

        drinkMenuLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(tableNo.getText().toString().trim())) {
                    Toast.makeText(TableActivity.this, "Please select table", Toast.LENGTH_SHORT).show();
                } else {
                    lauchDrinksActivity();
                }
            }
        });
    }

    private void lauchItemActivity() {
        FoodtruckInfo foodtruckInfo = new FoodtruckInfo();
        foodtruckInfo.setFoodTruckName(foodTruck.getFoodTruckName());
        foodtruckInfo.setFoodTruckImage(foodTruck.getFoodTruckLogo());
        foodtruckInfo.setFoodTruckId(foodTruck.getFoodTruckId());
        foodtruckInfo.setOrderStatus(foodTruck.getFoodTruckOpenStatus());
        Intent intent = new Intent(TableActivity.this, FoodTruckItemsActivity.class);
        intent.putExtra(Consts.FOODTRUCK_INFO, foodtruckInfo);
        intent.putExtra(Consts.IS_SEARCH, false);
        intent.putExtra(Consts.IS_DRINKS, false);
        intent.putParcelableArrayListExtra(Consts.FOODTRUCK_ITEM, (ArrayList<? extends Parcelable>) foodTruck.getFoodTruckItemList());

        startActivityForResult(intent, Consts.ITEMS_ACTIVITY);
    }

    private void lauchDrinksActivity() {
        FoodtruckInfo foodtruckInfo = new FoodtruckInfo();
        foodtruckInfo.setFoodTruckName(foodTruck.getFoodTruckName());
        foodtruckInfo.setFoodTruckImage(foodTruck.getFoodTruckLogo());
        foodtruckInfo.setFoodTruckId(foodTruck.getFoodTruckId());
        foodtruckInfo.setOrderStatus(foodTruck.getFoodTruckOpenStatus());
        Intent intent = new Intent(TableActivity.this, FoodTruckDrinksActivity.class);
        intent.putExtra(Consts.FOODTRUCK_INFO, foodtruckInfo);
        intent.putExtra(Consts.IS_SEARCH, false);
        intent.putExtra(Consts.IS_DRINKS, true);
        intent.putParcelableArrayListExtra(Consts.FOODTRUCK_ITEM, (ArrayList<? extends Parcelable>) foodTruck.getFoodTruckDrinkList());
        startActivityForResult(intent, Consts.DRINKS_ACTIVITY);
    }
@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == Consts.ITEMS_ACTIVITY) {
                lauchDrinksActivity();
            } else if (requestCode == Consts.DRINKS_ACTIVITY) {
                lauchItemActivity();
            }
        }
    }
}

FoodTruckItemsActivity.java

public class FoodTruckItemsActivity extends AppCompatActivity implements
        FoodTruckItemsAdapter.OnItemClickListener, FoodTruckItemFragment.FoodTruckItemListener,
        ViewPager.OnPageChangeListener, View.OnClickListener {

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

 routeView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                routeToAnotherMenu();
            }
        });
    }

 private void routeToAnotherMenu() {
        setResult(Activity.RESULT_OK);

    }
}

FoodTruckItemsActivity.java and FoodTruckDrinksActivity.java are identical. So what I want here is if I press routeView, it should switch from FoodTruckItemsActivity.java to FoodTruckDrinksActivity.java and vice-versa.
  For that I have written routeToAnotherMenu() method. Now problem here is if I do not write finish() inside routeToAnotherMenu, it does not load another activity. But if I write finish after setResult() then it works perfectly.

The main  reason why I do not prefer finish() inside that method because it will erase the data . So is there any way through which I can do it without writing finish() method?


问:
Finding percentage of shared tokens (percent similarity) between multiple strings
I want to find unique strings in a list of strings with a specific percentage (in Python). However, these strings should be significantly different. If there is a small difference between two strings then it's not interesting for me.

I can loop through the strings for finding their similarity percentage but I was wondering if there is a better way to do it?

For example,

```<code>String A: He is going to school.
String B: He is going to school tomorrow.
</code>```

Let's say that these two strings are 80% similar.

Similarity: The string with exact same words in the same order are most similar. A string can be 100% similar with itself

It's a bit vague definition but it works for my use-case.

答:
If you want to check the amount that two sentences are similar and you want to know when they are the exact same word ordering, then you can use single sentence BLEU score.

I would use the sentence_bleu found here: http://www.nltk.org/_modules/nltk/translate/bleu_score.html

You will need to make sure that you do something with your weights for short sentences. An example from something I have done in the past is

```<code>from nltk.translate.bleu_score import sentence_bleu
from nltk import word_tokenize

sentence1 = "He is a dog"
sentence2 = "She is a dog"

reference = word_tokenize(sentence1.lower())
hypothesis = word_tokenize(sentence2.lower())
if min(len(hypothesis), len(reference)) < 4:
        weighting = 1.0 / min(len(hypothesis), len(reference))
        weights = tuple([weighting] * min(len(hypothesis), len(reference)))
else:
    weights = (0.25, 0.25, 0.25, 0.25)
bleu_score = sentence_bleu([reference], hypothesis, weights=weights)
</code>```

Note that single sentence BLEU is quite bad at detecting similar sentences with different word orderings. So if that's what you're interested in then be careful. Other methods you could try are document similarity, Jaccard similarity, and cosine similarity.

Body:
I want to find unique strings in a list of strings with a specific percentage (in Python). However, these strings should be significantly different. If there is a small difference between two strings then it's not interesting for me.

I can loop through the strings for finding their similarity percentage but I was wondering if there is a better way to do it?

For example,

String A: He is going to school.
String B: He is going to school tomorrow.

Let's say that these two strings are 80% similar.

Similarity: The string with exact same words in the same order are most similar. A string can be 100% similar with itself

It's a bit vague definition but it works for my use-case.

Body:
If you want to check the amount that two sentences are similar and you want to know when they are the exact same word ordering, then you can use single sentence BLEU score.

I would use the sentence_bleu found here: http://www.nltk.org/_modules/nltk/translate/bleu_score.html

You will need to make sure that you do something with your weights for short sentences. An example from something I have done in the past is

from nltk.translate.bleu_score import sentence_bleu
from nltk import word_tokenize

sentence1 = "He is a dog"
sentence2 = "She is a dog"

reference = word_tokenize(sentence1.lower())
hypothesis = word_tokenize(sentence2.lower())
if min(len(hypothesis), len(reference)) < 4:
        weighting = 1.0 / min(len(hypothesis), len(reference))
        weights = tuple([weighting] * min(len(hypothesis), len(reference)))
else:
    weights = (0.25, 0.25, 0.25, 0.25)
bleu_score = sentence_bleu([reference], hypothesis, weights=weights)

Note that single sentence BLEU is quite bad at detecting similar sentences with different word orderings. So if that's what you're interested in then be careful. Other methods you could try are document similarity, Jaccard similarity, and cosine similarity.


问:
oracle between query not taking end date time
Oracle between query ignoring end date time.

Below is my table.

```<code>Id   Upload Date
1   05-JUL-17 12.02.11.309000000 PM
2   05-JUL-17 12.03.34.123000000 PM
3   05-JUL-17 12.04.15.334000000 PM
</code>```

My requirement is to fetch the files between the given date time.

```<code> select * from fileupload where uploaddate between to_DATE('05-07-17 12:02:11', 'DD-MM-YY HH24:MI:SS') and to_DATE('05-07-17 12:04:15', 'DD-MM-YY HH24:MI:SS')

select * from fileupload where uploaddate between to_timestamp('05-07-17 12:02:11', 'DD-MM-YY HH24:MI:SS') and to_timestamp('05-07-17 12:04:15', 'DD-MM-YY HH24:MI:SS')
</code>```

Both queries not returns the end date time it returns only two row.

```<code>Id   Upload Date
1   05-JUL-17 12.02.11.309000000 PM
2   05-JUL-17 12.03.34.123000000 PM
</code>```

But the expected result is

```<code> Id   Upload Date
    1   05-JUL-17 12.02.11.309000000 PM
    2   05-JUL-17 12.03.34.123000000 PM
    3   05-JUL-17 12.04.15.334000000 PM
</code>```

why the end date time is not fetching when using between.

Any help will be greatly appreciated!!!!

答:
You need to use TO_TIMESTAMP().. It can handle milliseconds.

TO_DATE doesn't handle milliseconds

Body:
Oracle between query ignoring end date time.

Below is my table.

Id   Upload Date
1   05-JUL-17 12.02.11.309000000 PM
2   05-JUL-17 12.03.34.123000000 PM
3   05-JUL-17 12.04.15.334000000 PM

My requirement is to fetch the files between the given date time.

 select * from fileupload where uploaddate between to_DATE('05-07-17 12:02:11', 'DD-MM-YY HH24:MI:SS') and to_DATE('05-07-17 12:04:15', 'DD-MM-YY HH24:MI:SS')

select * from fileupload where uploaddate between to_timestamp('05-07-17 12:02:11', 'DD-MM-YY HH24:MI:SS') and to_timestamp('05-07-17 12:04:15', 'DD-MM-YY HH24:MI:SS')

Both queries not returns the end date time it returns only two row.

Id   Upload Date
1   05-JUL-17 12.02.11.309000000 PM
2   05-JUL-17 12.03.34.123000000 PM

But the expected result is

 Id   Upload Date
    1   05-JUL-17 12.02.11.309000000 PM
    2   05-JUL-17 12.03.34.123000000 PM
    3   05-JUL-17 12.04.15.334000000 PM

why the end date time is not fetching when using between.

Any help will be greatly appreciated!!!!


问:
How to correctly update entities in EF4 using POCO and custom ObjectContext?
Using the technique described here I have a simple POCO EF4 model up and running. Saving new and deleting is straightforward (using AddObject() and DeleteObject() respectively). But the only way of updating objects I have found is to retrieve the stored version of the object and manually update its properties with new values from the object being saved. Surely there is a better way?

My ObjectContext is disconnected - in otherwords, I use a new ObjectContext instance for each operation on the model.

Thanks.

答:
Use the stub technique:

```<code>public void UpdateOrder(Order o)
{
   var stub = new Order { Id = o.OrderId }; // create stub with EntityKey
   ctx.Orders.Attach(stub); // attach stub to graph
   ctx.ApplyCurrentValues("Orders", o); // override stub with values.
   ctx.SaveChanges();
}
</code>```

If the entity is already in the graph, you will get an OSM exception (entity with key already exists).

I counteract this by checking if the object exists in the graph first (TryGetObjectStateEntry) and only attaching if it doesn't.

Body:
Use the stub technique:

public void UpdateOrder(Order o)
{
   var stub = new Order { Id = o.OrderId }; // create stub with EntityKey
   ctx.Orders.Attach(stub); // attach stub to graph
   ctx.ApplyCurrentValues("Orders", o); // override stub with values.
   ctx.SaveChanges();
}

If the entity is already in the graph, you will get an OSM exception (entity with key already exists).

I counteract this by checking if the object exists in the graph first (TryGetObjectStateEntry) and only attaching if it doesn't.


问:
Copy a section of a record to another record ind Dynamics NAV
I have a record with let's say 100 lines, that a user marks. I retrieve the record like this:

```<code>CurrPage.SETSELECTIONFILTER(recSelection);
recSelection.FINDSET;
</code>```

Now, I want to copy 20 lines of the selection at a time into another record variable and pass that to a function.

How can i process a record in steps?
something like this:

```<code>batchSize := 20;
currSize := 0;
totalSize := recSelection.COUNT;
totalProcessed := 0;
recSelection.FINDSET;
REPEAT
  IF (currSize = 0) THEN BEGIN
    tmpRec.INIT;
  END;

  // how can I add the current to the tmp?
  // tmpRec.INSERT -> recSelection

  currSize += 1;
  totalProcessed += 1;

  IF (currSize = batchSize) OR (totalProcessed = totalSize) THEN BEGIN
     SomeHeavyFunction(tmpRec);
     currSize := 0;
  END;

UNTIL recSelection.NEXT = 0;
</code>```

答:
I got it to work by this:

(deleteall with temp records are always a bit scary for me :P), recTemp is a Temporary record

```<code>CURR_BATCH_SIZE := 0;
TOTAL_ITEMS := recSelected.COUNT;
BATCH_SIZE := 20;
TOTAL_PROCESSED := 0;
IF recSelected.FIND('-') THEN
REPEAT

  IF (CURR_BATCH_SIZE = 0) THEN BEGIN
    recTemp.RESET;
    recTemp.DELETEALL;
    recTemp.INIT;
  END;

  // copy over
  recTemp := recSelected;
  recTemp.INSERT;

  // store state
  CURR_BATCH_SIZE := CURR_BATCH_SIZE + 1;
  TOTAL_PROCESSED := TOTAL_PROCESSED + 1;

  // did we reach batch limit or end?
  IF (CURR_BATCH_SIZE = BATCH_SIZE) OR (TOTAL_PROCESSED = TOTAL_ITEMS) THEN BEGIN
    // process batch
    MESSAGE('Processing next %1. total processed %2/%3', FORMAT(recTemp.COUNT), FORMAT(TOTAL_PROCESSED), FORMAT(TOTAL_ITEMS));

    // reset counters
    CURR_BATCH_SIZE := 0;
  END;

UNTIL recSelected.NEXT = 0;
</code>```

Body:
I have a record with let's say 100 lines, that a user marks. I retrieve the record like this:

CurrPage.SETSELECTIONFILTER(recSelection);
recSelection.FINDSET;

Now, I want to copy 20 lines of the selection at a time into another record variable and pass that to a function.

How can i process a record in steps?
something like this:

batchSize := 20;
currSize := 0;
totalSize := recSelection.COUNT;
totalProcessed := 0;
recSelection.FINDSET;
REPEAT
  IF (currSize = 0) THEN BEGIN
    tmpRec.INIT;
  END;

  // how can I add the current to the tmp?
  // tmpRec.INSERT -> recSelection

  currSize += 1;
  totalProcessed += 1;

  IF (currSize = batchSize) OR (totalProcessed = totalSize) THEN BEGIN
     SomeHeavyFunction(tmpRec);
     currSize := 0;
  END;

UNTIL recSelection.NEXT = 0;

Body:
I got it to work by this:

(deleteall with temp records are always a bit scary for me :P), recTemp is a Temporary record

CURR_BATCH_SIZE := 0;
TOTAL_ITEMS := recSelected.COUNT;
BATCH_SIZE := 20;
TOTAL_PROCESSED := 0;
IF recSelected.FIND('-') THEN
REPEAT

  IF (CURR_BATCH_SIZE = 0) THEN BEGIN
    recTemp.RESET;
    recTemp.DELETEALL;
    recTemp.INIT;
  END;

  // copy over
  recTemp := recSelected;
  recTemp.INSERT;

  // store state
  CURR_BATCH_SIZE := CURR_BATCH_SIZE + 1;
  TOTAL_PROCESSED := TOTAL_PROCESSED + 1;

  // did we reach batch limit or end?
  IF (CURR_BATCH_SIZE = BATCH_SIZE) OR (TOTAL_PROCESSED = TOTAL_ITEMS) THEN BEGIN
    // process batch
    MESSAGE('Processing next %1. total processed %2/%3', FORMAT(recTemp.COUNT), FORMAT(TOTAL_PROCESSED), FORMAT(TOTAL_ITEMS));

    // reset counters
    CURR_BATCH_SIZE := 0;
  END;

UNTIL recSelected.NEXT = 0;


问:
if else condition using sql query
I have problem to generate SQL query for below table.
Here is my table:

```<code>County          | Store     | Stock | Display | Designation
--------------- | --------- | ----- | ------- | ------------
USA             | USD       | 1     | Yes     | Merchandiser
USA             | USD       | 2     | Yes     | Promoter
</code>```

I want to be result like this

```<code>County          | Store     | Stock | Display | Designation
--------------- | --------- | ----- | ------- | ------------
USA             | USD       | 2     | Yes     | Merchandiser
USA             | USD       | 2     | Yes     | Promoter
</code>```

The Scenario is if Designation is Promoter, use both Display and Stock data.
If Designation is from Merchandiser, use data from Promoter for Stock data
How can i achieve this?

答:
Please try the below code to create temporary table

```<code>--===== If the test table already exists, drop it
 IF OBJECT_ID('TestDB..#mytable','U') IS NOT NULL
     DROP TABLE #mytable
 --===== Create the test table with
 CREATE TABLE #mytable
        (
        Country varchar(20),
        Store varchar(20),
        Stock int,
        Display varchar(5),
        Designation varchar(20)
        )
   --===== Insert the test data into the test table
 INSERT INTO #mytable
       (Country, Store, Stock, Display, Designation)

 SELECT 'SG','a','2','YES','Merchandiser' UNION ALL
 SELECT 'SG','a','4','YES','Promoter'
</code>```

Now use the below above query

```<code>SELECT Country,
       Store ,
       (CASE WHEN (Designation = 'Merchandiser') THEN (SELECT SUM(STOCK) FROM #mytable WHERE Country = Country AND Designation = 'Promoter' GROUP BY Country) ELSE STOCK END) AS "stock",
       Display,
       Designation FROM #mytable
</code>```

Title: if else condition using sql query

Body:
I have problem to generate SQL query for below table.
Here is my table:

County          | Store     | Stock | Display | Designation
--------------- | --------- | ----- | ------- | ------------
USA             | USD       | 1     | Yes     | Merchandiser
USA             | USD       | 2     | Yes     | Promoter

I want to be result like this

County          | Store     | Stock | Display | Designation
--------------- | --------- | ----- | ------- | ------------
USA             | USD       | 2     | Yes     | Merchandiser
USA             | USD       | 2     | Yes     | Promoter

The Scenario is if Designation is Promoter, use both Display and Stock data.
If Designation is from Merchandiser, use data from Promoter for Stock data
How can i achieve this?

Body:
Please try the below code to create temporary table

--===== If the test table already exists, drop it
 IF OBJECT_ID('TestDB..#mytable','U') IS NOT NULL
     DROP TABLE #mytable
 --===== Create the test table with
 CREATE TABLE #mytable
        (
        Country varchar(20),
        Store varchar(20),
        Stock int,
        Display varchar(5),
        Designation varchar(20)
        )
   --===== Insert the test data into the test table
 INSERT INTO #mytable
       (Country, Store, Stock, Display, Designation)

 SELECT 'SG','a','2','YES','Merchandiser' UNION ALL
 SELECT 'SG','a','4','YES','Promoter'

Now use the below above query

SELECT Country,
       Store ,
       (CASE WHEN (Designation = 'Merchandiser') THEN (SELECT SUM(STOCK) FROM #mytable WHERE Country = Country AND Designation = 'Promoter' GROUP BY Country) ELSE STOCK END) AS "stock",
       Display,
       Designation FROM #mytable


问:
Edit data in Primefaces dialog
How I can edit data in form? I have this Primefaces dialog which hI wants to use to edit data.</p>

```<code><p:dialog header="System User Details" widgetVar="carDialog" modal="true" showEffect="fade" hideEffect="fade" resizable="true">
                        <p:outputPanel id="carDetail" style="text-align:center;">
                            <p:panelGrid  columns="2" rendered="#{not empty systemusers.selectedSystemUser}" columnClasses="label,value">

                                <h:outputText value="Username" />
                                <h:outputText value="#{systemusers.selectedSystemUser.username}" />

                                <h:outputText value="Last Login" />
                                <h:outputText value="#{systemusers.selectedSystemUser.lastLogin}" />

                                .........

                                <h:outputText value="Action" />
                                <h:outputText value="Download Delete" />

                            </p:panelGrid>
                        </p:outputPanel>
                    </p:dialog>
</code>```

答:
Firstly you would need to have an <h:form /> component inside of the
 component tags.  You would also need to change the outputText components to that of  inputText.

You could use a <p:commandButton to confirm and persist the input. For example:

```<code><p:dialog header="System User Details" widgetVar="carDialog" modal="true" appendTo="@body">
  <h:form id="dialogForm">
      <p:outputLabel for="username" value="Username">
      <p:inputText id="username" value="#{systemusers.selectedSystemUser.username}" required="true" requiredMessage="Value is required" label="Username" />
       ....

      <p:commandButton value="Submit" update=":mainForm" actionListener="#{beanName.updateData}" oncomplete="PF('cardDialog').hide()" />
      <p:commandButton value="Cancel" type="button" onclick="PF('cardDialog').hide()" />
  </h:form>
</p:dialog>
</code>```

Title: Edit data in Primefaces dialog

Body:
How I can edit data in form? I have this Primefaces dialog which hI wants to use to edit data.

                                <h:outputText value="Username" />
                                <h:outputText value="#{systemusers.selectedSystemUser.username}" />

                                <h:outputText value="Last Login" />
                                <h:outputText value="#{systemusers.selectedSystemUser.lastLogin}" />

                                .........

                                <h:outputText value="Action" />
                                <h:outputText value="Download Delete" />

Body:
Firstly you would need to have an <h:form /> component inside of the <p:dialog /> component tags.  You would also need to change the outputText components to that of  inputText.

You could use a <p:commandButton to confirm and persist the input. For example:

<p:dialog header="System User Details" widgetVar="carDialog" modal="true" appendTo="@body">
  <h:form id="dialogForm">
      <p:outputLabel for="username" value="Username">
      <p:inputText id="username" value="#{systemusers.selectedSystemUser.username}" required="true" requiredMessage="Value is required" label="Username" />
       ....

      <p:commandButton value="Submit" update=":mainForm" actionListener="#{beanName.updateData}" oncomplete="PF('cardDialog').hide()" />
      <p:commandButton value="Cancel" type="button" onclick="PF('cardDialog').hide()" />
  </h:form>
</p:dialog>


问:
Initialize a Entity Data Model in WCF Service
I am struggling quite a bit with the following question. I have a WCF Service which contains a Entity Data Model. Actually this model is initialized with all the data contained within the underlying table, so at runtime it contains all the data. What I need is to have only certain data in my Entity Data Model.

Is it possible to initialize my Entity Data Model with a subset of the data stored in the database table? Lets say by giving a patricular where-clause somewhere?

Any help is really appreciated.

Thanks all and kind regards
Sandro

答:
I'm not sure you understand the concepts.
Entity Data Model just describes the structure of data using concepts like entity type, association type, and property. An instance of an entity type is what actually describes an object like a Customer, a Category etc and this is what is actually mapped to the underlying table. </p>

<p>That being said, there are many ways to filter your data, one of the most familiar being linq. Here are some resources: https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/ef/language-reference/queries-in-linq-to-entities  </p>

Body:
I'm not sure you understand the concepts.
Entity Data Model just describes the structure of data using concepts like entity type, association type, and property. An instance of an entity type is what actually describes an object like a Customer, a Category etc and this is what is actually mapped to the underlying table.

That being said, there are many ways to filter your data, one of the most familiar being linq. Here are some resources: https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/ef/language-reference/queries-in-linq-to-entities


问:
Opening PDF file in ionic 2 app
I am trying to make an ionic 2 app. I have a pdf generated using jsPDF.

The code for the same is

```<code>var doc = new jsPDF();
doc.setFontStyle('Bold');
doc.setFontSize(14);
doc.text('Testing PDFs', 20, 20);
</code>```

Now I want to save the open the PDF in the mobile app,

but doc.output('save', 'tester.pdf'); doesn't seem to work in the mobile app.

Please can you tell me which plugin can I install so as to view and share the newly made pdf.

答:
I think includes script via external URL may not a good option in ionic. There is an other way as below:

1-Install ng2-pdf-viewer module

```<code>npm install ng2-pdf-viewer --save
</code>```

And import PdfViewerComponent in your app.moudle.ts as below:

2- Instead of including jspdf.debug.js via extenal url, you can  install jspdf module

```<code>npm install jspdf --save
</code>```

3- Implement ionic copy custom script

Create scripts folder in root of your ionic project and create a file name copy-custom-libs.js inside scripts folder.

```<code>module.exports = {
  copyCustomScript: {
    src: ["{{ROOT}}/node_modules/jspdf/dist/jspdf.min.js"],
    dest: "{{WWW}}/assets"
  }
}
</code>```

In package.json, add config attribute at bottom as below:

```<code> "config": {
      "ionic_copy": "./scripts/copy-custom-libs.js"
  }
</code>```

Update index.html and add jspdf.min.js from your assets folder.

```<code><script src="assets/jspdf.min.js"></script>
</code>```

4-Finally, you can write code as below:

The source code of this example can be found here: ionic pdf viewer

I Hope this could help you, Thanks :)

Title: Opening PDF file in ionic 2 app

Body:
I am trying to make an ionic 2 app. I have a pdf generated using jsPDF.

The code for the same is

var doc = new jsPDF();
doc.setFontStyle('Bold');
doc.setFontSize(14);
doc.text('Testing PDFs', 20, 20);

Now I want to save the open the PDF in the mobile app,

but doc.output('save', 'tester.pdf'); doesn't seem to work in the mobile app.

Please can you tell me which plugin can I install so as to view and share the newly made pdf.

Body:
I think includes script via external URL may not a good option in ionic. There is an other way as below:

1-Install ng2-pdf-viewer module

npm install ng2-pdf-viewer --save

And import PdfViewerComponent in your app.moudle.ts as below:

2- Instead of including jspdf.debug.js via extenal url, you can  install jspdf module

npm install jspdf --save

3- Implement ionic copy custom script

Create scripts folder in root of your ionic project and create a file name copy-custom-libs.js inside scripts folder.

module.exports = {
  copyCustomScript: {
    src: ["{{ROOT}}/node_modules/jspdf/dist/jspdf.min.js"],
    dest: "{{WWW}}/assets"
  }
}

In package.json, add config attribute at bottom as below:

 "config": {
      "ionic_copy": "./scripts/copy-custom-libs.js"
  }

Update index.html and add jspdf.min.js from your assets folder.

<script src="assets/jspdf.min.js"></script>

4-Finally, you can write code as below:

The source code of this example can be found here: ionic pdf viewer

I Hope this could help you, Thanks :)


问:
Sending mass email using PHP
I am currently writing a music blog. The administrator posts a new article every 2-3 days. Once the administrator posts an article, a mass email will be sent to around 5000 subscribers immediately.

What is the best way to implement the mass mail feature?

Does the following function work?

```<code>function massmail()
{
  $content = '...';
  foreach ($recipients as $r) {
    $_content = $content . '<img src="http://xxx/trackOpenRate.php?id='.$r.'">';
    mail($r, 'subject', $_content);
  }
}
</code>```

Another question: If all 5000 subscribers are using Yahoo Mail, will Yahoo treat it as a DDOS attack and block the IP address of my SMTP server?

答:
You can use swiftmailer for it. By using batch process.</p>

```<code><?php
    $message = Swift_Message::newInstance()
      ->setSubject('Let\'s get together today.')
      ->setFrom(array('myfrom@domain.com' => 'From Me'))
      ->setBody('Here is the message itself')
      ->addPart('<b>Test message being sent!!</b>', 'text/html');

    $data = mysql_query('SELECT first, last, email FROM users WHERE is_active=1') or die(mysql_error());
    while($row = mysql_fetch_assoc($data))
    {
       $message->addTo($row['email'], $row['first'] . ' ' . $row['last']);
    }

    $message->batchSend();
?>
</code>```

Title: Sending mass email using PHP

Body:
I am currently writing a music blog. The administrator posts a new article every 2-3 days. Once the administrator posts an article, a mass email will be sent to around 5000 subscribers immediately.

What is the best way to implement the mass mail feature?

Does the following function work?

function massmail()
{
  $content = '...';
  foreach ($recipients as $r) {
    $_content = $content . '';
    mail($r, 'subject', $_content);
  }
}

Another question: If all 5000 subscribers are using Yahoo Mail, will Yahoo treat it as a DDOS attack and block the IP address of my SMTP server?

Body:
You can use swiftmailer for it. By using batch process.

<?php
    $message = Swift_Message::newInstance()
      ->setSubject('Let\'s get together today.')
      ->setFrom(array('myfrom@domain.com' => 'From Me'))
      ->setBody('Here is the message itself')
      ->addPart('<b>Test message being sent!!</b>', 'text/html');

    $data = mysql_query('SELECT first, last, email FROM users WHERE is_active=1') or die(mysql_error());
    while($row = mysql_fetch_assoc($data))
    {
       $message->addTo($row['email'], $row['first'] . ' ' . $row['last']);
    }

    $message->batchSend();
?>


问:
Ruby query need to update
Relationship:

account has_many users

user has_one sima

primary_partner_id is "account_id" which is passing as params.

```<code>User.where(primary_partner_id: 2).map{|a| a.sima}.reject{ |e| e.to_s.empty?}
</code>```

Results as below:

```<code> [
    #<Sima id: 93, user_id: 7, interviewer_account_user_id: 1945, interviewer_completion_date: "2017-06-09", transcriber_account_user_id: nil, transcriber_completion_date: nil, biographer_account_user_id: nil, biographer_completion_date: nil, reviewer_account_user_id: nil, reviewer_completion_date: nil, status: "accepted", autobiographical_form: "27381", autobiographical_form_completion_date: nil, sima_level_id: "1", created_at: "2017-06-06 20:17:57", updated_at: "2017-06-09 10:04:33", autobiographical_form_comments: nil, on_hold: nil, comments: [{:comment=>"easylims.xlsx", :user_name=>"Mike Burns", :created_at=>2017-06-06 20:17:57 UTC}, {:comment=>"ok", :user_name=>"SIMA Admin", :created_at=>2017-06-06 20:19:33 UTC}], interviewer_id: nil, interviewer_start_date: nil, transcriber_start_date: nil, biographer_start_date: nil, reviewer_start_date: nil>,
    #<Sima id: 92, user_id: 1, interviewer_account_user_id: nil, interviewer_completion_date: nil, transcriber_account_user_id: nil, transcriber_completion_date: nil, biographer_account_user_id: nil, biographer_completion_date: nil, reviewer_account_user_id: nil, reviewer_completion_date: nil, status: "accepted", autobiographical_form: "27437", autobiographical_form_completion_date: nil, sima_level_id: "1", created_at: "2017-06-06 20:01:50", updated_at: "2017-06-06 20:22:50", autobiographical_form_comments: nil, on_hold: nil, comments: [{:comment=>"original_msg (1).txt", :user_name=>"bild_cloud@bild.org", :created_at=>2017-06-06 20:01:50 UTC}, {:comment=>"ok", :user_name=>"SIMA Admin", :created_at=>2017-06-06 20:22:05 UTC}], interviewer_id: nil, interviewer_start_date: nil, transcriber_start_date: nil, biographer_start_date: nil, reviewer_start_date: nil>
 ]
</code>```

Sima has field like status and I have three statuses as "pending, accepted, declined"

Question:

Now I want to show the result as per status which will pass by the user as params. So the result should be as per status from Sima. If params is status=" accepted" then Sima list will have only which has status "accepted"

答:
```<code>User.preload(:sima).joins(:sima).where(sima: {status: params[:status]}, primary_partner_id: params[:account_id]).map(&:sima)
</code>```

or

As account to users relationship is already defined you can directly do...

```<code>Account.find(2).users.preload(:sima).joins(:sima).where(sima: {status: params[:status]}).map(&:sima)
</code>```

Title: Ruby query need to update

Body:
Relationship:

account has_many users

user has_one sima

primary_partner_id is "account_id" which is passing as params.

User.where(primary_partner_id: 2).map{|a| a.sima}.reject{ |e| e.to_s.empty?}

Results as below:

 [
    #<Sima id: 93, user_id: 7, interviewer_account_user_id: 1945, interviewer_completion_date: "2017-06-09", transcriber_account_user_id: nil, transcriber_completion_date: nil, biographer_account_user_id: nil, biographer_completion_date: nil, reviewer_account_user_id: nil, reviewer_completion_date: nil, status: "accepted", autobiographical_form: "27381", autobiographical_form_completion_date: nil, sima_level_id: "1", created_at: "2017-06-06 20:17:57", updated_at: "2017-06-09 10:04:33", autobiographical_form_comments: nil, on_hold: nil, comments: [{:comment=>"easylims.xlsx", :user_name=>"Mike Burns", :created_at=>2017-06-06 20:17:57 UTC}, {:comment=>"ok", :user_name=>"SIMA Admin", :created_at=>2017-06-06 20:19:33 UTC}], interviewer_id: nil, interviewer_start_date: nil, transcriber_start_date: nil, biographer_start_date: nil, reviewer_start_date: nil>,
    #<Sima id: 92, user_id: 1, interviewer_account_user_id: nil, interviewer_completion_date: nil, transcriber_account_user_id: nil, transcriber_completion_date: nil, biographer_account_user_id: nil, biographer_completion_date: nil, reviewer_account_user_id: nil, reviewer_completion_date: nil, status: "accepted", autobiographical_form: "27437", autobiographical_form_completion_date: nil, sima_level_id: "1", created_at: "2017-06-06 20:01:50", updated_at: "2017-06-06 20:22:50", autobiographical_form_comments: nil, on_hold: nil, comments: [{:comment=>"original_msg (1).txt", :user_name=>"bild_cloud@bild.org", :created_at=>2017-06-06 20:01:50 UTC}, {:comment=>"ok", :user_name=>"SIMA Admin", :created_at=>2017-06-06 20:22:05 UTC}], interviewer_id: nil, interviewer_start_date: nil, transcriber_start_date: nil, biographer_start_date: nil, reviewer_start_date: nil>
 ]

Sima has field like status and I have three statuses as "pending, accepted, declined"

Question:

Now I want to show the result as per status which will pass by the user as params. So the result should be as per status from Sima. If params is status=" accepted" then Sima list will have only which has status "accepted"

Body:
User.preload(:sima).joins(:sima).where(sima: {status: params[:status]}, primary_partner_id: params[:account_id]).map(&:sima)

or

As account to users relationship is already defined you can directly do...

Account.find(2).users.preload(:sima).joins(:sima).where(sima: {status: params[:status]}).map(&:sima)


问:
Check if file is alias Swift
How can I check if a file is an Alias on Mac? Here is my code so far:

```<code>public func getFiles(){
    let folderPath = "/Users/timeBro/Desktop/testfolder"
    let fileManager = NSFileManager.defaultManager()
    let enumerator:NSDirectoryEnumerator = fileManager.enumeratorAtPath(folderPath)!

    for url in enumerator.allObjects {

        let newurl = NSURL(string: url as! String)
        print("\(url as! String)")
        print(url);
        print(newurl?.isFileReferenceURL())
    }
}
</code>```

How can I check if the file is and alias?

答:
There is an easy solution which completely gets by without any pointer handling:

```<code>extension URL {
    func isAlias() -> Bool? {
        let values = try? url.resourceValues(forKeys: [.isSymbolicLinkKey, .isAliasFileKey])
        let alias = values?.isAliasFile
        let symbolic = values?.isSymbolicLink

        guard alias != nil, symbolic != nil else { return nil }
        if alias! && !symbolic! {
            return true
        }
        return false
    }
}
</code>```

Explanation: resourceValues(forKeys:) returns .isAliasFile and .isSymbolicLink for symbolic links so you have to make sure the former is returned and the latter isn’t when checking for aliases.
If the path doesn’t exist the function returns nil.

Title: Check if file is alias Swift

Body:
How can I check if a file is an Alias on Mac? Here is my code so far:

public func getFiles(){
    let folderPath = "/Users/timeBro/Desktop/testfolder"
    let fileManager = NSFileManager.defaultManager()
    let enumerator:NSDirectoryEnumerator = fileManager.enumeratorAtPath(folderPath)!

    for url in enumerator.allObjects {

        let newurl = NSURL(string: url as! String)
        print("\(url as! String)")
        print(url);
        print(newurl?.isFileReferenceURL())
    }
}

How can I check if the file is and alias?

Body:
There is an easy solution which completely gets by without any pointer handling:

extension URL {
    func isAlias() -> Bool? {
        let values = try? url.resourceValues(forKeys: [.isSymbolicLinkKey, .isAliasFileKey])
        let alias = values?.isAliasFile
        let symbolic = values?.isSymbolicLink

        guard alias != nil, symbolic != nil else { return nil }
        if alias! && !symbolic! {
            return true
        }
        return false
    }
}

Explanation: resourceValues(forKeys:) returns .isAliasFile and .isSymbolicLink for symbolic links so you have to make sure the former is returned and the latter isn’t when checking for aliases.
If the path doesn’t exist the function returns nil.


问:
How to get a character line from a website with Javascript
What i want to do is to get a line of character from a website which has a token generator that generates every time it opens a new code and then put into my link.</p>

答:
Not sure if it's what you want : </p>

```<code>    var link = "mylink.com/"+result ;
</code>```

Body:
Not sure if it's what you want :

    var link = "mylink.com/"+result ;


问:
SSAS MDX Create set fails with on an empty set
I am currently maintaining some legacy MDX code. After some ETL changes in one of the columns I have now only False values - previously there were both True and False values to be found in the [Bool1]. My question is hot to change the below code fragment so that it will not fail with only False values?

```<code>CREATE SET CURRENTCUBE.[Set1]
    AS { [Customer].[Bool1].&[True] }, DISPLAY_FOLDER = 'Dimension Filters';
</code>```

The error I am getting is:

The level '&[True]' object was not found in the cube when the string, [Customer].[Bool1].&[True], was parsed.

Maybe there is a reference later to this object and as it is empty it fails?

答:
I worked it around with set subtraction so that I do not call the &[True] level which does not exists:

{ [Customer].[Bool1].MEMBERS - [Customer].[Bool1].&[False] }

Body:
I am currently maintaining some legacy MDX code. After some ETL changes in one of the columns I have now only False values - previously there were both True and False values to be found in the [Bool1]. My question is hot to change the below code fragment so that it will not fail with only False values?

CREATE SET CURRENTCUBE.[Set1]
    AS { [Customer].[Bool1].&[True] }, DISPLAY_FOLDER = 'Dimension Filters';

The error I am getting is:

The level '&[True]' object was not found in the cube when the string, [Customer].[Bool1].&[True], was parsed.

Maybe there is a reference later to this object and as it is empty it fails?