问:
How to display the recent added data to the top of the recycler view
I'm creating an app where i am storing data to firebase and retriving it to my reclycler view and but   issue is, i want to display the most recent added data to the top of the recycler view. I am trying to get the latest data and I had done all possibly Solution still I am not getting.

please see the following code....

here is my Mainclass:

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

ProgressDialog progressDialog;
List<DataClass> list = new ArrayList<>();
RecyclerView recyclerView;
RecyclerView.Adapter adapter;

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

    recyclerView = findViewById(R.id.erecyclerView);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(ShowDetails.this));
    progressDialog = new ProgressDialog(ShowDetails.this);
    progressDialog.setMessage("Loading Data from Firebase Database");
    progressDialog.show();

    FirebaseOptions options = new FirebaseOptions.Builder()
            .setApplicationId("1:102738125513:android:3042292623f0448c") // Required for Analytics.
            .setApiKey("AIzaSyAZbWBpPzjAkrg23riK9kwk2T0tDf47dko") // Required for Auth.
            .setDatabaseUrl("https://citycare-fed31.firebaseio.com/") // Required for RTDB.
            .build();
    FirebaseApp.initializeApp(this);
            // Retrieve my other app.
            FirebaseApp app = FirebaseApp.getInstance("[DEFAULT]");
    // Get the database for the other app.
    FirebaseDatabase secondaryDatabase = FirebaseDatabase.getInstance(app);
    DatabaseReference data = secondaryDatabase.getInstance().getReference("Electricity");
    data.addValueEventListener(new ValueEventListener() {

        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            for (DataSnapshot ds : dataSnapshot.getChildren()) {

                for (DataSnapshot dSnapshot : ds.getChildren()) {

                    DataClass DataClass = dSnapshot.getValue(DataClass.class);

                    Log.d("Show", DataClass.getEname() == null ? "" : DataClass.getEname());
                    list.add(DataClass);

                }
                adapter = new ShowDetails.DataAdapter(ShowDetails.this, list);
                recyclerView.setAdapter(adapter);
                adapter.notifyDataSetChanged();
                progressDialog.dismiss();
            }
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {
            progressDialog.dismiss();
        }
    });

}
</code>```

and this is my Adapter class:

```<code> private class DataAdapter extends RecyclerView.Adapter<ShowDetails.DataAdapter.ViewHolder>  {

    Context context;
    List<DataClass> listData;

    public DataAdapter(Context context, List<DataClass> list) {

        this.context = context;
        this.listData = list;
    }

    @Override
    public ShowDetails.DataAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.show_items, parent, false);
        ShowDetails.DataAdapter.ViewHolder viewHolder = new ShowDetails.DataAdapter.ViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(ShowDetails.DataAdapter.ViewHolder holder, int position) {

        final DataClass AllDetails = listData.get(position);
        holder.NameTextView.setText(AllDetails.getEname());
        holder.EmailTextView.setText(AllDetails.getEemail());
        holder.DateTextView.setText(AllDetails.getEdate());
        holder.LocationTextView.setText(AllDetails.getElocation());
        holder.TypeTextView.setText(AllDetails.getEtype());
        Picasso.with(context).load(AllDetails.getImgurl()).resize(120, 60).into(holder.ImageTextView);

        holder.ImageTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(ShowDetails.this, ShowImage.class);
                i.putExtra("img", AllDetails.getImgurl());
                startActivity(i);
            }
        });
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(ShowDetails.this, Email_Activity.class);
                i.putExtra("txt", AllDetails.getEemail());
                startActivity(i);
            }
        });
    }

    @Override
    public int getItemCount() {
        return listData.size();
    }

    class ViewHolder extends RecyclerView.ViewHolder {

        public TextView NameTextView;
        public TextView EmailTextView;
        public TextView DateTextView;
        public TextView LocationTextView;
        public TextView TypeTextView;
        public ImageView ImageTextView;
        public ViewHolder(View itemView) {

            super(itemView);
            NameTextView = itemView.findViewById(R.id.ShowNameTextView);
            EmailTextView = itemView.findViewById(R.id.ShowEmailTextView);
            DateTextView = itemView.findViewById(R.id.ShowDateTextView);
            LocationTextView = itemView.findViewById(R.id.ShowLocationTextView);
            TypeTextView = itemView.findViewById(R.id.ShowTypeTextView);
            ImageTextView = itemView.findViewById(R.id.ShowImageView);
        }
    }
}
</code>```

here is my database

firebase data structure

here is my API response after removing extra for loop
API response

please help me out i am new to programming

答:
NOTE: If your recycler view is displaying the data in reverse order..you can use the following method.

this will display in order if above condition meets

in your layout manager of your recycler view

```<code>LinearLayoutManager lm = new LinearLayoutManager(mActivity, RecyclerView.VERTICAL, true);
recyclerView.setLayoutManager(lm);
</code>```

this should solve your problem

Body:
I'm creating an app where i am storing data to firebase and retriving it to my reclycler view and but   issue is, i want to display the most recent added data to the top of the recycler view. I am trying to get the latest data and I had done all possibly Solution still I am not getting.

please see the following code....

here is my Mainclass:

public class ShowDetails extends AppCompatActivity {

ProgressDialog progressDialog;
List<DataClass> list = new ArrayList<>();
RecyclerView recyclerView;
RecyclerView.Adapter adapter;

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

    recyclerView = findViewById(R.id.erecyclerView);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(ShowDetails.this));
    progressDialog = new ProgressDialog(ShowDetails.this);
    progressDialog.setMessage("Loading Data from Firebase Database");
    progressDialog.show();

    FirebaseOptions options = new FirebaseOptions.Builder()
            .setApplicationId("1:102738125513:android:3042292623f0448c") // Required for Analytics.
            .setApiKey("AIzaSyAZbWBpPzjAkrg23riK9kwk2T0tDf47dko") // Required for Auth.
            .setDatabaseUrl("https://citycare-fed31.firebaseio.com/") // Required for RTDB.
            .build();
    FirebaseApp.initializeApp(this);
            // Retrieve my other app.
            FirebaseApp app = FirebaseApp.getInstance("[DEFAULT]");
    // Get the database for the other app.
    FirebaseDatabase secondaryDatabase = FirebaseDatabase.getInstance(app);
    DatabaseReference data = secondaryDatabase.getInstance().getReference("Electricity");
    data.addValueEventListener(new ValueEventListener() {

        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            for (DataSnapshot ds : dataSnapshot.getChildren()) {

                for (DataSnapshot dSnapshot : ds.getChildren()) {

                    DataClass DataClass = dSnapshot.getValue(DataClass.class);

                    Log.d("Show", DataClass.getEname() == null ? "" : DataClass.getEname());
                    list.add(DataClass);

                }
                adapter = new ShowDetails.DataAdapter(ShowDetails.this, list);
                recyclerView.setAdapter(adapter);
                adapter.notifyDataSetChanged();
                progressDialog.dismiss();
            }
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {
            progressDialog.dismiss();
        }
    });

}

and this is my Adapter class:

 private class DataAdapter extends RecyclerView.Adapter<ShowDetails.DataAdapter.ViewHolder>  {

    Context context;
    List<DataClass> listData;

    public DataAdapter(Context context, List<DataClass> list) {

        this.context = context;
        this.listData = list;
    }

    @Override
    public ShowDetails.DataAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.show_items, parent, false);
        ShowDetails.DataAdapter.ViewHolder viewHolder = new ShowDetails.DataAdapter.ViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(ShowDetails.DataAdapter.ViewHolder holder, int position) {

        final DataClass AllDetails = listData.get(position);
        holder.NameTextView.setText(AllDetails.getEname());
        holder.EmailTextView.setText(AllDetails.getEemail());
        holder.DateTextView.setText(AllDetails.getEdate());
        holder.LocationTextView.setText(AllDetails.getElocation());
        holder.TypeTextView.setText(AllDetails.getEtype());
        Picasso.with(context).load(AllDetails.getImgurl()).resize(120, 60).into(holder.ImageTextView);

        holder.ImageTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(ShowDetails.this, ShowImage.class);
                i.putExtra("img", AllDetails.getImgurl());
                startActivity(i);
            }
        });
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(ShowDetails.this, Email_Activity.class);
                i.putExtra("txt", AllDetails.getEemail());
                startActivity(i);
            }
        });
    }

    @Override
    public int getItemCount() {
        return listData.size();
    }

    class ViewHolder extends RecyclerView.ViewHolder {

        public TextView NameTextView;
        public TextView EmailTextView;
        public TextView DateTextView;
        public TextView LocationTextView;
        public TextView TypeTextView;
        public ImageView ImageTextView;
        public ViewHolder(View itemView) {

            super(itemView);
            NameTextView = itemView.findViewById(R.id.ShowNameTextView);
            EmailTextView = itemView.findViewById(R.id.ShowEmailTextView);
            DateTextView = itemView.findViewById(R.id.ShowDateTextView);
            LocationTextView = itemView.findViewById(R.id.ShowLocationTextView);
            TypeTextView = itemView.findViewById(R.id.ShowTypeTextView);
            ImageTextView = itemView.findViewById(R.id.ShowImageView);
        }
    }
}

here is my database

firebase data structure

here is my API response after removing extra for loop
API response

please help me out i am new to programming

Body:
NOTE: If your recycler view is displaying the data in reverse order..you can use the following method.

this will display in order if above condition meets

in your layout manager of your recycler view

LinearLayoutManager lm = new LinearLayoutManager(mActivity, RecyclerView.VERTICAL, true);
recyclerView.setLayoutManager(lm);

this should solve your problem


来源: stackexchange

问:
Why is github asking me username/password although I setup SSH authentication?
I have followed these instructions to set up the SSH key for github. But now when I do

```<code>> git pull
Username for 'https://github.com':
</code>```

in a repository on the local computer I have taken the public SSH key from, I am still asked for a username/password. Did I miss a step?

答:
This can also be done by editing the git config file for your project. With your favourite editor open .git/config and find the existing URL:

```<code>[remote "origin"]
    url=https://github.com/<usr>/<repo>.git
</code>```

Change to:

```<code>[remote "origin"]
    url=git@github.com:<usr>/<repo>.git
</code>```

Personally, I find this a bit easier to remember at the risk of being a little more 'internal'.

ContentLicense: CC BY-SA 3.0

Body:
I have followed these instructions to set up the SSH key for github. But now when I do

> git pull
Username for 'https://github.com':

in a repository on the local computer I have taken the public SSH key from, I am still asked for a username/password. Did I miss a step?

Body:
This can also be done by editing the git config file for your project. With your favourite editor open .git/config and find the existing URL:

[remote "origin"]
    url=https://github.com/<usr>/<repo>.git

Change to:

[remote "origin"]
    url=git@github.com:<usr>/<repo>.git

Personally, I find this a bit easier to remember at the risk of being a little more 'internal'.

ContentLicense: CC BY-SA 4.0


问:
Using java google app engine bulkloader.yaml to upload data with export_transform on __key__ changes ID/NAME coloumn from id (long) to name (string)
I think my question is similar to: BulkLoader -export_transform OR https://stackoverflow.com/questions/3220911/gae-datastore-export-transform

Basically, I'm using the bulkloader to backup and restore entities that I've created.
To test I'm using the "Game" kind and outputting it to a csv file called game.csv.

This is the process I go through:

Download the game kind to game.csv using:

appcfg.py download_data --config_file=bulkloader.yaml --kind=Game --filename=game.csv --application=MyAppId --url=http://MyAppId.appspot.com/remote_api --rps_limit=500 --bandwidth_limit=2500000 --batch_size=100

Delete all game entities. I then checked the my app's admin portal datastore viewer tab and I see that there are no more entities in my data store.

Upload the game kind using the game.csv created using (command is the same as download_data but with upload_data):

appcfg.py upload_data --config_file=bulkloader.yaml --kind=Game --filename=game.csv --application=MyAppId --url=http://MyAppId.appspot.com/remote_api --rps_limit=500 --bandwidth_limit=2500000 --batch_size=100

Run a servlet that retrieves an entity by 'name' (this is the property shown in Game.java below).

The following error occurs:

```<code>Uncaught exception from servlet
java.lang.IllegalStateException: Loaded Entity has name but com.example.app.model.Game has no String @Id
    at com.googlecode.objectify.impl.ConcreteEntityMetadata.setKey(ConcreteEntityMetadata.java:343)
    at com.googlecode.objectify.impl.ConcreteEntityMetadata.toObject(ConcreteEntityMetadata.java:210)
    at com.googlecode.objectify.impl.QueryImpl$ToObjectIterator.translate(QueryImpl.java:640)
    at com.googlecode.objectify.impl.QueryImpl$ToObjectIterator.translate(QueryImpl.java:629)
    at com.googlecode.objectify.util.TranslatingIterator.next(TranslatingIterator.java:35)
    at com.googlecode.objectify.impl.QueryImpl.list(QueryImpl.java:470)
</code>```

I suspect it has something to do with my bulkloader.yaml file not being configure correct for the __key__ property. So I've posted it below:

```<code>- import: google.appengine.ext.bulkload.transform
- import: google.appengine.ext.bulkload.bulkloader_wizard
- import: google.appengine.ext.db
- import: google.appengine.api.datastore
- import: google.appengine.api.users

transformers:

- kind: Game
  connector: csv
  connector_options:
    # TODO: Add connector options here--these are specific to each connector.
  property_map:
    - property: __key__
      external_name: key
      export_transform: transform.key_id_or_name_as_string

    - property: __scatter__
      #external_name: __scatter__
      # Type: ShortBlob Stats: 56 properties of this type in this kind.

    - property: genre
      external_name: genre
      # Type: String Stats: 6639 properties of this type in this kind.

    - property: name
      external_name: name
      # Type: String Stats: 6639 properties of this type in this kind.

    - property: releasedate
      external_name: releasedate
      # Type: Date/Time Stats: 6548 properties of this type in this kind.
      import_transform: transform.import_date_time('%Y-%m-%dT%H:%M:%S')
      export_transform: transform.export_date_time('%Y-%m-%dT%H:%M:%S')
</code>```

Prior to the deletion and upload of data, the "Game" kind (within the datastore viewer tab of the app's admin portal) shows the ID/NAME column with hyperlinks that look like ID=12345, ID=67890 ... for each entitiy row.

After the upload the datastire viewer shows the ID/NAME column with hyperlinks that look like NAME=12345, NAME=67890 ... for each entitiy row.

Possible cause?

I've actually posted my question on, https://groups.google.com/forum/?hl=en#!topic/objectify-appengine/FFuB2Onfnzc but we don't know the syntax to avoid transforming the __key__ property to string when uploading back the data.

Jeff (creator of Objectify3.0) says:

The error message says that the data in the datastore as a String name
key, but your Game entity has a numeric Long @Id.  I don't really know
the syntax for the bulk loader, but the most suspect line is this one:

```<code>export_transform: transform.key_id_or_name_as_string
</code>```

It looks like you are converting all numeric ids to strings here,
which would be your problem.  Leave them as numbers.

I've tried removing the export_transform: transform.key_id_or_name_as_string but when I do the download the csv file is empty.

Maybe a solution is to avoid using the --config_file parameter and bulkloader.yaml file and just let the bulkloader download/upload the data without any transformations?

Extra information incase it might be relevant

I'm using the objectify3.0.jar to manipulate my GAE datastore. So my Game kind looks like this:

```<code>public class Game {
    @Id private Long id; //This is my key property, auto generated by objectify
    private String name;
    private String genre;
    private Date releasedate;

    //ommitting getters and setters
}
</code>```

答:
I did some experiements and I believe I have the solution.

I actually got the idea from another stackoverflow post I asked: Using Java Google App Engine bulkloader to download entire datastore to one csv file

The fix is to avoid using the --config_file and bulkloader.yaml.

I used the following to download every kind to a single csv file:

```<code>appcfg.py download_data --filename=backup.csv --application=MyAppId --url=http://MyAppId.appspot.com/remote_api --rps_limit=500 --bandwidth_limit=2500000 --batch_size=100
</code>```

I used the following to upload the single csv file back to the datastore:

```<code>appcfg.py upload_data --filename=backup.csv --application=MyAppId --url=http://MyAppId.appspot.com/remote_api --rps_limit=500 --bandwidth_limit=2500000 --batch_size=100
</code>```

They are the same commands but just download_data and upload_data swapped around.

The idea is just to let appcfg download and upload all entities (not being kind specific) i.e. not using any export or import transformations.

Body:
I think my question is similar to: BulkLoader -export_transform OR https://stackoverflow.com/questions/3220911/gae-datastore-export-transform

Basically, I'm using the bulkloader to backup and restore entities that I've created.
To test I'm using the "Game" kind and outputting it to a csv file called game.csv.

This is the process I go through:

Download the game kind to game.csv using:

appcfg.py download_data --config_file=bulkloader.yaml --kind=Game --filename=game.csv --application=MyAppId --url=http://MyAppId.appspot.com/remote_api --rps_limit=500 --bandwidth_limit=2500000 --batch_size=100

Delete all game entities. I then checked the my app's admin portal datastore viewer tab and I see that there are no more entities in my data store.

Upload the game kind using the game.csv created using (command is the same as download_data but with upload_data):

appcfg.py upload_data --config_file=bulkloader.yaml --kind=Game --filename=game.csv --application=MyAppId --url=http://MyAppId.appspot.com/remote_api --rps_limit=500 --bandwidth_limit=2500000 --batch_size=100

Run a servlet that retrieves an entity by 'name' (this is the property shown in Game.java below).

The following error occurs:

Uncaught exception from servlet
java.lang.IllegalStateException: Loaded Entity has name but com.example.app.model.Game has no String @Id
    at com.googlecode.objectify.impl.ConcreteEntityMetadata.setKey(ConcreteEntityMetadata.java:343)
    at com.googlecode.objectify.impl.ConcreteEntityMetadata.toObject(ConcreteEntityMetadata.java:210)
    at com.googlecode.objectify.impl.QueryImpl$ToObjectIterator.translate(QueryImpl.java:640)
    at com.googlecode.objectify.impl.QueryImpl$ToObjectIterator.translate(QueryImpl.java:629)
    at com.googlecode.objectify.util.TranslatingIterator.next(TranslatingIterator.java:35)
    at com.googlecode.objectify.impl.QueryImpl.list(QueryImpl.java:470)

I suspect it has something to do with my bulkloader.yaml file not being configure correct for the __key__ property. So I've posted it below:

- import: google.appengine.ext.bulkload.transform
- import: google.appengine.ext.bulkload.bulkloader_wizard
- import: google.appengine.ext.db
- import: google.appengine.api.datastore
- import: google.appengine.api.users

transformers:

- kind: Game
  connector: csv
  connector_options:
    # TODO: Add connector options here--these are specific to each connector.
  property_map:
    - property: __key__
      external_name: key
      export_transform: transform.key_id_or_name_as_string

    - property: __scatter__
      #external_name: __scatter__
      # Type: ShortBlob Stats: 56 properties of this type in this kind.

    - property: genre
      external_name: genre
      # Type: String Stats: 6639 properties of this type in this kind.

    - property: name
      external_name: name
      # Type: String Stats: 6639 properties of this type in this kind.

    - property: releasedate
      external_name: releasedate
      # Type: Date/Time Stats: 6548 properties of this type in this kind.
      import_transform: transform.import_date_time('%Y-%m-%dT%H:%M:%S')
      export_transform: transform.export_date_time('%Y-%m-%dT%H:%M:%S')

Prior to the deletion and upload of data, the "Game" kind (within the datastore viewer tab of the app's admin portal) shows the ID/NAME column with hyperlinks that look like ID=12345, ID=67890 ... for each entitiy row.

After the upload the datastire viewer shows the ID/NAME column with hyperlinks that look like NAME=12345, NAME=67890 ... for each entitiy row.

Possible cause?

I've actually posted my question on, https://groups.google.com/forum/?hl=en#!topic/objectify-appengine/FFuB2Onfnzc but we don't know the syntax to avoid transforming the __key__ property to string when uploading back the data.

Jeff (creator of Objectify3.0) says:

The error message says that the data in the datastore as a String name
key, but your Game entity has a numeric Long @Id.  I don't really know
the syntax for the bulk loader, but the most suspect line is this one:

export_transform: transform.key_id_or_name_as_string

It looks like you are converting all numeric ids to strings here,
which would be your problem.  Leave them as numbers.

I've tried removing the export_transform: transform.key_id_or_name_as_string but when I do the download the csv file is empty.

Maybe a solution is to avoid using the --config_file parameter and bulkloader.yaml file and just let the bulkloader download/upload the data without any transformations?

Extra information incase it might be relevant

I'm using the objectify3.0.jar to manipulate my GAE datastore. So my Game kind looks like this:

public class Game {
    @Id private Long id; //This is my key property, auto generated by objectify
    private String name;
    private String genre;
    private Date releasedate;

    //ommitting getters and setters
}

Body:
I did some experiements and I believe I have the solution.

I actually got the idea from another stackoverflow post I asked: Using Java Google App Engine bulkloader to download entire datastore to one csv file

The fix is to avoid using the --config_file and bulkloader.yaml.

I used the following to download every kind to a single csv file:

appcfg.py download_data --filename=backup.csv --application=MyAppId --url=http://MyAppId.appspot.com/remote_api --rps_limit=500 --bandwidth_limit=2500000 --batch_size=100

I used the following to upload the single csv file back to the datastore:

appcfg.py upload_data --filename=backup.csv --application=MyAppId --url=http://MyAppId.appspot.com/remote_api --rps_limit=500 --bandwidth_limit=2500000 --batch_size=100

They are the same commands but just download_data and upload_data swapped around.

The idea is just to let appcfg download and upload all entities (not being kind specific) i.e. not using any export or import transformations.


问:
How to convert C# Linq to query in SQL Server?
I'm a junior developer and trying to convert the following linq statement to T-SQL:

```<code>var items = from u in DataContext.Users_SearchUsers(searchPara.UserFirstName,
                                                    searchPara.UserLastName,
                                                    searchPara.UserEmailAddress,
                                                    fetchOptions.page,
                                                    fetchOptions.rp,
                                                    fetchOptions.sortname,
                                                    fetchOptions.sortorder)
                                 .ToList()
            join a in DataContext.UserAccesses
                                 .Where(x => x.Access.AccessTypeId == 4).ToList() on u.UserID equals a.UserId into accessGroup
            select new {};
</code>```

Can one please help me ? into accessGroup ---> (very important)

答:
First of all you need to understand where your data is coming from. You are loading information from Users_SearchUsers on the one hand and UserAccesses on the other hand. The first query looks like

```<code>select <somecolumns>
from users
where <somefilters>;
</code>```

(you need to use your actual columns and criteria, but Users_SearchUsers is not specified in the question at all). I have ignored paging here for the sake of simplicity

The second query looks like this:

```<code>select *
from user_accesses
where access_type_id = 4;
</code>```

Let's join the two:

```<code>select <someoutercolumns>
from
(
select <someinnercolumns>
from users
where <somefilters>
) t1
join
(
select <someotherinnercolumns>
from user_accesses
where access_type_id = 4
) t2
on t1.user_id = t2.user_id;
</code>```

These queries are probably not the exact solutions you need, but you want the answers to improve, then improve your question.

The requirement makes sense if the LINQ query is very slow. In that case you will need to refactor it in the following manner:

```<code>select <somecolumns>
from users
join user_accesses
on users.user_id = user_accesses.user_id and user_accesses.access_type_id = 4
where <somefilters>;
</code>```

Body:
I'm a junior developer and trying to convert the following linq statement to T-SQL:

var items = from u in DataContext.Users_SearchUsers(searchPara.UserFirstName,
                                                    searchPara.UserLastName,
                                                    searchPara.UserEmailAddress,
                                                    fetchOptions.page,
                                                    fetchOptions.rp,
                                                    fetchOptions.sortname,
                                                    fetchOptions.sortorder)
                                 .ToList()
            join a in DataContext.UserAccesses
                                 .Where(x => x.Access.AccessTypeId == 4).ToList() on u.UserID equals a.UserId into accessGroup
            select new {};

Can one please help me ? into accessGroup ---> (very important)

Body:
First of all you need to understand where your data is coming from. You are loading information from Users_SearchUsers on the one hand and UserAccesses on the other hand. The first query looks like

select <somecolumns>
from users
where <somefilters>;

(you need to use your actual columns and criteria, but Users_SearchUsers is not specified in the question at all). I have ignored paging here for the sake of simplicity

The second query looks like this:

select *
from user_accesses
where access_type_id = 4;

Let's join the two:

select <someoutercolumns>
from
(
select <someinnercolumns>
from users
where <somefilters>
) t1
join
(
select <someotherinnercolumns>
from user_accesses
where access_type_id = 4
) t2
on t1.user_id = t2.user_id;

These queries are probably not the exact solutions you need, but you want the answers to improve, then improve your question.

The requirement makes sense if the LINQ query is very slow. In that case you will need to refactor it in the following manner:

select <somecolumns>
from users
join user_accesses
on users.user_id = user_accesses.user_id and user_accesses.access_type_id = 4
where <somefilters>;


问:
Dataframe Groupby to combine multiple rows, summing float-type columns
Terrible title, but Here goes.  I have a 13,000 x 91 dataframe.  26 of the columns are numeric.  The rows are individual projects, with project performance split by year.  Like this:

```<code>| Year | Control | Description   | USD_Cost | USD_Profit |
|------|---------|---------------|----------|------------|
| 1991 | A1      | A description | 1        | 2          |
| 1992 | A1      | A Description | 100      | 300        |
| 1991 | B1      | B Description | 3        | 50         |
| 1995 | C1      | C Description | 5        | 10         |
| 1990 | D1      | D Description | 2        | 1          |
| 1996 | D1      | D Description | 1        | 1          |
</code>```

Rather than recording how each project performed in each particular year, I just want to record how long each project lasted, and the overall project performance:

```<code>| Years | Control | Description   | USD_Cost | USDProfit |
|-------|---------|---------------|----------|-----------|
| 2     | A1      | A description | 101      | 302       |
| 1     | B1      | B Description | 3        | 50        |
| 1     | C1      | C Description | 5        | 10        |
| 2     | D1      | D Description | 3        | 2         |
</code>```

Control and Description aren't changed, but the numeric columns beginning with USD are summed across rows.  And there are 26 USD columns for different performance aspects. There are about 8000 unique Control Numbers but 13000 total Year-ControlNumber combos.

I know how to groupby for one element (e.g. print(dft.groupby(['Control'])['USD_Cost', 'USD_Profit'].sum() ) but when I do that, I think I am losing all the non-numeric columns.  Also, I would like to avoid typing in the names of all 26 USD columns.

Can this be done with groupby?

答:
This is a really common kind of operation, and pandas has an elegant way of doing it. To avoid a tedious task of replicating 26 summation functions, I use dictionary comprehension.

First you define a dictionary of actions by column, then you use agg function:

```<code>df = pd.DataFrame({
    "Year": [1991, 1992, 1991, 1995, 1990, 1996],
    "Control": ["A1", "A1", "B1", "C1", "D1", "D1"],
    "Description": [
        "A description",
        "A description",
        "B description",
        "C description",
        "D description",
        "D description"
    ],
    "USD_Cost": [1, 100, 3, 5, 2, 1],
    "USD_Profit": [2, 300, 50, 10, 1, 1],
})

actions = {'Year': pd.Series.nunique,
           'Description': lambda x: x.iloc[0]}
actions.update({x: sum for x in df.columns if x.startswith('USD_')})

df.groupby('Control').agg(actions).reset_index()
</code>```

And this provides

```<code>  Control  Year    Description  USD_Cost  USD_Profit
0      A1     2  A description       101         302
1      B1     1  B description         3          50
2      C1     1  C description         5          10
3      D1     2  D description         3           2
</code>```

Body:
Terrible title, but Here goes.  I have a 13,000 x 91 dataframe.  26 of the columns are numeric.  The rows are individual projects, with project performance split by year.  Like this:

| Year | Control | Description   | USD_Cost | USD_Profit |
|------|---------|---------------|----------|------------|
| 1991 | A1      | A description | 1        | 2          |
| 1992 | A1      | A Description | 100      | 300        |
| 1991 | B1      | B Description | 3        | 50         |
| 1995 | C1      | C Description | 5        | 10         |
| 1990 | D1      | D Description | 2        | 1          |
| 1996 | D1      | D Description | 1        | 1          |

Rather than recording how each project performed in each particular year, I just want to record how long each project lasted, and the overall project performance:

| Years | Control | Description   | USD_Cost | USDProfit |
|-------|---------|---------------|----------|-----------|
| 2     | A1      | A description | 101      | 302       |
| 1     | B1      | B Description | 3        | 50        |
| 1     | C1      | C Description | 5        | 10        |
| 2     | D1      | D Description | 3        | 2         |

Control and Description aren't changed, but the numeric columns beginning with USD are summed across rows.  And there are 26 USD columns for different performance aspects. There are about 8000 unique Control Numbers but 13000 total Year-ControlNumber combos.

I know how to groupby for one element (e.g. print(dft.groupby(['Control'])['USD_Cost', 'USD_Profit'].sum() ) but when I do that, I think I am losing all the non-numeric columns.  Also, I would like to avoid typing in the names of all 26 USD columns.

Can this be done with groupby?

Body:
This is a really common kind of operation, and pandas has an elegant way of doing it. To avoid a tedious task of replicating 26 summation functions, I use dictionary comprehension.

First you define a dictionary of actions by column, then you use agg function:

df = pd.DataFrame({
    "Year": [1991, 1992, 1991, 1995, 1990, 1996],
    "Control": ["A1", "A1", "B1", "C1", "D1", "D1"],
    "Description": [
        "A description",
        "A description",
        "B description",
        "C description",
        "D description",
        "D description"
    ],
    "USD_Cost": [1, 100, 3, 5, 2, 1],
    "USD_Profit": [2, 300, 50, 10, 1, 1],
})

actions = {'Year': pd.Series.nunique,
           'Description': lambda x: x.iloc[0]}
actions.update({x: sum for x in df.columns if x.startswith('USD_')})

df.groupby('Control').agg(actions).reset_index()

And this provides

  Control  Year    Description  USD_Cost  USD_Profit
0      A1     2  A description       101         302
1      B1     1  B description         3          50
2      C1     1  C description         5          10
3      D1     2  D description         3           2


问:
Hibernate click event binding with jQuery
I a code similar to the following

```<code>$(element).click(function() {
$(slider).slide();
});
</code>```

What I want to do is to deactivate the click event until the sliding finish (or more precisely the function complete) so that users don't abuse it. How can I do that?

答:
http://jsfiddle.net/samccone/8u2KP/

The trick is to check if

if (!$('#slider').is(':animated')) {//CODE HERE}

Body:
I a code similar to the following

$(element).click(function() {
$(slider).slide();
});

What I want to do is to deactivate the click event until the sliding finish (or more precisely the function complete) so that users don't abuse it. How can I do that?


问:
'Overload resolution ambiguity' with and without 'suspend' lambda in functions
Look at this example:

```<code>fun f(block: suspend () -> Unit) {
    println("with suspend")
}

fun f(block: () -> Unit) {
    println("without suspend")
}

fun main() {
    f(suspend {
    })

    // This call cause compilation error:
    // Error:(16, 5) Kotlin: Overload resolution ambiguity:
    // public fun f(block: () -> Unit): Unit defined in root package in file Main.kt
    // public fun f(block: suspend () -> Unit): Unit defined in root package in file Main.kt
    //
    // f({
    // })

    // This call cause compilation error:
    //
    // Error:(25, 5) Kotlin: Overload resolution ambiguity:
    // public fun f(block: () -> Unit): Unit defined in root package in file Main.kt
    // public fun f(block: suspend () -> Unit): Unit defined in root package in file Main.kt
    //
    // f {
    // }
}
</code>```

Here is declared two functions (one with suspend keyword in lambda and one without).

Questions:

1) How to call first or second function? As you can see I can call function with suspend but can't call function without suspend keyword.

2) It is possible to rewrite f(suspend {}) with trailing lambda (i.e. use something like f suspend {})?

答:
1) You can call the second function with some workarounds. For example,

```<code>val foo = {}
f(foo)
</code>```

or

```<code>f({}.also{})
</code>```

or even shorter:

```<code>f({}!!)
</code>```

will invoke the function with non-suspend parameter. In these cases you declare the lambda out of the context of being a function parameter, so it's not suspendable by default.

2) Trailing lambda syntax does not support explicit suspend modifier, so you have to use parentheses to declare that your lambda is suspendable.

Body:
Look at this example:

fun f(block: suspend () -> Unit) {
    println("with suspend")
}

fun f(block: () -> Unit) {
    println("without suspend")
}

fun main() {
    f(suspend {
    })

    // This call cause compilation error:
    // Error:(16, 5) Kotlin: Overload resolution ambiguity:
    // public fun f(block: () -> Unit): Unit defined in root package in file Main.kt
    // public fun f(block: suspend () -> Unit): Unit defined in root package in file Main.kt
    //
    // f({
    // })

    // This call cause compilation error:
    //
    // Error:(25, 5) Kotlin: Overload resolution ambiguity:
    // public fun f(block: () -> Unit): Unit defined in root package in file Main.kt
    // public fun f(block: suspend () -> Unit): Unit defined in root package in file Main.kt
    //
    // f {
    // }
}

Here is declared two functions (one with suspend keyword in lambda and one without).

Questions:

1) How to call first or second function? As you can see I can call function with suspend but can't call function without suspend keyword.

2) It is possible to rewrite f(suspend {}) with trailing lambda (i.e. use something like f suspend {})?

Body:
1) You can call the second function with some workarounds. For example,

val foo = {}
f(foo)

or

f({}.also{})

or even shorter:

f({}!!)

will invoke the function with non-suspend parameter. In these cases you declare the lambda out of the context of being a function parameter, so it's not suspendable by default.

2) Trailing lambda syntax does not support explicit suspend modifier, so you have to use parentheses to declare that your lambda is suspendable.


问:
Use mutate in purrr workflow
I got the following datasets:

```<code>dflist <- list(mtcars, mtcars)

dflist[[1]] %>%
  mutate(cyl2 = cyl * 2)
</code>```

This works!

```<code>dflist %>%
  map(.x, ~.x$cyl2 = .x$cyl * 2)

Error: unexpected '=' in:
"dflist %>%
  map(.x, ~x$cyl2 ="
</code>```

This results in an error. I tried other options, but the function does not except the = sign. What is wrong there?

Title: Use mutate in purrr workflow

Body:
I got the following datasets:

dflist <- list(mtcars, mtcars)

dflist[[1]] %>%
  mutate(cyl2 = cyl * 2)

This works!

dflist %>%
  map(.x, ~.x$cyl2 = .x$cyl * 2)

Error: unexpected '=' in:
"dflist %>%
  map(.x, ~x$cyl2 ="

This results in an error. I tried other options, but the function does not except the = sign. What is wrong there?

Body:
Try :

library(dplyr)
library(purrr)

dflist %>% map(~.x %>% mutate(cyl2 = cyl * 2))

#[[1]]
#    mpg cyl  disp  hp drat    wt  qsec vs am gear carb cyl2
#1  21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4   12
#2  21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4   12
#3  22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1    8
#4  21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1   12
#5  18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2   16
#....

#[[2]]
#    mpg cyl  disp  hp drat    wt  qsec vs am gear carb cyl2
#1  21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4   12
#2  21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4   12
#3  22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1    8
#4  21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1   12
#5  18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2   16
#...

Or keeping it in base R:

lapply(dflist, function(x) transform(x, cyl2 = cyl * 2))


问:
Wikimedia Maps Layer (open street maps) getting 429 error (trouble connecting to ssl with wget)
Trying to trace down why The wikimedia map layer is down, wondering if anyone has heard anything.  Google wasn't very helpful

This has been broken since at least yesterday for our maps : https://maps.wikimedia.org/osm-intl/{z}/{x}/{y}{r}.png

The site is up, trying to find out if they changed how the layers were pulled?

https://maps.wikimedia.org/#4/40.75/-73.96

I used wget and getting this

```<code>Resolving maps.wikimedia.org... 208.80.154.240
Connecting to maps.wikimedia.org|208.80.154.240|:443... connected.
OpenSSL: error:1407742E:SSL routines:SSL23_GET_SERVER_HELLO:tlsv1 alert protocol version
Unable to establish SSL connection.```

```

答:
It does seem as if your apllication does not support modern TLS protocols but tries to connect with the really old TLS 1.0 that is not supported anymore by wikimedia maps.

Upgrade your TLS to version 1.2 and you should be fine.

Edit: wikimedia now blocks map access for external users. See https://phabricator.wikimedia.org/T245145#5880898

I don't understand why this produces a TLS error, but the likely reason for your problems is the 429 http error code because of wikimedias blocking external projects. You'll need a different tile provider.

Body:
Trying to trace down why The wikimedia map layer is down, wondering if anyone has heard anything.  Google wasn't very helpful

This has been broken since at least yesterday for our maps : https://maps.wikimedia.org/osm-intl/{z}/{x}/{y}{r}.png

The site is up, trying to find out if they changed how the layers were pulled?

https://maps.wikimedia.org/#4/40.75/-73.96

I used wget and getting this

Resolving maps.wikimedia.org... 208.80.154.240
Connecting to maps.wikimedia.org|208.80.154.240|:443... connected.
OpenSSL: error:1407742E:SSL routines:SSL23_GET_SERVER_HELLO:tlsv1 alert protocol version
Unable to establish SSL connection.```


问:
Why is my MEVN app only showing the backend when deploying to Heroku?
My app is currently deployed online through Heroku but it is displaying the backend server rather than my Vue app.

Note: I have an if statement in app.js that serves the files only in production.  I removed the if statement to see if the app would appear without environmental conditions. It did not work.

Also I have a minified Vue js folder called dist in my express directory.

Updated

The heroku method I am using is the Heroku Git Cli

```<code>$ cd my-project/
$ git init
$ heroku git:remote -a testingew
</code>```

```<code>$ git add .
$ git commit -am "make it better"
$ git push heroku master
</code>```

This is what I see, which is the backend response to the "/" route. The code is in app.js

app.js
The full code

```<code>const serveStatic = require("serve-static");
const path = require("path");
const express = require("express");
const app = express();
const userRoutes = require("./routes/user");
const budgetRoutes = require("./routes/budget");
const profileRoutes = require("./routes/profile");
require("dotenv/config");
const port = process.env.PORT || 3000;
const cors = require("cors");
const morgan = require("morgan");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const cookieParser = require("cookie-parser");
const sessions = require("express-session");
const MongoStore = require("connect-mongo")(sessions);
const passport = require("passport");
const passportSetup = require("./config/passport.js");

//Log when making request
app.use(morgan("combined"));

//Parse body for post request
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

var corsOption = {
  origin: true,
  methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
  credentials: true
};

app.use(cors(corsOption));

app.use(
  sessions({
    secret: process.env.SESSION_COOKIEKEY,
    saveUninitialized: false,
    resave: false,
    store: new MongoStore({
      mongooseConnection: mongoose.connection
    }),
    cookie: {
      // secure: true,
      maxAge: 86400000
    }
  })
);

//Initialize passport
app.use(passport.initialize());
app.use(passport.session());

//Automatic route placer
app.use("/auth", userRoutes);
app.use("/api/budget", budgetRoutes);
app.use("/api/profile", profileRoutes);
app.get("/", (req, res) => {
  res.send("App is on");
});

//404 error and pas to error handler
app.use((req, res, next) => {
  const error = new Error("An error has occured");
  error.status = 404;
  next(error);
});

//Error handler
app.use((error, req, res, next) => {
  //Respond Client
  res.status(error.status || 500);
  res.json({
    error: {
      message: error.message
    }
  });
  console.log(error.message);
});

//Mongo connection
mongoose.connect(
  process.env.DB_CONNECTION,
  {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    useFindAndModify: false
  },
  () => console.log("connected to mongo atlas")
);

//Handle production
app.use(express.static(path.join(__dirname, "dist")));

// Redirect all requests to `index.html`
app.get("/*", (req, res) => {
  res.sendFile(path.join(__dirname, "dist", "index.html"));
});
//Start app
app.listen(port, () => {
  console.log(`Server is on port ${port}`);
});

</code>```

Vue Router

Note: I am also using route navigation guards within components if that means anything

```<code>import Vue from "vue";
import VueRouter from "vue-router";

//import axios from "axios";

Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    name: "login",
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () =>
      import(/* webpackChunkName: "about" */ "../views/Login.vue")
  },
  {
    path: "/userprofile",
    name: "userProfile",
    component: () => import("../views/userProfile.vue"),
    meta: {
      requireAuth: true
    }
  },
  {
    path: "/budgetform",
    name: "form",
    component: () => import("../views/budgetForm.vue"),
    meta: {
      requireAuth: true
    }
  },
  {
    path: "/mybudget",
    name: "myBudget",
    component: () => import("../views/myBudget.vue"),
    meta: {
      requireAuth: true
    }
  }
];

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes
});

export default router;
</code>```

File directory of Express

Hopefully this helps

答:
EDIT

Based on your edit showing your Express app, you need to remove everything between

```<code>app.use("/api/profile", profileRoutes);
</code>```

and Mongo.  The app can't run if you do other things on the route instead.  The "App is on" and error checking stuff is blocking your app.  I don't think you mean to run the error on every route, but that's what's happening.  I would suggest browsing some Express tutorials and starting from scratch to try to understand why that can't work.

ORIGINAL

Try to replace everything above app.listen with:

```<code>// Serve static assets
app.use(express.static(path.join(__dirname, 'dist')));

// Redirect all requests to `index.html`
app.get('/*', (req, res) => {
  res.sendFile(path.join(__dirname, 'dist', 'index.html'));
})
</code>```

Your wildcard match was wrong, and would only match file paths that begin with a dot,  path.join wasn't used correctly, there should be no slash literals.  I changed some other syntax too.  If this doesn't completely fix the issue, there are many possibilities for error that are beyond the scope of this question:

1) directory structure
2) .gitignore
3) vue-router
4) package.json start script

Body:
My app is currently deployed online through Heroku but it is displaying the backend server rather than my Vue app.

Note: I have an if statement in app.js that serves the files only in production.  I removed the if statement to see if the app would appear without environmental conditions. It did not work.

Also I have a minified Vue js folder called dist in my express directory.

Updated

The heroku method I am using is the Heroku Git Cli

$ cd my-project/
$ git init
$ heroku git:remote -a testingew

$ git add .
$ git commit -am "make it better"
$ git push heroku master

This is what I see, which is the backend response to the "/" route. The code is in app.js

app.js
The full code

const serveStatic = require("serve-static");
const path = require("path");
const express = require("express");
const app = express();
const userRoutes = require("./routes/user");
const budgetRoutes = require("./routes/budget");
const profileRoutes = require("./routes/profile");
require("dotenv/config");
const port = process.env.PORT || 3000;
const cors = require("cors");
const morgan = require("morgan");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const cookieParser = require("cookie-parser");
const sessions = require("express-session");
const MongoStore = require("connect-mongo")(sessions);
const passport = require("passport");
const passportSetup = require("./config/passport.js");

//Log when making request
app.use(morgan("combined"));

//Parse body for post request
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

var corsOption = {
  origin: true,
  methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
  credentials: true
};

app.use(cors(corsOption));

app.use(
  sessions({
    secret: process.env.SESSION_COOKIEKEY,
    saveUninitialized: false,
    resave: false,
    store: new MongoStore({
      mongooseConnection: mongoose.connection
    }),
    cookie: {
      // secure: true,
      maxAge: 86400000
    }
  })
);

//Initialize passport
app.use(passport.initialize());
app.use(passport.session());

//Automatic route placer
app.use("/auth", userRoutes);
app.use("/api/budget", budgetRoutes);
app.use("/api/profile", profileRoutes);
app.get("/", (req, res) => {
  res.send("App is on");
});

//404 error and pas to error handler
app.use((req, res, next) => {
  const error = new Error("An error has occured");
  error.status = 404;
  next(error);
});

//Error handler
app.use((error, req, res, next) => {
  //Respond Client
  res.status(error.status || 500);
  res.json({
    error: {
      message: error.message
    }
  });
  console.log(error.message);
});

//Mongo connection
mongoose.connect(
  process.env.DB_CONNECTION,
  {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    useFindAndModify: false
  },
  () => console.log("connected to mongo atlas")
);

//Handle production
app.use(express.static(path.join(__dirname, "dist")));

// Redirect all requests to `index.html`
app.get("/*", (req, res) => {
  res.sendFile(path.join(__dirname, "dist", "index.html"));
});
//Start app
app.listen(port, () => {
  console.log(`Server is on port ${port}`);
});

Vue Router

Note: I am also using route navigation guards within components if that means anything

import Vue from "vue";
import VueRouter from "vue-router";

//import axios from "axios";

Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    name: "login",
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () =>
      import(/* webpackChunkName: "about" */ "../views/Login.vue")
  },
  {
    path: "/userprofile",
    name: "userProfile",
    component: () => import("../views/userProfile.vue"),
    meta: {
      requireAuth: true
    }
  },
  {
    path: "/budgetform",
    name: "form",
    component: () => import("../views/budgetForm.vue"),
    meta: {
      requireAuth: true
    }
  },
  {
    path: "/mybudget",
    name: "myBudget",
    component: () => import("../views/myBudget.vue"),
    meta: {
      requireAuth: true
    }
  }
];

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes
});

export default router;

File directory of Express

Hopefully this helps

Body:
EDIT

Based on your edit showing your Express app, you need to remove everything between

app.use("/api/profile", profileRoutes);

and Mongo.  The app can't run if you do other things on the route instead.  The "App is on" and error checking stuff is blocking your app.  I don't think you mean to run the error on every route, but that's what's happening.  I would suggest browsing some Express tutorials and starting from scratch to try to understand why that can't work.

ORIGINAL

Try to replace everything above app.listen with:

// Serve static assets
app.use(express.static(path.join(__dirname, 'dist')));

// Redirect all requests to `index.html`
app.get('/*', (req, res) => {
  res.sendFile(path.join(__dirname, 'dist', 'index.html'));
})

Your wildcard match was wrong, and would only match file paths that begin with a dot,  path.join wasn't used correctly, there should be no slash literals.  I changed some other syntax too.  If this doesn't completely fix the issue, there are many possibilities for error that are beyond the scope of this question:

1) directory structure
2) .gitignore
3) vue-router
4) package.json start script


问:
Transpose rows to Columns in Spark SQL (pyspark)
I want to make the following transformations in Spark My objective is to get output and I hope If I can make Intermediate transformation, I can easily get output. Any ideas of how to convert rows to columns would be much helpful.  </p>

```<code>RowID  Name  Place
1      Gaga India,US,UK
1      Katy UK,India,Europe
1      Bey  Europe
2      Gaga Null
2      Katy India,Europe
2      Bey  US
3      Gaga Europe
3      Katy US
3      Bey  Null

Output:

RowID   Id  Gaga    Katy    Bey
1       1   India   UK      Europe
1       2   US      India   Null
1       3   UK      Europe  Null
2       1   Null    India   US
2       2   Null    Europe  Null
3       1   Europe  US      Null

Intermediate Output:

RowID   Gaga         Katy               Bey
1       India,US,UK  UK,India,Europe    Europe
2       Null         India,Europe       US
3       Europe       US                 Null
</code>```

答:
Alternative solution without using UDF:
```<code></p>

```from pyspark.sql import Row
from pyspark.sql.types import StructField, StructType, StringType, IntegerType
from pyspark.sql.window import Window
from pyspark.sql.functions import create_map, explode, struct, split, row_number, to_json
from functools import reduce
```

<p>/* DataFrame Schema */</p>

```dfSchema = StructType([
    StructField('RowID', IntegerType()),
    StructField('Name', StringType()),
    StructField('Place', StringType())
])
```

<p>/* Raw Data */</p>

```rowID_11 = Row(1, 'Gaga', 'India,US,UK')
rowID_12 = Row(1, 'Katy', 'UK,India,Europe')
rowID_13 = Row(1, 'Bey', 'Europe')
rowID_21 = Row(2, 'Gaga', None)
rowID_22 = Row(2, 'Katy', 'India,Europe')
rowID_23 = Row(2, 'Bey', 'US')
rowID_31 = Row(3, 'Gaga', 'Europe')
rowID_32 = Row(3, 'Katy', 'US')
rowID_33 = Row(3, 'Bey', None)

rowList = [rowID_11, rowID_12, rowID_13,
           rowID_21, rowID_22, rowID_23,
           rowID_31, rowID_32, rowID_33]
```

<p>/* Create initial DataFrame */</p>

```df = spark.createDataFrame(rowList, dfSchema)
df.show()
```

<p>+-----+----+---------------+
|RowID|Name|          Place|
+-----+----+---------------+
|    1|Gaga|    India,US,UK|
|    1|Katy|UK,India,Europe|
|    1| Bey|         Europe|
|    2|Gaga|           null|
|    2|Katy|   India,Europe|
|    2| Bey|             US|
|    3|Gaga|         Europe|
|    3|Katy|             US|
|    3| Bey|           null|
+-----+----+---------------+</p>

<p>/* Use create_map, struct and to_json to create intermediate output */</p>

```jsonDFCol = df.select(
                 to_json(
                 create_map('Name',
                            struct('RowID', 'Place')))\
                                .alias('name_place'))

jsonList = [js[0] for js in jsonDFCol.rdd.collect()]
jsonDF = spark.read.json(sc.parallelize(jsonList))

intermediateList = [jsonDF .selectExpr(f'{name}.RowID', f'{name}.Place AS {name}')\
    .where('RowID is not Null') for name in jsonDF .columns]

intermediateDF = reduce(lambda curr, nxt:
                        curr.join(nxt, on='RowID'),
                        intermediateList).sort('RowID')\
                        .select('RowID', 'Gaga', 'Katy', 'Bey')

intermediateDF.show()
```

<p>+-----+-----------+---------------+------+
|RowID|       Gaga|           Katy|   Bey|
+-----+-----------+---------------+------+
|    1|India,US,UK|UK,India,Europe|Europe|
|    2|       null|   India,Europe|    US|
|    3|     Europe|             US|  null|
+-----+-----------+---------------+------+</p>

<p>/* Use window to create Id column */</p>

```rowWindow = Window.partitionBy('RowID').orderBy('RowID')
```

<p>/* Use split and explode functions to obtain final output */</p>

```finalDFList = \
[intermediateDF\
    .select('RowID',
            explode(split(intermediateDF[col_], ',')).alias(col_))\
            .withColumn('id', row_number().over(rowWindow))
for col_ in intermediateDF.columns[1:]]

finalDFID = reduce(lambda curr, nxt: curr.select('RowID', 'Id')\
    .unionAll(nxt.select('RowId', 'Id')), finalDFList)

finalDF = reduce(lambda curr, nxt:
                        curr.join(nxt, on=['RowID', 'Id'], how='left'),
                        finalDFList, finalDFID).distinct()\
                        .sort('RowId', 'Id')\
                        .select('RowID', 'Id',
                                'Gaga', 'Katy', 'Bey')

finalDF.show()
```

<p>+-----+---+------+------+------+
|RowID| Id|  Gaga|  Katy|   Bey|
+-----+---+------+------+------+
|    1|  1| India|    UK|Europe|
|    1|  2|    US| India|  null|
|    1|  3|    UK|Europe|  null|
|    2|  1|  null| India|    US|
|    2|  2|  null|Europe|  null|
|    3|  1|Europe|    US|  null|
+-----+---+------+------+------+</p>

<p>```

Body:
I want to make the following transformations in Spark My objective is to get output and I hope If I can make Intermediate transformation, I can easily get output. Any ideas of how to convert rows to columns would be much helpful.

RowID  Name  Place
1      Gaga India,US,UK
1      Katy UK,India,Europe
1      Bey  Europe
2      Gaga Null
2      Katy India,Europe
2      Bey  US
3      Gaga Europe
3      Katy US
3      Bey  Null

Output:

RowID   Id  Gaga    Katy    Bey
1       1   India   UK      Europe
1       2   US      India   Null
1       3   UK      Europe  Null
2       1   Null    India   US
2       2   Null    Europe  Null
3       1   Europe  US      Null

Intermediate Output:

RowID   Gaga         Katy               Bey
1       India,US,UK  UK,India,Europe    Europe
2       Null         India,Europe       US
3       Europe       US                 Null

Body:
Alternative solution without using UDF:

from pyspark.sql import Row
from pyspark.sql.types import StructField, StructType, StringType, IntegerType
from pyspark.sql.window import Window
from pyspark.sql.functions import create_map, explode, struct, split, row_number, to_json
from functools import reduce

/* DataFrame Schema */

dfSchema = StructType([
    StructField('RowID', IntegerType()),
    StructField('Name', StringType()),
    StructField('Place', StringType())
])

/* Raw Data */

rowID_11 = Row(1, 'Gaga', 'India,US,UK')
rowID_12 = Row(1, 'Katy', 'UK,India,Europe')
rowID_13 = Row(1, 'Bey', 'Europe')
rowID_21 = Row(2, 'Gaga', None)
rowID_22 = Row(2, 'Katy', 'India,Europe')
rowID_23 = Row(2, 'Bey', 'US')
rowID_31 = Row(3, 'Gaga', 'Europe')
rowID_32 = Row(3, 'Katy', 'US')
rowID_33 = Row(3, 'Bey', None)

rowList = [rowID_11, rowID_12, rowID_13,
           rowID_21, rowID_22, rowID_23,
           rowID_31, rowID_32, rowID_33]

/* Create initial DataFrame */

df = spark.createDataFrame(rowList, dfSchema)
df.show()

+-----+----+---------------+
|RowID|Name|          Place|
+-----+----+---------------+
|    1|Gaga|    India,US,UK|
|    1|Katy|UK,India,Europe|
|    1| Bey|         Europe|
|    2|Gaga|           null|
|    2|Katy|   India,Europe|
|    2| Bey|             US|
|    3|Gaga|         Europe|
|    3|Katy|             US|
|    3| Bey|           null|
+-----+----+---------------+

/* Use create_map, struct and to_json to create intermediate output */

jsonDFCol = df.select(
                 to_json(
                 create_map('Name',
                            struct('RowID', 'Place')))\
                                .alias('name_place'))

jsonList = [js[0] for js in jsonDFCol.rdd.collect()]
jsonDF = spark.read.json(sc.parallelize(jsonList))

intermediateList = [jsonDF .selectExpr(f'{name}.RowID', f'{name}.Place AS {name}')\
    .where('RowID is not Null') for name in jsonDF .columns]

intermediateDF = reduce(lambda curr, nxt:
                        curr.join(nxt, on='RowID'),
                        intermediateList).sort('RowID')\
                        .select('RowID', 'Gaga', 'Katy', 'Bey')

intermediateDF.show()

+-----+-----------+---------------+------+
|RowID|       Gaga|           Katy|   Bey|
+-----+-----------+---------------+------+
|    1|India,US,UK|UK,India,Europe|Europe|
|    2|       null|   India,Europe|    US|
|    3|     Europe|             US|  null|
+-----+-----------+---------------+------+

/* Use window to create Id column */

rowWindow = Window.partitionBy('RowID').orderBy('RowID')

/* Use split and explode functions to obtain final output */

finalDFList = \
[intermediateDF\
    .select('RowID',
            explode(split(intermediateDF[col_], ',')).alias(col_))\
            .withColumn('id', row_number().over(rowWindow))
for col_ in intermediateDF.columns[1:]]

finalDFID = reduce(lambda curr, nxt: curr.select('RowID', 'Id')\
    .unionAll(nxt.select('RowId', 'Id')), finalDFList)

finalDF = reduce(lambda curr, nxt:
                        curr.join(nxt, on=['RowID', 'Id'], how='left'),
                        finalDFList, finalDFID).distinct()\
                        .sort('RowId', 'Id')\
                        .select('RowID', 'Id',
                                'Gaga', 'Katy', 'Bey')

finalDF.show()

+-----+---+------+------+------+
|RowID| Id|  Gaga|  Katy|   Bey|
+-----+---+------+------+------+
|    1|  1| India|    UK|Europe|
|    1|  2|    US| India|  null|
|    1|  3|    UK|Europe|  null|
|    2|  1|  null| India|    US|
|    2|  2|  null|Europe|  null|
|    3|  1|Europe|    US|  null|
+-----+---+------+------+------+


问:
Ansible get_url is timing out
I have troubles downloading a jar file from Artifactory on a CentOs7 instance with Ansible. It is the first time i do that on a Linux instance.

I am using the win_get_url module on every Windows instance and it is working normaly

```<code>   - name: download artifacts
     win_get_url:
       url: '{{ some_url }}'
       username: '{{ jfrog_username }}'
       password: '{{ jfrog_password }}'
       dest: '{{ some_dest }}'
       force: no
       proxy_url: {{ some_proxy }}
</code>```

When i use the get_url module it is timeing out. I have noticed that the Linux module doen't support the parameter "proxy_url". so i have tried to run the tasks with some other parameters like

```<code>   - name: download artifacts
     get_url:
       url: '{{ some_url }}'
       username: '{{ jfrog_username }}'
       password: '{{ jfrog_password }}'
       dest: '{{ some_dest }}'
       force: no
       use_proxy: yes
       http_agent"{{ proxy }}
       checksum: {{ checksum }}
</code>```

But it gives me always this error:

```<code>  "status": -1,
  "url": "https://some_url/installer.jar",
  "msg": "Failed to connect to www.jfrog.io at port 443: [Errno 110] Connection timed out",
  "invocation": {
</code>```

I have checked the Firewall setting and https is open from/into this server.

Any help would be appreciated.

UPDATE:

If i use curl, based on the tip mentioned by Zeitounator it works! i can download the file with:

```<code>     curl -O -u --user user:password 'https://some_url/installer.jar'
</code>```

I am not using proxy password. When curl asked voor proxy password i just pressed enter and curl downloaded the file without any issues.

But with Ansible still no luck.

答:
Following our comments: you need to declare the proxy your are using in an environment stanza, either at task or play level.

```<code>environment:
  http_proxy: http://my_proxy:8080
  https_proxy: http://my_proxy:8080
  no_proxy: 127.0.0.1,localhost,.my_local_domain.com
</code>```

If your proxy needs authentification, you'll have to pass the auth in the uri:

```<code>http://user:password@my_proxy:8080
</code>```

Title: Ansible get_url is timing out

Body:
I have troubles downloading a jar file from Artifactory on a CentOs7 instance with Ansible. It is the first time i do that on a Linux instance.

I am using the win_get_url module on every Windows instance and it is working normaly

   - name: download artifacts
     win_get_url:
       url: '{{ some_url }}'
       username: '{{ jfrog_username }}'
       password: '{{ jfrog_password }}'
       dest: '{{ some_dest }}'
       force: no
       proxy_url: {{ some_proxy }}

When i use the get_url module it is timeing out. I have noticed that the Linux module doen't support the parameter "proxy_url". so i have tried to run the tasks with some other parameters like

   - name: download artifacts
     get_url:
       url: '{{ some_url }}'
       username: '{{ jfrog_username }}'
       password: '{{ jfrog_password }}'
       dest: '{{ some_dest }}'
       force: no
       use_proxy: yes
       http_agent"{{ proxy }}
       checksum: {{ checksum }}

But it gives me always this error:

  "status": -1,
  "url": "https://some_url/installer.jar",
  "msg": "Failed to connect to www.jfrog.io at port 443: [Errno 110] Connection timed out",
  "invocation": {

I have checked the Firewall setting and https is open from/into this server.

Any help would be appreciated.

UPDATE:

If i use curl, based on the tip mentioned by Zeitounator it works! i can download the file with:

     curl -O -u --user user:password 'https://some_url/installer.jar'

I am not using proxy password. When curl asked voor proxy password i just pressed enter and curl downloaded the file without any issues.

But with Ansible still no luck.

Body:
Following our comments: you need to declare the proxy your are using in an environment stanza, either at task or play level.

environment:
  http_proxy: http://my_proxy:8080
  https_proxy: http://my_proxy:8080
  no_proxy: 127.0.0.1,localhost,.my_local_domain.com

If your proxy needs authentification, you'll have to pass the auth in the uri:

http://user:password@my_proxy:8080


问:
help with memory issues on adding a UIImageView to a cell
I am adding an image to the first cell in a UITableView cellForRowAtIndexPath like so:

```<code>if (row == 0) {
        UIImage *image = [UIImage imageNamed:@"numberOneIcon.png"];
        //create a framework for the ui image view
        CGRect frame = CGRectMake(10, 37, image.size.width, image.size.height);
        //initialize the ui image view
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:frame];
        imageView.image = image;

        [cell.contentView addSubview:imageView];
        [image release];
        //[imageView release];
}
</code>```

If I uncomment out the [imageView release]; it will crash when you 'close' the app (press the home bttn) then return to the app and return to the view with the UITableView in it.

If I leave this commented it doesn't crash but am I not leaking memory here? If so is there another way to do this so as not to leak.

Many thanks

答:
You should be releasing imageView rather than image. Change that code to the following:

```<code>[cell.contentView addSubview:imageView];
        //[image release];
        [imageView release];
</code>```

You do not own image as you did not create it with alloc, new, nor did you retain it, thus you are not supposed to be releasing it. You did alloc an instance of imageView however, so that is what you release. I strongly recommend reading this.

Body:
I am adding an image to the first cell in a UITableView cellForRowAtIndexPath like so:

if (row == 0) {
        UIImage *image = [UIImage imageNamed:@"numberOneIcon.png"];
        //create a framework for the ui image view
        CGRect frame = CGRectMake(10, 37, image.size.width, image.size.height);
        //initialize the ui image view
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:frame];
        imageView.image = image;

        [cell.contentView addSubview:imageView];
        [image release];
        //[imageView release];
}

If I uncomment out the [imageView release]; it will crash when you 'close' the app (press the home bttn) then return to the app and return to the view with the UITableView in it.

If I leave this commented it doesn't crash but am I not leaking memory here? If so is there another way to do this so as not to leak.

Many thanks

Body:
You should be releasing imageView rather than image. Change that code to the following:

[cell.contentView addSubview:imageView];
        //[image release];
        [imageView release];

You do not own image as you did not create it with alloc, new, nor did you retain it, thus you are not supposed to be releasing it. You did alloc an instance of imageView however, so that is what you release. I strongly recommend reading this.


问:
Android Studio 3.5 ...Getting the error default activity not found after upgraded
I Just upgraded android studio :

```<code>Android Studio 3.5
Build #AI-191.8026.42.35.5791312, built on August 9, 2019
JRE: 1.8.0_202-release-1483-b03 amd64
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
Windows 10 10.0
</code>```

I am getting the error:

```<code>11:35   Error running 'app': Default Activity not found
</code>```

I tried all possible solutions like

Invalidate caches restart

clean and rebuild

deleting cache folder of android studio

Default activity is mentioned in manifest

I also tried solution in this questions, didn't work:
https://stackoverflow.com/q/15825081/1083093

This was working before until I upgraded the android studio

答:
I tried:

Cleaning and rebuilding.

Invalidating caches and restarting.

Deleting cache folder of Android Studio

These way can not work for me.

I just removed all the code in the application label in the manifest file except for launcher activity and it worked!

Then you just revert your change.

Body:
I Just upgraded android studio :

Android Studio 3.5
Build #AI-191.8026.42.35.5791312, built on August 9, 2019
JRE: 1.8.0_202-release-1483-b03 amd64
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
Windows 10 10.0

I am getting the error:

11:35   Error running 'app': Default Activity not found

I tried all possible solutions like

Invalidate caches restart

clean and rebuild

deleting cache folder of android studio

Default activity is mentioned in manifest

I also tried solution in this questions, didn't work:
https://stackoverflow.com/q/15825081/1083093

This was working before until I upgraded the android studio


问:
Get Pixel color of UIImage
How can I get the RGB value of a particular pixel in a UIImage?</p>

答:
Swift 5 version

The answers given here are either outdated or incorrect because they don't take into account the following:

The pixel size of the image can differ from its point size that is returned by image.size.width/image.size.height.

There can be various layouts used by pixel components in the image, such as BGRA, ABGR, ARGB etc. or may not have an alpha component at all, such as BGR and RGB. For example, UIView.drawHierarchy(in:afterScreenUpdates:) method can produce BGRA images.

Color components can be premultiplied by the alpha for all pixels in the image and need to be divided by alpha in order to restore the original color.

For memory optimization used by CGImage, the size of a pixel row in bytes can be greater than the mere multiplication of the pixel width by 4.

The code below is to provide a universal Swift 5 solution to get the UIColor of a pixel for all such special cases. The code is optimized for usability and clarity, not for performance.

public extension UIImage {
    var pixelWidth: Int {
        return cgImage?.width ?? 0
    }

    var pixelHeight: Int {
        return cgImage?.height ?? 0
    }

    func pixelColor(x: Int, y: Int) -> UIColor {
        assert(
            0 ..< pixelWidth ~= x && 0 ..< pixelHeight ~= y,
            "Pixel coordinates are out of bounds"
        )

        guard
            let cgImage = cgImage,
            let data = cgImage.dataProvider?.data,
            let dataPtr = CFDataGetBytePtr(data),
            let colorSpaceModel = cgImage.colorSpace?.model,
            let componentLayout = cgImage.bitmapInfo.componentLayout
        else {
            assertionFailure("Could not get a pixel of an image")
            return .clear
        }

        assert(
            colorSpaceModel == .rgb,
            "The only supported color space model is RGB"
        )
        assert(
            cgImage.bitsPerPixel == 32 || cgImage.bitsPerPixel == 24,
            "A pixel is expected to be either 4 or 3 bytes in size"
        )

        let bytesPerRow = cgImage.bytesPerRow
        let bytesPerPixel = cgImage.bitsPerPixel / 8
        let pixelOffset = y * bytesPerRow + x * bytesPerPixel

        if componentLayout.count == 4 {
            let components = (
                dataPtr[pixelOffset + 0],
                dataPtr[pixelOffset + 1],
                dataPtr[pixelOffset + 2],
                dataPtr[pixelOffset + 3]
            )

            var alpha: UInt8 = 0
            var red: UInt8 = 0
            var green: UInt8 = 0
            var blue: UInt8 = 0

            switch componentLayout {
            case .bgra:
                alpha = components.3
                red = components.2
                green = components.1
                blue = components.0
            case .abgr:
                alpha = components.0
                red = components.3
                green = components.2
                blue = components.1
            case .argb:
                alpha = components.0
                red = components.1
                green = components.2
                blue = components.3
            case .rgba:
                alpha = components.3
                red = components.0
                green = components.1
                blue = components.2
            default:
                return .clear
            }

            /// If chroma components are premultiplied by alpha and the alpha is `0`,
            /// keep the chroma components to their current values.
            if cgImage.bitmapInfo.chromaIsPremultipliedByAlpha, alpha != 0 {
                let invisibleUnitAlpha = 255 / CGFloat(alpha)
                red = UInt8((CGFloat(red) * invisibleUnitAlpha).rounded())
                green = UInt8((CGFloat(green) * invisibleUnitAlpha).rounded())
                blue = UInt8((CGFloat(blue) * invisibleUnitAlpha).rounded())
            }

            return .init(red: red, green: green, blue: blue, alpha: alpha)

        } else if componentLayout.count == 3 {
            let components = (
                dataPtr[pixelOffset + 0],
                dataPtr[pixelOffset + 1],
                dataPtr[pixelOffset + 2]
            )

            var red: UInt8 = 0
            var green: UInt8 = 0
            var blue: UInt8 = 0

            switch componentLayout {
            case .bgr:
                red = components.2
                green = components.1
                blue = components.0
            case .rgb:
                red = components.0
                green = components.1
                blue = components.2
            default:
                return .clear
            }

            return .init(red: red, green: green, blue: blue, alpha: UInt8(255))

        } else {
            assertionFailure("Unsupported number of pixel components")
            return .clear
        }
    }
}

public extension UIColor {
    convenience init(red: UInt8, green: UInt8, blue: UInt8, alpha: UInt8) {
        self.init(
            red: CGFloat(red) / 255,
            green: CGFloat(green) / 255,
            blue: CGFloat(blue) / 255,
            alpha: CGFloat(alpha) / 255
        )
    }
}

public extension CGBitmapInfo {
    enum ComponentLayout {
        case bgra
        case abgr
        case argb
        case rgba
        case bgr
        case rgb

        var count: Int {
            switch self {
            case .bgr, .rgb: return 3
            default: return 4
            }
        }
    }

    var componentLayout: ComponentLayout? {
        guard let alphaInfo = CGImageAlphaInfo(rawValue: rawValue & Self.alphaInfoMask.rawValue) else { return nil }
        let isLittleEndian = contains(.byteOrder32Little)

        if alphaInfo == .none {
            return isLittleEndian ? .bgr : .rgb
        }
        let alphaIsFirst = alphaInfo == .premultipliedFirst || alphaInfo == .first || alphaInfo == .noneSkipFirst

        if isLittleEndian {
            return alphaIsFirst ? .bgra : .abgr
        } else {
            return alphaIsFirst ? .argb : .rgba
        }
    }

    var chromaIsPremultipliedByAlpha: Bool {
        let alphaInfo = CGImageAlphaInfo(rawValue: rawValue & Self.alphaInfoMask.rawValue)
        return alphaInfo == .premultipliedFirst || alphaInfo == .premultipliedLast
    }
}
```

ContentLicense: CC BY-SA 2.5

Title: Get Pixel color of UIImage


问:
What exactly are "PHPDoc style comments"?
An evil, nasty bug bit me today. For a long time, I've calculated the number of "pure" rows of PHP source code from PHP scripts. To accomplish this, I looped through all the tokens and removed any instance of T_COMMENT.

In the manual, at https://www.php.net/manual/en/tokens.php , it says:

```<code>T_COMMENT   // or #, and /* */  comments
</code>```

It turns out that this did not delete some kind of fancy alternative-style comment, apparently called "PHPDoc style comments". On the same page, further down (which I never looked for, because I had no idea they existed), it says:

```<code>T_DOC_COMMENT   /** */  PHPDoc style comments
</code>```

Now, my code works, because I account for both kinds.

However, I still wonder what a "PHPDoc style comment" is supposed to be, and why they are not considered part of T_COMMENT.

Frustratingly, the "PHPDoc style comments" hyperlink on that manual page just links to a generic "comments" page which doesn't mention "PHPDoc" anywhere!

So, what is it? Why is it considered a special kind of comment? Why isn't it documented? Why must everything in this life be a complete damn mystery?!

答: These kind of comments are used to read by documentation tools, which analyze your source code and generate documentations about your functions and classes. As an example the phpDocumentor is such a tool to generate documentations, similar to javadoc.</p>

Body:
An evil, nasty bug bit me today. For a long time, I've calculated the number of "pure" rows of PHP source code from PHP scripts. To accomplish this, I looped through all the tokens and removed any instance of T_COMMENT.

In the manual, at https://www.php.net/manual/en/tokens.php , it says:

T_COMMENT   // or #, and /* */  comments

It turns out that this did not delete some kind of fancy alternative-style comment, apparently called "PHPDoc style comments". On the same page, further down (which I never looked for, because I had no idea they existed), it says:

T_DOC_COMMENT   /** */  PHPDoc style comments

Now, my code works, because I account for both kinds.

However, I still wonder what a "PHPDoc style comment" is supposed to be, and why they are not considered part of T_COMMENT.

Frustratingly, the "PHPDoc style comments" hyperlink on that manual page just links to a generic "comments" page which doesn't mention "PHPDoc" anywhere!

So, what is it? Why is it considered a special kind of comment? Why isn't it documented? Why must everything in this life be a complete damn mystery?!


问:
Custom ViewRenderer<> displays Forms element behind the native control
In my Xamarin Forms app, I have a custom view that derives from ContentView. On iOS and macOS, I would like to replace this view with a native control ([UI|NS]SegmentedControl). So I created a renderer that derives from ViewRenderer and implemented it.

It's working, but there is a flaw. The original Forms control (known as Element within the renderer) is displaying behind the UISegmentedControl. My expectation is that only the native control would be rendered when using ViewRenderer.

Any changes made to the appearance of the Forms element are reflected on the native control, so simply hiding it or making it transparent won't work.

Here's my iOS renderer.

```<code>public class CustomContentViewRenderer : ViewRenderer<CustomContentView, UISegmentedControl>
{
    protected override void OnElementChanged(ElementChangedEventArgs<CustomContentView> e) {
        base.OnElementChanged(e);

        if (e.NewElement != null ) {
            if ( Control == null )
                SetNativeControl(new UISegmentedControl(new string[] { "One", "Two", "Three" }));
        }
    }
}
</code>```

CustomContentView here is simply derived from ContentView with a BoxView as content. Here's what it looks like on iOS:

My understanding of renderers is that a custom renderer completely overrides the forms element. Am I missing something big here? Can ViewRenderer<> be used to completely replace a Xamarin ContentView with a native control?

EDIT: In the sample above I'm using a BoxView as a placeholder for the actual cross platform picker I use for UWP. The real control is a StackLayout containing toggle buttons. Here's a screen grab on macOS showing the issue.

In the end, setting Element.Content.IsVisible = false worked.

答:
as per as documentation of Xamarin custom renderers just override Xamarin.Forms appearance and behvoir.
 Here you gave custom content view background orange then in your custom renderer you didn't override it and as I know default background in iOS is transparent so make sense to still in orange color.
Hope to be useful </p>

Body:
In my Xamarin Forms app, I have a custom view that derives from ContentView. On iOS and macOS, I would like to replace this view with a native control ([UI|NS]SegmentedControl). So I created a renderer that derives from ViewRenderer and implemented it.

It's working, but there is a flaw. The original Forms control (known as Element within the renderer) is displaying behind the UISegmentedControl. My expectation is that only the native control would be rendered when using ViewRenderer.

Any changes made to the appearance of the Forms element are reflected on the native control, so simply hiding it or making it transparent won't work.

Here's my iOS renderer.

public class CustomContentViewRenderer : ViewRenderer<CustomContentView, UISegmentedControl>
{
    protected override void OnElementChanged(ElementChangedEventArgs<CustomContentView> e) {
        base.OnElementChanged(e);

        if (e.NewElement != null ) {
            if ( Control == null )
                SetNativeControl(new UISegmentedControl(new string[] { "One", "Two", "Three" }));
        }
    }
}

CustomContentView here is simply derived from ContentView with a BoxView as content. Here's what it looks like on iOS:

My understanding of renderers is that a custom renderer completely overrides the forms element. Am I missing something big here? Can ViewRenderer<> be used to completely replace a Xamarin ContentView with a native control?

EDIT: In the sample above I'm using a BoxView as a placeholder for the actual cross platform picker I use for UWP. The real control is a StackLayout containing toggle buttons. Here's a screen grab on macOS showing the issue.

In the end, setting Element.Content.IsVisible = false worked.


问:
Order a table by a key in an array of json (stored as jsonb) in Postgres
I have a postgres which has a jsonb column which is an array of jsons.

```<code>id  array_json
123 [{"end_time": 22, "start_time": 21}]
124 [{"end_time": 22, "start_time": 9}, {"end_time": 20, "start_time": 0}]
126 [{"end_time": 22, "start_time": 0}]
125 [{"end_time": 22, "start_time": 1}, {"end_time": 20, "start_time": 6}]
</code>```

I want to order these by the "start_time". A row has an array of jsons. In such cases, the ordering has to be considering the earliest start time in the entire array. If two arrays have the same start time, it doesnt matter which one comes first.
The final result should be:

```<code>id  array_json
126 [{"end_time": 22, "start_time": 0}]
124 [{"end_time": 22, "start_time": 9}, {"end_time": 20, "start_time": 0}]
125 [{"end_time": 22, "start_time": 1}, {"end_time": 20, "start_time": 6}]
123 [{"end_time": 22, "start_time": 21}]
</code>```

I've created a fiddle of this table. How should this be done?

答:
This query can be used:</p>

```<code>select id, min(start_time) min_start_time, array_json
from (
   select
       id,
       array_json,
       -- we must convert start_time to integer for right sort order
       (jsonb_array_elements(array_json)->>'start_time')::int4 as start_time
    from the_table
) tmp
group by id, array_json
order by min_start_time;
</code>```

Body:
I have a postgres which has a jsonb column which is an array of jsons.

id  array_json
123 [{"end_time": 22, "start_time": 21}]
124 [{"end_time": 22, "start_time": 9}, {"end_time": 20, "start_time": 0}]
126 [{"end_time": 22, "start_time": 0}]
125 [{"end_time": 22, "start_time": 1}, {"end_time": 20, "start_time": 6}]

I want to order these by the "start_time". A row has an array of jsons. In such cases, the ordering has to be considering the earliest start time in the entire array. If two arrays have the same start time, it doesnt matter which one comes first.
The final result should be:

id  array_json
126 [{"end_time": 22, "start_time": 0}]
124 [{"end_time": 22, "start_time": 9}, {"end_time": 20, "start_time": 0}]
125 [{"end_time": 22, "start_time": 1}, {"end_time": 20, "start_time": 6}]
123 [{"end_time": 22, "start_time": 21}]

I've created a fiddle of this table. How should this be done?

Body:
This query can be used:

select id, min(start_time) min_start_time, array_json
from (
   select
       id,
       array_json,
       -- we must convert start_time to integer for right sort order
       (jsonb_array_elements(array_json)->>'start_time')::int4 as start_time
    from the_table
) tmp
group by id, array_json
order by min_start_time;


问:
Iterate over string with commas
I have two strings:

```<code>x = 'a1,a2,a3'
y = 'b1,b2,b3'
</code>```

I want to concatenate these two string as:

```<code>z = ['a1b1','a1b2','a1b3','a2b1','a2b2','a2b3','a3b1','a3b2','a3b3']
</code>```

I used the code snippet:

```<code>for i in x:
     for j in y:
         z.append(i+j)
</code>```

But the result was not as required. How can I obtain the required result?

答:
You can use starmap on the product with the add operator for that

```<code>from operator import add
from itertools import starmap, product
x = 'a1,a2,a3'
y = 'b1,b2,b3'
z=list(starmap(add, product(x.split(','),y.split(','))))
</code>```

Title: Iterate over string with commas

Body:
I have two strings:

x = 'a1,a2,a3'
y = 'b1,b2,b3'

I want to concatenate these two string as:

z = ['a1b1','a1b2','a1b3','a2b1','a2b2','a2b3','a3b1','a3b2','a3b3']

I used the code snippet:

for i in x:
     for j in y:
         z.append(i+j)

But the result was not as required. How can I obtain the required result?

Body:
You can use starmap on the product with the add operator for that

from operator import add
from itertools import starmap, product
x = 'a1,a2,a3'
y = 'b1,b2,b3'
z=list(starmap(add, product(x.split(','),y.split(','))))


问:
Android app - user communication through Firebase
I'm trying to add a feature in my Android app for users to be able to send custom objects (as JSONs I guess) between them. I am new to Firebase and user-to-user interactions and I've been reading through a few things and couple of codelabs about Firebase, but what I want is not a realtime database, nor a Whatsapp messaging styled implementation.

All I want to know, is what is the easiest way for user A to send something across to user B using Firebase? What Firebase product or practice should I be looking at?

答:
You can use Firebase storage for this.
If User A wants to send a file to User B:

User A will upload a file to firebase storage and get a link to the file.

User A shares the link with User B.

User B will then download the file from firebase storage.

You can check out the documentation here: Firebase storage docs


答:
You need to str.splitsplit the strings on ",", then you can use itertools.product to get the cartesian product of the two lists:

```<code>from itertools import product

x = "a1,a2,a3"
y = "b1,b2,b3"

print([fst + snd for fst, snd in product(x.split(","), y.split(","))])
# ['a1b1', 'a1b2', 'a1b3', 'a2b1', 'a2b2', 'a2b3', 'a3b1', 'a3b2', 'a3b3']
</code>```

You could also do this nested loops in a list comprehension to achieve the same result:

```<code>print([fst + snd for fst in x.split(",") for snd in y.split(",")])
# ['a1b1', 'a1b2', 'a1b3', 'a2b1', 'a2b2', 'a2b3', 'a3b1', 'a3b2', 'a3b3']
</code>```

Or use a solution similar to your original approach:

```<code>z = []
for fst in x.split(","):
    for snd in y.split(","):
        z.append(fst + snd)

print(z)
# ['a1b1', 'a1b2', 'a1b3', 'a2b1', 'a2b2', 'a2b3', 'a3b1', 'a3b2', 'a3b3']
</code>```

Title: Iterate over string with commas

Body:
You need to str.splitsplit the strings on ",", then you can use itertools.product to get the cartesian product of the two lists:

from itertools import product

x = "a1,a2,a3"
y = "b1,b2,b3"

print([fst + snd for fst, snd in product(x.split(","), y.split(","))])
# ['a1b1', 'a1b2', 'a1b3', 'a2b1', 'a2b2', 'a2b3', 'a3b1', 'a3b2', 'a3b3']

You could also do this nested loops in a list comprehension to achieve the same result:

print([fst + snd for fst in x.split(",") for snd in y.split(",")])
# ['a1b1', 'a1b2', 'a1b3', 'a2b1', 'a2b2', 'a2b3', 'a3b1', 'a3b2', 'a3b3']

Or use a solution similar to your original approach:

z = []
for fst in x.split(","):
    for snd in y.split(","):
        z.append(fst + snd)

print(z)
# ['a1b1', 'a1b2', 'a1b3', 'a2b1', 'a2b2', 'a2b3', 'a3b1', 'a3b2', 'a3b3']


问:
how do i create a prompt in javascript with 3 checkboxes/radio buttons as choices?
How do I create a javascript prompt box where you have to select 1 of 3 choices? I'm looking to do something similar to a html form's radio buttons except within a javascript prompt.</p>

答:
You can't do this from an "alert" box if thats what you mean.. But you could use any number of libraries to create a popup window which is basically just a  and do your form within there.

You could then tie a button or whatever to a function which closes the box and parses the form into your structures within Javascript.