问:
Can I run only a specific container in detach mode with docker-compose?
I'm running three containers consisting of mongo, express, and react using docker-compose.

While I run them by docker-compose, what I need to watch is only the output of express container. So I want to run the mongo container in detach mode.

I'm aware of there is a command to run docker-compose in detach mode, docker-compose up -d
However, what I want to do is not to run whole containers in detach mode, but to run some specific containers in detach mode.

Is there any way to handle this?

答:
yes you can by using the service name as a parmaeter</p>

```<code>docker-compose up -d service1
docker-compose up -d service2
docker-compose up service3
</code>```

Body:
yes you can by using the service name as a parmaeter

docker-compose up -d service1
docker-compose up -d service2
docker-compose up service3


来源: stackexchange

问:
Check that two different methods call the same methods on mocked object
I am using Moq as a mocking framework. I have a situation where I want to execute two different methods, that both call methods an an interface. I want to make sure, that both methods call exactly the same methods on my interface, in the same order and with the same parameters. To illustrate, here is the code:

```<code>[TestMethod]
public void UnitTest()
{
var classToTest = new ClassToTest();
Mock<IMyInterface> mock1 = new Mock<IMyInterface>();
// Setup the mock
Mock<IMyInterface> mock2 = new Mock<IMyInterface>();
// Setup the mock

classToTest.MethodToTest(mock1.Object);
classToTest.DifferentMethodToTest(mock2.Object);

// here I need help:
mock1.Verify(theSameMethodsAsMock2);
}
</code>```

For example, if IMyInterface had two methods, Method1(int i) and Method2(string s), the test should pass if MethodToTest has the structure

```<code>void MethodToTest(IMyInterface x)
{
x.Method1(42);
x.Method2("example");
x.Method1(0);
}
</code>```

and DifferentMethodToTest looks like that:

```<code>void MethodToTest(IMyInterface x)
{
int a = 10 + 32;
x.Method1(a);
string s = "examples";
x.Method2(s.Substring(0, 7));
x.Method1(0);
// might also have some code here that not related to IMyInterface at all,
// e.g. calling methods in other classes and so on
}
</code>```

Same order, same methods, same parameters. Is this possible with Moq? Or do I need another mocking framework?

答:
I found a solution by myself which uses InvocationAction:

```<code>[TestMethod]
public void Test()
{
var classToTest = new ClassToTest();

var methodCalls1 = new List<string>();
var invocationAction1 = new InvocationAction((ia) =>
{
     string methodCall = $"{ia.Method.Name} was called with parameters {string.Join(", ", ia.Arguments.Select(x => x?.ToString() ?? "null"))}";
     methodCalls1.Add(methodCall);
});
Mock<IMyInterface> mock1 = new Mock<IMyInterface>();
mock1.Setup(x => x.Method1(It.IsAny<int>())).Callback(invocationAction1);
mock1.Setup(x => x.Method2(It.IsAny<string>())).Callback(invocationAction1);

// Same for mock2 ...

classToTest.MethodToTest(mock1.Object);
classToTest.DifferentMethodToTest(mock2.Object);

CollectionAssert.AreEqual(methodCalls1, methodCalls2);
}
</code>```

I know that the code is very clumsy, especially the string comparisons, but it's sufficient for the time being.

ContentLicense: CC BY-SA 4.0

Body:
I am using Moq as a mocking framework. I have a situation where I want to execute two different methods, that both call methods an an interface. I want to make sure, that both methods call exactly the same methods on my interface, in the same order and with the same parameters. To illustrate, here is the code:

[TestMethod]
public void UnitTest()
{
var classToTest = new ClassToTest();
Mock<IMyInterface> mock1 = new Mock<IMyInterface>();
// Setup the mock
Mock<IMyInterface> mock2 = new Mock<IMyInterface>();
// Setup the mock

classToTest.MethodToTest(mock1.Object);
classToTest.DifferentMethodToTest(mock2.Object);

// here I need help:
mock1.Verify(theSameMethodsAsMock2);
}

For example, if IMyInterface had two methods, Method1(int i) and Method2(string s), the test should pass if MethodToTest has the structure

void MethodToTest(IMyInterface x)
{
x.Method1(42);
x.Method2("example");
x.Method1(0);
}

and DifferentMethodToTest looks like that:

void MethodToTest(IMyInterface x)
{
int a = 10 + 32;
x.Method1(a);
string s = "examples";
x.Method2(s.Substring(0, 7));
x.Method1(0);
// might also have some code here that not related to IMyInterface at all,
// e.g. calling methods in other classes and so on
}

Same order, same methods, same parameters. Is this possible with Moq? Or do I need another mocking framework?

Body:
I found a solution by myself which uses InvocationAction:

[TestMethod]
public void Test()
{
var classToTest = new ClassToTest();

var methodCalls1 = new List<string>();
var invocationAction1 = new InvocationAction((ia) =>
{
     string methodCall = $"{ia.Method.Name} was called with parameters {string.Join(", ", ia.Arguments.Select(x => x?.ToString() ?? "null"))}";
     methodCalls1.Add(methodCall);
});
Mock<IMyInterface> mock1 = new Mock<IMyInterface>();
mock1.Setup(x => x.Method1(It.IsAny<int>())).Callback(invocationAction1);
mock1.Setup(x => x.Method2(It.IsAny<string>())).Callback(invocationAction1);

// Same for mock2 ...

classToTest.MethodToTest(mock1.Object);
classToTest.DifferentMethodToTest(mock2.Object);

CollectionAssert.AreEqual(methodCalls1, methodCalls2);
}

I know that the code is very clumsy, especially the string comparisons, but it's sufficient for the time being.


问:
Iterate through objects in objects in Firebase using FirebaseRecyclerAdapter
I did some reading on my problem & while a lot of people pointed to using DataSnapshot.forEach() to solve my issue, I would like to know if it's possible to modify my query inside FirebaseRecyclerAdapter to fit my needs.

This is the structure I currently have where a Request may have 1 or many Orders. Each Order comes with its set of values such as restaurantID.
I want to basically iterate through all those requests & only display the ones that have an order with a certain restaurantID.

In my application, the user logs in & has a value for restaurantID. I want to show inside my RecyclerView only the orders that are related to that account, based on that value.

Below is the code. I tried to do some funny stuff in populateViewHolder() to fix this with ordersForThisRestaurant but it did not quite work out. I would love any help on this, I have been stuck & wasn't able to make any progress for some time. Would be awesome to advance!

THANK YOU!

OrderStatus.java

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

    RecyclerView recyclerView;
    RecyclerView.LayoutManager layoutManager;

    FirebaseRecyclerAdapter<Request, OrderViewHolder> adapter;

    FirebaseDatabase database;
    DatabaseReference requests;

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

        //Initialize the Firebase database.
        database = FirebaseDatabase.getInstance();
        requests = database.getReference("Requests");

        recyclerView = (RecyclerView) findViewById(R.id.recyclerOrder);
        recyclerView.setHasFixedSize(true);
        layoutManager = new GridLayoutManager(this, 2);
        recyclerView.setLayoutManager(layoutManager);

        loadOrders();
    }

    private void loadOrders() {
        adapter = new FirebaseRecyclerAdapter<Request, OrderViewHolder>(
                Request.class,
                R.layout.order_layout,
                OrderViewHolder.class,
                requests
        ) {
            @Override
            protected void populateViewHolder(OrderViewHolder orderViewHolder, Request request, int i) {
                List<Order> activeOrders = request.getOrder();
                List<Order> ordersForThisRestaurant = new ArrayList<>();
                for(int pos=0; pos<activeOrders.size(); pos++) {
                    Order currentOrder = activeOrders.get(pos);
                    String restaurantID = currentOrder.getRestaurantID();
                    if(restaurantID.equals(Common.currentUser.getRestaurantID())) {
                        ordersForThisRestaurant.add(activeOrders.get(pos));
                    }
                }
                if(ordersForThisRestaurant.size() == 0) return;     //This means the request was not for this restaurant.

                orderViewHolder.orderID.setText(adapter.getRef(i).getKey());
                orderViewHolder.orderStatus.setText(Common.convertCodeToStatus(request.getStatus()));
                String orderMenu = "";

                for(int pos=0; pos<ordersForThisRestaurant.size(); pos++) {
                    String currentMenu = ordersForThisRestaurant.get(pos).getMenuName();
                    String currentQuantity = ordersForThisRestaurant.get(pos).getQuantity();
                    //orderMenu += currentMenu + " x" + currentQuantity + " | ";
                    if(pos != 0) {
                        orderMenu += "\n";
                    }
                    orderMenu += currentQuantity + " " + currentMenu;
                }

                orderViewHolder.orderMenu.setText(orderMenu);
                orderViewHolder.setItemClickListener(new ItemClickListener() {
                    @Override
                    public void onClick(View view, int position, boolean isLongClick) {
                        //Empty -> just to fix crash because of context menu
                    }
                });
            }
        };

        adapter.notifyDataSetChanged();
        recyclerView.setAdapter(adapter);

    }
</code>```

OrderViewHolder.java

```<code>public class OrderViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnCreateContextMenuListener{

    public TextView orderID;
    public TextView orderStatus;
    public TextView orderMenu;

    private ItemClickListener itemClickListener;

    public OrderViewHolder(@NonNull View itemView) {
        super(itemView);
        orderID = (TextView) itemView.findViewById(R.id.orderID);
        orderStatus = (TextView) itemView.findViewById(R.id.orderStatus);
        orderMenu = (TextView) itemView.findViewById(R.id.orderMenu);
        itemView.setOnClickListener(this);
        itemView.setOnCreateContextMenuListener(this);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        menu.setHeaderTitle("Select an action");
        menu.add(0, 0, getAdapterPosition(), "Update");
        menu.add(0, 1, getAdapterPosition(), "Delete");

    }

    public void setItemClickListener(ItemClickListener itemClickListener) {
        this.itemClickListener = itemClickListener;
    }

    @Override
    public void onClick(View v) {
        //No onClick => otherwise it throws an error.
        //itemClickListener.onClick(v, getAdapterPosition(), false);
    }

}
</code>```

Request.java

```<code>public class Request {
    private String email;
    private String name;
    private List<Order> order;
    private String restriction;
    private String status;

    public Request() { }

    public Request(String email, String name, String restriction, List<Order> order) {
        this.email = email;
        this.name = name;
        this.restriction = restriction;
        this.order = order;
        this.status = "0";          //0: Placed. 1: Ready. 2: Picked up.
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }
    public String getRestriction() {
        return restriction;
    }
    public void setRestriction(String restriction) {
        this.restriction = restriction;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public List<Order> getOrder() {
        return order;
    }
    public void setOrder(List<Order> order) {
        this.order = order;
    }
}
</code>```

答:
I eventually found a solution. Continuing that route with the current database schema I had didn't seem like a viable option so I worked on restructuring what that looked like. Using the regular .orderByChild(restaurantID).equalTo("01") worked from there.

Something I was about to explore if this did not work out was building my own Adapter & ViewHolder and find some way of retrieving the needed data with Firebase's ValueListener.

Body:
I did some reading on my problem & while a lot of people pointed to using DataSnapshot.forEach() to solve my issue, I would like to know if it's possible to modify my query inside FirebaseRecyclerAdapter to fit my needs.

This is the structure I currently have where a Request may have 1 or many Orders. Each Order comes with its set of values such as restaurantID.
I want to basically iterate through all those requests & only display the ones that have an order with a certain restaurantID.

In my application, the user logs in & has a value for restaurantID. I want to show inside my RecyclerView only the orders that are related to that account, based on that value.

Below is the code. I tried to do some funny stuff in populateViewHolder() to fix this with ordersForThisRestaurant but it did not quite work out. I would love any help on this, I have been stuck & wasn't able to make any progress for some time. Would be awesome to advance!

THANK YOU!

OrderStatus.java

public class OrderStatus extends AppCompatActivity {

    RecyclerView recyclerView;
    RecyclerView.LayoutManager layoutManager;

    FirebaseRecyclerAdapter<Request, OrderViewHolder> adapter;

    FirebaseDatabase database;
    DatabaseReference requests;

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

        //Initialize the Firebase database.
        database = FirebaseDatabase.getInstance();
        requests = database.getReference("Requests");

        recyclerView = (RecyclerView) findViewById(R.id.recyclerOrder);
        recyclerView.setHasFixedSize(true);
        layoutManager = new GridLayoutManager(this, 2);
        recyclerView.setLayoutManager(layoutManager);

        loadOrders();
    }

    private void loadOrders() {
        adapter = new FirebaseRecyclerAdapter<Request, OrderViewHolder>(
                Request.class,
                R.layout.order_layout,
                OrderViewHolder.class,
                requests
        ) {
            @Override
            protected void populateViewHolder(OrderViewHolder orderViewHolder, Request request, int i) {
                List<Order> activeOrders = request.getOrder();
                List<Order> ordersForThisRestaurant = new ArrayList<>();
                for(int pos=0; pos<activeOrders.size(); pos++) {
                    Order currentOrder = activeOrders.get(pos);
                    String restaurantID = currentOrder.getRestaurantID();
                    if(restaurantID.equals(Common.currentUser.getRestaurantID())) {
                        ordersForThisRestaurant.add(activeOrders.get(pos));
                    }
                }
                if(ordersForThisRestaurant.size() == 0) return;     //This means the request was not for this restaurant.

                orderViewHolder.orderID.setText(adapter.getRef(i).getKey());
                orderViewHolder.orderStatus.setText(Common.convertCodeToStatus(request.getStatus()));
                String orderMenu = "";

                for(int pos=0; pos<ordersForThisRestaurant.size(); pos++) {
                    String currentMenu = ordersForThisRestaurant.get(pos).getMenuName();
                    String currentQuantity = ordersForThisRestaurant.get(pos).getQuantity();
                    //orderMenu += currentMenu + " x" + currentQuantity + " | ";
                    if(pos != 0) {
                        orderMenu += "\n";
                    }
                    orderMenu += currentQuantity + " " + currentMenu;
                }

                orderViewHolder.orderMenu.setText(orderMenu);
                orderViewHolder.setItemClickListener(new ItemClickListener() {
                    @Override
                    public void onClick(View view, int position, boolean isLongClick) {
                        //Empty -> just to fix crash because of context menu
                    }
                });
            }
        };

        adapter.notifyDataSetChanged();
        recyclerView.setAdapter(adapter);

    }

OrderViewHolder.java

public class OrderViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnCreateContextMenuListener{

    public TextView orderID;
    public TextView orderStatus;
    public TextView orderMenu;

    private ItemClickListener itemClickListener;

    public OrderViewHolder(@NonNull View itemView) {
        super(itemView);
        orderID = (TextView) itemView.findViewById(R.id.orderID);
        orderStatus = (TextView) itemView.findViewById(R.id.orderStatus);
        orderMenu = (TextView) itemView.findViewById(R.id.orderMenu);
        itemView.setOnClickListener(this);
        itemView.setOnCreateContextMenuListener(this);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        menu.setHeaderTitle("Select an action");
        menu.add(0, 0, getAdapterPosition(), "Update");
        menu.add(0, 1, getAdapterPosition(), "Delete");

    }

    public void setItemClickListener(ItemClickListener itemClickListener) {
        this.itemClickListener = itemClickListener;
    }

    @Override
    public void onClick(View v) {
        //No onClick => otherwise it throws an error.
        //itemClickListener.onClick(v, getAdapterPosition(), false);
    }

}

Request.java

public class Request {
    private String email;
    private String name;
    private List<Order> order;
    private String restriction;
    private String status;

    public Request() { }

    public Request(String email, String name, String restriction, List<Order> order) {
        this.email = email;
        this.name = name;
        this.restriction = restriction;
        this.order = order;
        this.status = "0";          //0: Placed. 1: Ready. 2: Picked up.
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }
    public String getRestriction() {
        return restriction;
    }
    public void setRestriction(String restriction) {
        this.restriction = restriction;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public List<Order> getOrder() {
        return order;
    }
    public void setOrder(List<Order> order) {
        this.order = order;
    }
}


问:
Accepting request from specific ip in Spring Boot
I referred this tutorial to restrict certain ip in jboss and Spring Boot application.
http://www.mastertheboss.com/jboss-web/jbosswebserver/how-to-restrict-access-to-jboss-web-application-by-ip-or-host

But the tutorial is not complete. Where should I place those codes? Are there any other methods to do that?

If any one know any other methods please mention that here. Thanks in advance.

答:
IMO the Valves mentioned in tutorial are the ways to customize tomcat embedded into the Jboss application. Note that this tutorial is really old - from 2014, probably JBoss has changed since then.

I remember back that times JBoss indeed included Tomcat inside to handle the web requests, so probably there was some kind of server.xml of tomcat.

Now, there are other ways:

Place the application behind some proxy that would restrict the access. Probably its the best approach if your environment supports that.

Use filters inside the application. You can create a web filter and register it in spring boot application regardless whether its a Jar with embedded server or WAR that you're planning to deploy on JBoss. This can be really flexible but on the other hand it includes some java coding and will consume some resources of your application. You can use this approach if you don't have spring security in your application and you don't want to introduce one, otherwise read (3).

Kind of paraphrase on 2 but used with spring security, that has the filtering facility built in: here is how you can do that. Note that besides the actual Java code used for implementation, 3 and 2 are pretty similar.


问:
Invariant Violation: Element type is invalid: expected a string , or a class/function , but got: undefined
App.js:

```<code>import React from 'react';
import Home from './screens/home';
import Navigator from './routes/drawer';
import Login from './screens/login';

export default class App extends React.Component{

    render() {
        if (false) {
            return (
                <Navigator />
            );
        } else {
            return (
                <Login />
            );
        }
    }
}
</code>```

login.js:

```<code>import React, {View, Text} from 'react';

export default class Login extends React.Component {

    render() {
        return (
            <View style={{ padding: 20 }}>
                <Text>Some text</Text>
            </View>
        )
    }
}
</code>```

This program gives me the error in the title, this DOES work for the Navigator but not for the Login (when the if is set to true instead of false the program runs correctly.) The Navigator acts as a typical drawer container for an android app, but at the bottom of the imports everything appears to act the same as for rendering options. The full error log is below...

```<code>Invariant Violation: Element type is invalid: expected a string (for built in components) or a class/function (for composite components) but got: undefined.
You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named exports.

Check the render method of 'Login'.

This error is located at:
in Login...
in App...RCTView...AppContainer...
</code>```

答:
Check your Login.js file. Some imports are wrong!

Check the components and API inside React Native here

SOLUTION

Remove imports View and Text from react

```<code>import React from 'react';
import { View, Text } from 'react-native';

export default class Login extends React.Component {

    render() {
        return (
            <View style={{ padding: 20 }}>
                <Text>Some text</Text>
            </View>
        )
    }
}
</code>```

Body:
App.js:

import React from 'react';
import Home from './screens/home';
import Navigator from './routes/drawer';
import Login from './screens/login';

export default class App extends React.Component{

    render() {
        if (false) {
            return (
                <Navigator />
            );
        } else {
            return (
                <Login />
            );
        }
    }
}

login.js:

import React, {View, Text} from 'react';

export default class Login extends React.Component {

    render() {
        return (
            <View style={{ padding: 20 }}>
                <Text>Some text</Text>
            </View>
        )
    }
}

This program gives me the error in the title, this DOES work for the Navigator but not for the Login (when the if is set to true instead of false the program runs correctly.) The Navigator acts as a typical drawer container for an android app, but at the bottom of the imports everything appears to act the same as for rendering options. The full error log is below...

Invariant Violation: Element type is invalid: expected a string (for built in components) or a class/function (for composite components) but got: undefined.
You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named exports.

Check the render method of 'Login'.

This error is located at:
in Login...
in App...RCTView...AppContainer...

Body:
Check your Login.js file. Some imports are wrong!

Check the components and API inside React Native here

SOLUTION

Remove imports View and Text from react

import React from 'react';
import { View, Text } from 'react-native';

export default class Login extends React.Component {

    render() {
        return (
            <View style={{ padding: 20 }}>
                <Text>Some text</Text>
            </View>
        )
    }
}


问:
Not getting all required docs(posts) of the logged in user - MongoDB/Node.js
I want to get the posts of the loggedin user and display on his feed. Right now instead, I'm getting all the posts by all users. I just want the user's posts to show.

User.js

const userSchema = new Schema({
    username: { type: String, required: true },
    email: { type: String, required: true },
    password: { type: String, required: true },
    posts: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: "Post"
    }]
}, { timestamps: true })
```

<p><strong>Post.js</strong></p>

<pre class="lang-js prettyprint-override"><code>const postSchema = new Schema({
  postTitle: { type: String, required: true },
  postDescription: { type: String, required: true },
  user: { type: Schema.Types.ObjectId, ref: "User" },
}, { timestamps: true }
)
</code>```

router.get("/posts/:id", usersController.getUserPosts)

usersController.js

    getUserPosts: (req, res) => {
        User.findById(req.params.id).populate("posts").exec((err, posts) => {
            if (err) console.log(err)
            console.log(posts)
        })
    }
```

<p>I'm getting this:</p>

<pre class="lang-js prettyprint-override"><code>{ posts: [],
  _id: 5e4e3e7eecd9a53c185117d4,
  username: 'rick',
  email: 'rick@gmail.com',
  createdAt: 2020-02-20T08:08:30.878Z,
  updatedAt: 2020-02-20T08:08:30.878Z,
  __v: 0 }
</code>```

答:
Try below code :</p>

```<code>const mongoose = require('mongoose');
const id = mongoose.Types.ObjectId(req.user.userId);

/** Assuming 'req.user._id' is a string & converting it into ObjectId() to match with user field, Also updated find syntax */

getUserPosts: (req, res) => {
    Post.find({ user: id }, (error, posts) => {
        if (error) console.log("error occurred"); /** return from here */
        if (posts.length) {
            console.log(
                "currentUser->", req.user,
                "posts by this user->", posts
            )
        } else {
            console.log('No posts found for given user')
        }
    })
}
</code>```

Body:
I want to get the posts of the loggedin user and display on his feed. Right now instead, I'm getting all the posts by all users. I just want the user's posts to show.

User.js

const userSchema = new Schema({
    username: { type: String, required: true },
    email: { type: String, required: true },
    password: { type: String, required: true },
    posts: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: "Post"
    }]
}, { timestamps: true })

Post.js

const postSchema = new Schema({
  postTitle: { type: String, required: true },
  postDescription: { type: String, required: true },
  user: { type: Schema.Types.ObjectId, ref: "User" },
}, { timestamps: true }
)

router.get("/posts/:id", usersController.getUserPosts)

usersController.js

    getUserPosts: (req, res) => {
        User.findById(req.params.id).populate("posts").exec((err, posts) => {
            if (err) console.log(err)
            console.log(posts)
        })
    }

I'm getting this:

{ posts: [],
  _id: 5e4e3e7eecd9a53c185117d4,
  username: 'rick',
  email: 'rick@gmail.com',
  createdAt: 2020-02-20T08:08:30.878Z,
  updatedAt: 2020-02-20T08:08:30.878Z,
  __v: 0 }

Body:
Try below code :

const mongoose = require('mongoose');
const id = mongoose.Types.ObjectId(req.user.userId);

/** Assuming 'req.user._id' is a string & converting it into ObjectId() to match with user field, Also updated find syntax */

getUserPosts: (req, res) => {
    Post.find({ user: id }, (error, posts) => {
        if (error) console.log("error occurred"); /** return from here */
        if (posts.length) {
            console.log(
                "currentUser->", req.user,
                "posts by this user->", posts
            )
        } else {
            console.log('No posts found for given user')
        }
    })
}


问:
Recyclerview DiffUtil Item Update
I have endless scroll in my recyclerview, so, it will update when there is new data. and i am using DiffUtil to update data in the recyclerview. DiffUtil does updates the data but whenever there is update data, recyclerview scroll to top and what it looks like is "using the notifydatasetchanged()". here is my DiffUtil and my adapter to update data.

```<code>class ProductDiffUtil(
    val oldProductList: List<ProductModel>, val newProductList: List<ProductModel>
) : DiffUtil.Callback() {

    override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
        return oldProductList[oldItemPosition].id == newProductList[newItemPosition].id
    }

    override fun getOldListSize(): Int = oldProductList.size

    override fun getNewListSize(): Int = newProductList.size

    override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
        return oldProductList[oldItemPosition] == newProductList[newItemPosition]
    }

    override fun getChangePayload(oldItemPosition: Int, newItemPosition: Int): Any? {
        return super.getChangePayload(oldItemPosition, newItemPosition)
    }
}
</code>```

Here is my adapter to update data

```<code>fun addProductList(productList: List<ProductModel>?) {
        val diffResult = DiffUtil.calculateDiff(ProductDiffUtil(this.productList, productList!!))
        this.productList.addAll(productList)
        diffResult.dispatchUpdatesTo(this)
    }
</code>```

please help me with this. it is working fine when i am using notifyItemRangeChanged()... so what should i use to update data in recyclerview for best practice.

https://drive.google.com/open?id=1SapXW2wusmTpyGCRA9fa0aSLCYNL1fzN

答:
Check if the layout manager has already been set and get the current scroll position. Like this:

```<code>var itemPostion= 0
if(myRecyclerView.layoutmanager != null){
  itemPostion = (myRecyclerView.layoutmanager as LinearLayoutManager)
.findFirstCompletelyVisibleItemPosition()
}
</code>```

You can have a look at this sample project on GitHub

Title: Recyclerview DiffUtil Item Update

Body:
I have endless scroll in my recyclerview, so, it will update when there is new data. and i am using DiffUtil to update data in the recyclerview. DiffUtil does updates the data but whenever there is update data, recyclerview scroll to top and what it looks like is "using the notifydatasetchanged()". here is my DiffUtil and my adapter to update data.

class ProductDiffUtil(
    val oldProductList: List<ProductModel>, val newProductList: List<ProductModel>
) : DiffUtil.Callback() {

    override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
        return oldProductList[oldItemPosition].id == newProductList[newItemPosition].id
    }

    override fun getOldListSize(): Int = oldProductList.size

    override fun getNewListSize(): Int = newProductList.size

    override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
        return oldProductList[oldItemPosition] == newProductList[newItemPosition]
    }

    override fun getChangePayload(oldItemPosition: Int, newItemPosition: Int): Any? {
        return super.getChangePayload(oldItemPosition, newItemPosition)
    }
}

Here is my adapter to update data

fun addProductList(productList: List<ProductModel>?) {
        val diffResult = DiffUtil.calculateDiff(ProductDiffUtil(this.productList, productList!!))
        this.productList.addAll(productList)
        diffResult.dispatchUpdatesTo(this)
    }

please help me with this. it is working fine when i am using notifyItemRangeChanged()... so what should i use to update data in recyclerview for best practice.

https://drive.google.com/open?id=1SapXW2wusmTpyGCRA9fa0aSLCYNL1fzN

Body:
Check if the layout manager has already been set and get the current scroll position. Like this:

var itemPostion= 0
if(myRecyclerView.layoutmanager != null){
  itemPostion = (myRecyclerView.layoutmanager as LinearLayoutManager)
.findFirstCompletelyVisibleItemPosition()
}

You can have a look at this sample project on GitHub


问:
RecyclerView is cutting off the last item
I have a fragment with a toolbar and a recyclerView inside it.

I am populating the recyclerView with dummy data and then try to show them. For some reason, the last element of the recyclerView is getting cut-off.

This is the XML of the fragment:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/background_1"
    android:fitsSystemWindows="true">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar_layout"
        android:layout_width="match_parent"
        android:layout_height="@dimen/height_of_app_bar"
        android:fitsSystemWindows="true"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsing_toolbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            app:contentScrim="@color/primary"
            app:expandedTitleMarginEnd="64dp"
            app:expandedTitleMarginStart="48dp"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

            <ImageView
                android:id="@+id/backdrop"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:fitsSystemWindows="true"
                android:scaleType="centerCrop"
                android:src="@drawable/placeholder_rect_header"
                app:layout_collapseMode="parallax"/>

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_collapseMode="pin"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

        </android.support.design.widget.CollapsingToolbarLayout>

    </android.support.design.widget.AppBarLayout>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/simpleList"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

</android.support.design.widget.CoordinatorLayout>
</code>```

The items at the list are really simple ones:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="200dp"
    android:background="@color/background_1"
    android:orientation="horizontal"
    android:padding="@dimen/space_for_a_bit_of_air">

    <ImageView
        android:id="@+id/album_cover"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_gravity="center_vertical"
        android:scaleType="fitXY"
        android:src="@drawable/placeholder_album_cover"/>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:layout_marginLeft="@dimen/space_for_distinguishing_stuff"
        android:orientation="vertical">

        <TextView
            android:id="@+id/album_title"
            style="@style/titleText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/sample_text_c"/>

        <TextView
            android:id="@+id/album_year"
            style="@style/subtitleText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/sample_text_a"/>

    </LinearLayout>

</LinearLayout>
</code>```

I am now at the end of the list, but the last element still looks cut-off.

I am using the latest version as of 2015-09-23 of google libraries, 23.0.1, (i.e. com.android.support:recyclerview-v7:23.0.1), and the following configuration at the build.gradle:

```<code>compileSdkVersion 23
buildToolsVersion "23.0.1"

defaultConfig {
   minSdkVersion 14
   targetSdkVersion 23
   versionCode 1
   versionName "1.0"

   multiDexEnabled true// Enabling multidex support
 }
</code>```

Any help would be greatly appreciated since I am going nuts with this problem :(

SOLUTION

Ok, after cleaning the code to the bare essentials and removing complexity, I found the problem: it was a combination of wrong flags and missing or extra attributes. The following works fine for both Android 4.x and 5.x:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/background_1"
    android:fitsSystemWindows="true">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar_layout"
        android:layout_width="match_parent"
        android:layout_height="@dimen/height_of_app_bar"
        android:fitsSystemWindows="true">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsing_toolbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            app:collapsedTitleTextAppearance="@style/Title.collapsed"
            app:contentScrim="@color/primary"
            app:expandedTitleMarginStart="48dp"
            app:expandedTitleTextAppearance="@style/Title.Expanded"
            app:layout_scrollFlags="scroll|enterAlways|enterAlwaysCollapsed">

            <ImageView
                android:id="@+id/backdrop"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:fitsSystemWindows="true"
                android:scaleType="centerCrop"
                android:src="@drawable/artistic_4"
                app:layout_collapseMode="parallax"/>

            <View
                android:layout_width="match_parent"
                android:layout_height="@dimen/height_of_app_bar"
                android:background="@drawable/gradient"/>

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_collapseMode="pin"/>

        </android.support.design.widget.CollapsingToolbarLayout>

    </android.support.design.widget.AppBarLayout>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/simpleList"
        style="@style/genericRecyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        tools:listitem="@layout/item_discography_album"/>

</android.support.design.widget.CoordinatorLayout>
</code>```

In a nutshell, android:fitsSystemWindows="true" should only be at the coordinatorLayout, AppBarLayout and theCollapsingToolbarLayout (which are the ones that we want to be adjusted based on the screen on Android 5.x), the app:layout_scrollFlags should be set to "scroll|enterAlways|enterAlwaysCollapsed" and the toolbar should have as height, the height of the actionBar. Finally, it's better to keep the RecyclerView as clean as possible so you can control the layout spacing at each line item.

答:
I was facing the same issue and what I did is created a LinearLayout and placed my RecyclerView inside it and it solved my issue. I hope this will solve other issue as well.

```<code> <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="0dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/companyLabelView">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/companiesRecyclerView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="@dimen/_8dp"
        android:layout_marginStart="@dimen/_8sdp"
        android:layout_marginLeft="@dimen/_8sdp"
        android:layout_marginTop="@dimen/_8sdp"
        android:layout_marginEnd="@dimen/_8sdp"
        android:layout_marginRight="@dimen/_8sdp"
        android:layout_marginBottom="@dimen/_8sdp"
        android:overScrollMode="never"
        app:layoutManager="androidx.recyclerview.widget.GridLayoutManager"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:spanCount="3"
        tools:itemCount="10"
        tools:listitem="@layout/company_item_view" />

</LinearLayout>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a fragment with a toolbar and a recyclerView inside it.

I am populating the recyclerView with dummy data and then try to show them. For some reason, the last element of the recyclerView is getting cut-off.

This is the XML of the fragment:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/background_1"
    android:fitsSystemWindows="true">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar_layout"
        android:layout_width="match_parent"
        android:layout_height="@dimen/height_of_app_bar"
        android:fitsSystemWindows="true"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsing_toolbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            app:contentScrim="@color/primary"
            app:expandedTitleMarginEnd="64dp"
            app:expandedTitleMarginStart="48dp"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

            <ImageView
                android:id="@+id/backdrop"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:fitsSystemWindows="true"
                android:scaleType="centerCrop"
                android:src="@drawable/placeholder_rect_header"
                app:layout_collapseMode="parallax"/>

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_collapseMode="pin"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

        </android.support.design.widget.CollapsingToolbarLayout>

    </android.support.design.widget.AppBarLayout>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/simpleList"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

</android.support.design.widget.CoordinatorLayout>

The items at the list are really simple ones:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="200dp"
    android:background="@color/background_1"
    android:orientation="horizontal"
    android:padding="@dimen/space_for_a_bit_of_air">

    <ImageView
        android:id="@+id/album_cover"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_gravity="center_vertical"
        android:scaleType="fitXY"
        android:src="@drawable/placeholder_album_cover"/>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:layout_marginLeft="@dimen/space_for_distinguishing_stuff"
        android:orientation="vertical">

        <TextView
            android:id="@+id/album_title"
            style="@style/titleText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/sample_text_c"/>

        <TextView
            android:id="@+id/album_year"
            style="@style/subtitleText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/sample_text_a"/>

    </LinearLayout>

</LinearLayout>

I am now at the end of the list, but the last element still looks cut-off.

I am using the latest version as of 2015-09-23 of google libraries, 23.0.1, (i.e. com.android.support:recyclerview-v7:23.0.1), and the following configuration at the build.gradle:

compileSdkVersion 23
buildToolsVersion "23.0.1"

defaultConfig {
   minSdkVersion 14
   targetSdkVersion 23
   versionCode 1
   versionName "1.0"

   multiDexEnabled true// Enabling multidex support
 }

Any help would be greatly appreciated since I am going nuts with this problem :(

SOLUTION

Ok, after cleaning the code to the bare essentials and removing complexity, I found the problem: it was a combination of wrong flags and missing or extra attributes. The following works fine for both Android 4.x and 5.x:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/background_1"
    android:fitsSystemWindows="true">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar_layout"
        android:layout_width="match_parent"
        android:layout_height="@dimen/height_of_app_bar"
        android:fitsSystemWindows="true">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsing_toolbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            app:collapsedTitleTextAppearance="@style/Title.collapsed"
            app:contentScrim="@color/primary"
            app:expandedTitleMarginStart="48dp"
            app:expandedTitleTextAppearance="@style/Title.Expanded"
            app:layout_scrollFlags="scroll|enterAlways|enterAlwaysCollapsed">

            <ImageView
                android:id="@+id/backdrop"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:fitsSystemWindows="true"
                android:scaleType="centerCrop"
                android:src="@drawable/artistic_4"
                app:layout_collapseMode="parallax"/>

            <View
                android:layout_width="match_parent"
                android:layout_height="@dimen/height_of_app_bar"
                android:background="@drawable/gradient"/>

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_collapseMode="pin"/>

        </android.support.design.widget.CollapsingToolbarLayout>

    </android.support.design.widget.AppBarLayout>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/simpleList"
        style="@style/genericRecyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        tools:listitem="@layout/item_discography_album"/>

</android.support.design.widget.CoordinatorLayout>

In a nutshell, android:fitsSystemWindows="true" should only be at the coordinatorLayout, AppBarLayout and theCollapsingToolbarLayout (which are the ones that we want to be adjusted based on the screen on Android 5.x), the app:layout_scrollFlags should be set to "scroll|enterAlways|enterAlwaysCollapsed" and the toolbar should have as height, the height of the actionBar. Finally, it's better to keep the RecyclerView as clean as possible so you can control the layout spacing at each line item.

Body:
I was facing the same issue and what I did is created a LinearLayout and placed my RecyclerView inside it and it solved my issue. I hope this will solve other issue as well.

 <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="0dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/companyLabelView">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/companiesRecyclerView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="@dimen/_8dp"
        android:layout_marginStart="@dimen/_8sdp"
        android:layout_marginLeft="@dimen/_8sdp"
        android:layout_marginTop="@dimen/_8sdp"
        android:layout_marginEnd="@dimen/_8sdp"
        android:layout_marginRight="@dimen/_8sdp"
        android:layout_marginBottom="@dimen/_8sdp"
        android:overScrollMode="never"
        app:layoutManager="androidx.recyclerview.widget.GridLayoutManager"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:spanCount="3"
        tools:itemCount="10"
        tools:listitem="@layout/company_item_view" />

</LinearLayout>


问:
Call bootstrap alert with jquery
I'm trying to call a bootstrap alert with jQuery while meeting some if statements.

Here is my code in HTML:

Attention

You haven't select the metrial you need

Are you going to check next step anyway?

    <button type="button" class="btn btn-primary">Yes</button>
    <button type="button" class="btn btn-secondary">No</button>

```

<p>here is my code for jQuery:</p>

<pre class="lang-js prettyprint-override"><code>if ($("#checkbox1").prop('checked')==false){
    $(".alert").addClass('in');
    return false;
}
</code>```

I want to call this alert while one specific checkbox is not checked as I wrote above.

I also want to mention: I used $(".alert").hide(); to hide my alert when the page is loaded – not sure if that's correct.

I want to know how to call this alert when specific conditions are met and how to hide it properly.

Thanks

答:
Add d-none and remove show class when checkbox is checked so these two classes are predefined in Bootstrap4.

$('#checkbox1').on('change', function(){
  if($(this).is(':checked')) {
    $('#myAlert').removeClass('show').addClass('d-none');
  }
  else {
    $('#myAlert').removeClass('d-none').addClass('show');
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>

<div class="container my-3">
  <div class="row">
    <div class="col-sm-12">
      <label class="custom-control custom-checkbox">
        <input type="checkbox" class="custom-control-input" id="checkbox1">
        <div class="custom-control-label">Are you sure?</div>
      </label>
      <div class="alert alert-warning fade show" role="alert" id="myAlert">
        <h4 class="alert-heading">Attention</h4>
        <p>You haven't select the metrial you need</p>
        <hr>
        <p class="mb-0">Are you going to check next step anyway?</p>
        <button type="button" class="btn btn-primary">Yes</button>
        <button type="button" class="btn btn-secondary">No</button>
      </div>
      <p>
        Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo onsequat.
      </p>
    </div>
  </div>
</div></code>```

Title: Call bootstrap alert with jquery

Body:
I'm trying to call a bootstrap alert with jQuery while meeting some if statements.

Here is my code in HTML:

Attention

You haven't select the metrial you need

Are you going to check next step anyway?

    <button type="button" class="btn btn-primary">Yes</button>
    <button type="button" class="btn btn-secondary">No</button>

here is my code for jQuery:

if ($("#checkbox1").prop('checked')==false){
    $(".alert").addClass('in');
    return false;
}

I want to call this alert while one specific checkbox is not checked as I wrote above.

I also want to mention: I used $(".alert").hide(); to hide my alert when the page is loaded – not sure if that's correct.

I want to know how to call this alert when specific conditions are met and how to hide it properly.

Thanks

Body:
Add d-none and remove show class when checkbox is checked so these two classes are predefined in Bootstrap4.

$('#checkbox1').on('change', function(){
  if($(this).is(':checked')) {
    $('#myAlert').removeClass('show').addClass('d-none');
  }
  else {
    $('#myAlert').removeClass('d-none').addClass('show');
  }
});

<link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>

<div class="container my-3">
  <div class="row">
    <div class="col-sm-12">
      <label class="custom-control custom-checkbox">
        <input type="checkbox" class="custom-control-input" id="checkbox1">
        <div class="custom-control-label">Are you sure?</div>
      </label>
      <div class="alert alert-warning fade show" role="alert" id="myAlert">
        <h4 class="alert-heading">Attention</h4>
        <p>You haven't select the metrial you need</p>
        <hr>
        <p class="mb-0">Are you going to check next step anyway?</p>
        <button type="button" class="btn btn-primary">Yes</button>
        <button type="button" class="btn btn-secondary">No</button>
      </div>
      <p>
        Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo onsequat.
      </p>
    </div>
  </div>
</div>


问:
How do I test a method in Django which closes the database connection?
I have a long running Python process which uses the Django ORM. It looks something like this:

```<code>import django
from django.db import connection

from my_app import models

def my_process():
    django.setup()
    while (True):
        do_stuff()
        connection.close()
        models.MyDjangoModel().save()
</code>```

Sometimes do_stuff takes a really long time, at which point I was running into an error where my MySql connection timed out because the database server killed the connection as idle. Adding the connection.close() line forces django to get a new connection every time and fixes that issue. (See https://code.djangoproject.com/ticket/21597).

However, I am testing this process using a django.test.TestCase, and calling connection.close causes those tests to fail, as django's TestCase class wraps the test in a transaction, and closing the connection within that transaction causes the transaction to break and raises a django.db.transaction.TransactionManagementError.

One attempt at resolving this issue I tried is setting the CONN_MAX_AGE database parameter and calling connection.close_if_unusable_or_obsolete instead, but the transaction also changes the connection's autocommit setting from the settings' default value of True to False which in turn causes close_if_unusable_or_obsolete to try and close the connection anyway (https://github.com/django/django/blob/master/django/db/backends/base/base.py#L497).

I guess I could also mock connection.close in test so it does nothing, but that seems kind of hacky.

What is the best way to test a django method which needs to close the database connection?

答:
Instead of modifying myprocess function you can inherit your Test class from TransactionTestCase which doesn't wrap your test function in transaction atomic block in the first place. If you are keen about having the transaction atomic in your test function then wrap it only around where you need it.

```<code>class Test(TransactionTestCase):
     def test_function(self):
         do_stuff()
         with transaction.atomic():
             your_transaction_atomic_test()
         my_process()
         do_other_stuff()
</code>```

ps: Inheriting your Test class from TestCase will wrap your total test function with transaction atomic block.

Body:
I have a long running Python process which uses the Django ORM. It looks something like this:

import django
from django.db import connection

from my_app import models

def my_process():
    django.setup()
    while (True):
        do_stuff()
        connection.close()
        models.MyDjangoModel().save()

Sometimes do_stuff takes a really long time, at which point I was running into an error where my MySql connection timed out because the database server killed the connection as idle. Adding the connection.close() line forces django to get a new connection every time and fixes that issue. (See https://code.djangoproject.com/ticket/21597).

However, I am testing this process using a django.test.TestCase, and calling connection.close causes those tests to fail, as django's TestCase class wraps the test in a transaction, and closing the connection within that transaction causes the transaction to break and raises a django.db.transaction.TransactionManagementError.

One attempt at resolving this issue I tried is setting the CONN_MAX_AGE database parameter and calling connection.close_if_unusable_or_obsolete instead, but the transaction also changes the connection's autocommit setting from the settings' default value of True to False which in turn causes close_if_unusable_or_obsolete to try and close the connection anyway (https://github.com/django/django/blob/master/django/db/backends/base/base.py#L497).

I guess I could also mock connection.close in test so it does nothing, but that seems kind of hacky.

What is the best way to test a django method which needs to close the database connection?

Body:
Instead of modifying myprocess function you can inherit your Test class from TransactionTestCase which doesn't wrap your test function in transaction atomic block in the first place. If you are keen about having the transaction atomic in your test function then wrap it only around where you need it.

class Test(TransactionTestCase):
     def test_function(self):
         do_stuff()
         with transaction.atomic():
             your_transaction_atomic_test()
         my_process()
         do_other_stuff()

ps: Inheriting your Test class from TestCase will wrap your total test function with transaction atomic block.


问:
Work item access for non visual-studio users
We're using TFS for source control and are trialling using the TFS work item tracking. I am trying to find out, is it possible for people who don't have visual studio installed to access, create and edit work items via a browser based user interface?

Our technical support team need to be able to use work items. TFS work items won't be suitable for our company if the support team and project managers can't get sufficient access.

I'm not familiar with how the licensing works either. If there is a way for non visual studio users to use TFS work items, will they need a license?

答: Team System Web Access is a good web-based option for non-visual studio users.</p>

OwnerDisplayName: Scott Langham

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Scott Langham

OwnerDisplayName: Chris Ballance


问:
Data type for large amounts of text?
I'm developing a Java package that makes basic HTTP requests (GET, POST, PUT, and DELETE). Right now, I'm having it just print the output of the request. I would like to store it in a field, but I'm not sure if String supports large amounts of text. Is there a data type for large amounts of text, or is there a reasonable alternative to it? Right now, because I'm just printing it, I can't do anything with the data that is returned (like parse it, if it's JSON).

Any ideas would be helpful.

Edit: The code is online on GitHub.

答: Strings can take up to 2^31 - 1 characters so I suspect are big enough. Data from SO question</p>

Title: Data type for large amounts of text?


问:
How to structure a Microservice solution
When I'm thinking about creating a Microservice solution.

Should I create a different project for my Domain? Maybe my question should be if I must share common projects between different solutions.

The benefit of it will be other Microservice could share this Domain project.

This is often my approach to a monolithic project. I normally create a project for Domain where I add Models and DTOs. Also, I have a project for some common classes.

This is my first Microservice solution and I'm not sure about how to approach it, I already had a look on this post. But I'm not convinced yet.

答:
This is very general,  but I can share a couple of thoughts.

9/10 cases,  would not require sharing dtos and models or dals. This is because microservices are meant to be independent of each other, with their own models and databases.

For horizontal aspects, maybe you will need them,  but it's better to use other providers to do your logging, notifications and such

Yes, some contacts could be shareable in the nuget or any other packaging format, when one domain model adheres fully to another domain and they are communicating with each other.

As a general rule, if you need a microservices architecture, try to go the full way. Learn about domain driven design, learn about the advantages of said structure and let them be an option even if you don't use them.

Remember, microservices are meant to be written by individual teams, possibly using different technologies and programming frameworks.


问:
FireFox 72.0.2 on Mac Stuck in "Remote Control" mode
72.0.2 (64-bit) on MacOS 10.14.6 (18G3020)
Ran a python selenium script for automation and after that FF still shows the orange stripes bar and an icon which says "Browser is under remote control"

Rebooted machine but no luck.
Is there way to take out FF in normal mode now?

(Not able to access saved logins in this mode)

Thanks!

答:
This did the trick.

Setup FireFox sync account

Create a new empty profile and make it default

Restart FF with that profile

Login to FF sync and get back bookmarks/saved logins etc.

Now FF is auto-filling passwords again.

Strange thing is that address bar still shows slanted orange/light orange stripes and "Browser is under remote control" but works like regular browser.


问:
Regex not giving output as desired
I am using the regex - [{]{[}][}] for the input {{id}}
The output I expect is id. But I am getting {{id}}.

My java code is as below:

```<code>  String string = "\"{\n" +
                "    \"id\": {{dsm_id}},\n" +
                "    \"title\": \"Automation Test\",\n" +
                "    \"code\": \"aut_test\",\n" +
                "    \"companyId\": 286,\n" +
                "    \"enabled\": true,\n" +
                "    \"enableAdvanceFilter\": false,\n" +
                "    \"deleteAfterScheduledTime\": false,\n" +
                "    \"enableDataStoreLog\": false\n" +
                "}\"";
        String patternString = "[{][{](.*)[}][}]";
        Pattern pattern = Pattern.compile(patternString);
        Matcher matcher = pattern.matcher(string);
        List<String> allMatches = new ArrayList<String>();
        while (matcher.find()) {
            allMatches.add(matcher.group());
        }
        System.out.println(allMatches);
</code>```

The only solution I need is having the right regex. I cannot use or don't want to use DTO or Json parser here.

答:
It will be better to convert it to object and then you can find whatever you need.

Create DTO object

```<code>    public class DsmDto{
     private String id;
     private String title;
     private String code;
     private float companyId;
     private boolean enabled;
     private boolean enableAdvanceFilter;
     private boolean deleteAfterScheduledTime;
     private boolean enableDataStoreLog;

     // Getter Methods

     public String getId() {
      return id;
     }

     public String getTitle() {
      return title;
     }

     public String getCode() {
      return code;
     }

     public float getCompanyId() {
      return companyId;
     }

     public boolean getEnabled() {
      return enabled;
     }

     public boolean getEnableAdvanceFilter() {
      return enableAdvanceFilter;
     }

     public boolean getDeleteAfterScheduledTime() {
      return deleteAfterScheduledTime;
     }

     public boolean getEnableDataStoreLog() {
      return enableDataStoreLog;
     }

     // Setter Methods

     public void setId(String id) {
      this.id = id;
     }

     public void setTitle(String title) {
      this.title = title;
     }

     public void setCode(String code) {
      this.code = code;
     }

     public void setCompanyId(float companyId) {
      this.companyId = companyId;
     }

     public void setEnabled(boolean enabled) {
      this.enabled = enabled;
     }

     public void setEnableAdvanceFilter(boolean enableAdvanceFilter) {
      this.enableAdvanceFilter = enableAdvanceFilter;
     }

     public void setDeleteAfterScheduledTime(boolean deleteAfterScheduledTime) {
      this.deleteAfterScheduledTime = deleteAfterScheduledTime;
     }

     public void setEnableDataStoreLog(boolean enableDataStoreLog) {
      this.enableDataStoreLog = enableDataStoreLog;
     }
    }
</code>```

Create converter class and convert method

```<code>public class DmsConverter{

ObjectMapper mapper = new ObjectMapper();

public static DsmDto jsonToDsm(String json){
    return mapper.readValue(json, DsmDto.class);
}

}
</code>```

Usage:

```<code>DsmDto dsmDto = DsmConverter.jsonToDsm(json);
System.out.println(dsmDto.getId());
</code>```

Title: Regex not giving output as desired

Body:
I am using the regex - [{]{[}][}] for the input {{id}}
The output I expect is id. But I am getting {{id}}.

My java code is as below:

  String string = "\"{\n" +
                "    \"id\": {{dsm_id}},\n" +
                "    \"title\": \"Automation Test\",\n" +
                "    \"code\": \"aut_test\",\n" +
                "    \"companyId\": 286,\n" +
                "    \"enabled\": true,\n" +
                "    \"enableAdvanceFilter\": false,\n" +
                "    \"deleteAfterScheduledTime\": false,\n" +
                "    \"enableDataStoreLog\": false\n" +
                "}\"";
        String patternString = "[{][{](.*)[}][}]";
        Pattern pattern = Pattern.compile(patternString);
        Matcher matcher = pattern.matcher(string);
        List<String> allMatches = new ArrayList<String>();
        while (matcher.find()) {
            allMatches.add(matcher.group());
        }
        System.out.println(allMatches);

The only solution I need is having the right regex. I cannot use or don't want to use DTO or Json parser here.

Body:
It will be better to convert it to object and then you can find whatever you need.

Create DTO object

    public class DsmDto{
     private String id;
     private String title;
     private String code;
     private float companyId;
     private boolean enabled;
     private boolean enableAdvanceFilter;
     private boolean deleteAfterScheduledTime;
     private boolean enableDataStoreLog;

     // Getter Methods

     public String getId() {
      return id;
     }

     public String getTitle() {
      return title;
     }

     public String getCode() {
      return code;
     }

     public float getCompanyId() {
      return companyId;
     }

     public boolean getEnabled() {
      return enabled;
     }

     public boolean getEnableAdvanceFilter() {
      return enableAdvanceFilter;
     }

     public boolean getDeleteAfterScheduledTime() {
      return deleteAfterScheduledTime;
     }

     public boolean getEnableDataStoreLog() {
      return enableDataStoreLog;
     }

     // Setter Methods

     public void setId(String id) {
      this.id = id;
     }

     public void setTitle(String title) {
      this.title = title;
     }

     public void setCode(String code) {
      this.code = code;
     }

     public void setCompanyId(float companyId) {
      this.companyId = companyId;
     }

     public void setEnabled(boolean enabled) {
      this.enabled = enabled;
     }

     public void setEnableAdvanceFilter(boolean enableAdvanceFilter) {
      this.enableAdvanceFilter = enableAdvanceFilter;
     }

     public void setDeleteAfterScheduledTime(boolean deleteAfterScheduledTime) {
      this.deleteAfterScheduledTime = deleteAfterScheduledTime;
     }

     public void setEnableDataStoreLog(boolean enableDataStoreLog) {
      this.enableDataStoreLog = enableDataStoreLog;
     }
    }

Create converter class and convert method

public class DmsConverter{

ObjectMapper mapper = new ObjectMapper();

public static DsmDto jsonToDsm(String json){
    return mapper.readValue(json, DsmDto.class);
}

}

Usage:

DsmDto dsmDto = DsmConverter.jsonToDsm(json);
System.out.println(dsmDto.getId());


问:
How do I write a method that has the same implementation for multiple kinds of objects (Java)?
I am writing a (currently) String-based Pokemon game in Java. With the structure I have, there are currently 2 kinds of objects that I want to do Type matchups for: Pokemon and moves. The method I want to write (isStrongAgainst()) would be the same for both. For example, a water type pokemon and a water type move are strong against fire type Pokemon, but these comparisons can imply different things based on context. Both classes have differently implemented isType() methods.

The idea I had was to use an interface that implements a default isStrongAgainst() method and declares an abstract isType() method. I would think that since any class that implements this interface would have to implement isType(), I could use it in my isStrongAgainst(), but I cannot. Is there any way around this or a better suggestion given my problem?

```<code>public interface TypeMatch<T> {
    boolean isType(Type t);
    default boolean isStrongAgainst(Pokemon opponent){
        if(T.isType(Type.NORMAL)){
            return false;
        }
        if(T.isType(Type.WATER)){
            return opponent.isType(Type.FIRE) ||
                    opponent.isType(Type.ROCK) ||
                    opponent.isType(Type.GROUND);
        } //etc...
</code>```

答:
You may:

define Pokemon as an abstract class to implement TypeMatch

move isStrongAgainst(Pokemon opponent) from TypeMatch to Pokemon.

any class that extends Pokemon has the same implementation of isStrongAgainst(Pokemon opponent)

Body:
I am writing a (currently) String-based Pokemon game in Java. With the structure I have, there are currently 2 kinds of objects that I want to do Type matchups for: Pokemon and moves. The method I want to write (isStrongAgainst()) would be the same for both. For example, a water type pokemon and a water type move are strong against fire type Pokemon, but these comparisons can imply different things based on context. Both classes have differently implemented isType() methods.

The idea I had was to use an interface that implements a default isStrongAgainst() method and declares an abstract isType() method. I would think that since any class that implements this interface would have to implement isType(), I could use it in my isStrongAgainst(), but I cannot. Is there any way around this or a better suggestion given my problem?

public interface TypeMatch<T> {
    boolean isType(Type t);
    default boolean isStrongAgainst(Pokemon opponent){
        if(T.isType(Type.NORMAL)){
            return false;
        }
        if(T.isType(Type.WATER)){
            return opponent.isType(Type.FIRE) ||
                    opponent.isType(Type.ROCK) ||
                    opponent.isType(Type.GROUND);
        } //etc...


问:
WebView in CoordinatorLayout with CollapsingToolbarLayout
I'd like to add a WebView in a CoordinatorLayout, having CollapsingToolbarLayout in AppBarLayout.
The problem is that WebView shrinks in height and doesn't fill the space below the toolbar, making it not usable.
I tried also to use WebView as child of NestedScrollView: initially it doesn't work (it shrinks my WebView in height), but scrolling my shrinked WebView makes it fill viewport.

Here is the layout I used:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    android:id="@+id/main_content"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="256dp"
        android:fitsSystemWindows="true"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsing_toolbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            app:contentScrim="?attr/colorPrimary"
            app:expandedTitleMarginEnd="64dp"
            app:expandedTitleMarginStart="48dp"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

            <ImageView
                android:id="@+id/backdrop"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:fitsSystemWindows="true"
                android:scaleType="centerCrop"
                app:layout_collapseMode="parallax" />

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_collapseMode="pin"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

        </android.support.design.widget.CollapsingToolbarLayout>

    </android.support.design.widget.AppBarLayout>

    <android.support.v4.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <WebView
            android:id="@+id/article"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </android.support.v4.widget.NestedScrollView>
</android.support.design.widget.CoordinatorLayout>
</code>```

答:
this works for me. </p>

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

    <com.google.android.material.appbar.AppBarLayout
        android:id="@+id/app_bar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fitsSystemWindows="true">

        <com.google.android.material.appbar.CollapsingToolbarLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@color/backgroundColor"
            android:fitsSystemWindows="true"
            app:layout_scrollFlags="scroll|enterAlways|snap">

            <FrameLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="bottom">

                <androidx.appcompat.widget.AppCompatImageButton
                    android:id="@+id/back_bt"
                    android:layout_width="48dp"
                    android:layout_height="48dp"
                    android:background="@color/transparent"
                    android:src="@drawable/ic_arrow_back_black_24dp" />
            </FrameLayout>

        </com.google.android.material.appbar.CollapsingToolbarLayout>

    </com.google.android.material.appbar.AppBarLayout>

    <androidx.core.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fillViewport="false"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <WebView
                android:id="@+id/web_view"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />
        </LinearLayout>
    </androidx.core.widget.NestedScrollView>

</androidx.coordinatorlayout.widget.CoordinatorLayout>
</code>```

Body:
I'd like to add a WebView in a CoordinatorLayout, having CollapsingToolbarLayout in AppBarLayout.
The problem is that WebView shrinks in height and doesn't fill the space below the toolbar, making it not usable.
I tried also to use WebView as child of NestedScrollView: initially it doesn't work (it shrinks my WebView in height), but scrolling my shrinked WebView makes it fill viewport.

Here is the layout I used:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    android:id="@+id/main_content"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="256dp"
        android:fitsSystemWindows="true"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsing_toolbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            app:contentScrim="?attr/colorPrimary"
            app:expandedTitleMarginEnd="64dp"
            app:expandedTitleMarginStart="48dp"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

            <ImageView
                android:id="@+id/backdrop"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:fitsSystemWindows="true"
                android:scaleType="centerCrop"
                app:layout_collapseMode="parallax" />

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_collapseMode="pin"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

        </android.support.design.widget.CollapsingToolbarLayout>

    </android.support.design.widget.AppBarLayout>

    <android.support.v4.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <WebView
            android:id="@+id/article"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </android.support.v4.widget.NestedScrollView>
</android.support.design.widget.CoordinatorLayout>

Body:
this works for me.

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <com.google.android.material.appbar.AppBarLayout
        android:id="@+id/app_bar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fitsSystemWindows="true">

        <com.google.android.material.appbar.CollapsingToolbarLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@color/backgroundColor"
            android:fitsSystemWindows="true"
            app:layout_scrollFlags="scroll|enterAlways|snap">

            <FrameLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="bottom">

                <androidx.appcompat.widget.AppCompatImageButton
                    android:id="@+id/back_bt"
                    android:layout_width="48dp"
                    android:layout_height="48dp"
                    android:background="@color/transparent"
                    android:src="@drawable/ic_arrow_back_black_24dp" />
            </FrameLayout>

        </com.google.android.material.appbar.CollapsingToolbarLayout>

    </com.google.android.material.appbar.AppBarLayout>

    <androidx.core.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fillViewport="false"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <WebView
                android:id="@+id/web_view"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />
        </LinearLayout>
    </androidx.core.widget.NestedScrollView>

</androidx.coordinatorlayout.widget.CoordinatorLayout>


问:
Best practice to record large amount of hits into MySQL database
Well, this is the thing. Let's say that my future PHP CMS need to drive 500k visitors daily and I need to record them all in MySQL database (referrer, ip address, time etc.). This way I need to insert 300-500 rows per minute and update 50 more. The main problem is that script would call database every time I want to insert new row, which is every time someone hits a page.

My question, is there any way to locally cache incoming hits first (and what is the best solution for that apc, csv...?) and periodically send them to database every 10 minutes for example? Is this good solution and what is the best practice for this situation?

答: For an high number of write operations and this kind of data you might find more suitable mongodb or couchdb</p>


问:
Can I run only a specific container in detach mode with docker-compose?
I'm running three containers consisting of mongo, express, and react using docker-compose.

While I run them by docker-compose, what I need to watch is only the output of express container. So I want to run the mongo container in detach mode.

I'm aware of there is a command to run docker-compose in detach mode, docker-compose up -d
However, what I want to do is not to run whole containers in detach mode, but to run some specific containers in detach mode.

Is there any way to handle this?

答:
You can start your distributed application in detached mode with

```<code>docker-compose up -d
</code>```

and follow only the logs that you are interested in with

```<code>docker-compose logs -f express
</code>```

This way any dependencies defined in the docker-compose.yml e.g. dependencies services have to one other are maintained and containers are started in an appropriate order.

Body:
You can start your distributed application in detached mode with

docker-compose up -d

and follow only the logs that you are interested in with

docker-compose logs -f express

This way any dependencies defined in the docker-compose.yml e.g. dependencies services have to one other are maintained and containers are started in an appropriate order.


问:
Override PHPFox non-core modules/installed apps
I would like to override a non-core module of PHPFox,so basically, it is an installed 3rd party application developed by PHPFox themeselves. Here is the file I would like to override.

PF.Site/Apps/core-comments/views/block/comment.html.php

Anyway, I was able to override core modules in my theme following the naming convention from their documentation like the Feeds Module.

答:
Did you mean you'd like to override above file with the file in your module?
In the library, at step render template file, there is a hook. You can use this hook in your module and change above the to the file you want.</p>


问:
Replacing a checkbox element with icons
I want to customize the browser checkbox. When the status is checked, the icon checked.svg should be displayed instead of checkbox and the icon unchecked.svg otherwise.

Here is my code.
HTML:

```<code><div class="checkbox-custom">
   <input type="checkbox"/>
      <div class="checkmark">
          <img src="@/assets/images/icons/checkbox/unchecked.svg" class="unchecked"/>
          <img src="@/assets/images/icons/checkbox/checked.svg" class="checked"/>
    </div>
</div>
</code>```

SASS:

```<code>.checkbox-custom {
    position: absolute;
    width: 28px;
    height: 28px;
    left: 0;
    top: 0;

    // Hide default browser checkbox
    input[type=checkbox] {
                display: none;
            }

   input[type=checkbox] + .checkmark {
        position: absolute;
        left: 3.5px;
        top: 3.5px;
        right: 3.5px;
        bottom: 3.5px;

        display: inline-block;
        cursor: pointer;

        img {
            width: 21px;
            height: 21px;
        }

        .checked {
            display: none;
        }
    }

    input[type=checkbox]:checked + .checkmark {
        .checked {
            display: block;
        }

        .unchecked {
            display: none;
        }
    }
 }
</code>```

When i click on the checkbox, nothing happens. What could be the error?

答:
http://jsfiddle.net/pKM3x/

CSS:

```<code>.checkbox{
    width: 23px;
    height: 21px;
     background: transparent url(http://i.stack.imgur.com/S4p2R.png ) no-repeat 0 50%
}
.checked{
    background: transparent url(http://i.stack.imgur.com/S4p2R.png ) no-repeat 80% 50%
}
</code>```

HTML:

```<code><div class="checkbox">
</div>
</code>```

JQUERY:

```<code>$(".checkbox").click(function(){
    $(this).toggleClass('checked')
});
</code>```

This also possible to do with pure JS.

Title: Replacing a checkbox element with icons

Body:
I want to customize the browser checkbox. When the status is checked, the icon checked.svg should be displayed instead of checkbox and the icon unchecked.svg otherwise.

Here is my code.
HTML:

   <input type="checkbox"/>

SASS:

.checkbox-custom {
    position: absolute;
    width: 28px;
    height: 28px;
    left: 0;
    top: 0;

    // Hide default browser checkbox
    input[type=checkbox] {
                display: none;
            }

   input[type=checkbox] + .checkmark {
        position: absolute;
        left: 3.5px;
        top: 3.5px;
        right: 3.5px;
        bottom: 3.5px;

        display: inline-block;
        cursor: pointer;

        img {
            width: 21px;
            height: 21px;
        }

        .checked {
            display: none;
        }
    }

    input[type=checkbox]:checked + .checkmark {
        .checked {
            display: block;
        }

        .unchecked {
            display: none;
        }
    }
 }

When i click on the checkbox, nothing happens. What could be the error?

Body:
http://jsfiddle.net/pKM3x/

CSS:

.checkbox{
    width: 23px;
    height: 21px;
     background: transparent url(http://i.stack.imgur.com/S4p2R.png ) no-repeat 0 50%
}
.checked{
    background: transparent url(http://i.stack.imgur.com/S4p2R.png ) no-repeat 80% 50%
}

HTML:

<div class="checkbox">
</div>

JQUERY:

$(".checkbox").click(function(){
    $(this).toggleClass('checked')
});

This also possible to do with pure JS.


问:
Cartesian Product of PCollection with itself
Say I have a bounded PCollection p of type KV<String, Integer>. Assume p cannot fit in memory, and therefore cannot be a side input of a DoFn.

Example p:

```<code>("foo", 0)
("bar", 1)
("baz", 2)
</code>```

How can I take the cartesian product of p and itself?

For example, p x p may look as follows:

```<code>("foo+foo", [("foo", 0), ("foo", 0)])
("foo+bar", [("foo", 0), ("bar", 1)])
("foo+baz", [("foo", 0), ("baz", 2)])
("bar+foo", [("bar", 1), ("foo", 0)])
("bar+bar", [("bar", 1), ("bar", 1)])
("bar+baz", [("bar", 1), ("baz", 2)])
("baz+foo", [("baz", 2), ("foo", 0)])
("baz+bar", [("baz", 2), ("bar", 1)])
("baz+baz", [("baz", 2), ("baz", 2)])
</code>```

答:
I will propose a solution using Python.

In the first place, let's implement the algorithm and after that resolve the problems with the memory limitation

```<code>import itertools

# Let's build a list with your pairs
collection_items = [("foo", 0), ("bar", 1), ("baz", 2)]

"""
A Python generator is a function that produces a sequence of results.
It works by maintaining its local state, so that the function can resume again exactly where
it left off when called subsequent times. Same generator can't be used twice.
I will explain a little later why I use generators
"""

collection_generator1 = (el for el in collection_items)  # Create the first generator
# For example; calling next(collection_generator1) => ("foo", 0); next(collection_generator1) => ("bar", 1),
# next(collection_generator1) => ("bar": 2)
collection_generator2 = (el for el in collection_items) # Create the second generator
cartesian_product = itertools.product(collection_generator1, collection_generator2) # Create the cartesian product

for pair in cartesian_product:
    first_el, second_el = pair
    str_pair1, val_pair1 = first_el
    str_pair2, val_pair2 = first_el

    name = "{str_pair1}+{str_pair2}".format(str_pair1=str_pair1, str_pair2=str_pair2)
    item = (name, [first_el, second_el]) # Compose the item
    print(item)

# OUTPUT

('foo+foo', [('foo', 0), ('foo', 0)])
('foo+foo', [('foo', 0), ('bar', 1)])
('foo+foo', [('foo', 0), ('baz', 2)])
('bar+bar', [('bar', 1), ('foo', 0)])
('bar+bar', [('bar', 1), ('bar', 1)])
('bar+bar', [('bar', 1), ('baz', 2)])
('baz+baz', [('baz', 2), ('foo', 0)])
('baz+baz', [('baz', 2), ('bar', 1)])
('baz+baz', [('baz', 2), ('baz', 2)])
</code>```

Now let's solve the problems with memory

Since you have a lot of data, a good idea would be to store them in a file, writing a pair on each line (as in you example)
Now let's read the file ("input.txt") and create a generator with its data.

```<code>file_generator_1 = (line.strip() for line in open("input.txt"))
file_generator_2 = (line.strip() for line in open("input.txt").readlines())
</code>```

Now, the only modification you have to do is to replace the variables name collection_generator1, collection_generator2 to file_generator_1, file_generator_2

Body:
Say I have a bounded PCollection p of type KV<String, Integer>. Assume p cannot fit in memory, and therefore cannot be a side input of a DoFn.

Example p:

("foo", 0)
("bar", 1)
("baz", 2)

How can I take the cartesian product of p and itself?

For example, p x p may look as follows:

("foo+foo", [("foo", 0), ("foo", 0)])
("foo+bar", [("foo", 0), ("bar", 1)])
("foo+baz", [("foo", 0), ("baz", 2)])
("bar+foo", [("bar", 1), ("foo", 0)])
("bar+bar", [("bar", 1), ("bar", 1)])
("bar+baz", [("bar", 1), ("baz", 2)])
("baz+foo", [("baz", 2), ("foo", 0)])
("baz+bar", [("baz", 2), ("bar", 1)])
("baz+baz", [("baz", 2), ("baz", 2)])

Body:
I will propose a solution using Python.

In the first place, let's implement the algorithm and after that resolve the problems with the memory limitation

import itertools

# Let's build a list with your pairs
collection_items = [("foo", 0), ("bar", 1), ("baz", 2)]

"""
A Python generator is a function that produces a sequence of results.
It works by maintaining its local state, so that the function can resume again exactly where
it left off when called subsequent times. Same generator can't be used twice.
I will explain a little later why I use generators
"""

collection_generator1 = (el for el in collection_items)  # Create the first generator
# For example; calling next(collection_generator1) => ("foo", 0); next(collection_generator1) => ("bar", 1),
# next(collection_generator1) => ("bar": 2)
collection_generator2 = (el for el in collection_items) # Create the second generator
cartesian_product = itertools.product(collection_generator1, collection_generator2) # Create the cartesian product

for pair in cartesian_product:
    first_el, second_el = pair
    str_pair1, val_pair1 = first_el
    str_pair2, val_pair2 = first_el

    name = "{str_pair1}+{str_pair2}".format(str_pair1=str_pair1, str_pair2=str_pair2)
    item = (name, [first_el, second_el]) # Compose the item
    print(item)

# OUTPUT

('foo+foo', [('foo', 0), ('foo', 0)])
('foo+foo', [('foo', 0), ('bar', 1)])
('foo+foo', [('foo', 0), ('baz', 2)])
('bar+bar', [('bar', 1), ('foo', 0)])
('bar+bar', [('bar', 1), ('bar', 1)])
('bar+bar', [('bar', 1), ('baz', 2)])
('baz+baz', [('baz', 2), ('foo', 0)])
('baz+baz', [('baz', 2), ('bar', 1)])
('baz+baz', [('baz', 2), ('baz', 2)])

Now let's solve the problems with memory

Since you have a lot of data, a good idea would be to store them in a file, writing a pair on each line (as in you example)
Now let's read the file ("input.txt") and create a generator with its data.

file_generator_1 = (line.strip() for line in open("input.txt"))
file_generator_2 = (line.strip() for line in open("input.txt").readlines())

Now, the only modification you have to do is to replace the variables name collection_generator1, collection_generator2 to file_generator_1, file_generator_2


问:
How can I get the array length in nlohmann's json library?
I am using nlohmann/json lib and want to get the length of a json array. Image i have:

```<code>[
"test",
"test2"
]
</code>```

and want to recieve the length (2). When i tried the .length() method, it showed me this error:

using json = using json = class nlohmann::basic_json<>' {aka 'class nlohmann::basic_json<>'} has no member named 'length

so how can I get the length in this library?

答: You want to use myJsonArray.size() method here.

Body:
I am using nlohmann/json lib and want to get the length of a json array. Image i have:

[
"test",
"test2"
]

and want to recieve the length (2). When i tried the .length() method, it showed me this error:

using json = using json = class nlohmann::basic_json<>' {aka 'class nlohmann::basic_json<>'} has no member named 'length

so how can I get the length in this library?


问:
How would I find the row and column length of this matrix? (Python)
I'm given a matrix from a file that looks like this:

```<code>1 1 0 0 0 1 0 0 1 0 0 0 0 0 0 0

0 0 0 0 1 1 0 1 0 0 1 0 0 0 0 0

0 0 1 1 0 0 0 1 0 0 1 0 0 1 0 0

0 0 1 1 0 0 0 1 0 1 0 0 0 1 0 0

0 0 1 0 1 0 0 1 0 1 0 0 0 1 0 0

0 0 1 0 1 0 0 1 0 1 1 1 1 1 0 0

0 0 0 0 1 0 0 1 0 0 0 0 0 1 0 0

0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0

0 0 0 0 1 0 0 0 0 1 1 1 0 0 1 0

0 0 0 0 1 0 0 0 0 1 0 0 0 1 1 0

1 1 1 1 1 0 0 1 1 1 0 0 0 0 G 0
</code>```

The goal is to be able to read in the matrix to another function and also find the row and column length. I'm also not trying to import any additional libraries. Here's what I have so far:

```<code>    with open('matrix.txt','r') as txt:
        data = txt.readlines()

    for row in data:
        print(row)
        for column in row:
            print(column)
</code>```

答:
```<code>with open('data.txt', 'r') as fp:
    row  = 0
    for line in fp:
        if line in ['\n', '\r\n']:
            continue
        row += 1
    arr = list(map(str,line.split(' ')))
    col = len(arr)

print(row,col)
</code>```

For each line we are incrementing row counter and for col we are checking how many characters are there in one line by splitting the line according to separator : ' ' .

Body:
I'm given a matrix from a file that looks like this:

1 1 0 0 0 1 0 0 1 0 0 0 0 0 0 0

0 0 0 0 1 1 0 1 0 0 1 0 0 0 0 0

0 0 1 1 0 0 0 1 0 0 1 0 0 1 0 0

0 0 1 1 0 0 0 1 0 1 0 0 0 1 0 0

0 0 1 0 1 0 0 1 0 1 0 0 0 1 0 0

0 0 1 0 1 0 0 1 0 1 1 1 1 1 0 0

0 0 0 0 1 0 0 1 0 0 0 0 0 1 0 0

0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0

0 0 0 0 1 0 0 0 0 1 1 1 0 0 1 0

0 0 0 0 1 0 0 0 0 1 0 0 0 1 1 0

1 1 1 1 1 0 0 1 1 1 0 0 0 0 G 0

The goal is to be able to read in the matrix to another function and also find the row and column length. I'm also not trying to import any additional libraries. Here's what I have so far:

    with open('matrix.txt','r') as txt:
        data = txt.readlines()

    for row in data:
        print(row)
        for column in row:
            print(column)

Body:
with open('data.txt', 'r') as fp:
    row  = 0
    for line in fp:
        if line in ['\n', '\r\n']:
            continue
        row += 1
    arr = list(map(str,line.split(' ')))
    col = len(arr)

print(row,col)

For each line we are incrementing row counter and for col we are checking how many characters are there in one line by splitting the line according to separator : ' ' .