问:
Replica - MongoDB EC2 instances
Added 3 EC2 instances in in AWS cloud.
Installed 3 MongoDB instances in 3 different instances and all are running fine.

I am adding replication for the same DBs.

below are the steps i followed:

sudo service mongod start --sslPEMKeyFile "/etc/ssl/mongodb.pem" --sslMode "requireSSL" --replSet "myReplSet" ( in all 3 mongo instances)

config = {_id : "myReplSet" , members: [{_id: 0, host:"ip-10-0-0-68:27017"},{_id: 1, host:"ip-10-0-0-247:27017"},{_id: 2, host:"ip-10-0-0-148:27017"}]}

rs.initiate(config)

Error as below:

```<code>   MongoDB Enterprise > rs.initiate(config)
   {
    "ok" : 0,
    "errmsg" : "This node was not started with the replSet option",
    "code" : 76,
    "codeName" : "NoReplicationEnabled"
  }
</code>```

EDIT

I added same security groups and Elastic IP for all 3 instances.
All 3 are new DBs.
Now I am getting error as:

```<code>   {
"ok" : 0,
"errmsg" : "'ip-10-0-0-148:27017' has data already, cannot initiate set.",
"code" : 110,
"codeName" : "CannotInitializeNodeWithData"
   }
</code>```

EDIT-2

Config file for one the servers:

```<code>    # mongod.conf

    # for documentation of all options, see:
    #   http://docs.mongodb.org/manual/reference/configuration-options/

    # where to write logging data.
    systemLog:
    destination: file
    logAppend: true
    path: /var/log/mongodb/mongod.log

    # Where and how to store data.
    storage:
    dbPath: /var/lib/mongo
    journal:
    enabled: true
    #  engine:
    #  mmapv1:
    #  wiredTiger:

    # how the process runs
     processManagement:
    fork: true  # fork and run in background
     pidFilePath: /var/run/mongodb/mongod.pid  # location of pidfile

    # network interfaces
    net:
    port: 27017
    #  bindIp: 127.0.0.1,13.58.225.174,13.58.180.226  # Listen to local   interface only, comment to listen on all interfaces.

    #security:

    #operationProfiling:

    replication:
      replSetName: rs0
</code>```

答:
The service start command does not accept parameters. So

```<code>sudo service mongod start --sslPEMKeyFile "/etc/ssl/mongodb.pem" --sslMode "requireSSL" --replSet "myReplSet"
</code>```

Is equivalent to

```<code>sudo service mongod start
</code>```

If you want to add those settings to the mongod configuration, you will need to edit /etc/mongod.conf to add them in. Since the names of some options vary between the command line and the configuration file, you should take a look at the Configuration File Options documentation to ensure you use the correct settings.

EDIT

Based on your edits and the error message, it appears the mongod process (ip-10-0-0-148:27017) already has data on it. You cannot add a mongod process that already has data to a replica set. You can, however, initiate the replica set on a mongod process that already has data. You should connect to that mongod process and run the rs.initiate() there. Then you run rs.add() to add the remaining, empty, mongod processes to the replica set.

Note: MongoDB does offer MongoDB Cloud Manager and MongoDB Atlas which can do some or all of this for you. However, they are not free, so its up to you if you want to use them.

Title: Replica - MongoDB EC2 instances

Body:
Added 3 EC2 instances in in AWS cloud.
Installed 3 MongoDB instances in 3 different instances and all are running fine.

I am adding replication for the same DBs.

below are the steps i followed:

sudo service mongod start --sslPEMKeyFile "/etc/ssl/mongodb.pem" --sslMode "requireSSL" --replSet "myReplSet" ( in all 3 mongo instances)

config = {_id : "myReplSet" , members: [{_id: 0, host:"ip-10-0-0-68:27017"},{_id: 1, host:"ip-10-0-0-247:27017"},{_id: 2, host:"ip-10-0-0-148:27017"}]}

rs.initiate(config)

Error as below:

   MongoDB Enterprise > rs.initiate(config)
   {
    "ok" : 0,
    "errmsg" : "This node was not started with the replSet option",
    "code" : 76,
    "codeName" : "NoReplicationEnabled"
  }

EDIT

I added same security groups and Elastic IP for all 3 instances.
All 3 are new DBs.
Now I am getting error as:

   {
"ok" : 0,
"errmsg" : "'ip-10-0-0-148:27017' has data already, cannot initiate set.",
"code" : 110,
"codeName" : "CannotInitializeNodeWithData"
   }

EDIT-2

Config file for one the servers:

    # mongod.conf

    # for documentation of all options, see:
    #   http://docs.mongodb.org/manual/reference/configuration-options/

    # where to write logging data.
    systemLog:
    destination: file
    logAppend: true
    path: /var/log/mongodb/mongod.log

    # Where and how to store data.
    storage:
    dbPath: /var/lib/mongo
    journal:
    enabled: true
    #  engine:
    #  mmapv1:
    #  wiredTiger:

    # how the process runs
     processManagement:
    fork: true  # fork and run in background
     pidFilePath: /var/run/mongodb/mongod.pid  # location of pidfile

    # network interfaces
    net:
    port: 27017
    #  bindIp: 127.0.0.1,13.58.225.174,13.58.180.226  # Listen to local   interface only, comment to listen on all interfaces.

    #security:

    #operationProfiling:

    replication:
      replSetName: rs0

Body:
The service start command does not accept parameters. So

sudo service mongod start --sslPEMKeyFile "/etc/ssl/mongodb.pem" --sslMode "requireSSL" --replSet "myReplSet"

Is equivalent to

sudo service mongod start

If you want to add those settings to the mongod configuration, you will need to edit /etc/mongod.conf to add them in. Since the names of some options vary between the command line and the configuration file, you should take a look at the Configuration File Options documentation to ensure you use the correct settings.

EDIT

Based on your edits and the error message, it appears the mongod process (ip-10-0-0-148:27017) already has data on it. You cannot add a mongod process that already has data to a replica set. You can, however, initiate the replica set on a mongod process that already has data. You should connect to that mongod process and run the rs.initiate() there. Then you run rs.add() to add the remaining, empty, mongod processes to the replica set.

Note: MongoDB does offer MongoDB Cloud Manager and MongoDB Atlas which can do some or all of this for you. However, they are not free, so its up to you if you want to use them.


来源: stackexchange

问:
Firebase DB Architecting: filter based on two criteria, favorites and location
In my iOS app I'm using Firebase Realtime Database and I have the following models: Users and Venues.

So Users can favorite a Venue. What I want to do is be able to see all the Venues around me that people I follow have favorited. My main issue is I could generate a ‘favoritedFeed’ similar to how FriendlyPix does it, but I really need to consider the distance I am away from the venues and exclude ones that are too far.

Would it be beneficial to just build a ‘favoritedFeed’ of all the venues people I follow favorite, and then filter that feed by distance on the client side? Also I would like to paginate the feed if possible, but if I take this approach, that might not be possible.

I’ll draw my JSON tree, maybe that should be restructured.

```<code>users
   [user_id]
      …
      comments
         [comment_id]  = true
      favorites
         [venue_id] = true
comments
   [comment_id]
      user = [user_id]
      comment = “…..”
venues
  [venue_id]
      ...
      favorites
         [user_id] = true
</code>```

Right now I just iterate over all of the Users a user follows and then fetch their comments. That way doesn’t scale very well, but its the only way I can figure out how to get the comments at the moment.

答:
You can maintain another root node for the Geofire locations of the events the users you're following have favourited. So whenever someone you follow favourites an event, using Geofire you must write the location of the venue to user-feed-location/$userId for the key $venueId.

I would recommend using Cloud Functions to create an onWrite listener for user-favourites/$userId/$venueId. When a user favourites a venue, for each of their followers, using Geofire update user-feed-location/$followerId with the venue's location and id.

```<code>"user-favourites": {
    "$userId": {
        "$venueId": { ... }
    }
},
"user-feed-location": {
    "$userId": {
        "$venueId": {
            "g": "xxxxxxxxxx",
            "l": { ... }
        }
    }
},
"user-followers": {
    "$userId": {
        "$followerId": { ... }
    }
},
"user-followees": {
    "$userId": {
        "$followeeId": { ... }
    }
},
"users": {
    "$userId": { ... }
},
"venue-location": {
    "$venueId": {
        "g": "xxxxxxxxxx",
        "l": { ... }
    }
},
"venues": {
    "$venueId": { ... }
}
</code>```

By having corresponding Geofire listeners, the addition of a venue to the feed of a particular user within the queried radius would trigger the .keyEntered event. The response block gives you the id and location of the venue with which you can get the venue information and determine the distance between the user and the location returned in the block.

ContentLicense: CC BY-SA 3.0

Body:
In my iOS app I'm using Firebase Realtime Database and I have the following models: Users and Venues.

So Users can favorite a Venue. What I want to do is be able to see all the Venues around me that people I follow have favorited. My main issue is I could generate a ‘favoritedFeed’ similar to how FriendlyPix does it, but I really need to consider the distance I am away from the venues and exclude ones that are too far.

Would it be beneficial to just build a ‘favoritedFeed’ of all the venues people I follow favorite, and then filter that feed by distance on the client side? Also I would like to paginate the feed if possible, but if I take this approach, that might not be possible.

I’ll draw my JSON tree, maybe that should be restructured.

users
   [user_id]
      …
      comments
         [comment_id]  = true
      favorites
         [venue_id] = true
comments
   [comment_id]
      user = [user_id]
      comment = “…..”
venues
  [venue_id]
      ...
      favorites
         [user_id] = true

Right now I just iterate over all of the Users a user follows and then fetch their comments. That way doesn’t scale very well, but its the only way I can figure out how to get the comments at the moment.

Body:
You can maintain another root node for the Geofire locations of the events the users you're following have favourited. So whenever someone you follow favourites an event, using Geofire you must write the location of the venue to user-feed-location/$userId for the key $venueId.

I would recommend using Cloud Functions to create an onWrite listener for user-favourites/$userId/$venueId. When a user favourites a venue, for each of their followers, using Geofire update user-feed-location/$followerId with the venue's location and id.

"user-favourites": {
    "$userId": {
        "$venueId": { ... }
    }
},
"user-feed-location": {
    "$userId": {
        "$venueId": {
            "g": "xxxxxxxxxx",
            "l": { ... }
        }
    }
},
"user-followers": {
    "$userId": {
        "$followerId": { ... }
    }
},
"user-followees": {
    "$userId": {
        "$followeeId": { ... }
    }
},
"users": {
    "$userId": { ... }
},
"venue-location": {
    "$venueId": {
        "g": "xxxxxxxxxx",
        "l": { ... }
    }
},
"venues": {
    "$venueId": { ... }
}

By having corresponding Geofire listeners, the addition of a venue to the feed of a particular user within the queried radius would trigger the .keyEntered event. The response block gives you the id and location of the venue with which you can get the venue information and determine the distance between the user and the location returned in the block.


问:
Wordpress Pagination - can't access to second page
I use WP Beginner pagination (without plugin) on my website, but I can't access to second and other pages.

```<code><?php

$category = get_category( get_query_var( 'cat' ) );
$cat_id = $category->cat_ID;

 $custom_query_args = array(
        'post_type' => array( 'tutorials','post' ),
        'posts_per_page' => 2,
        'cat' => $cat_id,
 );

// Get current page and append to custom query parameters array
$custom_query_args['paged'] = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1;

// Instantiate custom query
$custom_query = new WP_Query( $custom_query_args );

// Pagination fix
$temp_query = $wp_query;
$wp_query   = NULL;
$wp_query   = $custom_query;

// Output custom query loop
if ( $custom_query->have_posts() ) :
        while ( $custom_query->have_posts() ) :
                        $custom_query->the_post();

            echo '<article class="other-post col-xs-12 col-sm-12 col-md-3 col-lg-3">';
            echo '<div class="back-color">';
            echo '<h3>';
            echo the_post_thumbnail('post-thumbnail', array( 'class' => 'post-image' ));
            echo '<a href="'. get_permalink() .'" title="'. get_the_title() .'">';
            echo '<span><b>'. get_the_title() .'</b></span>';
            echo '</a>';
            echo '</h3>';
            echo '</div>';
            echo '</article>';

        endwhile;
endif;

// Reset postdata
wp_reset_postdata();

// Custom query loop pagination
wpbeginner_numeric_posts_nav();

// Reset main query object
$wp_query = NULL;
$wp_query = $temp_query;
?>
</code>```

Here is code from function.php, but I think it isn't the problem.
http://virtual-wizard.eu/function.txt

答:
You’re missing the paged parameter in your query args.

I would also replace the page query, so instead of this:

```<code>// Get current page and append to custom query parameters array
$custom_query_args['paged'] = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1;
</code>```

You have this:

```<code>// Get current page and append to custom query parameters array
if ( get_query_var( 'paged' ) ) {
    $paged = get_query_var( 'paged' );
} elseif ( get_query_var( 'page' ) ) {
    $paged = get_query_var( 'page' );
} else {
    $paged = 1;
}
</code>```

And then change your query to this:

```<code>$custom_query_args = array(
   'post_type' => array( 'tutorials','post' ),
   'posts_per_page' => 2,
   'cat' => $cat_id,
   'paged' => $paged,
);
</code>```

I hope that helps.

Body:
I use WP Beginner pagination (without plugin) on my website, but I can't access to second and other pages.

<?php

$category = get_category( get_query_var( 'cat' ) );
$cat_id = $category->cat_ID;

 $custom_query_args = array(
        'post_type' => array( 'tutorials','post' ),
        'posts_per_page' => 2,
        'cat' => $cat_id,
 );

// Get current page and append to custom query parameters array
$custom_query_args['paged'] = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1;

// Instantiate custom query
$custom_query = new WP_Query( $custom_query_args );

// Pagination fix
$temp_query = $wp_query;
$wp_query   = NULL;
$wp_query   = $custom_query;

// Output custom query loop
if ( $custom_query->have_posts() ) :
        while ( $custom_query->have_posts() ) :
                        $custom_query->the_post();

            echo '
';
            echo '
';
            echo '
';
            echo the_post_thumbnail('post-thumbnail', array( 'class' => 'post-image' ));
            echo '';
            echo ''. get_the_title() .'';
            echo '';
            echo '
';
            echo '
';
            echo '
';

        endwhile;
endif;

// Reset postdata
wp_reset_postdata();

// Custom query loop pagination
wpbeginner_numeric_posts_nav();

// Reset main query object
$wp_query = NULL;
$wp_query = $temp_query;
?>

Here is code from function.php, but I think it isn't the problem.
http://virtual-wizard.eu/function.txt

Body:
You’re missing the paged parameter in your query args.

I would also replace the page query, so instead of this:

// Get current page and append to custom query parameters array
$custom_query_args['paged'] = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1;

You have this:

// Get current page and append to custom query parameters array
if ( get_query_var( 'paged' ) ) {
    $paged = get_query_var( 'paged' );
} elseif ( get_query_var( 'page' ) ) {
    $paged = get_query_var( 'page' );
} else {
    $paged = 1;
}

And then change your query to this:

$custom_query_args = array(
   'post_type' => array( 'tutorials','post' ),
   'posts_per_page' => 2,
   'cat' => $cat_id,
   'paged' => $paged,
);

I hope that helps.


问:
Is there an easy way to create a database diagram in SQL Server
I'm not sure if I have worded this question properly I will explain what I am trying to acheieve further.

I am looking to create a graphical representation of an existing database showing table relationships Key relationships etc.

I have seen posts around the internet that suggest you can just go; New > Database Diagram. But I have seen nothing to this effect in Management Studio

Something similar to this:

答: You first need to install the Diagram Support objects.  Then you all you expand the database out and right click the Database Diagram folder

ContentLicense: CC BY-SA 2.5


问:
Replace child Fragment dynamically from Child Fragment itself
I am using a Viewpager which naturally contain fragments.
inside one of the fragments I have a sub fragment (child fragment)
each child fragment contains a button which calls the following to replace the child fragment itself

```<code>FragmentManager manager = getChildFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.containerProfileDetails, new ProfileDetailsAddressFragment());
transaction.commit();
</code>```

just to make it more visual:

1) is the parent fragment

2) is the child fragment.
I need to replace the child fragment by pressing a button inside the child fragment itself

```<code>┌--------┐
|   1    |
| ┌-----┐|
| | 2   ||
| |     ||
| └-----┘|
└--------┘
</code>```

Note: I know it is possible to replace the fragments using this approach, however, it seems that it is not possible to do this with child fragments as it throws following error.

java.lang.IllegalArgumentException: No view found for id 0x7f0f0104 (com.example.app:id/containerProfileDetails) for fragment ProfileDetailsAddressFragment

Update

Parent Fragment XML:

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
tools:context="com.example.app.fragments.ProfileDetailsFragment">

<TextView
    android:id="@+id/lbl_page"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:textSize="42sp"
    tools:text="2"
    android:visibility="gone"/>

<FrameLayout
    android:id="@+id/containerProfileDetails"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    ></FrameLayout>
</LinearLayout>
</code>```

Child Fragment XML:

```<code><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.app.fragments.ProfileDetailsUserFragment">

<TextView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:text="Fragment Profile User Details" />

<Button
    android:id="@+id/btnProfileDetailsUserNext"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|center"/>

</FrameLayout>
</code>```

Parent Fragment Java:

```<code> public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_profile_details, container, false);
    lblPage = (TextView) view.findViewById(R.id.lbl_page);

    FragmentManager manager = getChildFragmentManager();
    FragmentTransaction transaction = manager.beginTransaction();
    transaction.add(R.id.containerProfileDetails, new ProfileDetailsUserFragment());
    transaction.commit();
    return view;
}
</code>```

Child Fragment Java:

```<code>    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v = inflater.inflate(R.layout.fragment_profile_details_user, container, false);

    Button _btnProfileDetailsUserNext = (Button) v.findViewById(R.id.btnProfileDetailsUserNext);
    _btnProfileDetailsUserNext.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            FragmentManager manager = getChildFragmentManager();
            FragmentTransaction transaction = manager.beginTransaction();
            transaction.replace(R.id.containerProfileDetails, new ProfileDetailsAddressFragment());
            transaction.commit();
        }
    });
    return v;
}
</code>```

答:
Replace your Parent Fragment and Child Fragment Code with below

Parent_Fragment.Java

```<code> public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_profile_details, container, false);
    lblPage = (TextView) view.findViewById(R.id.lbl_page);

    FragmentManager manager = getChildFragmentManager();
    FragmentTransaction transaction = manager.beginTransaction();
    transaction.add(R.id.containerProfileDetails, new ProfileDetailsUserFragment());
    transaction.commit();
    return view;
}
</code>```

Child_Fragment.Java

```<code> public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v = inflater.inflate(R.layout.fragment_profile_details_user, container, false);

    Button _btnProfileDetailsUserNext = (Button) v.findViewById(R.id.btnProfileDetailsUserNext);
    _btnProfileDetailsUserNext.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            FragmentManager manager = getFragmentManager();
            FragmentTransaction transaction = manager.beginTransaction();
            transaction.replace(R.id.containerProfileDetails, new ProfileDetailsAddressFragment());
            transaction.commit();
        }
    });
    return v;
}
</code>```

I Have not tested the code, it may Produce some compilation error, but way is correct to implement.

Body:
I am using a Viewpager which naturally contain fragments.
inside one of the fragments I have a sub fragment (child fragment)
each child fragment contains a button which calls the following to replace the child fragment itself

FragmentManager manager = getChildFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.containerProfileDetails, new ProfileDetailsAddressFragment());
transaction.commit();

just to make it more visual:

1) is the parent fragment

2) is the child fragment.
I need to replace the child fragment by pressing a button inside the child fragment itself

┌--------┐
|   1    |
| ┌-----┐|
| | 2   ||
| |     ||
| └-----┘|
└--------┘

Note: I know it is possible to replace the fragments using this approach, however, it seems that it is not possible to do this with child fragments as it throws following error.

java.lang.IllegalArgumentException: No view found for id 0x7f0f0104 (com.example.app:id/containerProfileDetails) for fragment ProfileDetailsAddressFragment

Update

Parent Fragment XML:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
tools:context="com.example.app.fragments.ProfileDetailsFragment">

<TextView
    android:id="@+id/lbl_page"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:textSize="42sp"
    tools:text="2"
    android:visibility="gone"/>

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

Child Fragment XML:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.app.fragments.ProfileDetailsUserFragment">

<TextView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:text="Fragment Profile User Details" />

<Button
    android:id="@+id/btnProfileDetailsUserNext"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|center"/>

</FrameLayout>

Parent Fragment Java:

 public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_profile_details, container, false);
    lblPage = (TextView) view.findViewById(R.id.lbl_page);

    FragmentManager manager = getChildFragmentManager();
    FragmentTransaction transaction = manager.beginTransaction();
    transaction.add(R.id.containerProfileDetails, new ProfileDetailsUserFragment());
    transaction.commit();
    return view;
}

Child Fragment Java:

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v = inflater.inflate(R.layout.fragment_profile_details_user, container, false);

    Button _btnProfileDetailsUserNext = (Button) v.findViewById(R.id.btnProfileDetailsUserNext);
    _btnProfileDetailsUserNext.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            FragmentManager manager = getChildFragmentManager();
            FragmentTransaction transaction = manager.beginTransaction();
            transaction.replace(R.id.containerProfileDetails, new ProfileDetailsAddressFragment());
            transaction.commit();
        }
    });
    return v;
}

Body:
Replace your Parent Fragment and Child Fragment Code with below

Parent_Fragment.Java

 public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_profile_details, container, false);
    lblPage = (TextView) view.findViewById(R.id.lbl_page);

    FragmentManager manager = getChildFragmentManager();
    FragmentTransaction transaction = manager.beginTransaction();
    transaction.add(R.id.containerProfileDetails, new ProfileDetailsUserFragment());
    transaction.commit();
    return view;
}

Child_Fragment.Java

 public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v = inflater.inflate(R.layout.fragment_profile_details_user, container, false);

    Button _btnProfileDetailsUserNext = (Button) v.findViewById(R.id.btnProfileDetailsUserNext);
    _btnProfileDetailsUserNext.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            FragmentManager manager = getFragmentManager();
            FragmentTransaction transaction = manager.beginTransaction();
            transaction.replace(R.id.containerProfileDetails, new ProfileDetailsAddressFragment());
            transaction.commit();
        }
    });
    return v;
}

I Have not tested the code, it may Produce some compilation error, but way is correct to implement.


问:
Sorting collection 2 times
So I want to sort a collection (that's ok for me) but if in this sort result 2 values are equal, I want to compare two other values to determine what goes first.

Ex: I have 30 teams, they all have points, but some teams can have the same number of points. If so, I want to check the victories each team has and put the team with most victories in front of the one with the less.

rankings = $team_stats->sortByDesc(function($product) {
     return ($product['nhl_season_w'] * 2) + $product['nhl_season_otl']
});

So yeah! That sorts the team's points, now I want to sort the equalities by victories.

Thanks for the help!

EDIT SOLVED:

I use $key + 1 to make sure my team ID's stays the same so it's easier to use to get anything else from the team ranking :)

答:
Just concatenate the victories after the point value

```<code>$rankings = $team_stats->sortByDesc(function($product) {
     return (($product['nhl_season_w'] * 2) + $product['nhl_season_otl']) . '_' . $procuct['victories'];
});
</code>```

This will add the victories to the sort string and makes sure the highest victory stays on top when two products have the same score.

Title: Sorting collection 2 times

Body:
Just concatenate the victories after the point value

$rankings = $team_stats->sortByDesc(function($product) {
     return (($product['nhl_season_w'] * 2) + $product['nhl_season_otl']) . '_' . $procuct['victories'];
});

This will add the victories to the sort string and makes sure the highest victory stays on top when two products have the same score.


问:
performance of rho2hat and ppm in spatstat
I want to compare the performance of nonparametric intensity function estimator "rho2hat" with "ppm".

My question how can I perform a test to see estimation works better? I couldn't use quadrat.test?

答:
As mentioned in the comment by @adrian-baddeley your suggested strategy
will just measure the difference between two results. The way you can
calculate the expected number of points in different regions from an
estimated intensity is as follows:

library(spatstat)
#> Loading required package: nlme
#> Loading required package: rpart
#>
#> spatstat 1.51-0.035       (nickname: 'Spatfefe')
#> For an introduction to spatstat, type 'beginner'
elev <- bei.extra$elev
grad <- bei.extra$grad
non <- rho2hat(bei, elev, grad)
pred <- predict(non)
grid <- quadrats(pred, nx = 4, ny = 2)
by(pred, grid, integral)
#> 1:
#> [1] 522.0247
#>
#> 2:
#> [1] 503.6255
#>
#> 3:
#> [1] 344.8552
#>
#> 4:
#> [1] 522.834
#>
#> 5:
#> [1] 454.5958
#>
#> 6:
#> [1] 470.2484
#>
#> 7:
#> [1] 556.1989
#>
#> 8:
#> [1] 415.8889
```


问:
django StreamingHttpResponse - catch exception raised in streaming_content iterator
I'm trying to handle errors while returning a StreamingHttpResponse:

The exception raised manually inside the iterator used as straeming_content is not caught.

here's the code:

```<code>def reportgen_iterator(request, object_id):
    output_format = request.GET.get('output', 'pdf')
    debug_mode = request.GET.get('debug', False)
    response_data = {
        'progress': 'Retrieving data...',
    }
    # code....
    yield json.dumps(response_data)

    # code ...
    raise Exception('bla bla') # manually raised exception

    # other code ......
    yield json.dumps(response_data)

class StreamingView(View):
    def get(self, request, object_id):
        """
        """
        stream = reportgen_iterator(request, object_id)
        try:
            response = StreamingHttpResponse(
                streaming_content=stream, status=200,
                content_type='application/octet-stream'
            )
            response['Cache-Control'] = 'no-cache'
            return response
        except Exception as e:
            # exception not catched
            return HttpResponseServerError(e.message)
</code>```

any help about how correctly handle this? The except clause is never reached.

Thanks

答:
You have returned from the get method long before the exception in reportgen_iterator has been raised.

Why is that?

It should be given an iterator that yields strings as content. You
  cannot access its content, except by iterating the response object
  itself. This should only occur when the response is returned to the
  client.

The view function returns with the iterator (in your case the generator) but that isn't iterated fully while you are still inside the function. That's why the exception is never caught in the get method.

https://docs.djangoproject.com/en/1.11/ref/request-response/#streaminghttpresponse-objects

Body:
I'm trying to handle errors while returning a StreamingHttpResponse:

The exception raised manually inside the iterator used as straeming_content is not caught.

here's the code:

def reportgen_iterator(request, object_id):
    output_format = request.GET.get('output', 'pdf')
    debug_mode = request.GET.get('debug', False)
    response_data = {
        'progress': 'Retrieving data...',
    }
    # code....
    yield json.dumps(response_data)

    # code ...
    raise Exception('bla bla') # manually raised exception

    # other code ......
    yield json.dumps(response_data)

class StreamingView(View):
    def get(self, request, object_id):
        """
        """
        stream = reportgen_iterator(request, object_id)
        try:
            response = StreamingHttpResponse(
                streaming_content=stream, status=200,
                content_type='application/octet-stream'
            )
            response['Cache-Control'] = 'no-cache'
            return response
        except Exception as e:
            # exception not catched
            return HttpResponseServerError(e.message)

any help about how correctly handle this? The except clause is never reached.

Thanks


问:
Order independent hashing
I'm creating keys for key-value data by taking a few (<10) pieces of information that identify the data and producing one hash from them combined. For this, I've been using CryptoPP's SHA256::Update function, which lets you add pieces at a time:

```<code>#include "sha.h"
...
byte outputBuf[CryptoPP::SHA256::DIGESTSIZE];
CryptoPP::SHA256 hash;
hash.Update(pData1, lenData1); // pData* can point to int, double or std::string
hash.Update(pData2, lenData2);
...
hash.Final(outputBuf);
</code>```

I've noticed that the order of the calls to Update matters (i.e. if you change the order of the two Update statements, you'll get a different hash). I would like this to be order independent instead. So:

Does CryptoPP offer a way to do this?

If not, can you suggest an alternative approach? So far I think using xor to combine the  parameters would work. One problem is that if two pieces of data are the same, they'll cancel out. Can you foresee problems with this?

答:
The comment saying that xor will increase the number of collisions is only true, if you consider {1, 2} and {2, 1} to be different inputs. I guess, you don't, as otherwise you wouldn't want an order-independent hash. So h({1, 2}) = h({2, 1}) is no collision as you're providing the same input.

The simplest solution is sorting and than using your favorite hash function. It is as secure as your hash function (confirm on crypto.stackexchange.com if you care).

Xoring hashes is definitely a bad idea as two equal elements cancel out. Adding them is much better, but with two equal elements, the least significant bit will be zero (with four such elements, two bits will be zero, etc.). This may be acceptable.

Note that any such method is pretty insecure as it allows finding collisions much faster (proof upon request). You may or may not need security, but don't try to invent a secure method, as it's practically impossible (every well-known hash function has many man-months of analysis behind it).

Title: Order independent hashing

Body:
I'm creating keys for key-value data by taking a few (<10) pieces of information that identify the data and producing one hash from them combined. For this, I've been using CryptoPP's SHA256::Update function, which lets you add pieces at a time:

#include "sha.h"
...
byte outputBuf[CryptoPP::SHA256::DIGESTSIZE];
CryptoPP::SHA256 hash;
hash.Update(pData1, lenData1); // pData* can point to int, double or std::string
hash.Update(pData2, lenData2);
...
hash.Final(outputBuf);

I've noticed that the order of the calls to Update matters (i.e. if you change the order of the two Update statements, you'll get a different hash). I would like this to be order independent instead. So:

Does CryptoPP offer a way to do this?

If not, can you suggest an alternative approach? So far I think using xor to combine the  parameters would work. One problem is that if two pieces of data are the same, they'll cancel out. Can you foresee problems with this?


问:
Find string in list within list of objects
I have a list of objects with lists:

```<code>ls = [
    {'id': 1, 'content': ['lorem', 'ipsum']},
    {'id': 1, 'content': ['dolor', 'sit', 'amet']},
]
</code>```

i want to get the index of the object with e.g. 'lorem'

So far i tried:

```<code>'lorem' in [x['content'] for x in ls]
</code>```

This does not return true nor does it return an index.

答:
This algorithm sets a keyword to a string and then searches through the list of dictionaries to see if the keyword exists the value for the key 'content'. If it does exist, the index is returned. If it does not, "not found" is returned.

```<code>keyword = "dolor"

ls = [
{'id': 1, 'content': ['lorem', 'ipsum']},
{'id': 1, 'content': ['dolor', 'sit', 'amet']},
]

indices = [i['content'].index(keyword) if keyword in i['content'] else "not found" for i in ls]
</code>```

Edit:

Another way to find the index without a "not found" statement can be done below:

```<code> [i['content'].index(keyword) for i in ls if keyword in i['content']]
</code>```

Body:
I have a list of objects with lists:

ls = [
    {'id': 1, 'content': ['lorem', 'ipsum']},
    {'id': 1, 'content': ['dolor', 'sit', 'amet']},
]

i want to get the index of the object with e.g. 'lorem'

So far i tried:

'lorem' in [x['content'] for x in ls]

This does not return true nor does it return an index.

Body:
This algorithm sets a keyword to a string and then searches through the list of dictionaries to see if the keyword exists the value for the key 'content'. If it does exist, the index is returned. If it does not, "not found" is returned.

keyword = "dolor"

ls = [
{'id': 1, 'content': ['lorem', 'ipsum']},
{'id': 1, 'content': ['dolor', 'sit', 'amet']},
]

indices = [i['content'].index(keyword) if keyword in i['content'] else "not found" for i in ls]

Edit:

Another way to find the index without a "not found" statement can be done below:

 [i['content'].index(keyword) for i in ls if keyword in i['content']]


问:
Python: Callbacks, Delegates, ... ? What is common?
Just want to know what's the common way to react on events in python. There are several ways in other languages like callback functions, delegates, listener-structures and so on.
Is there a common way? Which default language concepts or additional modules are there and which can you recommend?</p>

答: Most of the Python libraries I have used implement a callback model for their event notifications, which I think suits the language fairly well.  Pygtk does this by deriving all objects from GObject, which implements callback-based signal handling.  (Although this is a feature of the underlying C GTK implementation, not something inspired by the language.)  However, Pygtkmvc does an interesting job of implementing an observer pattern (and MVC) over the top of Pygtk.  It uses a very ornate metaclass based implementation, but I have found that it works fairly well for most cases.  The code is reasonably straightforward to follow, as well, if you are interested in seeing one way in which this has been done.</p>

OwnerDisplayName: okoman

OwnerDisplayName: bouvard


问:
Conditional Compilation and Objective-C/Xcode
So I am working on a learning project and I am trying to create a header file that contains a store of URL's so that you can just change a single flag to change from Debug to Production.  This is what I am trying to do with the compiler and it is clearly wrong.  I can't find any information on how to do this in Objective-C, so that's why I came here.

```<code>#define DEBUG 1
#if DEBUG
  NSString *URL = @"dev.myserver.com";
#else
  NSString *URL = @"myserver.com";
#endif

@interface GlobalURLRefrences : NSObject {
  //NSString *URL; removed this
}

//@property (nonatomic, retain) NSString *URL; removed this

@end
</code>```

Now I am not sure if I need to declare that as a property or not.  Also, once this is compiled properly, how to I access it from an outside class (of course after you #import the globalURL's class)  Any sort of guidance on the proper method of doing this would be greatly appreciated.

答:
I think you are trying to define the same variable twice.  How about this:

In your header:

```<code>#define DEBUG 1
</code>```

In the init of your .m file:

```<code>#if DEBUG
   URL = @"dev.myserver.com";
#else
   URL = @"myserver.com";
#endif
</code>```

Body:
So I am working on a learning project and I am trying to create a header file that contains a store of URL's so that you can just change a single flag to change from Debug to Production.  This is what I am trying to do with the compiler and it is clearly wrong.  I can't find any information on how to do this in Objective-C, so that's why I came here.

#define DEBUG 1
#if DEBUG
  NSString *URL = @"dev.myserver.com";
#else
  NSString *URL = @"myserver.com";
#endif

@interface GlobalURLRefrences : NSObject {
  //NSString *URL; removed this
}

//@property (nonatomic, retain) NSString *URL; removed this

@end

Now I am not sure if I need to declare that as a property or not.  Also, once this is compiled properly, how to I access it from an outside class (of course after you #import the globalURL's class)  Any sort of guidance on the proper method of doing this would be greatly appreciated.

Body:
I think you are trying to define the same variable twice.  How about this:

In your header:

#define DEBUG 1

In the init of your .m file:

#if DEBUG
   URL = @"dev.myserver.com";
#else
   URL = @"myserver.com";
#endif


问:
Getting Error: Module parse failed: ... unexpected character '#'
I am using webpack for the first time and want to use some css with my react/redux application. I followed a guide, but still seem to be having problems. I am getting the above error as you can see.

folder structure looks like this:

```<code>.git
-node_modules
-public
 -bundle.js
 -index.html
-src
 -actions
 -components
 -reducers
 app.js
-style
 -style.css
.babelrc
.gitingore
package-lock.json
package.json
README.md
server.js
webpack.config.js
</code>```

This is the exact error:

```<code>Uncaught Error: Module parse failed: C:\Users\Amazo\projects\reduxApp\style\style.css Unexpected character '#' (1:0)
You may need an appropriate loader to handle this file type.
| #row1 {
|   margin-top: 15px;
| }
</code>```

I will post my webpack config file below:

```<code>var path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
var HTMLWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  entry: './src/app.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'public')
  },
  watch: true,
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude:/node_modules/,
        loader: 'babel-loader',
        query: {
          presets: ['react', 'es2015', 'stage-1']
        }
      },
      {
        use: ['style-loader', 'css-loader'],
        test: /\.css$/
      }
    ]
  },
  resolve: {
    extensions: ['.js','.jsx']
  },
  plugins: [
    new HTMLWebpackPlugin({
      template: 'public/index.html';
    }),
    new ExtractTextPlugin('style.css')
  ]
};
</code>```

答:
Add .css to your resolve

```<code>resolve: {
  extensions: ['.js','.jsx', '.css']
},
</code>```

Otherwise, webpack won't be able to process it correctly

Body:
I am using webpack for the first time and want to use some css with my react/redux application. I followed a guide, but still seem to be having problems. I am getting the above error as you can see.

folder structure looks like this:

.git
-node_modules
-public
 -bundle.js
 -index.html
-src
 -actions
 -components
 -reducers
 app.js
-style
 -style.css
.babelrc
.gitingore
package-lock.json
package.json
README.md
server.js
webpack.config.js

This is the exact error:

Uncaught Error: Module parse failed: C:\Users\Amazo\projects\reduxApp\style\style.css Unexpected character '#' (1:0)
You may need an appropriate loader to handle this file type.
| #row1 {
|   margin-top: 15px;
| }

I will post my webpack config file below:

var path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
var HTMLWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  entry: './src/app.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'public')
  },
  watch: true,
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude:/node_modules/,
        loader: 'babel-loader',
        query: {
          presets: ['react', 'es2015', 'stage-1']
        }
      },
      {
        use: ['style-loader', 'css-loader'],
        test: /\.css$/
      }
    ]
  },
  resolve: {
    extensions: ['.js','.jsx']
  },
  plugins: [
    new HTMLWebpackPlugin({
      template: 'public/index.html';
    }),
    new ExtractTextPlugin('style.css')
  ]
};

Body:
Add .css to your resolve

resolve: {
  extensions: ['.js','.jsx', '.css']
},

Otherwise, webpack won't be able to process it correctly


问:
Deleting database value using spring

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>

 Select type of material<select id="mySelect" onchange="myFunction()">
  <option value="mango">mango
  <option value="grape">grape
  </select>
  Select weight type<select id="mySelect" onchange="myFunction()">
  <option value="Tons">Tons
  <option value="KG">KG
  </select>
 Enter Value<input type="text" >
 <input type="button" value="Enter">

```

I want to delete database value in Spring based programming. How can I do
 this. I want to do this operation in backend. What is the process?

答:
In a Spring based application, database operations such as delete are performed by Repository classes. Based on your question, I suppose you are "too far" from repository layer. So I suggest you take a step-by-step tutorial. It will guide you through all the way down to the business logic and data access.

Another great way to get started with Spring is Spring Boot: here and here

Title: Deleting database value using spring

Body:
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>

 Select type of material<select id="mySelect" onchange="myFunction()">
  <option value="mango">mango
  <option value="grape">grape
  </select>
  Select weight type<select id="mySelect" onchange="myFunction()">
  <option value="Tons">Tons
  <option value="KG">KG
  </select>
 Enter Value<input type="text" >
 <input type="button" value="Enter">

I want to delete database value in Spring based programming. How can I do
 this. I want to do this operation in backend. What is the process?


问:
Difference between Container and ContainerBuilder in Symfony
I'm trying to understand the Symfony core, but I'm not not completely sure about some things happening in the DI component.

What is the difference between the Container and the ContainerBuilder? The name would suggest that the ContainerBuilder is used to build a Container object, but regarding the docs it can be directly instantiated and used as a container:

```<code>$container = new ContainerBuilder();
$container->register('mailer', 'Mailer');
</code>```

Why not use $container = new Container() here?

答:
Ok, below from Symfony's documentation (http://api.symfony.com/3.0/Symfony/Component/DependencyInjection/ContainerBuilder.html):

```<code>class ContainerBuilder extends Container implements TaggedContainerInterface
</code>```

ContainerBuilder is a DI container that provides an API to easily describe services.

You see, ContainerBuilder extends Container. Compare the documentation with http://api.symfony.com/3.0/Symfony/Component/DependencyInjection/Container.html

Body:
I'm trying to understand the Symfony core, but I'm not not completely sure about some things happening in the DI component.

What is the difference between the Container and the ContainerBuilder? The name would suggest that the ContainerBuilder is used to build a Container object, but regarding the docs it can be directly instantiated and used as a container:

$container = new ContainerBuilder();
$container->register('mailer', 'Mailer');

Why not use $container = new Container() here?

Body:
Ok, below from Symfony's documentation (http://api.symfony.com/3.0/Symfony/Component/DependencyInjection/ContainerBuilder.html):

class ContainerBuilder extends Container implements TaggedContainerInterface

ContainerBuilder is a DI container that provides an API to easily describe services.

You see, ContainerBuilder extends Container. Compare the documentation with http://api.symfony.com/3.0/Symfony/Component/DependencyInjection/Container.html


问:
Can I configure the DNN Search to be Section 508/WCAG 2.0 compliant?
I have several DNN (DotNetNuke) portals that use the DNN Search token on their respective skins. When I run a Section 508 / WCAG 2.0 accessibility report, it indicates that the DNN Search does not meet Section 508 / WCAG 2.0 guidelines.

Has anyone ran into this issue? If so, what steps would you recommend to remedy the problem?

I am using DNN Evoq Content 8.5

Thank you.

答:
You didn't say what the problem is, but there are things that can be modified for compliance.  If I were to do this, I would clone the Search skin object and modify it (presumably the markup for the object) for compliance.

If the Search Results is the problem, you could do something similar.

Finally, I would contact DNN Corp. about this.  It's my understanding that compliance is a target of DNN (and Evoq) version 9.  Their goal is to be compliant "out of the box" and that does include Search.  I'm not sure where that stands, but it's worth asking.


问:
firebase authentication - does firebase differentiate facebook and google login accounts
I want to use firebase as my apps authentication method.  But I'd like my users to log in using Google or Facebook. I am a little confused what happens here.

Lets say a user successfully authenticates with Facebook only. Then I get a callback from Facebook with some token of success. Now I send that token to firebase for further authentication.
Firebase can return success or failure. This part I understand.

But what I am confused about is if the same user uses the Google account to login, will that not be considered a different login?  Will firebase know that the Facebook user is the same google user or will it create two different accounts? I don't want the user to have two different accounts because they chose a different login provider. I want firebase to be able to know its the same user. That is why I wanted to user firebase authentication as its a central place. Can someone advise me?

UPDATE:

Thanks. So if I understand correctly at least one account must already be currently logged into firebase inorder to link another one ? So that being the case ...imagine i am currently logged in with a google account. How would i ask the user to link there facebook account? I wish i could link the second account seamlessly but seems you cant. Therefore how doni prompt the user or under what condition can i link the second account effortlessly? I'm having trouble visualizing how this would work without me directly asking the user.

答:
Firebase supports multiple Auth Providers to an Account. All you have to do is to use linkWithCredential(credential) method. Here is a code snipset from firebase website.

```<code>mAuth.getCurrentUser().linkWithCredential(credential)
    .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
        @Override
        public void onComplete(@NonNull Task<AuthResult> task) {
            if (task.isSuccessful()) {
                Log.d(TAG, "linkWithCredential:success");
                FirebaseUser user = task.getResult().getUser();
                updateUI(user);
            } else {
                Log.w(TAG, "linkWithCredential:failure", task.getException());
                Toast.makeText(AnonymousAuthActivity.this, "Authentication failed.",
                        Toast.LENGTH_SHORT).show();
                updateUI(null);
            }

            // ...
        }
    });
</code>```

Take note that the call to linkWithCredential will fail if the credentials are already linked to another user account. In this situation, you must handle merging the accounts and associated data as appropriate for your app.

Body:
Firebase supports multiple Auth Providers to an Account. All you have to do is to use linkWithCredential(credential) method. Here is a code snipset from firebase website.

mAuth.getCurrentUser().linkWithCredential(credential)
    .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
        @Override
        public void onComplete(@NonNull Task<AuthResult> task) {
            if (task.isSuccessful()) {
                Log.d(TAG, "linkWithCredential:success");
                FirebaseUser user = task.getResult().getUser();
                updateUI(user);
            } else {
                Log.w(TAG, "linkWithCredential:failure", task.getException());
                Toast.makeText(AnonymousAuthActivity.this, "Authentication failed.",
                        Toast.LENGTH_SHORT).show();
                updateUI(null);
            }

            // ...
        }
    });

Take note that the call to linkWithCredential will fail if the credentials are already linked to another user account. In this situation, you must handle merging the accounts and associated data as appropriate for your app.


问:
how can I store my data in a global variable?
```<code>$(function(){

    var astronautsData;

    $.getJSON('http://api.open-notify.org/astros.json', doSomething);

    function doSomething(data) {
        astronautsData = data;
    }

    alert(astronautsData.people[0].name)

});
</code>```

I would like to be able to use the data in every function I make, that's why I tried to put it in the variable astronautsData, but unfortunately astronautsdata is undefined.

答:
You can access astronautsData  inside doSomething.your alert() will get executed
before getJSON. that's why you are getting undefined. </p>

```<code>$(function(){

  var astronautsData;

  $.getJSON('http://api.open-notify.org/astros.json', doSomething);

  function doSomething(data) {
    astronautsData = data;
    alert(astronautsData.people[0].name)
  }
});
</code>```

Body:
$(function(){

    var astronautsData;

    $.getJSON('http://api.open-notify.org/astros.json', doSomething);

    function doSomething(data) {
        astronautsData = data;
    }

    alert(astronautsData.people[0].name)

});

I would like to be able to use the data in every function I make, that's why I tried to put it in the variable astronautsData, but unfortunately astronautsdata is undefined.

Body:
You can access astronautsData  inside doSomething.your alert() will get executed
before getJSON. that's why you are getting undefined.

$(function(){

  var astronautsData;

  $.getJSON('http://api.open-notify.org/astros.json', doSomething);

  function doSomething(data) {
    astronautsData = data;
    alert(astronautsData.people[0].name)
  }
});


问:
Comparator<File> for "directories-first" order
I'm stumped... Let's say I have this directory tree:

```<code>{someRoot}/
{someRoot}/bar/
{someRoot}/bar/file1.txt
{someRoot}/foo/
{someRoot}/foo/baz/
{someRoot}/foo/baz/file3.txt
{someRoot}/foo/abracadabra.txt
{someRoot}/foo/file2.txt
{someRoot}/aardvark.txt
{someRoot}/food.txt
{someRoot}/zebra.txt
</code>```

You'll note the ordering. Call this order1. At each stage, the directories come first before the files. (NOTE:  bar/file1.txt comes before foo, so on a global basis, the directories do not all come before all the files.)

If I enumerate this directory tree, and then recursively enumerate the subdirectories, I'll get the following List<File>, with ordering order2.

```<code>{someRoot}/
{someRoot}/aardvark.txt
{someRoot}/bar/
{someRoot}/foo/
{someRoot}/food.txt
{someRoot}/zebra.txt
{someRoot}/bar/file1.txt
{someRoot}/foo/abracadabra.txt
{someRoot}/foo/baz/
{someRoot}/foo/file2.txt
{someRoot}/foo/baz/file3.txt
</code>```

If I create the straightforward Comparator<File>:

```<code>Comparator<File> fc = new Comparator<File>(){
    @Override public int compare(File o1, File o2) {
        return o1.compareTo(o2);
    }
};
</code>```

and I sort, I get this ordering (order3) from lexicographic ordering:

```<code>{someRoot}
{someRoot}/aardvark.txt
{someRoot}/bar
{someRoot}/bar/file1.txt
{someRoot}/foo
{someRoot}/food.txt
{someRoot}/foo/abracadabra.txt
{someRoot}/foo/baz
{someRoot}/foo/baz/file3.txt
{someRoot}/foo/file2.txt
{someRoot}/zebra.txt
</code>```

But I don't want this ordering (which has problems: note that food.txt comes between directory foo and its sub-items), I want order1. How can I write a Comparator to get me that?

答:
I did find a way to implement the pseudo-opposite of what I wanted (directories after files, haven't checked the edge cases where files and directory names are at the root level).

...And no, it's not trivial to transform this into what I do want, because I'm using lexicographic ordering of directories, which couples the ordering of directories at different levels and the ordering of directories at the same level.

```<code>static class FileDirectoryPriorityComparator implements Comparator<File>
{
    @Override public int compare(File f1, File f2) {
        if (f1.isDirectory())
        {
            if (f2.isDirectory())
            {
                return f1.compareTo(f2);
            }
            else
            {
                return compareDirFile(f1, f2);
            }
        }
        else
        {
            if (f2.isDirectory())
            {
                return -compareDirFile(f2, f1);
            }
            // f1 and f2 are both files
            else
            {
                return compareFiles(f1, f2);
            }
        }
    }

    private int compareDirFile(File dir, File file) {
        /*
         * If dir compares differently to file's parent, use that ordering.
         * Otherwise, dir comes before file.
         */
        File fparent = file.getParentFile();

        if (fparent == null)
            return -1;

        int i = dir.compareTo(fparent);
        if (i != 0)
            return i;

        return -1;
    }

    private int compareFiles(File f1, File f2) {
        /*
         * If f1's parent compares differently to f2's parent, use that ordering.
         * Otherwise use default ordering.
         */
        File fp1 = f1.getParentFile();
        File fp2 = f2.getParentFile();

        if (fp1 == null)
        {
            if (fp2 != null)
            {
                return 1;
            }
        }
        else
        {
            if (fp2 == null)
            {
                return -1;
            }
            else
            {
                int i = fp1.compareTo(fp2);
                if (i != 0)
                    return i;
            }
        }

        return f1.compareTo(f2);
    }
}
</code>```

Body:
I'm stumped... Let's say I have this directory tree:

{someRoot}/
{someRoot}/bar/
{someRoot}/bar/file1.txt
{someRoot}/foo/
{someRoot}/foo/baz/
{someRoot}/foo/baz/file3.txt
{someRoot}/foo/abracadabra.txt
{someRoot}/foo/file2.txt
{someRoot}/aardvark.txt
{someRoot}/food.txt
{someRoot}/zebra.txt

You'll note the ordering. Call this order1. At each stage, the directories come first before the files. (NOTE:  bar/file1.txt comes before foo, so on a global basis, the directories do not all come before all the files.)

If I enumerate this directory tree, and then recursively enumerate the subdirectories, I'll get the following List<File>, with ordering order2.

{someRoot}/
{someRoot}/aardvark.txt
{someRoot}/bar/
{someRoot}/foo/
{someRoot}/food.txt
{someRoot}/zebra.txt
{someRoot}/bar/file1.txt
{someRoot}/foo/abracadabra.txt
{someRoot}/foo/baz/
{someRoot}/foo/file2.txt
{someRoot}/foo/baz/file3.txt

If I create the straightforward Comparator<File>:

Comparator<File> fc = new Comparator<File>(){
    @Override public int compare(File o1, File o2) {
        return o1.compareTo(o2);
    }
};

and I sort, I get this ordering (order3) from lexicographic ordering:

{someRoot}
{someRoot}/aardvark.txt
{someRoot}/bar
{someRoot}/bar/file1.txt
{someRoot}/foo
{someRoot}/food.txt
{someRoot}/foo/abracadabra.txt
{someRoot}/foo/baz
{someRoot}/foo/baz/file3.txt
{someRoot}/foo/file2.txt
{someRoot}/zebra.txt

But I don't want this ordering (which has problems: note that food.txt comes between directory foo and its sub-items), I want order1. How can I write a Comparator to get me that?

Body:
I did find a way to implement the pseudo-opposite of what I wanted (directories after files, haven't checked the edge cases where files and directory names are at the root level).

...And no, it's not trivial to transform this into what I do want, because I'm using lexicographic ordering of directories, which couples the ordering of directories at different levels and the ordering of directories at the same level.

static class FileDirectoryPriorityComparator implements Comparator<File>
{
    @Override public int compare(File f1, File f2) {
        if (f1.isDirectory())
        {
            if (f2.isDirectory())
            {
                return f1.compareTo(f2);
            }
            else
            {
                return compareDirFile(f1, f2);
            }
        }
        else
        {
            if (f2.isDirectory())
            {
                return -compareDirFile(f2, f1);
            }
            // f1 and f2 are both files
            else
            {
                return compareFiles(f1, f2);
            }
        }
    }

    private int compareDirFile(File dir, File file) {
        /*
         * If dir compares differently to file's parent, use that ordering.
         * Otherwise, dir comes before file.
         */
        File fparent = file.getParentFile();

        if (fparent == null)
            return -1;

        int i = dir.compareTo(fparent);
        if (i != 0)
            return i;

        return -1;
    }

    private int compareFiles(File f1, File f2) {
        /*
         * If f1's parent compares differently to f2's parent, use that ordering.
         * Otherwise use default ordering.
         */
        File fp1 = f1.getParentFile();
        File fp2 = f2.getParentFile();

        if (fp1 == null)
        {
            if (fp2 != null)
            {
                return 1;
            }
        }
        else
        {
            if (fp2 == null)
            {
                return -1;
            }
            else
            {
                int i = fp1.compareTo(fp2);
                if (i != 0)
                    return i;
            }
        }

        return f1.compareTo(f2);
    }
}


问:
Trouble added cell to UICollectionView
Trying to add a cell to my ViewController, and I'm having trouble.  I'm wondering if I have all my delegates.  Currently, I can change the color of the collection view's background, but can't add any cells.

I'm using an array of text from my Listing() object to drive the collection view cells.  On viewDidLoad the length is 4.  I envisioned using this count for the numberofItemsInSection, however, if I put the print statement there it is never printed.  Which makes me think the wrong delegate is called and the method is never hit.  Correct?

```<code>import UIKit

class ListingDetailViewController: UIViewController,
UICollectionViewDelegateFlowLayout {
    var listing = Listing()
    //    @IBOutlet var image: UIImageView!
    @IBOutlet var post: UITextView!
    @IBOutlet var price: UILabel!
    @IBOutlet var amenitiesCollection: UICollectionView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        navigationItem.title = listing.title
        self.amenitiesCollection!.backgroundColor = UIColor.gray
        print(listing.amenities.count)//printed 4

    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
        print(listing.amenities.count)
        return listing.amenities.count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let identifier = "UICollectionViewCell"
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath)
        return cell
    }
}
</code>```

答:
Make sure you have linked the CollectionView delegate and datasource to your view controller.

In viewDidLoad() add:

```<code>    self.amenitiesCollection.delegate = self
    self.amenitiesCollection.dataSource = self
</code>```

==================================

EDIT:

If you have already linked the delegate and dataSource, try reloading the collection view in viewDidAppear(_:)

```<code>override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    self.amenitiesCollection.reloadData()
}
</code>```

Title: Trouble added cell to UICollectionView

Body:
Trying to add a cell to my ViewController, and I'm having trouble.  I'm wondering if I have all my delegates.  Currently, I can change the color of the collection view's background, but can't add any cells.

I'm using an array of text from my Listing() object to drive the collection view cells.  On viewDidLoad the length is 4.  I envisioned using this count for the numberofItemsInSection, however, if I put the print statement there it is never printed.  Which makes me think the wrong delegate is called and the method is never hit.  Correct?

import UIKit

class ListingDetailViewController: UIViewController,
UICollectionViewDelegateFlowLayout {
    var listing = Listing()
    //    @IBOutlet var image: UIImageView!
    @IBOutlet var post: UITextView!
    @IBOutlet var price: UILabel!
    @IBOutlet var amenitiesCollection: UICollectionView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        navigationItem.title = listing.title
        self.amenitiesCollection!.backgroundColor = UIColor.gray
        print(listing.amenities.count)//printed 4

    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
        print(listing.amenities.count)
        return listing.amenities.count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let identifier = "UICollectionViewCell"
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath)
        return cell
    }
}

Body:
Make sure you have linked the CollectionView delegate and datasource to your view controller.

In viewDidLoad() add:

    self.amenitiesCollection.delegate = self
    self.amenitiesCollection.dataSource = self

==================================

EDIT:

If you have already linked the delegate and dataSource, try reloading the collection view in viewDidAppear(_:)

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    self.amenitiesCollection.reloadData()
}


问:
Force download mp3 from an url on all browers. Javascript/jQuery/reactJS
I'm working for a project where I have to implement a functionality : mp3 download. I only got the hosted file url on Amazon S3 and when I click on a button it should trigger the download.
I tried the download attribute for HTML5 but it doesn't work on mozilla, and its not possible for me.

```<code><a href="www.myurl.cloudfront.net/mymp3.mp3" download> Download </a>
</code>```

Do you guys have any solution to make it works on every browsers ? Or any other solutions..

Thanks !

Nael

答:
jQuery and React don't really work well together, at least not manipulating DOM nodes.

If you are using jQuery to do AJAX calls and React as your view layer, you could hook up an onClick handler to your tag so that when the user clicks, you get an AJAX request to wherever you want:

```<code>class YourComponent extends Component {
  constructor(props) {
    super(props);
    this.handleClick = this.handleClick.bind(this)
  }
  handleClick(evt) {
    const { currentTarget } = evt;
    // currentTarget holds information of where you clicked, you can get your url from here
    $.ajax({
      //Your ajax call here
    }).then(data => //Handle your data, setState, etc.)
  }
  render() {
    <div>
      //Everything else
      <a onClick={this.handleClick} url='...'> Download</a>
    </div>
  }
};
</code>```

Body:
I'm working for a project where I have to implement a functionality : mp3 download. I only got the hosted file url on Amazon S3 and when I click on a button it should trigger the download.
I tried the download attribute for HTML5 but it doesn't work on mozilla, and its not possible for me.

 Download

Do you guys have any solution to make it works on every browsers ? Or any other solutions..

Thanks !

Nael

Body:
jQuery and React don't really work well together, at least not manipulating DOM nodes.

If you are using jQuery to do AJAX calls and React as your view layer, you could hook up an onClick handler to your tag so that when the user clicks, you get an AJAX request to wherever you want:

class YourComponent extends Component {
  constructor(props) {
    super(props);
    this.handleClick = this.handleClick.bind(this)
  }
  handleClick(evt) {
    const { currentTarget } = evt;
    // currentTarget holds information of where you clicked, you can get your url from here
    $.ajax({
      //Your ajax call here
    }).then(data => //Handle your data, setState, etc.)
  }
  render() {
    <div>
      //Everything else
      <a onClick={this.handleClick} url='...'> Download</a>
    </div>
  }
};


问:
How to catch number into InnerException C#
How is possible catch number in InnerException ?
I want sort my error exception by this number. I am loking for something like

```<code>catch (Exception e) when (e.Number == 1000)
{
    throw new ApplicationException("IP of database is wrong);
}
</code>```

(attached picLinks for better imagine)
https://ibb.co/dgnBav

EDIT

In general I want sort expections by some specific number of error exception so if you know how can I get this number it will good solution

答:
The "connection request timed out" error message looks like it's used by Oracle's .NET client library: Oracle.DataAccess.Client.OracleException.

We can use the as operator to safely check the Number property:

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

...

catch( Exception ex ) when ( (ex.InnerException as OracleException)?.Number == 1000 )
{
    // stuff
}
</code>```

This can be made more readable with a static helper function and the is-expression introduced in C# 7.0:

```<code>private static Boolean CheckOracleException(Exception ex, Int32 oracleErrorNumber)
{
    if( ex.InnerException is OracleException oEx )
    {
        return oEx.Number == oracleErrorNumber;
    }
    else
    {
        return false;
    }
}
</code>```

Used like so:

```<code>catch( Exception ex ) when ( CheckOracleException( ex, 1000 ) )
{
    OracleException oEx = (OracleException )ex.InnerException;

    // do stuff
}
</code>```

Body:
How is possible catch number in InnerException ?
I want sort my error exception by this number. I am loking for something like

catch (Exception e) when (e.Number == 1000)
{
    throw new ApplicationException("IP of database is wrong);
}

(attached picLinks for better imagine)
https://ibb.co/dgnBav

EDIT

In general I want sort expections by some specific number of error exception so if you know how can I get this number it will good solution

Body:
The "connection request timed out" error message looks like it's used by Oracle's .NET client library: Oracle.DataAccess.Client.OracleException.

We can use the as operator to safely check the Number property:

using Oracle.DataAccess.Client;

...

catch( Exception ex ) when ( (ex.InnerException as OracleException)?.Number == 1000 )
{
    // stuff
}

This can be made more readable with a static helper function and the is-expression introduced in C# 7.0:

private static Boolean CheckOracleException(Exception ex, Int32 oracleErrorNumber)
{
    if( ex.InnerException is OracleException oEx )
    {
        return oEx.Number == oracleErrorNumber;
    }
    else
    {
        return false;
    }
}

Used like so:

catch( Exception ex ) when ( CheckOracleException( ex, 1000 ) )
{
    OracleException oEx = (OracleException )ex.InnerException;

    // do stuff
}


问:
Asp.NetCore bringing table into existing DbContext
I have successfully created a DbContext with tables in asp.netcore.

However, I have realized there are a few more tables that I need to add.  I know that .edmx files and updating the database model are no longer available in .netcore and was wondering if it is possible to automatically generate these tables into classes if the dbcontext has already been created.

答: you need to learn the Entity Framework core migration using CLI/Package Console, it will create migration snapshot classes files and you need to examine the apply migration, you can refer Migrations - EF Core with ASP.NET Core </p>

ContentLicense: CC BY-SA 4.0


问:
C# base class/Interface with a generic method that accepts the derived class as a parameter
I would like to have a method defined on the base class (and in an interface) that accepts a derived class as its parameter.

i.e.

```<code>abstract class Base : IBase
{
    public void CloneMeToProvidedEntity(??? destination) {};
}

public class Derived : Base
{
     public override void CloneMeToProvidedEntity(Derived destination)
     {
         blah blah ....
     }
}
</code>```

I would be eternally grateful if someone can tell me what the Interface would look like and how to do this... or if possible

With Anticipation

Lance

答:
You can use a generic class where the generic type have to be of type IBase :

```<code>public abstract class Base<T> : IBase where T : IBase
{
    public virtual void CloneMeToProvidedEntity(T destination) { }
}

public class Derived : Base<Derived>
{
    public override void CloneMeToProvidedEntity(Derived destination)
    {
        // blah blah ....
    }
}
</code>```

Body:
I would like to have a method defined on the base class (and in an interface) that accepts a derived class as its parameter.

i.e.

abstract class Base : IBase
{
    public void CloneMeToProvidedEntity(??? destination) {};
}

public class Derived : Base
{
     public override void CloneMeToProvidedEntity(Derived destination)
     {
         blah blah ....
     }
}

I would be eternally grateful if someone can tell me what the Interface would look like and how to do this... or if possible

With Anticipation

Lance

Body:
You can use a generic class where the generic type have to be of type IBase :

public abstract class Base<T> : IBase where T : IBase
{
    public virtual void CloneMeToProvidedEntity(T destination) { }
}

public class Derived : Base<Derived>
{
    public override void CloneMeToProvidedEntity(Derived destination)
    {
        // blah blah ....
    }
}


问:
Community edition UML tool
Can anyone suggest me a free or community edition UML tool for C++. Any UML tool is fine but I need something that can generate class templates for c++. Why I need to generate class codes is because, if in future if I make some changes to my Class diagram it should easily reflect in my code. </p>

答: If you are using Linux or OSX then Umbrello is very well featured and includes code generation.</p>

Title: Community edition UML tool


问:
AngularJS combining objects in array on properties
I have a large array of objects (1500+) and the objects match on one of the properties. So the overall number of objects could be reduced e.g. for better performance in ng-repeat.
I'm kind of new to AngularJS and JS itself, so help is much appreciated!

my Array of Objects (simplified)

```<code>myArray = [
    {
        "role": "user111",
        "operation": "create",
        "concept": "folder"
    },
    {
        "role": "user111",
        "operation": "create",
        "concept": "task"
    },
    {
        "role": "user111",
        "operation": "delete",
        "concept": "task"
    },
    {
        "role": "user222",
        "operation": "create",
        "concept": "folder"
    },
    {
        "role": "user222",
        "operation": "create",
        "concept": "task"
    },
    {
        "role": "user222",
        "operation": "delete",
        "concept": "task"
    }
]
</code>```

desired Output

```<code>dreamArray = [
    {
        "role": "user111",
        "operation": {
               "create": ["folder", "task"],
               "delete": ["task"]
                      }
    },
    {
        "role": "user222",
        "operation": {
                   "create": ["folder", "task"],
                   "delete": ["task"]
                      }
    }
]
</code>```

答:
You could use a hash table and store the reference to the groups.

var array = [{ role: "user111", operation: "create", concept: "folder" }, { role: "user111", operation: "create", concept: "task" }, { role: "user111", operation: "delete", concept: "task" }, { role: "user222", operation: "create", concept: "folder" }, { role: "user222", operation: "create", concept: "task" }, { role: "user222", operation: "delete", concept: "task" }],
    grouped = array.reduce(function (hash) {
        return function (r, o) {
            if (!hash[o.role]) {
                hash[o.role] = {};
                r.push({ role: o.role, operation: hash[o.role]});
            }
            hash[o.role][o.operation] = hash[o.role][o.operation] || [];
            hash[o.role][o.operation].push(o.concept);
            return r;
        };
    }(Object.create(null)), []);

console.log(grouped);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
I have a large array of objects (1500+) and the objects match on one of the properties. So the overall number of objects could be reduced e.g. for better performance in ng-repeat.
I'm kind of new to AngularJS and JS itself, so help is much appreciated!

my Array of Objects (simplified)

myArray = [
    {
        "role": "user111",
        "operation": "create",
        "concept": "folder"
    },
    {
        "role": "user111",
        "operation": "create",
        "concept": "task"
    },
    {
        "role": "user111",
        "operation": "delete",
        "concept": "task"
    },
    {
        "role": "user222",
        "operation": "create",
        "concept": "folder"
    },
    {
        "role": "user222",
        "operation": "create",
        "concept": "task"
    },
    {
        "role": "user222",
        "operation": "delete",
        "concept": "task"
    }
]

desired Output

dreamArray = [
    {
        "role": "user111",
        "operation": {
               "create": ["folder", "task"],
               "delete": ["task"]
                      }
    },
    {
        "role": "user222",
        "operation": {
                   "create": ["folder", "task"],
                   "delete": ["task"]
                      }
    }
]

Body:
You could use a hash table and store the reference to the groups.

var array = [{ role: "user111", operation: "create", concept: "folder" }, { role: "user111", operation: "create", concept: "task" }, { role: "user111", operation: "delete", concept: "task" }, { role: "user222", operation: "create", concept: "folder" }, { role: "user222", operation: "create", concept: "task" }, { role: "user222", operation: "delete", concept: "task" }],
    grouped = array.reduce(function (hash) {
        return function (r, o) {
            if (!hash[o.role]) {
                hash[o.role] = {};
                r.push({ role: o.role, operation: hash[o.role]});
            }
            hash[o.role][o.operation] = hash[o.role][o.operation] || [];
            hash[o.role][o.operation].push(o.concept);
            return r;
        };
    }(Object.create(null)), []);

console.log(grouped);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
How to get currently logged in auth state/user from angularfire2
I have an ionic2 app and am using Firebase and angularFire2.  I'd like to get the current authentication state and current auth object/user from firebase using angularFire2.

Here's what's working so far - I can authenticate the user and subscribe to the FirebaseAuthState to get the facebook user object.

```<code>  constructor(platform: Platform, private auth: FirebaseAuth) {

    auth.subscribe((user: FirebaseAuthState) => {
      if (user) {
        // I could store user in localstorage, but I'd like to see an All Firebase solution
        this.rootPage = TabsPage;
      } else {
        this.rootPage = LoginPage;
      }
    });
</code>```

Now I can just set localstorage here and cache my user object to remember auth state.  However, I am curious to see how I can use Firebase only without me implementing my own custom local storage key.  I see that Firebase stores a localStorage key of it's own so knows that its logged in.

How can I get the auth object from code?  Additionally, I tried the listed example in the AngularFire2 documentation to render the auth state in the template - but that gives me an error.

```<code>import {FirebaseAuth} from 'angularfire2';
@Component({
  selector: 'auth-status',
  template: `
    <div *ng-if="auth | async">You are logged in</div>
    <div *ng-if="!(auth | async)">Please log in</div>
  `
})
class App {
  constructor (@Inject(FirebaseAuth) public auth: FirebaseAuth) {}
}
</code>```

答:
Import: import { AngularFireAuth } from 'angularfire2/auth';

Inject: constructor(public afAuth: AngularFireAuth) { }

Check:

```<code>this.afAuth.authState.subscribe(res => {
  if (res && res.uid) {
    console.log('user is logged in');
  } else {
    console.log('user not logged in');
  }
});
</code>```

Body:
I have an ionic2 app and am using Firebase and angularFire2.  I'd like to get the current authentication state and current auth object/user from firebase using angularFire2.

Here's what's working so far - I can authenticate the user and subscribe to the FirebaseAuthState to get the facebook user object.

  constructor(platform: Platform, private auth: FirebaseAuth) {

    auth.subscribe((user: FirebaseAuthState) => {
      if (user) {
        // I could store user in localstorage, but I'd like to see an All Firebase solution
        this.rootPage = TabsPage;
      } else {
        this.rootPage = LoginPage;
      }
    });

Now I can just set localstorage here and cache my user object to remember auth state.  However, I am curious to see how I can use Firebase only without me implementing my own custom local storage key.  I see that Firebase stores a localStorage key of it's own so knows that its logged in.

How can I get the auth object from code?  Additionally, I tried the listed example in the AngularFire2 documentation to render the auth state in the template - but that gives me an error.

import {FirebaseAuth} from 'angularfire2';
@Component({
  selector: 'auth-status',
  template: `

You are logged in

Please log in

  `
})
class App {
  constructor (@Inject(FirebaseAuth) public auth: FirebaseAuth) {}
}

Body:
Import: import { AngularFireAuth } from 'angularfire2/auth';

Inject: constructor(public afAuth: AngularFireAuth) { }

Check:

this.afAuth.authState.subscribe(res => {
  if (res && res.uid) {
    console.log('user is logged in');
  } else {
    console.log('user not logged in');
  }
});


问:
Java: How to set a socket timeout with a "try with resources"
I want to set a socket connection timeout. I know that I can set it using the connect method but this is my code:</p>

```<code>try(Socket socket = new Socket(InetAddress.getByName(ip), port);
    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
    PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8")), true)){
</code>```

答:
```<code>try(Socket socket = new Socket(InetAddress.getByName(ip), port)) {
    socket.connect(adress, timeout);
} catch (Throwable t) {
    handleException(t);
}
</code>```

Body:
I want to set a socket connection timeout. I know that I can set it using the connect method but this is my code:

try(Socket socket = new Socket(InetAddress.getByName(ip), port);
    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
    PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8")), true)){


问:
Accessing MySQL from PHP and another process at the same time
I'm writing a program that runs (24/7) on a Linux server and adds entries to a MySQL database.
The contents of the database are presented on a web interface with PHP and the user should be able to delete entries using the web interface.
Is it possible to access the database from multiple processes at the same time?</p>

答:
Yes and there will not be any problems while trying to delete records in the presence of that automated program which runs 24/7 if you are using the InnoDb engine. This is because transactions happen one at a time, one starts after another has finished and the database is consistent everytime.

This answer How to implement the ACID model for a database has many relevant points.

Read about the ACID Properties of a database. A Mysql database with InnoDb engine will take care of all these things for you and you need not worry about that.


问:
AngularJS and contentEditable two way binding doesn't work as expected
Why in the following example the initial rendered value is {{ person.name }} rather than David? How would you fix this?

Live example here

HTML:

```<code><body ng-controller="MyCtrl">
  <div contenteditable="true" ng-model="person.name">{{ person.name }}</div>
  <pre ng-bind="person.name">```

```

<p>JS:</p>

```app.controller('MyCtrl', function($scope) {
  $scope.person = {name: 'David'};
});

app.directive('contenteditable', function() {
  return {
    require: 'ngModel',
    link: function(scope, element, attrs, ctrl) {
      // view -> model
      element.bind('blur', function() {
        scope.$apply(function() {
          ctrl.$setViewValue(element.html());
        });
      });

      // model -> view
      ctrl.$render = function() {
        element.html(ctrl.$viewValue);
      };

      // load init value from DOM
      ctrl.$setViewValue(element.html());
    }
  };
});
```

答:
You may run into issues using @Vanaun's code if a scope.$apply is already in progress. In this case I use $timeout instead which resolves the issue:

Html:

```<code><!doctype html>
<html ng-app="customControl">
  <head>
    <script src="http://code.angularjs.org/1.2.0-rc.2/angular.min.js"></script>
    <script src="script.js"></script>
  </head>
  <body>
    <form name="myForm">
     <div contenteditable
          name="myWidget" ng-model="userContent"
          strip-br="true"
          required>Change me!</div>
      <span ng-show="myForm.myWidget.$error.required">Required!</span>
     <hr>
     <textarea ng-model="userContent"></textarea>
    </form>
  </body>
</html>
</code>```

JavaScript:

```<code>angular.module('customControl', []).
  directive('contenteditable', function($timeout) {
    return {
      restrict: 'A', // only activate on element attribute
      require: '?ngModel', // get a hold of NgModelController
      link: function(scope, element, attrs, ngModel) {
        if(!ngModel) return; // do nothing if no ng-model

        // Specify how UI should be updated
        ngModel.$render = function() {
          element.html(ngModel.$viewValue || '');
        };

        // Listen for change events to enable binding
        element.on('blur keyup change', function() {
          $timeout(read);
        });
        read(); // initialize

        // Write data to the model
        function read() {
          var html = element.html();
          // When we clear the content editable the browser leaves a <br> behind
          // If strip-br attribute is provided then we strip this out
          if( attrs.stripBr && html == '<br>' ) {
            html = '';
          }
          ngModel.$setViewValue(html);
        }
      }
    };
  });
</code>```

Working Example: Plunkr

Body:
Why in the following example the initial rendered value is {{ person.name }} rather than David? How would you fix this?

Live example here

HTML:

{{ person.name }}

JS:

app.controller('MyCtrl', function($scope) {
  $scope.person = {name: 'David'};
});

app.directive('contenteditable', function() {
  return {
    require: 'ngModel',
    link: function(scope, element, attrs, ctrl) {
      // view -> model
      element.bind('blur', function() {
        scope.$apply(function() {
          ctrl.$setViewValue(element.html());
        });
      });

      // model -> view
      ctrl.$render = function() {
        element.html(ctrl.$viewValue);
      };

      // load init value from DOM
      ctrl.$setViewValue(element.html());
    }
  };
});

Body:
You may run into issues using @Vanaun's code if a scope.$apply is already in progress. In this case I use $timeout instead which resolves the issue:

Html:

<!doctype html>
<html ng-app="customControl">
  <head>
    <script src="http://code.angularjs.org/1.2.0-rc.2/angular.min.js"></script>
    <script src="script.js"></script>
  </head>
  <body>
    <form name="myForm">
     <div contenteditable
          name="myWidget" ng-model="userContent"
          strip-br="true"
          required>Change me!</div>
      <span ng-show="myForm.myWidget.$error.required">Required!</span>
     <hr>
     <textarea ng-model="userContent"></textarea>
    </form>
  </body>
</html>

JavaScript:

angular.module('customControl', []).
  directive('contenteditable', function($timeout) {
    return {
      restrict: 'A', // only activate on element attribute
      require: '?ngModel', // get a hold of NgModelController
      link: function(scope, element, attrs, ngModel) {
        if(!ngModel) return; // do nothing if no ng-model

        // Specify how UI should be updated
        ngModel.$render = function() {
          element.html(ngModel.$viewValue || '');
        };

        // Listen for change events to enable binding
        element.on('blur keyup change', function() {
          $timeout(read);
        });
        read(); // initialize

        // Write data to the model
        function read() {
          var html = element.html();
          // When we clear the content editable the browser leaves a <br> behind
          // If strip-br attribute is provided then we strip this out
          if( attrs.stripBr && html == '<br>' ) {
            html = '';
          }
          ngModel.$setViewValue(html);
        }
      }
    };
  });

Working Example: Plunkr


问:
Sorting collection 2 times
So I want to sort a collection (that's ok for me) but if in this sort result 2 values are equal, I want to compare two other values to determine what goes first.

Ex: I have 30 teams, they all have points, but some teams can have the same number of points. If so, I want to check the victories each team has and put the team with most victories in front of the one with the less.

rankings = $team_stats->sortByDesc(function($product) {
     return ($product['nhl_season_w'] * 2) + $product['nhl_season_otl']
});

So yeah! That sorts the team's points, now I want to sort the equalities by victories.

Thanks for the help!

EDIT SOLVED:

I use $key + 1 to make sure my team ID's stays the same so it's easier to use to get anything else from the team ranking :)

答:
Create a multi dimension array, with points being the the first key and victory being the second key, php will automatically sort them key wise.</p>

```<code><?php
//each array with (Teams, Points, Wins)
$rank[] = array('Team' => "A", 'Points' => 24, 'Wins' => 11);
$rank[] = array('Team' => "B", 'Points' => 26, 'Wins' => 11);
$rank[] = array('Team' => "C", 'Points' => 25, 'Wins' => 10);
$rank[] = array('Team' => "D", 'Points' => 24, 'Wins' => 12);
$rank[] = array('Team' => "E", 'Points' => 25, 'Wins' => 11);
$rank[] = array('Team' => "F", 'Points' => 27, 'Wins' => 13);

foreach ($rank as $key => $row) {
    $points[$key]  = $row['Points'];
    $wins[$key] = $row['Wins'];
}

array_multisort($points, SORT_DESC, $wins, SORT_DESC, $rank);

echo "<ol>";
for ($line = 0; $line < 6; $line++){
    echo "<li><b> Rank</b>";
    foreach($rank[$line] as $key => $value){
        echo "|".$key."-".$value."|";
    }
    echo "</li>";
}
echo "</ol>";
?>
</code>```

Title: Sorting collection 2 times

Body:
Create a multi dimension array, with points being the the first key and victory being the second key, php will automatically sort them key wise.

<?php
//each array with (Teams, Points, Wins)
$rank[] = array('Team' => "A", 'Points' => 24, 'Wins' => 11);
$rank[] = array('Team' => "B", 'Points' => 26, 'Wins' => 11);
$rank[] = array('Team' => "C", 'Points' => 25, 'Wins' => 10);
$rank[] = array('Team' => "D", 'Points' => 24, 'Wins' => 12);
$rank[] = array('Team' => "E", 'Points' => 25, 'Wins' => 11);
$rank[] = array('Team' => "F", 'Points' => 27, 'Wins' => 13);

foreach ($rank as $key => $row) {
    $points[$key]  = $row['Points'];
    $wins[$key] = $row['Wins'];
}

array_multisort($points, SORT_DESC, $wins, SORT_DESC, $rank);

echo "<ol>";
for ($line = 0; $line < 6; $line++){
    echo "<li><b> Rank</b>";
    foreach($rank[$line] as $key => $value){
        echo "|".$key."-".$value."|";
    }
    echo "</li>";
}
echo "</ol>";
?>


问:
site subdirectory acts as root dir? Should I redirect 301 permanent?
I have the following problem - my site is located one folder below the /www folder on my hosting account, let's say its /www/shop. All the visitors that come to the main domain are then redirected by .htaccess file in the /www folder which takes them to the subfolder.

Should I make this redirect 301 Permanent, so that search engines could index my site better?
Here's the simple .htaccess that I use for the purpose:

```<code>RewriteEngine On
RewriteRule ^$ /shop [L]
</code>```

答: As long as it's really permanent, yes.</p>

Body:
I have the following problem - my site is located one folder below the /www folder on my hosting account, let's say its /www/shop. All the visitors that come to the main domain are then redirected by .htaccess file in the /www folder which takes them to the subfolder.

Should I make this redirect 301 Permanent, so that search engines could index my site better?
Here's the simple .htaccess that I use for the purpose:

RewriteEngine On
RewriteRule ^$ /shop [L]

Body: As long as it's really permanent, yes.


答:
You can do this using forEach() loop and thisArg parameter.

var myArray = [{"role":"user111","operation":"create","concept":"folder"},{"role":"user111","operation":"create","concept":"task"},{"role":"user111","operation":"delete","concept":"task"},{"role":"user222","operation":"create","concept":"folder"},{"role":"user222","operation":"create","concept":"task"},{"role":"user222","operation":"delete","concept":"task"}]

var result = [];
myArray.forEach(function(e) {
  if(!this[e.role]) {
   this[e.role] = {role: e.role, operation: {[e.operation]: [e.concept]}}
    result.push(this[e.role]);
  } else {
    var op = this[e.role].operation[e.operation]
    if(op) op.push(e.concept)
    else this[e.role].operation[e.operation] = [e.concept]
  }
}, Object.create(null))

console.log(result)```

Title: AngularJS combining objects in array on properties