问:
Invalid layout param (layout_alignParentBottom) in TabLayout
I am trying to put TabLayout on the bottom of the screen. Trying to use layout_alignParentBottom but get an invalid layout param error. Any param I should use? Thanks.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".TabBar">

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabGravity="fill"
        app:tabMode="fixed"
        android:layout_alignParentBottom="true" />

    <FrameLayout
        android:id="@+id/frame_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>
```

答:
Try this

layout_alignParentBottom is a RelativeLayout.LayoutParams

```<code>  <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabGravity="fill"
        app:tabMode="fixed"
        android:layout_alignParentBottom="true" />

    <FrameLayout
        android:id="@+id/frame_container"
        android:layout_width="match_parent"
        android:layout_above="@+id/tabs"
        android:layout_height="match_parent" />

</RelativeLayout>
</code>```

Body:
Try this

layout_alignParentBottom is a RelativeLayout.LayoutParams

  <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabGravity="fill"
        app:tabMode="fixed"
        android:layout_alignParentBottom="true" />

    <FrameLayout
        android:id="@+id/frame_container"
        android:layout_width="match_parent"
        android:layout_above="@+id/tabs"
        android:layout_height="match_parent" />

</RelativeLayout>


来源: stackexchange

问:
Android Architecture Components: bind to ViewModel
I'm a bit confused about how data binding should work when using the new Architecture Components.

let's say I have a simple Activity with a list, a ProgressBar and a TextView. the Activity should be responsible for controlling the state of all the views, but the ViewModel should hold the data and the logic.
For example, my Activity now looks like this:

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

    binding = DataBindingUtil.setContentView(this, R.layout.activity_main);

    listViewModel = ViewModelProviders.of(this).get(ListViewModel.class);

    binding.setViewModel(listViewModel);

    list = findViewById(R.id.games_list);

    listViewModel.getList().observeForever(new Observer<List<Game>>() {
        @Override
        public void onChanged(@Nullable List<Game> items) {
            setUpList(items);
        }
    });

    listViewModel.loadGames();
}

private void setUpList(List<Game> items){
    list.setLayoutManager(new LinearLayoutManager(this));
    GameAdapter adapter = new GameAdapter();
    adapter.setList(items);
    list.setAdapter(adapter);
}
</code>```

and the ViewModel it's only responsible for loading the data and notify the Activity when the list is ready so it can prepare the Adapter and show the data:

```<code>public int progressVisibility = View.VISIBLE;

private MutableLiveData<List<Game>> list;

public void loadGames(){

    Retrofit retrofit = GamesAPI.create();

    GameService service = retrofit.create(GameService.class);

    Call<GamesResponse> call = service.fetchGames();

    call.enqueue(this);
}

@Override
public void onResponse(Call<GamesResponse> call, Response<GamesResponse> response) {
    if(response.body().response.equals("success")){
        setList(response.body().data);

    }
}

@Override
public void onFailure(Call<GamesResponse> call, Throwable t) {

}

public MutableLiveData<List<Game>> getList() {
    if(list == null)
        list = new MutableLiveData<>();
    if(list.getValue() == null)
        list.setValue(new ArrayList<Game>());
    return list;
}

public void setList(List<Game> list) {
    this.list.postValue(list);
}
</code>```

My question is: which is the correct way to show/hide the list, progressbar and error text?

should I add an Integer for each View in the ViewModel making it control the views and using it like:

```<code><TextView
    android:id="@+id/main_list_error"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@{viewModel.error}"
    android:visibility="@{viewModel.errorVisibility}" />
</code>```

or should the ViewModel instantiate a LiveData object for each property:

```<code>private MutableLiveData<Integer> progressVisibility = new MutableLiveData<>();
private MutableLiveData<Integer> listVisibility = new MutableLiveData<>();
    private MutableLiveData<Integer> errorVisibility = new MutableLiveData<>();
</code>```

update their value when needed and make the Activity observe their value?

```<code>viewModel.getProgressVisibility().observeForever(new Observer<Integer>() {
    @Override
    public void onChanged(@Nullable Integer visibility) {
        progress.setVisibility(visibility);
    }
});

viewModel.getListVisibility().observeForever(new Observer<Integer>() {
    @Override
    public void onChanged(@Nullable Integer visibility) {
        list.setVisibility(visibility);
    }
});

viewModel.getErrorVisibility().observeForever(new Observer<Integer>() {
    @Override
    public void onChanged(@Nullable Integer visibility) {
        error.setVisibility(visibility);
    }
});
</code>```

I'm really struggling to understand that. If someone can clarify that, it would be great.

Thanks

答:
Here are simple steps:

```<code>public class MainViewModel extends ViewModel {

    MutableLiveData<ArrayList<Game>> gamesLiveData = new MutableLiveData<>();
    // ObservableBoolean or ObservableField are classes from
    // databinding library (android.databinding.ObservableBoolean)

    public ObservableBoolean progressVisibile = new ObservableBoolean();
    public ObservableBoolean listVisibile = new ObservableBoolean();
    public ObservableBoolean errorVisibile = new ObservableBoolean();
    public ObservableField<String> error = new ObservableField<String>();

    // ...

    // For example we want to change list and progress visibility
    // We should just change ObservableBoolean property
    // databinding knows how to bind view to changed of field

    public void loadGames(){
        GamesAPI.create().create(GameService.class)
            .fetchGames().enqueue(this);

        listVisibile.set(false);
        progressVisibile.set(true);
    }

    @Override
    public void onResponse(Call<GamesResponse> call, Response<GamesResponse> response) {
        if(response.body().response.equals("success")){
            gamesLiveData.setValue(response.body().data);

            listVisibile.set(true);
            progressVisibile.set(false);
        }
    }

}
</code>```

And then

```<code><data>
    <import type="android.view.View"/>

    <variable
        name="viewModel"
        type="MainViewModel"/>
</data>

...

<ProgressBar
    android:layout_width="32dp"
    android:layout_height="32dp"
    android:visibility="@{viewModel.progressVisibile ? View.VISIBLE : View.GONE}"/>

<ListView
    android:layout_width="32dp"
    android:layout_height="32dp"
    android:visibility="@{viewModel.listVisibile ? View.VISIBLE : View.GONE}"/>

<TextView
    android:id="@+id/main_list_error"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@{viewModel.error}"
    android:visibility="@{viewModel.errorVisibile ? View.VISIBLE : View.GONE}"/>
</code>```

Also notice that it's your choice to make view observe

```<code>ObservableBoolean : false / true
    // or
ObservableInt : View.VISIBLE / View.INVISIBLE / View.GONE
</code>```

but ObservableBoolean is better for ViewModel testing.

Also you should observe LiveData considering lifecycle:

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    ...
    listViewModel.getList().observe((LifecycleOwner) this, new Observer<List<Game>>() {
        @Override
        public void onChanged(@Nullable List<Game> items) {
            setUpList(items);
        }
    });
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm a bit confused about how data binding should work when using the new Architecture Components.

let's say I have a simple Activity with a list, a ProgressBar and a TextView. the Activity should be responsible for controlling the state of all the views, but the ViewModel should hold the data and the logic.
For example, my Activity now looks like this:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    binding = DataBindingUtil.setContentView(this, R.layout.activity_main);

    listViewModel = ViewModelProviders.of(this).get(ListViewModel.class);

    binding.setViewModel(listViewModel);

    list = findViewById(R.id.games_list);

    listViewModel.getList().observeForever(new Observer<List<Game>>() {
        @Override
        public void onChanged(@Nullable List<Game> items) {
            setUpList(items);
        }
    });

    listViewModel.loadGames();
}

private void setUpList(List<Game> items){
    list.setLayoutManager(new LinearLayoutManager(this));
    GameAdapter adapter = new GameAdapter();
    adapter.setList(items);
    list.setAdapter(adapter);
}

and the ViewModel it's only responsible for loading the data and notify the Activity when the list is ready so it can prepare the Adapter and show the data:

public int progressVisibility = View.VISIBLE;

private MutableLiveData<List<Game>> list;

public void loadGames(){

    Retrofit retrofit = GamesAPI.create();

    GameService service = retrofit.create(GameService.class);

    Call<GamesResponse> call = service.fetchGames();

    call.enqueue(this);
}

@Override
public void onResponse(Call<GamesResponse> call, Response<GamesResponse> response) {
    if(response.body().response.equals("success")){
        setList(response.body().data);

    }
}

@Override
public void onFailure(Call<GamesResponse> call, Throwable t) {

}

public MutableLiveData<List<Game>> getList() {
    if(list == null)
        list = new MutableLiveData<>();
    if(list.getValue() == null)
        list.setValue(new ArrayList<Game>());
    return list;
}

public void setList(List<Game> list) {
    this.list.postValue(list);
}

My question is: which is the correct way to show/hide the list, progressbar and error text?

should I add an Integer for each View in the ViewModel making it control the views and using it like:

<TextView
    android:id="@+id/main_list_error"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@{viewModel.error}"
    android:visibility="@{viewModel.errorVisibility}" />

or should the ViewModel instantiate a LiveData object for each property:

private MutableLiveData<Integer> progressVisibility = new MutableLiveData<>();
private MutableLiveData<Integer> listVisibility = new MutableLiveData<>();
    private MutableLiveData<Integer> errorVisibility = new MutableLiveData<>();

update their value when needed and make the Activity observe their value?

viewModel.getProgressVisibility().observeForever(new Observer<Integer>() {
    @Override
    public void onChanged(@Nullable Integer visibility) {
        progress.setVisibility(visibility);
    }
});

viewModel.getListVisibility().observeForever(new Observer<Integer>() {
    @Override
    public void onChanged(@Nullable Integer visibility) {
        list.setVisibility(visibility);
    }
});

viewModel.getErrorVisibility().observeForever(new Observer<Integer>() {
    @Override
    public void onChanged(@Nullable Integer visibility) {
        error.setVisibility(visibility);
    }
});

I'm really struggling to understand that. If someone can clarify that, it would be great.

Thanks

Body:
Here are simple steps:

public class MainViewModel extends ViewModel {

    MutableLiveData<ArrayList<Game>> gamesLiveData = new MutableLiveData<>();
    // ObservableBoolean or ObservableField are classes from
    // databinding library (android.databinding.ObservableBoolean)

    public ObservableBoolean progressVisibile = new ObservableBoolean();
    public ObservableBoolean listVisibile = new ObservableBoolean();
    public ObservableBoolean errorVisibile = new ObservableBoolean();
    public ObservableField<String> error = new ObservableField<String>();

    // ...

    // For example we want to change list and progress visibility
    // We should just change ObservableBoolean property
    // databinding knows how to bind view to changed of field

    public void loadGames(){
        GamesAPI.create().create(GameService.class)
            .fetchGames().enqueue(this);

        listVisibile.set(false);
        progressVisibile.set(true);
    }

    @Override
    public void onResponse(Call<GamesResponse> call, Response<GamesResponse> response) {
        if(response.body().response.equals("success")){
            gamesLiveData.setValue(response.body().data);

            listVisibile.set(true);
            progressVisibile.set(false);
        }
    }

}

And then

<data>
    <import type="android.view.View"/>

    <variable
        name="viewModel"
        type="MainViewModel"/>
</data>

...

<ProgressBar
    android:layout_width="32dp"
    android:layout_height="32dp"
    android:visibility="@{viewModel.progressVisibile ? View.VISIBLE : View.GONE}"/>

<ListView
    android:layout_width="32dp"
    android:layout_height="32dp"
    android:visibility="@{viewModel.listVisibile ? View.VISIBLE : View.GONE}"/>

<TextView
    android:id="@+id/main_list_error"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@{viewModel.error}"
    android:visibility="@{viewModel.errorVisibile ? View.VISIBLE : View.GONE}"/>

Also notice that it's your choice to make view observe

ObservableBoolean : false / true
    // or
ObservableInt : View.VISIBLE / View.INVISIBLE / View.GONE

but ObservableBoolean is better for ViewModel testing.

Also you should observe LiveData considering lifecycle:

@Override
protected void onCreate(Bundle savedInstanceState) {
    ...
    listViewModel.getList().observe((LifecycleOwner) this, new Observer<List<Game>>() {
        @Override
        public void onChanged(@Nullable List<Game> items) {
            setUpList(items);
        }
    });
}


问:
htaccess RewriteRule with optional language switch
I've set up htaccess RewriteRules to rewrite e.g. "domain.ext/en/page" to "domain.ext?lang=en&p=page" which works as expected.

However, I want to make the language part optional, so "domain.ext/page" will also rewrite to "domain.ext?lang=en&p=page".

Here's the htaccess code:

```<code>RewriteEngine On
RewriteBase /

RewriteCond %{HTTP_REFERER} !^domain.ext/.*$ [NC]

Options +FollowSymlinks

RewriteRule ^$              index.php?lang=en
RewriteRule ^(en|nl)/?$         index.php?lang=$1
RewriteRule ^(en|nl)/([^/]+)/?$         index.php?lang=$1&p=$2
</code>```

So I'd like to add something like:

```<code>RewriteRule ^([^/][[NOT (en or nl)]]+)/?$           index.php?lang=en&p=$2
</code>```

答:
You can try the following regex:

```<code>^(?!en|nl)([^/]+)/?$
</code>```

to rewrite "domain.ext/page" will also rewrite to index.php?lang=en&p=$2.

You can also add:

```<code>^(?!en|nl)[a-z]{2}/([^/]+)/?$
</code>```

to rewrite jp/page/, fr/page/ to index.php?lang=en&p=$2

I hope that it helps you. Good luck :-)

Body:
I've set up htaccess RewriteRules to rewrite e.g. "domain.ext/en/page" to "domain.ext?lang=en&p=page" which works as expected.

However, I want to make the language part optional, so "domain.ext/page" will also rewrite to "domain.ext?lang=en&p=page".

Here's the htaccess code:

RewriteEngine On
RewriteBase /

RewriteCond %{HTTP_REFERER} !^domain.ext/.*$ [NC]

Options +FollowSymlinks

RewriteRule ^$              index.php?lang=en
RewriteRule ^(en|nl)/?$         index.php?lang=$1
RewriteRule ^(en|nl)/([^/]+)/?$         index.php?lang=$1&p=$2

So I'd like to add something like:

RewriteRule ^([^/][[NOT (en or nl)]]+)/?$           index.php?lang=en&p=$2

Body:
You can try the following regex:

^(?!en|nl)([^/]+)/?$

to rewrite "domain.ext/page" will also rewrite to index.php?lang=en&p=$2.

You can also add:

^(?!en|nl)[a-z]{2}/([^/]+)/?$

to rewrite jp/page/, fr/page/ to index.php?lang=en&p=$2

I hope that it helps you. Good luck :-)


问:
Muted Autoplay in Chrome still not working
I am having trouble getting chrome to autoplay a video. I have set the video to muted and it auto plays in both Safari and Firefox but not chrome.

```<code>            <video autoplay muted poster="path to video" id="bgvid">

        <source src="assets/uploads/hero/livePhotoNoSound.mp4" type="video/webm">

            <source src="assets/uploads/hero/livePhotoNoSound.mp4" type="video/mp4">

        </video>
</code>```

I want to video to start playing automatically. Currently the video loads, but is just still. Everything I've read says that as long as it's muted it should play, but that is not the result I'm getting.

答:
The example below, with minimal change from your code, plays in chrome (Version 62.0.3202.94 ) on a Mac (10.12.6):

<video autoplay muted poster="path to video" id="bgvid">
    <source src="http://clips.vorwaerts-gmbh.de/VfE_html5.mp4" type="video/mp4">
</video>  ```

It may be that Safari and Friefox are playing the mp4 and chrome the webm, and the issue related to the webm video itself rather than your HTML5 code.

Body:
I am having trouble getting chrome to autoplay a video. I have set the video to muted and it auto plays in both Safari and Firefox but not chrome.

            <video autoplay muted poster="path to video" id="bgvid">

        <source src="assets/uploads/hero/livePhotoNoSound.mp4" type="video/webm">

            <source src="assets/uploads/hero/livePhotoNoSound.mp4" type="video/mp4">

        </video>

I want to video to start playing automatically. Currently the video loads, but is just still. Everything I've read says that as long as it's muted it should play, but that is not the result I'm getting.

Body:
The example below, with minimal change from your code, plays in chrome (Version 62.0.3202.94 ) on a Mac (10.12.6):

<video autoplay muted poster="path to video" id="bgvid">
    <source src="http://clips.vorwaerts-gmbh.de/VfE_html5.mp4" type="video/mp4">
</video>

It may be that Safari and Friefox are playing the mp4 and chrome the webm, and the issue related to the webm video itself rather than your HTML5 code.


问:
check box value posting and jquery ajax
i have this scenario in my program, i'm printing a list of check boxes to my main page using below codes

```<code><form action="two.php" method="post">
    <div id="option_box" style="width: 250px; height: 400px; overflow: scroll;">
            <?php
            $sql = "SELECT * FROM gene_names ORDER BY name";
            $result = $db->query($sql);
            $counter = 0;
            echo "<table border=\"0\">";
            while ($row = $result->fetch()) {
                $output[] = "<tr>";
                $output[] = "<td>";
                $output[] = "<input type=\"checkbox\" value=\"".$row['name']."\" name=\"things[]\" id=\"ran\"/>";
                $output[] = " ";
                $output[] = $row['name'];
                                $output[] = "</td>";
                $output[] = "</tr>";
                $counter++;
            }
            echo join('',$output);
            echo "</table>";
        ?>
    </div>
    <input type="submit" value="See Interactions" name="see" id="see"/>
 </form>
</code>```

after that i'm using the below code to get the process done using jquery ajax

```<code>        $('#see').click(function(eve){
                eve.preventDefault();
                $.post('two.php', function(data) {
                        $('#results_of_interactions').html(data);
                });
    });
</code>```

but i need to get the selected check box values inside my two.php(the files handling the processes of the above form) file in order to execute a sql query, but when i use this jquery approach the check box variables are not available at my two.php file, so my query is not properly executed and i can't get the results, how can i correct this issue?please suggest some thing to do, a modification to this or another approach?

regards,
Rangana

答:
That's because you have to manually prepare the data and send it along with your post request, it does not submit the form, it submits whatever you manually tell it to submit to two.php

```<code>$('#see').click(function(eve){
    eve.preventDefault();

    //serialize form data to be sent with request
    var data = $('form').serialize();

    //send request with 'data'
    $.post('two.php', data, function(data) {
        $('#results_of_interactions').html(data);
    },'json');
});
</code>```

ContentLicense: CC BY-SA 2.5

Title: check box value posting and jquery ajax

Body:
i have this scenario in my program, i'm printing a list of check boxes to my main page using below codes

<form action="two.php" method="post">

            <?php
            $sql = "SELECT * FROM gene_names ORDER BY name";
            $result = $db->query($sql);
            $counter = 0;
            echo "
";
            while ($row = $result->fetch()) {
                $output[] = "
";
                $output[] = "";
                $output[] = "<input type=\"checkbox\" value=\"".$row['name']."\" name=\"things[]\" id=\"ran\"/>";
                $output[] = " ";
                $output[] = $row['name'];
                                $output[] = "	";
                $output[] = "
";
                $counter++;
            }
            echo join('',$output);
            echo "
";
        ?>

    <input type="submit" value="See Interactions" name="see" id="see"/>
 </form>

after that i'm using the below code to get the process done using jquery ajax

        $('#see').click(function(eve){
                eve.preventDefault();
                $.post('two.php', function(data) {
                        $('#results_of_interactions').html(data);
                });
    });

but i need to get the selected check box values inside my two.php(the files handling the processes of the above form) file in order to execute a sql query, but when i use this jquery approach the check box variables are not available at my two.php file, so my query is not properly executed and i can't get the results, how can i correct this issue?please suggest some thing to do, a modification to this or another approach?

regards,
Rangana

Body:
That's because you have to manually prepare the data and send it along with your post request, it does not submit the form, it submits whatever you manually tell it to submit to two.php

$('#see').click(function(eve){
    eve.preventDefault();

    //serialize form data to be sent with request
    var data = $('form').serialize();

    //send request with 'data'
    $.post('two.php', data, function(data) {
        $('#results_of_interactions').html(data);
    },'json');
});


问:
Issue when writing a python list to excel, list items are missing
Just recently started using Python, the version I have is 3.5

I'm using openpyxl to write a list to a single column on an excel sheet, nothing too complicated, here is the code:

```<code>import openpyxl
import random

wb = openpyxl.load_workbook('testSave.xlsx')
target_sheet = wb.get_sheet_by_name('Destination')

##create a list with random numbers
for i in range(1,20):
    container.append(random.randint(1,20))

for j in container:
    rowIn = container.index(i)
    target_sheet.cell(row = rowIn + 1, column = 1).value = container[rowIn]

wb.save('testSave.xlsx')
</code>```

When I open the workbook several of the list items are missing, 10 in total, not sure what I'm doing wrong, been researching about this for a few days now without any luck, it is probably something silly, any help will be greatly appreciated.

答:
list.index() is not doing what you think it does - it returns the first index of the element value found in the list. Given that you can have duplicate elements in the list you will never get indexes of the repeated elements. If you want to enumerate your list, use enumerate():

```<code>import openpyxl
import random

wb = openpyxl.load_workbook('testSave.xlsx')
target_sheet = wb.get_sheet_by_name('Destination')

##create a list with random numbers
for i in range(1,20):
    container.append(random.randint(1,20))

for i, j in enumerate(container):
    target_sheet.cell(row = i + 1, column = 1).value = j

wb.save('testSave.xlsx')
</code>```

Body:
Just recently started using Python, the version I have is 3.5

I'm using openpyxl to write a list to a single column on an excel sheet, nothing too complicated, here is the code:

import openpyxl
import random

wb = openpyxl.load_workbook('testSave.xlsx')
target_sheet = wb.get_sheet_by_name('Destination')

##create a list with random numbers
for i in range(1,20):
    container.append(random.randint(1,20))

for j in container:
    rowIn = container.index(i)
    target_sheet.cell(row = rowIn + 1, column = 1).value = container[rowIn]

wb.save('testSave.xlsx')

When I open the workbook several of the list items are missing, 10 in total, not sure what I'm doing wrong, been researching about this for a few days now without any luck, it is probably something silly, any help will be greatly appreciated.

Body:
list.index() is not doing what you think it does - it returns the first index of the element value found in the list. Given that you can have duplicate elements in the list you will never get indexes of the repeated elements. If you want to enumerate your list, use enumerate():

import openpyxl
import random

wb = openpyxl.load_workbook('testSave.xlsx')
target_sheet = wb.get_sheet_by_name('Destination')

##create a list with random numbers
for i in range(1,20):
    container.append(random.randint(1,20))

for i, j in enumerate(container):
    target_sheet.cell(row = i + 1, column = 1).value = j

wb.save('testSave.xlsx')


问:
Cognito get new token after updating user attributes
I have a question regarding Amazon Cognito.
What I want to achieve is to set default custom attribute for the user record.
Ideally it will be great if I could set it by default in user pool, for example "custom:domain": "some name". But I can't find an example for this, or maybe set it up in Pre sign-up trigger with Lambda, but I didn't find examples for it also. What I did, when user authenticate I get the user attributes and set the required one with updateAttributes (I use amazon-cognito-identity-js). The downside of this approach that I faced, on first user login he gets the tokens first and only after that this custom attribute it set. So in first login this attribute is missed in token. What I want to ask what is the best approach of doing this kind of staff? And if my variant is appropriate, how could I update user token after changing the user attributes, so they appear in that token.

答:
You will get the new attributes in the tokens on token refresh. However, the SDK's do not provide a method to manually refresh the tokens. We will consider this as a feature request for our SDK's.
Tokens are typically valid for an hour and are automatically refreshed by the SDK when they have expired. So your user's would get tokens with new attributes at-least after an hour.</p>

ContentLicense: CC BY-SA 4.0


问:
Xamarin TabbedPages MVVM Binding
How to bind tabbed page with different view models?
To make it clearer I have this tabbed page:

```<code><TabbedPage.Children>
    <tabPages:Page1/>
    <tabPages:Page2/>
    <tabPages:Page3/>
</TabbedPage.Children>
</code>```

These 3 pages have different view models. However, the problem is the view models of each pages won't bind. Is there a specific way in order to do this?

To test if my view models for each pages works, I inlined the code in tabbed page:
e.g.

```<code><TabbedPage.Children>
    <ContentPage Title="Test">
    <Label Text="{Binding TestBind}"/>
    </ContentPage>
</TabbedPage.Children>
</code>```

And for bind it to the view model of the tabbed page (parent) - this method works. However, if I do it separately, the view models wouldn't bind.
E.g.

```<code>public class Page1ViewModel : BaseViewModel
{
        public Page1ViewModel()
        {
            TestBind = "Test";
        }
        private string _TestBind;
        public string TestBind
        {
            get { return _TestBind; }
            set { SetProperty(ref _TestBind, value); }
        }
}
</code>```

Using it this way, it wouldn't bind

答:
I've made it worked, so this is what I did:

```<code>  <TabbedPage.Children>
        <views:ChildPage1>
            <views:ChildPage1.BindingContext>
                <viewModels:ChildPage1ViewModel/>
            </views:ChildPage1.BindingContext>
        </views:ChildPage1>
        <views:ChildPage2>
            <views:ChildPage2.BindingContext>
                <viewModels:ChildPage2ViewModel/>
            </views:ChildPage2.BindingContext>
        </views:ChildPage2>
    </TabbedPage.Children>
</code>```

I used binding context property of the element to set it.

Title: Xamarin TabbedPages MVVM Binding

Body:
How to bind tabbed page with different view models?
To make it clearer I have this tabbed page:

<TabbedPage.Children>
    <tabPages:Page1/>
    <tabPages:Page2/>
    <tabPages:Page3/>
</TabbedPage.Children>

These 3 pages have different view models. However, the problem is the view models of each pages won't bind. Is there a specific way in order to do this?

To test if my view models for each pages works, I inlined the code in tabbed page:
e.g.

<TabbedPage.Children>
    <ContentPage Title="Test">

    </ContentPage>
</TabbedPage.Children>

And for bind it to the view model of the tabbed page (parent) - this method works. However, if I do it separately, the view models wouldn't bind.
E.g.

public class Page1ViewModel : BaseViewModel
{
        public Page1ViewModel()
        {
            TestBind = "Test";
        }
        private string _TestBind;
        public string TestBind
        {
            get { return _TestBind; }
            set { SetProperty(ref _TestBind, value); }
        }
}

Using it this way, it wouldn't bind

Body:
I've made it worked, so this is what I did:

  <TabbedPage.Children>
        <views:ChildPage1>
            <views:ChildPage1.BindingContext>
                <viewModels:ChildPage1ViewModel/>
            </views:ChildPage1.BindingContext>
        </views:ChildPage1>
        <views:ChildPage2>
            <views:ChildPage2.BindingContext>
                <viewModels:ChildPage2ViewModel/>
            </views:ChildPage2.BindingContext>
        </views:ChildPage2>
    </TabbedPage.Children>

I used binding context property of the element to set it.


问:
Referencing data from sheet one to sheet 2
I have a large spread sheet with multiple pages, columns and rows on each page.

on page Teams, I have row 3 column B as rider #12, and Column C as Time:

I need Column C,row 3 to display the time of the rider# from B3 from page Master Score Sheet.  On master score sheet, rider Numbers are in Column A and their times are displayed in column W.

Any help would be appreciated!

答:
I think Sergy S has it right, you might just need a little more detail.

Here is a screenshot of the 'Teams' Tab:
This is the formula in cell C2:

```<code>=INDEX('Master Score Sheet'!W:W,MATCH(Teams!B2,'Master Score Sheet'!A:A,0))
</code>```

Here is a screenshot of the 'Master Score Sheet' Tab:

Let me know if you need any more info.

Thanks!

Body:
I think Sergy S has it right, you might just need a little more detail.

Here is a screenshot of the 'Teams' Tab:
This is the formula in cell C2:

=INDEX('Master Score Sheet'!W:W,MATCH(Teams!B2,'Master Score Sheet'!A:A,0))

Here is a screenshot of the 'Master Score Sheet' Tab:

Let me know if you need any more info.

Thanks!


问:
Counting rows and columns for named ranges in vba
I am trying to count the number of rows and columns in vba from a named range in excel. The row and column counts are then used in an 2D array to perform other calculations. The named range is "CF_Inputs" which is from A2:Z60 in a worksheet called "Price_Volumes_Inputs". I can't seem get a row & column count using named ranges, so I used the code below with the offset method to count rows and columns. Is there a way to do this using the actual named range? I'm new to the whole programming thing, so I apologize for the simple question.</p>

```<code>Dim Inputs As Variant
Sheets("Price_Volumes_Input").Activate

Inputs = Range("A2", Range("Z2").End(xlDown).End(xlToRight))
</code>```

答:
Welcome to the world of VBA programming.  If you're going to be doing Excel VBA programming then you need to bookmark Chip Pearson's website.  I've found it very useful.  The link is http://www.cpearson.com/Excel/MainPage.aspx

There are many ways to do this.  For example one simple way is

```<code>Dim dataRows As Long
Dim dataCols As Long
Dim workArray as Variant

With ActiveWorkbook.Sheets("Price_Volumes_Input").Range("CF_Inputs")
    dataRows = .Rows.Count
    dataCols = .Columns.Count
End With

Dim workArray() As Variant
Redim workArray(dataRows, dataCols) as Variant
Dim i as Long, j as Long
For i = 0 to dataRows - 1
    For j = 0 to dataCols - 1
        'do the calculations
    Next j
Next i
</code>```

Body:
I am trying to count the number of rows and columns in vba from a named range in excel. The row and column counts are then used in an 2D array to perform other calculations. The named range is "CF_Inputs" which is from A2:Z60 in a worksheet called "Price_Volumes_Inputs". I can't seem get a row & column count using named ranges, so I used the code below with the offset method to count rows and columns. Is there a way to do this using the actual named range? I'm new to the whole programming thing, so I apologize for the simple question.

Dim Inputs As Variant
Sheets("Price_Volumes_Input").Activate

Inputs = Range("A2", Range("Z2").End(xlDown).End(xlToRight))

Body:
Welcome to the world of VBA programming.  If you're going to be doing Excel VBA programming then you need to bookmark Chip Pearson's website.  I've found it very useful.  The link is http://www.cpearson.com/Excel/MainPage.aspx

There are many ways to do this.  For example one simple way is

Dim dataRows As Long
Dim dataCols As Long
Dim workArray as Variant

With ActiveWorkbook.Sheets("Price_Volumes_Input").Range("CF_Inputs")
    dataRows = .Rows.Count
    dataCols = .Columns.Count
End With

Dim workArray() As Variant
Redim workArray(dataRows, dataCols) as Variant
Dim i as Long, j as Long
For i = 0 to dataRows - 1
    For j = 0 to dataCols - 1
        'do the calculations
    Next j
Next i


问:
Detecting connection errors when using CFStreamCreatePairWithSocketToCFHost
I am finding the doc for CFStreamCreatePairWithSocketToCFHost confusing:

Specifically, its not clear to me how the function can set the readStream pointer to null on error.
as far as I understand, the pointer is passed by value - so the function can only change the objected pointed to by the pointer.
Right now I can't figure out how to detect connection errors.

Relevant doc snippet:

Creates readable and writable streams connected to a given CFHost object.

```<code>void CFStreamCreatePairWithSocketToCFHost (
   CFAllocatorRef alloc,
   CFHostRef host,
   SInt32 port,
   CFReadStreamRef *readStream,
   CFWriteStreamRef *writeStream
);
</code>```

readStream

Upon return, contains a CFReadStream object connected to the host host on port port, or NULL if there is a failure during creation. If you pass NULL, the function will not create a readable stream. Ownership follows the Create Rule.

This is my connecting code, it goes all the way to NSLog(@"Connected") even when the server is down.

```<code>NSLog(@"Attempting to (re)connect to %@:%d", m_host, m_port);
while(TRUE)
{
    CFHostRef host = CFHostCreateWithName(kCFAllocatorDefault, (CFStringRef)m_host);
    if (!host)
    {
        NSLog(@"Error resolving host %@", m_host);
        [NSThread sleepForTimeInterval:5.0];
        continue;
    }
    CFStreamCreatePairWithSocketToCFHost(kCFAllocatorDefault, host , m_port, &m_in, &m_out);
    CFRelease(host);

    if (!m_in)
    {
        NSLog(@"Error");
    }

    CFStreamClientContext context = {0, self,nil,nil,nil};

    if (CFReadStreamSetClient(m_in, kCFStreamEventHasBytesAvailable | kCFStreamEventErrorOccurred | kCFStreamEventEndEncountered, networkReadEvent, &context))
    {
        CFReadStreamScheduleWithRunLoop(m_in, CFRunLoopGetCurrent(),kCFRunLoopCommonModes);
    }

    if (CFWriteStreamSetClient(m_out, kCFStreamEventErrorOccurred | kCFStreamEventEndEncountered, networkWriteEvent, &context))
    {
        CFWriteStreamScheduleWithRunLoop(m_out, CFRunLoopGetCurrent(),kCFRunLoopCommonModes);
    }

    BOOL success = CFReadStreamOpen(m_in);
    CFErrorRef error = CFReadStreamCopyError(m_in);
    if (!success || (error && CFErrorGetCode(error) != 0))
    {
        NSLog(@"Connect error %s : %d", CFErrorGetDomain(error), CFErrorGetCode(error));
        [NSThread sleepForTimeInterval:5.0];
    }
    else
    {
        NSLog(@"Connected");
        break;
    }
}
</code>```

答:
So, the readStream param is a pointer to the CFReadStreamRef and, as such, can definitely be set to NULL by the function.  &foo means "address of foo" and if you have the address you can set the value.

My reading of the documentation for CFStreamCreatePairWithSocketToCFHost is that they will be set to NULL on failure, but that failure is not about connection failure, but other kinds of failure (memory, etc).  So not likely you'll get an error there.

Looks to me like the issue is that CFReadStreamOpen can return immediately with true when it can open the stream in the background and so this code is not really opening the stream or testing that it's been opened, merely queuing it for opening).  From the documentation for CFReadStreamOpen:

" If the stream can open in the background without blocking, this function always returns true."

So I think you will need to follow the rest of the instructions for CFReadStreamOpen and schedule the stream on a run loop, or perhaps poll (though obviously polling in a tight loop isn't likely to work).

Body:
I am finding the doc for CFStreamCreatePairWithSocketToCFHost confusing:

Specifically, its not clear to me how the function can set the readStream pointer to null on error.
as far as I understand, the pointer is passed by value - so the function can only change the objected pointed to by the pointer.
Right now I can't figure out how to detect connection errors.

Relevant doc snippet:

Creates readable and writable streams connected to a given CFHost object.

void CFStreamCreatePairWithSocketToCFHost (
   CFAllocatorRef alloc,
   CFHostRef host,
   SInt32 port,
   CFReadStreamRef *readStream,
   CFWriteStreamRef *writeStream
);

readStream

Upon return, contains a CFReadStream object connected to the host host on port port, or NULL if there is a failure during creation. If you pass NULL, the function will not create a readable stream. Ownership follows the Create Rule.

This is my connecting code, it goes all the way to NSLog(@"Connected") even when the server is down.

NSLog(@"Attempting to (re)connect to %@:%d", m_host, m_port);
while(TRUE)
{
    CFHostRef host = CFHostCreateWithName(kCFAllocatorDefault, (CFStringRef)m_host);
    if (!host)
    {
        NSLog(@"Error resolving host %@", m_host);
        [NSThread sleepForTimeInterval:5.0];
        continue;
    }
    CFStreamCreatePairWithSocketToCFHost(kCFAllocatorDefault, host , m_port, &m_in, &m_out);
    CFRelease(host);

    if (!m_in)
    {
        NSLog(@"Error");
    }

    CFStreamClientContext context = {0, self,nil,nil,nil};

    if (CFReadStreamSetClient(m_in, kCFStreamEventHasBytesAvailable | kCFStreamEventErrorOccurred | kCFStreamEventEndEncountered, networkReadEvent, &context))
    {
        CFReadStreamScheduleWithRunLoop(m_in, CFRunLoopGetCurrent(),kCFRunLoopCommonModes);
    }

    if (CFWriteStreamSetClient(m_out, kCFStreamEventErrorOccurred | kCFStreamEventEndEncountered, networkWriteEvent, &context))
    {
        CFWriteStreamScheduleWithRunLoop(m_out, CFRunLoopGetCurrent(),kCFRunLoopCommonModes);
    }

    BOOL success = CFReadStreamOpen(m_in);
    CFErrorRef error = CFReadStreamCopyError(m_in);
    if (!success || (error && CFErrorGetCode(error) != 0))
    {
        NSLog(@"Connect error %s : %d", CFErrorGetDomain(error), CFErrorGetCode(error));
        [NSThread sleepForTimeInterval:5.0];
    }
    else
    {
        NSLog(@"Connected");
        break;
    }
}


问:
Overcome typescript type error using ramda groupby
I don't know how to fix this typescript error. I'm trying to use ramda's groupBy function:

```<code>245: const groups = R.groupBy((row: Record) => {
246:            return row[this.props.groupBy]
247:        })(this.props.data)
</code>```

Where this.props.groupBy is defined as :

```<code>groupBy?: {[K in keyof Record]}
data: Array<Record>
</code>```

The error that I get is:

```<code>Error:(245, 38) TS2345:Argument of type '(row: Record) => <T>(obj: any) => T' is not assignable to parameter of type '(a: Record) => string'.
  Type '<T>(obj: any) => T' is not assignable to type 'string'.

Error:(246, 31) TS2683:'this' implicitly has type 'any' because it does not have a type annotation.
</code>```

EDIT: I decided not to struggle with the keyof type and just declared it a groupBy as a string. I don't think these were my real errors, but intellij was having trouble updating its error messages, so who knows. They've gone away now.

答:
Overcome typescript type error using ramda groupby

You can use a type assertion to any:

```<code>245: const groups = (R as any).groupBy((row: Record) => {
246:            return row[this.props.groupBy]
247:        })(this.props.data)
</code>```

More

Type assertion: https://basarat.gitbooks.io/typescript/docs/types/type-assertion.html

Body:
I don't know how to fix this typescript error. I'm trying to use ramda's groupBy function:

245: const groups = R.groupBy((row: Record) => {
246:            return row[this.props.groupBy]
247:        })(this.props.data)

Where this.props.groupBy is defined as :

groupBy?: {[K in keyof Record]}
data: Array<Record>

The error that I get is:

Error:(245, 38) TS2345:Argument of type '(row: Record) => <T>(obj: any) => T' is not assignable to parameter of type '(a: Record) => string'.
  Type '<T>(obj: any) => T' is not assignable to type 'string'.

Error:(246, 31) TS2683:'this' implicitly has type 'any' because it does not have a type annotation.

EDIT: I decided not to struggle with the keyof type and just declared it a groupBy as a string. I don't think these were my real errors, but intellij was having trouble updating its error messages, so who knows. They've gone away now.

Body:
Overcome typescript type error using ramda groupby

You can use a type assertion to any:

245: const groups = (R as any).groupBy((row: Record) => {
246:            return row[this.props.groupBy]
247:        })(this.props.data)

More

Type assertion: https://basarat.gitbooks.io/typescript/docs/types/type-assertion.html


问:
getting the next element with xpath
I have the following html block, I'm trying to get all the city links under Alabama in this case. This is the xpath I have constructed

```<code>//h3/a[contains(text(),'Alabama')]/following::ul/li/a
</code>```

But The xpath above matches too many things. Any idea what I am doing wrong?

```<code><div class="geoUnit">

                <h3><a href="http://example.com/" style="background-color: rgba(0, 0, 0, 0);">Alabama</a></h3>
                  <ul style="background-color: rgba(0, 0, 0, 0);">
                    <li style="background-color: rgba(0, 0, 0, 0);"><a href="http://example.com/" style="background-color: rgba(0, 0, 0, 0);">Auburn</a></li>
                    <li><a href="http://example.com/">Birmingham</a></li>
                    <li><a href="http://example.com/">Dothan</a></li>
                    <li><a href="http://example.com/">Gadsden</a></li>
                    <li><a href="http://example.com/">Huntsville</a></li>
                    <li><a href="http://example.com/">Mobile</a></li>
                    <li><a href="http://example.com/">Montgomery</a></li>
                    <li><a href="http://example.com/">Muscle Shoals</a></li>
                    <li><a href="http://example.com/">Tuscaloosa</a></li>
                 </ul>
</div>
</code>```

I want the following to be selected as an array in this case. I want to extract each city link. I am using xpath inside of Java

```<code>                    <li style="background-color: rgba(0, 0, 0, 0);"><a href="http://example.com/" style="background-color: rgba(0, 0, 0,

0);">Auburn</a></li>
                        <li><a href="http://example.com/">Birmingham</a></li>
                        <li><a href="http://example.com/">Dothan</a></li>
                        <li><a href="http://example.com/">Gadsden</a></li>
                        <li><a href="http://example.com/">Huntsville</a></li>
                        <li><a href="http://example.com/">Mobile</a></li>
                        <li><a href="http://example.com/">Montgomery</a></li>
                        <li><a href="http://example.com/">Muscle Shoals</a></li>
                        <li><a href="http://example.com/">Tuscaloosa</a></li>
</code>```

答:
I'm trying to get all the city links under Alabama in this case.

Your XPath does select all a that follow the targeted heading.

But The xpath above matches too many things.

Perhaps there are additional ul elements following the targeted heading in your complete document.  In this case, you can append a [1] to the ul step in your XPath to limit the selection to the immediately following ul element:

```<code>//h3/a[contains(text(),'Alabama')]/following::ul[1]/li/a
</code>```

or, cleaned-up a bit:

```<code>//h3[a='Alabama']/following-sibling::ul[1]/li/a
</code>```

This will limit the a elements to those of just the immediately following ul.

Title: getting the next element with xpath

Body:
I have the following html block, I'm trying to get all the city links under Alabama in this case. This is the xpath I have constructed

//h3/a[contains(text(),'Alabama')]/following::ul/li/a

But The xpath above matches too many things. Any idea what I am doing wrong?

Alabama

Auburn

Birmingham

Dothan

Gadsden

Huntsville

Mobile

Montgomery

Muscle Shoals

Tuscaloosa

I want the following to be selected as an array in this case. I want to extract each city link. I am using xpath inside of Java

Auburn

Birmingham

Dothan

Gadsden

Huntsville

Mobile

Montgomery

Muscle Shoals

Tuscaloosa

Body:
I'm trying to get all the city links under Alabama in this case.

Your XPath does select all a that follow the targeted heading.

But The xpath above matches too many things.

Perhaps there are additional ul elements following the targeted heading in your complete document.  In this case, you can append a [1] to the ul step in your XPath to limit the selection to the immediately following ul element:

//h3/a[contains(text(),'Alabama')]/following::ul[1]/li/a

or, cleaned-up a bit:

//h3[a='Alabama']/following-sibling::ul[1]/li/a

This will limit the a elements to those of just the immediately following ul.


问:
Typescript Error: TS2339: Property 'span' does not exist on type 'JSX.IntrinsicElements'
All of a sudden my react typescript project has started rejecting  tags with

```<code>TS2339: Property <span> does not exist on type 'JSX.IntrinsicElements'
</code>```

Every other tag is absolutely fine, but s any where in my .tsx files throw this error.

Can anyone advise?

答:
Can anyone advise?

Make sure you have import * as React from 'react' in your file

Update types for react npm install @types/react

Body:
All of a sudden my react typescript project has started rejecting  tags with

TS2339: Property  does not exist on type 'JSX.IntrinsicElements'

Every other tag is absolutely fine, but s any where in my .tsx files throw this error.

Can anyone advise?


问:
Free Monte carlo simulator for financial quotes?
I am experimenting with an application I am writing in prolog , and I need to use monte carlo simulator that would output prices for different randomly generated scenarios. Does anyone know where to look for something that would do this for free ? (I am not look for a library to use such as QuantLib)

Thanx

答:
I'm not sure if you are after a financial simulator in prolog, but if you are willing to use a different language I would try R.

For a brief taster, have a look at the following links:

R packages for financial applications.

Applied finance with R conference


问:
MySQL Syntax error in cursor loop
I am trying to run a cursor loop in a stored procedure using this script:

```<code>CREATE PROCEDURE migrateMStruct()
BEGIN
DECLARE finished INT DEFAULT FALSE;
DECLARE msId BIGINT(20) UNSIGNED;
DECLARE luId INT(11);

DECLARE msCursor CURSOR FOR
    SELECT id, live_unit_id FROM mounting_structures
    WHERE live_unit_id IS NOT NULL;

DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = TRUE;

OPEN msCursor;

read_loop: LOOP
    FETCH msCursor INTO msId, luId;
    IF finished THEN
        LEAVE read_loop;
    END IF;
    UPDATE live_units SET mountingStructureId = msId WHERE live_units.id = luId;
END LOOP;

CLOSE msCursor;
END;
</code>```

I wrote this script based on the MySQL documentation, but when executing the script I'm receiving the error:

```<code>SQL Error [1064] [42000]: You have an error in your SQL syntax; check the manual
that corresponds to your MySQL server version for the right syntax to use near ''
at line 19
</code>```

Line 19 is just the END IF; statement. Obviously not the most helpful error in the world, but based on MySQL's documentation, the syntax looks to be correct.

答:
I got the same error, you must to change the delimiter character temporary to prevent execution when the SQL interpreter found a semicolon <code>;</code> </p>

```<code>DELIMITER $$

CREATE PROCEDURE migrateMStruct()
BEGIN

  /*your procedure body*/

END$$

DELIMITER ;  /*back to previous delimiter*
</code>```

Title: MySQL Syntax error in cursor loop

Body:
I am trying to run a cursor loop in a stored procedure using this script:

CREATE PROCEDURE migrateMStruct()
BEGIN
DECLARE finished INT DEFAULT FALSE;
DECLARE msId BIGINT(20) UNSIGNED;
DECLARE luId INT(11);

DECLARE msCursor CURSOR FOR
    SELECT id, live_unit_id FROM mounting_structures
    WHERE live_unit_id IS NOT NULL;

DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = TRUE;

OPEN msCursor;

read_loop: LOOP
    FETCH msCursor INTO msId, luId;
    IF finished THEN
        LEAVE read_loop;
    END IF;
    UPDATE live_units SET mountingStructureId = msId WHERE live_units.id = luId;
END LOOP;

CLOSE msCursor;
END;

I wrote this script based on the MySQL documentation, but when executing the script I'm receiving the error:

SQL Error [1064] [42000]: You have an error in your SQL syntax; check the manual
that corresponds to your MySQL server version for the right syntax to use near ''
at line 19

Line 19 is just the END IF; statement. Obviously not the most helpful error in the world, but based on MySQL's documentation, the syntax looks to be correct.

Body:
I got the same error, you must to change the delimiter character temporary to prevent execution when the SQL interpreter found a semicolon ;

DELIMITER $$

CREATE PROCEDURE migrateMStruct()
BEGIN

  /*your procedure body*/

END$$

DELIMITER ;  /*back to previous delimiter*


问:
C# with QuickGraph package from NuGet
I have a problem while trying to use AdjacencyGraph class of QuickGraph package. Allow me to show my code as first and then describe the problem:

```<code>using System.Collections.Generic;
using QuickGraph;

public class StrategicMap
{

    private IList<Fraction> fractions;
    private AdjacencyGraph<ProvinceOnMap, EdgeOnMap> provinces;

    public StrategicMap(IList<Fraction> fractions, AdjacencyGraph<ProvinceOnMap, EdgeOnMap> provinces)
    {
        this.fractions = fractions;
        this.provinces = provinces;
    }
</code>```

I'm using a proper(?) import, well, "using". However, the compiler still doesn't know which class I refer to. From QuickGraph.Contracts or from QuickGraph.

Here is the last screenshot, which is telling more about the prob:

答:
Quite late with the answer, but perhaps it'll help you, or somebody else.

There are a few QuickGraph packages on NuGet.

I'm using this one

https://www.nuget.org/packages/QuickGraphPCL/

and this seems to work fine.

Title: C# with QuickGraph package from NuGet

Body:
I have a problem while trying to use AdjacencyGraph class of QuickGraph package. Allow me to show my code as first and then describe the problem:

using System.Collections.Generic;
using QuickGraph;

public class StrategicMap
{

    private IList<Fraction> fractions;
    private AdjacencyGraph<ProvinceOnMap, EdgeOnMap> provinces;

    public StrategicMap(IList<Fraction> fractions, AdjacencyGraph<ProvinceOnMap, EdgeOnMap> provinces)
    {
        this.fractions = fractions;
        this.provinces = provinces;
    }

I'm using a proper(?) import, well, "using". However, the compiler still doesn't know which class I refer to. From QuickGraph.Contracts or from QuickGraph.

Here is the last screenshot, which is telling more about the prob:


问:
unable to include logged in user id in url(address bar)
I'm trying to echo user id to be displayed in url view db structure here when a user is logged in to a system much like abc.php?uid=5 (Reason is, I need the logged in user id to be passed when a logged in user makes a post so as to use their user_id to display their details in a feeds view page) I've tried various codes but unable to achieve it. When I run the code below, there's no reaction, just stuck at the log in page. Pls I need help.</p>

```<code>    <?php
    session_start();
   include_once('queryclass.php');

  $error = false;
  if(isset($_POST['btn-login'])){
  $username = trim($_POST['username']);
  $username = htmlspecialchars(strip_tags($username));

  $password = trim($_POST['password']);
  $password = htmlspecialchars(strip_tags($password));

   if(empty($username)){
    $error = true;
    $errorUsername = 'Please Input Username';
  }

  if(empty($password)){
    $error = true;
    $errorPassword = 'Please Input Password';
   }elseif(strlen($password)< 6){
    $error = true;
    $errorPassword = 'Password must be at least six characters';
   }

  if(!$error){

        $password = md5($password);
    $sql = "select * from company where username='$username' ";
    $result = mysqli_query($conn, $sql);
    $count = mysqli_num_rows($result);
    $row = mysqli_fetch_assoc($result);
    if($count==1 && $row['password'] == $password){
        $_SESSION['username'] = $row['username'];
        function do_user_directory(){
        $users = $this->load_all_user_objects();
        foreach($users as $user){?>
        header('location: loggedin.php?uid=<?php echo $user->id;?>');
        <?php
        }
        }
    }else{
        $errorMsg = 'Invalid Username or Password';
    }
    }

    }

    ?>

   This is the queryclass.php

  <?php
  require_once('connectdb.php');

  function load_user_object($user_id){
  global $db;

  $table = 'users';

  $query = "
              SELECT * FROM $table
              WHERE ID = $user_id
           ";

   $obj = $db->select($query);
    if(!$obj) {
        return "No user found";
     }

    return $obj[0];

   }

   function load_all_user_objects(){
   global $db;

   $table = 'users';

     $query = "
              SELECT * FROM $table

           ";

   $obj = $db->select($query);

    if(!$obj) {
        return "No user found";
     }

     return $obj;

   }

   ?>
</code>```

答:
So let's just keep that id in $_SESSION too:

```<code>// building query to users table (sanitizing Your inputs from sql injections)
$q = "SELECT ID, username FROM users WHERE ";
$q.= " username='".mysqli_real_escape_string($conn, $username)."' AND ";
$q.= " password='".md5($password)."' LIMIT 1";

$r = @mysqli_fetch_assoc(@mysqli_query($conn, $q));
if(is_array($r) AND !empty($)) { // in case of success $r will keep user array
    $_SESSION['user'] = $r;      // same as doing $_SESSION['user'] = ['ID' => 1, 'username' => 'somebody'];
    session_write_close();       // closing session (commiting changes)
    header('Location: loggedin.php'); // redirecting user to loggedin.php
    exit(0);                     // preventing php script to go down to not execute other statements below
}
</code>```

and somewhere in loggedin.php

do guarding like:

```<code>if(!isset($_SESSION['user'])) {
  header('Location: logout.php');
  exit(0);
}
</code>```

get authenticated user's id like:

```<code>$user_id = $_SESSION['user']['ID'];
</code>```

if You want to echo user id in somewhere in html just do for example like:

```<code><?php $user_id = $_SESSION['user'] ? $_SESSION['user']['ID'] : 'default'; ?>
<img src="/uploads/users/<?=$user_id?>.jpg">
</code>```

Body:
I'm trying to echo user id to be displayed in url view db structure here when a user is logged in to a system much like abc.php?uid=5 (Reason is, I need the logged in user id to be passed when a logged in user makes a post so as to use their user_id to display their details in a feeds view page) I've tried various codes but unable to achieve it. When I run the code below, there's no reaction, just stuck at the log in page. Pls I need help.

    <?php
    session_start();
   include_once('queryclass.php');

  $error = false;
  if(isset($_POST['btn-login'])){
  $username = trim($_POST['username']);
  $username = htmlspecialchars(strip_tags($username));

  $password = trim($_POST['password']);
  $password = htmlspecialchars(strip_tags($password));

   if(empty($username)){
    $error = true;
    $errorUsername = 'Please Input Username';
  }

  if(empty($password)){
    $error = true;
    $errorPassword = 'Please Input Password';
   }elseif(strlen($password)< 6){
    $error = true;
    $errorPassword = 'Password must be at least six characters';
   }

  if(!$error){

        $password = md5($password);
    $sql = "select * from company where username='$username' ";
    $result = mysqli_query($conn, $sql);
    $count = mysqli_num_rows($result);
    $row = mysqli_fetch_assoc($result);
    if($count==1 && $row['password'] == $password){
        $_SESSION['username'] = $row['username'];
        function do_user_directory(){
        $users = $this->load_all_user_objects();
        foreach($users as $user){?>
        header('location: loggedin.php?uid=<?php echo $user->id;?>');
        <?php
        }
        }
    }else{
        $errorMsg = 'Invalid Username or Password';
    }
    }

    }

    ?>

   This is the queryclass.php

  <?php
  require_once('connectdb.php');

  function load_user_object($user_id){
  global $db;

  $table = 'users';

  $query = "
              SELECT * FROM $table
              WHERE ID = $user_id
           ";

   $obj = $db->select($query);
    if(!$obj) {
        return "No user found";
     }

    return $obj[0];

   }

   function load_all_user_objects(){
   global $db;

   $table = 'users';

     $query = "
              SELECT * FROM $table

           ";

   $obj = $db->select($query);

    if(!$obj) {
        return "No user found";
     }

     return $obj;

   }

   ?>

Body:
So let's just keep that id in $_SESSION too:

// building query to users table (sanitizing Your inputs from sql injections)
$q = "SELECT ID, username FROM users WHERE ";
$q.= " username='".mysqli_real_escape_string($conn, $username)."' AND ";
$q.= " password='".md5($password)."' LIMIT 1";

$r = @mysqli_fetch_assoc(@mysqli_query($conn, $q));
if(is_array($r) AND !empty($)) { // in case of success $r will keep user array
    $_SESSION['user'] = $r;      // same as doing $_SESSION['user'] = ['ID' => 1, 'username' => 'somebody'];
    session_write_close();       // closing session (commiting changes)
    header('Location: loggedin.php'); // redirecting user to loggedin.php
    exit(0);                     // preventing php script to go down to not execute other statements below
}

and somewhere in loggedin.php

do guarding like:

if(!isset($_SESSION['user'])) {
  header('Location: logout.php');
  exit(0);
}

get authenticated user's id like:

$user_id = $_SESSION['user']['ID'];

if You want to echo user id in somewhere in html just do for example like:

<?php $user_id = $_SESSION['user'] ? $_SESSION['user']['ID'] : 'default'; ?>
<img src="/uploads/users/<?=$user_id?>.jpg">


问:
Download images from url in order
I am getting html source and parsing it. After that, i want to download images. i download them. But sometimes not downloading. Because i couldnt use thread or parallel programming which i need, i dont know. My source is:

```<code>foreach(var pic in pics)
        {
            try {
             client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);
                client.DownloadFileAsync(new Uri(pic.Attributes[cmbAttr.Text].Value), folder + "\\" + picid.ToString() + ".jpg");

            System.Threading.Thread.Sleep(1500); // I wrote sleep code, because i dont know parallel programming. But sometimes it is not downloading in 1500 milisecond.

            picid++;
            }catch(Exception err)
            {
                label8.Text=(err.Message.ToString());
                continue;
            }
        }
</code>```

this is my code. i want to download the pictures in order. 1.jpg, 2.jpg etc. i download it too. But sometimes it is getting error. Because another download starting while last download before finished. I want to start after finish last download. My english is bad. I hope i tell it true.
Thanks for help.

答:
```<code>client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);

foreach(var pic in pics)
{
    Task.Factory.StartNew(Object state =>
    {

        var data = (dynamic)state;
        Int32 id = (Int32)state.Id;
        Picture picture = (Picture)state.Picture;

        client.DownloadFile(new Uri(picture.Attributes[cmbAttr.Text].Value), folder + "\\" + id.ToString() + ".jpg")

    }, new { Id = picid, Picture = pic });

    ++picid;
}
</code>```

Title: Download images from url in order

Body:
I am getting html source and parsing it. After that, i want to download images. i download them. But sometimes not downloading. Because i couldnt use thread or parallel programming which i need, i dont know. My source is:

foreach(var pic in pics)
        {
            try {
             client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);
                client.DownloadFileAsync(new Uri(pic.Attributes[cmbAttr.Text].Value), folder + "\\" + picid.ToString() + ".jpg");

            System.Threading.Thread.Sleep(1500); // I wrote sleep code, because i dont know parallel programming. But sometimes it is not downloading in 1500 milisecond.

            picid++;
            }catch(Exception err)
            {
                label8.Text=(err.Message.ToString());
                continue;
            }
        }

this is my code. i want to download the pictures in order. 1.jpg, 2.jpg etc. i download it too. But sometimes it is getting error. Because another download starting while last download before finished. I want to start after finish last download. My english is bad. I hope i tell it true.
Thanks for help.


问:
JQuery Default text on empty text box
I have a email form text box that while it is empty I would like it to have the value "E-Mail" And when you click on it the text goes away. If someone clicks on it and doesn't enter text. on Blur I would like for it to return to having the default text.

I have been trying a few things but nothing is working. Could someone please point me in the right direction?

答: It's pretty straightforward. Just erase the value onfocus, and then (if the value is still empty) refill it onblur.

Title: JQuery Default text on empty text box


问:
PC address for JSR
I have this block of code and I was wondering what address would be stored in the PC. From what I can see, it seems to be x3002 but im not quite sure.

```<code>.ORIG x3000
JSR FOO
ADD R0,R4,R2
FOO: ADD R0,R0,#1
 RET
</code>```

If it is not x3002 could you please let me know as to why this would be the case.

答:
JSR will simply store into the PC the address of the label.

FOO is at x3002.

so PC will jump to x3002 and R7 will have the value x3001.

Title: PC address for JSR

Body:
I have this block of code and I was wondering what address would be stored in the PC. From what I can see, it seems to be x3002 but im not quite sure.

.ORIG x3000
JSR FOO
ADD R0,R4,R2
FOO: ADD R0,R0,#1
 RET

If it is not x3002 could you please let me know as to why this would be the case.


问:
BigQuery - CASE WHEN x IN (field from other table), results in Semijoin error
I am trying to segment website visitors by whether or not they have ever purchased from us before. When I put in the below field in the SELECT statement, I get the further below error:

```<code>CASE WHEN fullVisitorId IN (SELECT fullVisitorId FROM [xxxx-0000:36363.unique_FullVisitorIds_of_past_purchasers_table]) THEN "Purchased"
ELSE "Never Purchased" END AS Previous_Purchase
</code>```

Error: "Error: (L10:20): Semijoin expression (i.e. "x IN (SELECT ...)") only supported in WHERE or HAVING clauses."

How would I go about doing this?

Thanks

答:
I suggest joining a summarized result along these lines:

```<code>SELECT
    CASE WHEN p.has_purchased = 1 THEN "Purchased"
         ELSE "Never Purchased"
    END AS Previous_Purchase
FROM existing_from_table f
LEFT JOIN (
    SELECT fullVisitorId, 1 has_purchased
    FROM [xxxx-0000:36363.unique_FullVisitorIds_of_past_purchasers_table]
    GROUP BY fullVisitorId
    ) p on f.fullVisitorId = p.fullVisitorId
</code>```

nb: The group by is used so that the overall number of rows is not affected.

Body:
I am trying to segment website visitors by whether or not they have ever purchased from us before. When I put in the below field in the SELECT statement, I get the further below error:

CASE WHEN fullVisitorId IN (SELECT fullVisitorId FROM [xxxx-0000:36363.unique_FullVisitorIds_of_past_purchasers_table]) THEN "Purchased"
ELSE "Never Purchased" END AS Previous_Purchase

Error: "Error: (L10:20): Semijoin expression (i.e. "x IN (SELECT ...)") only supported in WHERE or HAVING clauses."

How would I go about doing this?

Thanks

Body:
I suggest joining a summarized result along these lines:

SELECT
    CASE WHEN p.has_purchased = 1 THEN "Purchased"
         ELSE "Never Purchased"
    END AS Previous_Purchase
FROM existing_from_table f
LEFT JOIN (
    SELECT fullVisitorId, 1 has_purchased
    FROM [xxxx-0000:36363.unique_FullVisitorIds_of_past_purchasers_table]
    GROUP BY fullVisitorId
    ) p on f.fullVisitorId = p.fullVisitorId

nb: The group by is used so that the overall number of rows is not affected.


问:
Users address logic in laravel
I have 2 tables in my laravel application users and addresses and both of them crud currently working, what i want to do is:

Set several address for each user (DONE)

Set Primary address (Ability of choose in order settings and profile page)

Question is:

Do I need 3rd table such as address_user to get user and address id or as it is now i just can add primary column to address table and let it be?

here is what i have:

user model

```<code>public function addresses(){
       return $this->hasMany(Address::class);
    }
</code>```

Address model

```<code>public function user(){
     return $this->belongsTo(User::class);
  }
</code>```

Address table

```<code>Schema::create('addresses', function (Blueprint $table) {
            $table->increments('id');
            $table->string('address');
            $table->string('city');
            $table->string('postalcode')->nullable();
            $table->string('province');
            $table->integer('user_id')->unsigned();
            $table->timestamps();
        });
        Schema::table('addresses', function (Blueprint $table) {
            $table->foreign('user_id')->references('id')->on('users');
        });
</code>```

This is how i print data currently in users index

```<code><td class="text-center">
  <ol>
    @foreach($user->addresses as $uad)
       <li>{{$uad->address}}<br>{{$uad->city}},{{$uad->postalcode}},{{$uad->province}}</li>
    @endforeach
  </ol>
</td>
</code>```

UPDATE

So base on suggestions I added column is_primary to my addresses table and I can set is to 0 and 1 in order to get users primary address, BUT

Now I am in my user edit page and i have 2 address belongs to user
  with id 1 now I want to change selected primary address to another
  address but i am in user profile edit how do I update my address table
  is_primary column while my form route is users.update and not addresses_update ?

UPDATE 2

I've made some changes and here it is:

Users table have address_id column

Addresses table NO HAVE is_primary column anymore.
why? because user could set many address as primary! with this way user only can set 1 address as primary which will get id of that address.

Issue

1- I cannot get user primary address (don't know how!)

here is how i get user addresses:

```<code>@foreach($user->addresses as $address)
  <p>
    {{$address->address}}<br>
    {{$address->city}}, {{$address->province}}<br>
    {{$address->country}}<br>
    {{$address->postalcode}}
  </p>
@endforeach
</code>```

But I'm not able to get user primary address.

答:
Because $user->addresses will get you an instance of Illuminate\Database\Eloquent\Collection, you can then filter that collection so as you want.

Example of User class method:

```<code>public function getPrimaryAddress(): Address
{
    return $this->addresses->where("is_primary", "=", 1)->first();
}
</code>```

Of course you first getting ALL of the addresses which in most cases you do anyways.
If you want to issue a single query and get primary address you can still do so with just

```<code>public function getPrimaryAddress(): Address
{
    return Address::where('user_id', '=', $this->id)->andWhere('is_primary', '=', 1)->first();
}
</code>```

But both of those imply you have is_primary column within addresses table.

Having is_primary in your addresses table would be beneficial if you want to get a list and check in a loop if that address is primary, e.g.

```<code>foreach ($user->addresses as $address) {
    if ($address->is_primary) { /* this address is primary */ }
}
</code>```

To change primary address you need to set is_primary for the address which is already primary to 0 and set property is_primary of now-primary address to 1.

```<code>public function setPrimaryAddress($address): bool
{
    if (is_numeric($address)) { // Should be PK.
        $address = Address::find($address);
    }
    $prev = $this->getPrimaryAddress();
    if ($address->id == $prev->id) {
        return true;
    }
    if ($prev->update(['is_primary' => 0])) {
        return $address->update(['is_primary' => 1]);
    }
    return false;
}
</code>```

Title: Users address logic in laravel

Body:
I have 2 tables in my laravel application users and addresses and both of them crud currently working, what i want to do is:

Set several address for each user (DONE)

Set Primary address (Ability of choose in order settings and profile page)

Question is:

Do I need 3rd table such as address_user to get user and address id or as it is now i just can add primary column to address table and let it be?

here is what i have:

user model

public function addresses(){
       return $this->hasMany(Address::class);
    }

Address model

public function user(){
     return $this->belongsTo(User::class);
  }

Address table

Schema::create('addresses', function (Blueprint $table) {
            $table->increments('id');
            $table->string('address');
            $table->string('city');
            $table->string('postalcode')->nullable();
            $table->string('province');
            $table->integer('user_id')->unsigned();
            $table->timestamps();
        });
        Schema::table('addresses', function (Blueprint $table) {
            $table->foreign('user_id')->references('id')->on('users');
        });

This is how i print data currently in users index

    @foreach($user->addresses as $uad)

{{$uad->address}}
{{$uad->city}},{{$uad->postalcode}},{{$uad->province}}

    @endforeach

UPDATE

So base on suggestions I added column is_primary to my addresses table and I can set is to 0 and 1 in order to get users primary address, BUT

Now I am in my user edit page and i have 2 address belongs to user
  with id 1 now I want to change selected primary address to another
  address but i am in user profile edit how do I update my address table
  is_primary column while my form route is users.update and not addresses_update ?

UPDATE 2

I've made some changes and here it is:

Users table have address_id column

Addresses table NO HAVE is_primary column anymore.
why? because user could set many address as primary! with this way user only can set 1 address as primary which will get id of that address.

Issue

1- I cannot get user primary address (don't know how!)

here is how i get user addresses:

@foreach($user->addresses as $address)

    {{$address->address}}

    {{$address->city}}, {{$address->province}}

    {{$address->country}}

    {{$address->postalcode}}

@endforeach

But I'm not able to get user primary address.

Body:
Because $user->addresses will get you an instance of Illuminate\Database\Eloquent\Collection, you can then filter that collection so as you want.

Example of User class method:

public function getPrimaryAddress(): Address
{
    return $this->addresses->where("is_primary", "=", 1)->first();
}

Of course you first getting ALL of the addresses which in most cases you do anyways.
If you want to issue a single query and get primary address you can still do so with just

public function getPrimaryAddress(): Address
{
    return Address::where('user_id', '=', $this->id)->andWhere('is_primary', '=', 1)->first();
}

But both of those imply you have is_primary column within addresses table.

Having is_primary in your addresses table would be beneficial if you want to get a list and check in a loop if that address is primary, e.g.

foreach ($user->addresses as $address) {
    if ($address->is_primary) { /* this address is primary */ }
}

To change primary address you need to set is_primary for the address which is already primary to 0 and set property is_primary of now-primary address to 1.

public function setPrimaryAddress($address): bool
{
    if (is_numeric($address)) { // Should be PK.
        $address = Address::find($address);
    }
    $prev = $this->getPrimaryAddress();
    if ($address->id == $prev->id) {
        return true;
    }
    if ($prev->update(['is_primary' => 0])) {
        return $address->update(['is_primary' => 1]);
    }
    return false;
}


问:
Android - displaying UTF-8 (russian) on device
I'm debugging application on my android device (Motorola Defy, 2.1), the application gets Russian HTML page from network, but can't display it. It displays as link text.
HTML page is in UTF-8 (100% sure). Source code:

```<code>HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet("http://m.rasp.yandex.ru/direction?direction=" + direction);
        httpget.setHeader("charset", "utf-8");
        ResponseHandler<String> responseHandler = new BasicResponseHandler();

        String html = httpclient.execute(httpget, responseHandler);
</code>```

What am I need for normal displaying of Russian text? Sorry for bad English knowledge.

答:
httpget.setHeader("charset", "utf-8"); doesn't make any sense.

Encoding is determined by BasicResponseHandler. If response encoding is not specified in Content-Type header (as in your case), BasicResponseHandler assumes it to be ISO-8859-1, and it can't be configured.

So, you need to implement your own ResponseHandler that falls back to another default encoding, something like this:

```<code>ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
    public String handleResponse(final HttpResponse response)
        throws HttpResponseException, IOException {
        StatusLine statusLine = response.getStatusLine();
        if (statusLine.getStatusCode() >= 300) {
            throw new HttpResponseException(statusLine.getStatusCode(),
                    statusLine.getReasonPhrase());
        }

        HttpEntity entity = response.getEntity();
        return entity == null ? null : EntityUtils.toString(entity, "UTF-8");
    }
}
</code>```

Body:
I'm debugging application on my android device (Motorola Defy, 2.1), the application gets Russian HTML page from network, but can't display it. It displays as link text.
HTML page is in UTF-8 (100% sure). Source code:

HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet("http://m.rasp.yandex.ru/direction?direction=" + direction);
        httpget.setHeader("charset", "utf-8");
        ResponseHandler<String> responseHandler = new BasicResponseHandler();

        String html = httpclient.execute(httpget, responseHandler);

What am I need for normal displaying of Russian text? Sorry for bad English knowledge.

Body:
httpget.setHeader("charset", "utf-8"); doesn't make any sense.

Encoding is determined by BasicResponseHandler. If response encoding is not specified in Content-Type header (as in your case), BasicResponseHandler assumes it to be ISO-8859-1, and it can't be configured.

So, you need to implement your own ResponseHandler that falls back to another default encoding, something like this:

ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
    public String handleResponse(final HttpResponse response)
        throws HttpResponseException, IOException {
        StatusLine statusLine = response.getStatusLine();
        if (statusLine.getStatusCode() >= 300) {
            throw new HttpResponseException(statusLine.getStatusCode(),
                    statusLine.getReasonPhrase());
        }

        HttpEntity entity = response.getEntity();
        return entity == null ? null : EntityUtils.toString(entity, "UTF-8");
    }
}


问:
ReactNativeDisplay Json file in another format
rookie in RN, thanks in advance! I want to display a json file on a page.

This is the format of the json:

```<code>{
  "prediction": [
            { "name":"egg", "value":"0.95" },
            { "name":"apple", "value":"0.02" },
            { "name":"peach", "value":"0.01" },
            { "name":"orange", "value":"0.01" },
            { "name":"fish", "value":"0.01" }

  ]
}
</code>```

Assuming the Name of the json will be " /app/prediction.json ".
And the text input method I had on this page will be :

```<code>import { Tile, List, ListItem, Button } from 'react-native-elements';
import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  Dimensions,
  View
} from 'react-native';

export default class ProjectOne extends Component {
  render() {
    return (
      <View style={styles.container}>

       <Text style={styles.text}> Analysis </Text>
       <Text> The object has " 95% possibility to be an egg, 40% to be an apple "</Text>

      </View>
    );
  }

}

const styles = StyleSheet.create({
  text: {
    fontSize: 20,
    fontWeight: 'bold',
  },
  container: {
    height: 275,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  preview: {
   flex: 1,
   justifyContent: 'flex-end',
   alignItems: 'center',
   height: Dimensions.get('window').height,
   width: Dimensions.get('window').width
 },
  capture: {
    flex: 0,
    backgroundColor: 'black',
    borderRadius: 5,
    color: '#ffffff',
    padding: 10,
    margin: 40
  }
});

AppRegistry.registerComponent('ProjectOne', () => ProjectOne);
</code>```

Is there any way that I can fetch the json file, and then, display the json content into that text field on this page?

答: You can do it by using require('./app/prediction.json') then convert it to string or format if needed

Body:
rookie in RN, thanks in advance! I want to display a json file on a page.

This is the format of the json:

{
  "prediction": [
            { "name":"egg", "value":"0.95" },
            { "name":"apple", "value":"0.02" },
            { "name":"peach", "value":"0.01" },
            { "name":"orange", "value":"0.01" },
            { "name":"fish", "value":"0.01" }

  ]
}

Assuming the Name of the json will be " /app/prediction.json ".
And the text input method I had on this page will be :

import { Tile, List, ListItem, Button } from 'react-native-elements';
import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  Dimensions,
  View
} from 'react-native';

export default class ProjectOne extends Component {
  render() {
    return (
      <View style={styles.container}>

       <Text style={styles.text}> Analysis </Text>
       <Text> The object has " 95% possibility to be an egg, 40% to be an apple "</Text>

      </View>
    );
  }

}

const styles = StyleSheet.create({
  text: {
    fontSize: 20,
    fontWeight: 'bold',
  },
  container: {
    height: 275,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  preview: {
   flex: 1,
   justifyContent: 'flex-end',
   alignItems: 'center',
   height: Dimensions.get('window').height,
   width: Dimensions.get('window').width
 },
  capture: {
    flex: 0,
    backgroundColor: 'black',
    borderRadius: 5,
    color: '#ffffff',
    padding: 10,
    margin: 40
  }
});

AppRegistry.registerComponent('ProjectOne', () => ProjectOne);

Is there any way that I can fetch the json file, and then, display the json content into that text field on this page?


问:
PRISM Xamarin - Working with tabbed pages (IActiveAware)
I have tab pages implementing different views, but I cannot initialize each of the tabs when navigating.

```<code><TabbedPage.Children>
    <tabPages:Page1/>
    <tabPages:Page2/>
    <tabPages:Page3/>
</TabbedPage.Children>
</code>```

So what I did was to use IActiveAware as prism documentation suggested to know which tab page is currently active. So I have this class:

```<code>public abstract class TabbedChildViewModelBase : BaseViewModel, IActiveAware, INavigationAware, IDestructible

protected bool IsInitalized { get; set; }

    private bool _IsActive;
    public bool IsActive
    {
        get
        {
            return _IsActive;
        }
        set
        {
            SetProperty(ref _IsActive, value, RaiseIsActiveChanged);
        }
    }

    public event EventHandler IsActiveChanged;

    public virtual void OnNavigatingTo(NavigationParameters parameters)
    {

    }

    protected virtual void RaiseIsActiveChanged()
    {
        IsActiveChanged?.Invoke(this, EventArgs.Empty);
    }
    public virtual void Destroy()
    {

    }
}
</code>```

So each child view models inherits the child view model base:

```<code> public class Page1 : TabbedChildViewModelBase
 {
    public CurrentSeaServiceViewModel()
    {
        IsActiveChanged += HandleIsActiveTrue;
        IsActiveChanged += HandleIsActiveFalse;
    }

    private void HandleIsActiveTrue(object sender, EventArgs args)
    {
        if (IsActive == false)
        {
            TestLabelOnly = "Test";
        }

        // Handle Logic Here
    }

    private void HandleIsActiveFalse(object sender, EventArgs args)
    {
        if (IsActive == true) return;

        // Handle Logic Here
    }

    public override void Destroy()
    {
        IsActiveChanged -= HandleIsActiveTrue;
        IsActiveChanged -= HandleIsActiveFalse;
    }
}
</code>```

The problem is, the child vm isn't initializing. Is there something needed in order to implement IActiveAware properly nor launching the IsActive property

答:
I still used IActiveAware unfortunately, to make the childtabbedviewmodel work you need to bind the page to its own view model.

So here's what I did:

```<code><TabbedPage.Children>
      <views:ChildPage1>
          <views:ChildPage1.BindingContext>
              <viewModels:ChildPage1ViewModel/>
          </views:ChildPage1.BindingContext>
      </views:ChildPage1>
      <views:ChildPage2>
          <views:ChildPage2.BindingContext>
              <viewModels:ChildPage2ViewModel/>
          </views:ChildPage2.BindingContext>
     </views:ChildPage2>
</TabbedPage.Children>
</code>```

I used the property BindingContext of my views and
using IActiveAware I would also know what tab is currently active. Hope anyone helps this who finds trouble binding the child pages of a tab.

Body:
I have tab pages implementing different views, but I cannot initialize each of the tabs when navigating.

<TabbedPage.Children>
    <tabPages:Page1/>
    <tabPages:Page2/>
    <tabPages:Page3/>
</TabbedPage.Children>

So what I did was to use IActiveAware as prism documentation suggested to know which tab page is currently active. So I have this class:

public abstract class TabbedChildViewModelBase : BaseViewModel, IActiveAware, INavigationAware, IDestructible

protected bool IsInitalized { get; set; }

    private bool _IsActive;
    public bool IsActive
    {
        get
        {
            return _IsActive;
        }
        set
        {
            SetProperty(ref _IsActive, value, RaiseIsActiveChanged);
        }
    }

    public event EventHandler IsActiveChanged;

    public virtual void OnNavigatingTo(NavigationParameters parameters)
    {

    }

    protected virtual void RaiseIsActiveChanged()
    {
        IsActiveChanged?.Invoke(this, EventArgs.Empty);
    }
    public virtual void Destroy()
    {

    }
}

So each child view models inherits the child view model base:

 public class Page1 : TabbedChildViewModelBase
 {
    public CurrentSeaServiceViewModel()
    {
        IsActiveChanged += HandleIsActiveTrue;
        IsActiveChanged += HandleIsActiveFalse;
    }

    private void HandleIsActiveTrue(object sender, EventArgs args)
    {
        if (IsActive == false)
        {
            TestLabelOnly = "Test";
        }

        // Handle Logic Here
    }

    private void HandleIsActiveFalse(object sender, EventArgs args)
    {
        if (IsActive == true) return;

        // Handle Logic Here
    }

    public override void Destroy()
    {
        IsActiveChanged -= HandleIsActiveTrue;
        IsActiveChanged -= HandleIsActiveFalse;
    }
}

The problem is, the child vm isn't initializing. Is there something needed in order to implement IActiveAware properly nor launching the IsActive property

Body:
I still used IActiveAware unfortunately, to make the childtabbedviewmodel work you need to bind the page to its own view model.

So here's what I did:

<TabbedPage.Children>
      <views:ChildPage1>
          <views:ChildPage1.BindingContext>
              <viewModels:ChildPage1ViewModel/>
          </views:ChildPage1.BindingContext>
      </views:ChildPage1>
      <views:ChildPage2>
          <views:ChildPage2.BindingContext>
              <viewModels:ChildPage2ViewModel/>
          </views:ChildPage2.BindingContext>
     </views:ChildPage2>
</TabbedPage.Children>

I used the property BindingContext of my views and
using IActiveAware I would also know what tab is currently active. Hope anyone helps this who finds trouble binding the child pages of a tab.


问:
Can I safely ignore circular dependency warning when used in a decorator?
I have two classes defined like this:

```<code>// src/app/my-mapper.ts
export class MyMapper implements Mapper<MyModel> {
  public mapTo(source: any): MyModel {
    // map stuff...
  }
}
</code>```

and

```<code>// src/app/my-model.ts
@mappedBy(MyMapper)
export class MyModel {
  // fields etc...
  public someFunction(): void {
    // stuff...
  }
}
</code>```

My code works (I use a MapperWorker to map plain JS objects to concrete objects, MyModel in this case), I can call myModel.someFunction();

However, I get the following warning when compiling:

WARNING in Circular dependency detected: src/app/my-mapper.ts ->
  src/app/my-model.ts -> src/app/my-mapper.ts

WARNING in Circular dependency detected: src/app/my-model.ts ->
  src/app/my-mapper.ts -> src/app/my-model.ts

I don't know if my code is problematic or if this warning can safely be ignored, if it is safe to ignore then what's the best way of suppressing it?

I'm not sure if the error is generated by the Typescript compiler or Angular CLI. Moving the classes to the same file (with the mapper first) gets rid of the warning, but I don't want to have to do that.

答:
I don't know if my code is problematic or if this warning can safely be ignored, if it is safe to ignore then what's the best way of suppressing it

No. You might get a runtime undefined.

Quick Fix

Merge the three files into one. They are already tightly coupled.

Body:
I have two classes defined like this:

// src/app/my-mapper.ts
export class MyMapper implements Mapper<MyModel> {
  public mapTo(source: any): MyModel {
    // map stuff...
  }
}

and

// src/app/my-model.ts
@mappedBy(MyMapper)
export class MyModel {
  // fields etc...
  public someFunction(): void {
    // stuff...
  }
}

My code works (I use a MapperWorker to map plain JS objects to concrete objects, MyModel in this case), I can call myModel.someFunction();

However, I get the following warning when compiling:

WARNING in Circular dependency detected: src/app/my-mapper.ts ->
  src/app/my-model.ts -> src/app/my-mapper.ts

WARNING in Circular dependency detected: src/app/my-model.ts ->
  src/app/my-mapper.ts -> src/app/my-model.ts

I don't know if my code is problematic or if this warning can safely be ignored, if it is safe to ignore then what's the best way of suppressing it?

I'm not sure if the error is generated by the Typescript compiler or Angular CLI. Moving the classes to the same file (with the mapper first) gets rid of the warning, but I don't want to have to do that.


问:
What are projection and selection?
What is the difference between projection and selection? Is it:

Projection --> for selecting the columns of table; and

Selection ---> to select the rows of table?

So are projection and selection vertical and horizontal slicing respectively?

答:
Projections and Selections are two unary operations in Relational Algebra and has practical applications in RDBMS (relational database management systems).

In practical sense, yes Projection means selecting specific columns (attributes) from a table and Selection means filtering rows (tuples). Also, for a conventional table, Projection and Selection can be termed as vertical and horizontal slicing or filtering.

Wikipedia provides more formal definitions of these with examples and they can be good for further reading on relational algebra:

Projection: https://en.wikipedia.org/wiki/Projection_(relational_algebra)

Selection: https://en.wikipedia.org/wiki/Selection_(relational_algebra)

Relational Algebra: https://en.wikipedia.org/wiki/Relational_algebra

OwnerDisplayName: prabhahar

LastEditorDisplayName: prabhahar

Title: What are projection and selection?


问:
Invalid layout param (layout_alignParentBottom) in TabLayout
I am trying to put TabLayout on the bottom of the screen. Trying to use layout_alignParentBottom but get an invalid layout param error. Any param I should use? Thanks.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".TabBar">

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabGravity="fill"
        app:tabMode="fixed"
        android:layout_alignParentBottom="true" />

    <FrameLayout
        android:id="@+id/frame_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>
```

答:
Switch the positions and use layout_weight</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".TabBar">

    <FrameLayout
        android:id="@+id/frame_container"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabGravity="fill"
        app:tabMode="fixed" />

</LinearLayout>
</code>```

Body:
Switch the positions and use layout_weight

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".TabBar">

    <FrameLayout
        android:id="@+id/frame_container"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabGravity="fill"
        app:tabMode="fixed" />

</LinearLayout>


问:
Solve for x value given y = 0 in a random effects model in r
I have a random effects model that looks at the mean bias of the results from a numerical water temperature model given changes to a parameter, roughness. Roughness is the x variable, mean_bias is the y variable, and the location in the stream (1:9) is the random effect variable:

```<code>lmer_mb <- lmer(mean_bias ~ roughness + (1|location), data = W3T, REML=FALSE)
</code>```

I've tried using approx () to find the roughness value when mean_bias = 0:

```<code>xval <- approx(roughness = lmer_mb$fitted,  mean_bias = lmer_mb$roughness, xout = 0)$mean_bias
</code>```

But I keep getting the error:

Error in approx(roughness = lmer_mb$fitted, mean_bias =
  lmer_mb$roughness,  :    unused arguments (roughness = lmer_mb$fitted,
  mean_bias = lmer_mb$roughness)

I also want to plot the xval (once I figure it out) on my plot, and was going to adapt the code that I found in another question on stackoverflow:

```<code>xval <- approx(x = fit$fitted.values, y = x, xout = 30)$y
</code>```

Am I on the right track?

答:
I found the approach I needed to solve this problem. I needed to load the package

```<code>library(merTools)
</code>```

Then I used the wiggle function to generate a new data frame around the area where I wanted to solve for x:

```<code> opt2 <- wiggle(data=W3T, var="roughness", values = seq(0.05,0.1,0.001))
</code>```

Then, I filtered opt2 for the values I wanted and turned them into a list:

```<code>sub.opt2 <- filter(opt2,mean_bias == "0")
sub.opt3 <- list(sub.opt2)
</code>```

And finally, found the average roughness using the draw() function:

```<code>opt.roughness <- draw(lmer_mb, type = 'average', varList = sub.opt3)
opt.roughness
</code>```

My solution was based on the code I found here:
https://cran.r-project.org/web/packages/merTools/vignettes/merToolsIntro.html

Body:
I have a random effects model that looks at the mean bias of the results from a numerical water temperature model given changes to a parameter, roughness. Roughness is the x variable, mean_bias is the y variable, and the location in the stream (1:9) is the random effect variable:

lmer_mb <- lmer(mean_bias ~ roughness + (1|location), data = W3T, REML=FALSE)

I've tried using approx () to find the roughness value when mean_bias = 0:

xval <- approx(roughness = lmer_mb$fitted,  mean_bias = lmer_mb$roughness, xout = 0)$mean_bias

But I keep getting the error:

Error in approx(roughness = lmer_mb$fitted, mean_bias =
  lmer_mb$roughness,  :    unused arguments (roughness = lmer_mb$fitted,
  mean_bias = lmer_mb$roughness)

I also want to plot the xval (once I figure it out) on my plot, and was going to adapt the code that I found in another question on stackoverflow:

xval <- approx(x = fit$fitted.values, y = x, xout = 30)$y

Am I on the right track?

Body:
I found the approach I needed to solve this problem. I needed to load the package

library(merTools)

Then I used the wiggle function to generate a new data frame around the area where I wanted to solve for x:

 opt2 <- wiggle(data=W3T, var="roughness", values = seq(0.05,0.1,0.001))

Then, I filtered opt2 for the values I wanted and turned them into a list:

sub.opt2 <- filter(opt2,mean_bias == "0")
sub.opt3 <- list(sub.opt2)

And finally, found the average roughness using the draw() function:

opt.roughness <- draw(lmer_mb, type = 'average', varList = sub.opt3)
opt.roughness

My solution was based on the code I found here:
https://cran.r-project.org/web/packages/merTools/vignettes/merToolsIntro.html


问:
Paypal credit card payments
When a user clicks on the buy now button, the user is taken to a page, where the user chooses the payment option. Either to pay via paypal, or to create an account an pay with credit or debit card.

Questions:

Is it possible for people to pay with their cards, without being forced to create a paypal account?

If one chooses to pay via paypal, and there is no money in the paypal account, does paypal make the payment from the attached credit or debit card?

Thank you.

答:
Answer to 1.

Yes, if they have a Google account (gmail most likely), they can use Google checkout.

Cor you could use a credit-card payment processor like Stripe, then you can accept credit-cards directly.

You could also use Bitcoin, which would eliminate the payment-processor-parasite from the foodchain - but Bitcoin isn't popular enough as only-solution, yet.

Title: Paypal credit card payments