问:
Issue using ScrollListener to pull data from Firebase Realtime DB when user scrolls to the bottom of a RecyclerView
I have an application that pulls object data from a Firebase Realtime DB, adds it to an ArrayList, which is then added to a RecyclerView. I utilize an onScrollListener on my RecyclerView so that when a user scrolls to the bottom of the RecyclerView, a function is called to pull more data from Firebase, add it to the ArrayList and notify the RecyclerViewAdapter of the Data set change.

When I run my application, it presents the initial pull of data in my RecyclerView, then immediately begins calling the function to fetch more data from my DB continuously until there is no more data left to pull and my RecyclerView is updated with this data; this occurs regardless of whether I scroll(in any direction/of any magnitude) or not.

Ideally, I would want the application to only pull data if the user scrolled to the bottom of the RecyclerView, and to do so one pull at a time. I'm having a very hard time debugging this issue as the logic seems to be correct; any help would be immensely appreciated.

Relevant global variables

RecyclerView rvVertical;
RecyclerViewAdapter rvaVertical;
long mTotalChildren = 0;
int mLastKey = 0;

ChildEventListener childEventListenerMain, childEventListenerPager;
boolean Loading = false;

private ArrayList<BlogObject> blogArray = new ArrayList<>();
private ArrayList<BlogObject> tempList = new ArrayList<>();
```

<p>View loaded</p>

<pre class="lang-java prettyprint-override"><code>@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    final View view = inflater.inflate(R.layout.socialmediatab, container, false);

    rvVertical = (RecyclerView) view.findViewById(R.id.bloglistRecyclerView);
    Loading = true;
    Log.d(TAG, "onCreateView - Loading = " + Loading);
    firstEventListener();
    regAdapterVertical();

    addOnScrollListener();
    return view;
}
</code>```

First function that gets called. initializes the first pull of data from Firebase

private void firstEventListener() {

    FirebaseDatabase.getInstance().getReference().child("blogs").addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            mTotalChildren = dataSnapshot.getChildrenCount();
        }
        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) { }
    });

    final Query BlogQuery = FirebaseDatabase.getInstance().getReference().child("blogs").orderByChild("createdAt").limitToLast(3);

    childEventListenerMain = new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot ds, String s) {
            Loading = true;
            Log.d(TAG, "First get blogs instance - Loading = " + Loading);
            BlogObject addblog = ds.getValue(BlogObject.class);

            if (addblog != null) {
                BlogObject addBlog = new BlogObject(ds.getValue(BlogObject.class).getImage(), ds.getValue(BlogObject.class).getTitle(), ds.getValue(BlogObject.class).getTimeStamp(), ds.getValue(BlogObject.class).getCreatedAt());
                blogArray.add(addBlog);
                rvaVertical.notifyDataSetChanged();
                mLastKey = blogArray.get(0).getCreatedAt();
                rvVertical.scrollToPosition(blogArray.size() - 1);
            }
        }
        @Override
        public void onChildChanged(DataSnapshot dataSnapshot, String s) { }

        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) { }

        @Override
        public void onChildMoved(DataSnapshot dataSnapshot, String s) { }

        @Override
        public void onCancelled(DatabaseError databaseError) { }
    };

    BlogQuery.addChildEventListener(childEventListenerMain);
    ValueEventListener BlogChildSingleListener = new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            Loading = false;
        }
        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) { }
    };

    BlogQuery.addListenerForSingleValueEvent(BlogChildSingleListener);
}
```

<p>Adding the Scroll Listener to my Recycler View. Ideally, it is only supposed to fetch more data from Firebase if and only if the user scrolls to the bottom of the RecyclerView</p>

<pre class="lang-java prettyprint-override"><code>private void addOnScrollListener() {
    rvVertical.addOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
        }

        @Override
        public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
            Log.d(TAG, "Just Entered onScrolled and Loading = " + Loading);
            super.onScrolled(recyclerView, dx, dy);

            if(!rvVertical.canScrollVertically(1)) {
                LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                if (blogArray.size() >= 3 && !Loading && linearLayoutManager.findLastCompletelyVisibleItemPosition() == blogArray.size() - 1 && blogArray.size() < mTotalChildren) {
                    Loading = true;
                    getMoreBlogs();
                    Log.d(TAG, "Right After getMoreBlogs gets called. Loading = " + Loading);
                }
            }
        }
    });
}
</code>```

Initializing Adapter with first pull of data

private void regAdapterVertical() {
    LinearSnapHelper linearSnapHelper = new SnapHelperOneByOne();
    linearSnapHelper.attachToRecyclerView(rvVertical);
    rvaVertical = new RecyclerViewAdapter(blogArray);
    rvVertical.setAdapter(rvaVertical);
    rvVertical.setLayoutManager((RecyclerView.LayoutManager) new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
}
```

<p>This is my function to pull more data from Firebase. It gets called in my Scroll Listener</p>

<pre class="lang-java prettyprint-override"><code>public void getMoreBlogs() {
    tempList.clear();

    Query getMoreQuery = FirebaseDatabase.getInstance().getReference().child("blogs").orderByChild("createdAt").endAt(mLastKey).limitToLast(3);
    childEventListenerPager = new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot ds, String s) {
            Loading = true;
            BlogObject blogObject = ds.getValue(BlogObject.class);
            if (blogObject != null) {
                BlogObject addBlog = new BlogObject(ds.getValue(BlogObject.class).getImage(), ds.getValue(BlogObject.class).getTitle(), ds.getValue(BlogObject.class).getTimeStamp(), ds.getValue(BlogObject.class).getCreatedAt());
                tempList.add(addBlog);
            }
        }

        @Override
        public void onChildChanged(DataSnapshot dataSnapshot, String s) { }

        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) { }

        @Override
        public void onChildMoved(DataSnapshot dataSnapshot, String s) { }

        @Override
        public void onCancelled(DatabaseError databaseError) { }
    };

    getMoreQuery.addChildEventListener(childEventListenerPager);

    ValueEventListener addtoAdapter = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            tempList.remove(tempList.size() - 1);
            blogArray.addAll(0, tempList);
            mLastKey = blogArray.get(0).getCreatedAt();
            rvaVertical.notifyDataSetChanged();
            Loading = false;
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    };

    getMoreQuery.addListenerForSingleValueEvent(addtoAdapter);
}
}
</code>```

This is my Logcat of Loading(boolean), that I kept track of throughout the program because I believe it was a main part of the issue. I have attached it below:

```<code>2019-05-30 10:26:14.590 24930-24970/com.yourgesture.newsocialmediatab I/FirebaseAuth: [FirebaseAuth:] Loading module via FirebaseOptions.
2019-05-30 10:26:14.956 24930-24930/com.yourgesture.newsocialmediatab D/Social Media Tab: onCreateView - Loading = true
2019-05-30 10:26:16.399 24930-24930/com.yourgesture.newsocialmediatab D/Social Media Tab: First get blogs instance - Loading = true
2019-05-30 10:26:16.406 24930-24930/com.yourgesture.newsocialmediatab D/Social Media Tab: First get blogs instance - Loading = true
2019-05-30 10:26:16.534 24930-24930/com.yourgesture.newsocialmediatab D/Social Media Tab: Just Entered onScrolled and Loading = false
2019-05-30 10:26:16.539 24930-24930/com.yourgesture.newsocialmediatab D/Social Media Tab: Right After getMoreBlogs gets called. Loading = true
2019-05-30 10:26:16.663 24930-24930/com.yourgesture.newsocialmediatab D/Social Media Tab: Just Entered onScrolled and Loading = false
2019-05-30 10:26:16.666 24930-24930/com.yourgesture.newsocialmediatab D/Social Media Tab: Right After getMoreBlogs gets called. Loading = true
2019-05-30 10:26:16.826 24930-24930/com.yourgesture.newsocialmediatab D/Social Media Tab: Just Entered onScrolled and Loading = false
2019-05-30 10:26:16.828 24930-24930/com.yourgesture.newsocialmediatab D/Social Media Tab: Right After getMoreBlogs gets called. Loading = true
2019-05-30 10:26:16.976 24930-24930/com.yourgesture.newsocialmediatab D/Social Media Tab: Just Entered onScrolled and Loading = false
2019-05-30 10:26:16.977 24930-24930/com.yourgesture.newsocialmediatab D/Social Media Tab: Right After getMoreBlogs gets called. Loading = true
2019-05-30 10:26:17.229 24930-24930/com.yourgesture.newsocialmediatab D/Social Media Tab: Just Entered onScrolled and Loading = false
</code>```

答:
In Your firstEventListener() ,

getReference().child("blogs")
will actually fetches whole child data , which will be considered as read operation, even if you are not using it.

So there will be no any data saving in your approach.

Let me share one of the approach:

```<code>private void getUsers(String nodeId) {
    Query query;

    if (nodeId == null)
        query = FirebaseDatabase.getInstance().getReference()
                .child(Consts.FIREBASE_DATABASE_LOCATION_USERS)
                .orderByKey()
                .limitToFirst(mPostsPerPage);
    else
        query = FirebaseDatabase.getInstance().getReference()
                .child(Consts.FIREBASE_DATABASE_LOCATION_USERS)
                .orderByKey()
                .startAt(nodeId)
                .limitToFirst(mPostsPerPage);

    query.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            UserModel user;
            List<UserModel> userModels = new ArrayList<>();
            for (DataSnapshot userSnapshot : dataSnapshot.getChildren()) {
                userModels.add(userSnapshot.getValue(UserModel.class));
            }

            mAdapter.addAll(userModels);
            mIsLoading = false;
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            mIsLoading = false;
        }
    });
}
</code>```

Three new variables are important in the above function:
mPostsPerPage: It is the Integer constant defined in the MainActivity.java class which specifies how many records will be queried per page.

mIsLoading: It is a boolean defined in the MainActivity that is used to keep track of whether the Firebase Database query is in progress or not.

Consts.FIREBASE_DATABASE_LOCATION_USERS: It is the constant defined in the Consts.java class where simply the location of the “users” node is stored

Ref: https://blog.shajeelafzal.com/2017/12/13/firebase-realtime-database-pagination-guide-using-recyclerview/

Body:
I have an application that pulls object data from a Firebase Realtime DB, adds it to an ArrayList, which is then added to a RecyclerView. I utilize an onScrollListener on my RecyclerView so that when a user scrolls to the bottom of the RecyclerView, a function is called to pull more data from Firebase, add it to the ArrayList and notify the RecyclerViewAdapter of the Data set change.

When I run my application, it presents the initial pull of data in my RecyclerView, then immediately begins calling the function to fetch more data from my DB continuously until there is no more data left to pull and my RecyclerView is updated with this data; this occurs regardless of whether I scroll(in any direction/of any magnitude) or not.

Ideally, I would want the application to only pull data if the user scrolled to the bottom of the RecyclerView, and to do so one pull at a time. I'm having a very hard time debugging this issue as the logic seems to be correct; any help would be immensely appreciated.

Relevant global variables

RecyclerView rvVertical;
RecyclerViewAdapter rvaVertical;
long mTotalChildren = 0;
int mLastKey = 0;

ChildEventListener childEventListenerMain, childEventListenerPager;
boolean Loading = false;

private ArrayList<BlogObject> blogArray = new ArrayList<>();
private ArrayList<BlogObject> tempList = new ArrayList<>();

View loaded

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    final View view = inflater.inflate(R.layout.socialmediatab, container, false);

    rvVertical = (RecyclerView) view.findViewById(R.id.bloglistRecyclerView);
    Loading = true;
    Log.d(TAG, "onCreateView - Loading = " + Loading);
    firstEventListener();
    regAdapterVertical();

    addOnScrollListener();
    return view;
}

First function that gets called. initializes the first pull of data from Firebase

private void firstEventListener() {

    FirebaseDatabase.getInstance().getReference().child("blogs").addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            mTotalChildren = dataSnapshot.getChildrenCount();
        }
        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) { }
    });

    final Query BlogQuery = FirebaseDatabase.getInstance().getReference().child("blogs").orderByChild("createdAt").limitToLast(3);

    childEventListenerMain = new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot ds, String s) {
            Loading = true;
            Log.d(TAG, "First get blogs instance - Loading = " + Loading);
            BlogObject addblog = ds.getValue(BlogObject.class);

            if (addblog != null) {
                BlogObject addBlog = new BlogObject(ds.getValue(BlogObject.class).getImage(), ds.getValue(BlogObject.class).getTitle(), ds.getValue(BlogObject.class).getTimeStamp(), ds.getValue(BlogObject.class).getCreatedAt());
                blogArray.add(addBlog);
                rvaVertical.notifyDataSetChanged();
                mLastKey = blogArray.get(0).getCreatedAt();
                rvVertical.scrollToPosition(blogArray.size() - 1);
            }
        }
        @Override
        public void onChildChanged(DataSnapshot dataSnapshot, String s) { }

        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) { }

        @Override
        public void onChildMoved(DataSnapshot dataSnapshot, String s) { }

        @Override
        public void onCancelled(DatabaseError databaseError) { }
    };

    BlogQuery.addChildEventListener(childEventListenerMain);
    ValueEventListener BlogChildSingleListener = new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            Loading = false;
        }
        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) { }
    };

    BlogQuery.addListenerForSingleValueEvent(BlogChildSingleListener);
}

Adding the Scroll Listener to my Recycler View. Ideally, it is only supposed to fetch more data from Firebase if and only if the user scrolls to the bottom of the RecyclerView

private void addOnScrollListener() {
    rvVertical.addOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
        }

        @Override
        public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
            Log.d(TAG, "Just Entered onScrolled and Loading = " + Loading);
            super.onScrolled(recyclerView, dx, dy);

            if(!rvVertical.canScrollVertically(1)) {
                LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                if (blogArray.size() >= 3 && !Loading && linearLayoutManager.findLastCompletelyVisibleItemPosition() == blogArray.size() - 1 && blogArray.size() < mTotalChildren) {
                    Loading = true;
                    getMoreBlogs();
                    Log.d(TAG, "Right After getMoreBlogs gets called. Loading = " + Loading);
                }
            }
        }
    });
}

Initializing Adapter with first pull of data

private void regAdapterVertical() {
    LinearSnapHelper linearSnapHelper = new SnapHelperOneByOne();
    linearSnapHelper.attachToRecyclerView(rvVertical);
    rvaVertical = new RecyclerViewAdapter(blogArray);
    rvVertical.setAdapter(rvaVertical);
    rvVertical.setLayoutManager((RecyclerView.LayoutManager) new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
}

This is my function to pull more data from Firebase. It gets called in my Scroll Listener

public void getMoreBlogs() {
    tempList.clear();

    Query getMoreQuery = FirebaseDatabase.getInstance().getReference().child("blogs").orderByChild("createdAt").endAt(mLastKey).limitToLast(3);
    childEventListenerPager = new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot ds, String s) {
            Loading = true;
            BlogObject blogObject = ds.getValue(BlogObject.class);
            if (blogObject != null) {
                BlogObject addBlog = new BlogObject(ds.getValue(BlogObject.class).getImage(), ds.getValue(BlogObject.class).getTitle(), ds.getValue(BlogObject.class).getTimeStamp(), ds.getValue(BlogObject.class).getCreatedAt());
                tempList.add(addBlog);
            }
        }

        @Override
        public void onChildChanged(DataSnapshot dataSnapshot, String s) { }

        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) { }

        @Override
        public void onChildMoved(DataSnapshot dataSnapshot, String s) { }

        @Override
        public void onCancelled(DatabaseError databaseError) { }
    };

    getMoreQuery.addChildEventListener(childEventListenerPager);

    ValueEventListener addtoAdapter = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            tempList.remove(tempList.size() - 1);
            blogArray.addAll(0, tempList);
            mLastKey = blogArray.get(0).getCreatedAt();
            rvaVertical.notifyDataSetChanged();
            Loading = false;
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    };

    getMoreQuery.addListenerForSingleValueEvent(addtoAdapter);
}
}

This is my Logcat of Loading(boolean), that I kept track of throughout the program because I believe it was a main part of the issue. I have attached it below:

2019-05-30 10:26:14.590 24930-24970/com.yourgesture.newsocialmediatab I/FirebaseAuth: [FirebaseAuth:] Loading module via FirebaseOptions.
2019-05-30 10:26:14.956 24930-24930/com.yourgesture.newsocialmediatab D/Social Media Tab: onCreateView - Loading = true
2019-05-30 10:26:16.399 24930-24930/com.yourgesture.newsocialmediatab D/Social Media Tab: First get blogs instance - Loading = true
2019-05-30 10:26:16.406 24930-24930/com.yourgesture.newsocialmediatab D/Social Media Tab: First get blogs instance - Loading = true
2019-05-30 10:26:16.534 24930-24930/com.yourgesture.newsocialmediatab D/Social Media Tab: Just Entered onScrolled and Loading = false
2019-05-30 10:26:16.539 24930-24930/com.yourgesture.newsocialmediatab D/Social Media Tab: Right After getMoreBlogs gets called. Loading = true
2019-05-30 10:26:16.663 24930-24930/com.yourgesture.newsocialmediatab D/Social Media Tab: Just Entered onScrolled and Loading = false
2019-05-30 10:26:16.666 24930-24930/com.yourgesture.newsocialmediatab D/Social Media Tab: Right After getMoreBlogs gets called. Loading = true
2019-05-30 10:26:16.826 24930-24930/com.yourgesture.newsocialmediatab D/Social Media Tab: Just Entered onScrolled and Loading = false
2019-05-30 10:26:16.828 24930-24930/com.yourgesture.newsocialmediatab D/Social Media Tab: Right After getMoreBlogs gets called. Loading = true
2019-05-30 10:26:16.976 24930-24930/com.yourgesture.newsocialmediatab D/Social Media Tab: Just Entered onScrolled and Loading = false
2019-05-30 10:26:16.977 24930-24930/com.yourgesture.newsocialmediatab D/Social Media Tab: Right After getMoreBlogs gets called. Loading = true
2019-05-30 10:26:17.229 24930-24930/com.yourgesture.newsocialmediatab D/Social Media Tab: Just Entered onScrolled and Loading = false

Body:
In Your firstEventListener() ,

getReference().child("blogs")
will actually fetches whole child data , which will be considered as read operation, even if you are not using it.

So there will be no any data saving in your approach.

Let me share one of the approach:

private void getUsers(String nodeId) {
    Query query;

    if (nodeId == null)
        query = FirebaseDatabase.getInstance().getReference()
                .child(Consts.FIREBASE_DATABASE_LOCATION_USERS)
                .orderByKey()
                .limitToFirst(mPostsPerPage);
    else
        query = FirebaseDatabase.getInstance().getReference()
                .child(Consts.FIREBASE_DATABASE_LOCATION_USERS)
                .orderByKey()
                .startAt(nodeId)
                .limitToFirst(mPostsPerPage);

    query.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            UserModel user;
            List<UserModel> userModels = new ArrayList<>();
            for (DataSnapshot userSnapshot : dataSnapshot.getChildren()) {
                userModels.add(userSnapshot.getValue(UserModel.class));
            }

            mAdapter.addAll(userModels);
            mIsLoading = false;
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            mIsLoading = false;
        }
    });
}

Three new variables are important in the above function:
mPostsPerPage: It is the Integer constant defined in the MainActivity.java class which specifies how many records will be queried per page.

mIsLoading: It is a boolean defined in the MainActivity that is used to keep track of whether the Firebase Database query is in progress or not.

Consts.FIREBASE_DATABASE_LOCATION_USERS: It is the constant defined in the Consts.java class where simply the location of the “users” node is stored

Ref: https://blog.shajeelafzal.com/2017/12/13/firebase-realtime-database-pagination-guide-using-recyclerview/


来源: stackexchange

问:
Installing node-argon2 in Windows
Little background

I was trying to install node-argon2 but having trouble installing it. I've been trying to download GCC, I already installed node-gyp as in the docs said.

However I keep failing on this step..

```<code>CXX=g++-6 npm install argon2
</code>```

I had no idea what that function did, and this what came out when I tried to launch that in my terminal.

```<code>> argon2@0.21.0 install C:\Users\BizCon\Projects\express-ticket\node_modules\argon2
> node-gyp rebuild

C:\Users\BizCon\Projects\express-ticket\node_modules\argon2>if not defined npm_config_node_gyp (node "C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\node-gyp-bin\\..\..\node_modules\node-gyp\bin\node-gyp.js" rebuild )  else (node "C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\bin\node-gyp.js" rebuild )
Building the projects in this solution one at a time. To enable parallel build, please add the "/m" switch.
C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V140\Platforms\x64\PlatformToolsets\v140\Toolset.targets(36,5): error MSB8036: The Windows SDK version 8.1 was not found. Install the required version of Windows SDK or change the SDK version in the project property pages or by right-clicking the solution and selecting "Retarget solution". [C:\Users\BizCon\Projects\express-ticket\node_modules\argon2\build\libargon2.vcxproj]
gyp ERR! build error
gyp ERR! stack Error: `C:\Program Files (x86)\MSBuild\14.0\bin\msbuild.exe` failed with exit code: 1
gyp ERR! stack     at ChildProcess.onExit (C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\build.js:262:23)
gyp ERR! stack     at emitTwo (events.js:126:13)
gyp ERR! stack     at ChildProcess.emit (events.js:214:7)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:198:12)
gyp ERR! System Windows_NT 10.0.17134
gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild"
gyp ERR! cwd C:\Users\BizCon\Projects\express-ticket\node_modules\argon2
gyp ERR! node -v v8.12.0
gyp ERR! node-gyp -v v3.8.0
gyp ERR! not ok
npm WARN babel-loader@8.0.5 requires a peer of @babel/core@^7.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN babel-loader@8.0.5 requires a peer of webpack@>=2 but none is installed. You must install peer dependencies yourself.
npm WARN express-server@1.0.0 No repository field.

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! argon2@0.21.0 install: `node-gyp rebuild`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the argon2@0.21.0 install script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
</code>```

答:
Before installing

You MUST have a node-gyp global install before proceeding with install, along with GCC >= 5 / Clang >= 3.3. On Windows, you must compile under Visual Studio 2015 or newer.

node-argon2 works only and is tested against Node >=8.0.0.

ContentLicense: CC BY-SA 4.0

Title: Installing node-argon2 in Windows

Body:
Little background

I was trying to install node-argon2 but having trouble installing it. I've been trying to download GCC, I already installed node-gyp as in the docs said.

However I keep failing on this step..

CXX=g++-6 npm install argon2

I had no idea what that function did, and this what came out when I tried to launch that in my terminal.

> argon2@0.21.0 install C:\Users\BizCon\Projects\express-ticket\node_modules\argon2
> node-gyp rebuild

C:\Users\BizCon\Projects\express-ticket\node_modules\argon2>if not defined npm_config_node_gyp (node "C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\node-gyp-bin\\..\..\node_modules\node-gyp\bin\node-gyp.js" rebuild )  else (node "C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\bin\node-gyp.js" rebuild )
Building the projects in this solution one at a time. To enable parallel build, please add the "/m" switch.
C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V140\Platforms\x64\PlatformToolsets\v140\Toolset.targets(36,5): error MSB8036: The Windows SDK version 8.1 was not found. Install the required version of Windows SDK or change the SDK version in the project property pages or by right-clicking the solution and selecting "Retarget solution". [C:\Users\BizCon\Projects\express-ticket\node_modules\argon2\build\libargon2.vcxproj]
gyp ERR! build error
gyp ERR! stack Error: `C:\Program Files (x86)\MSBuild\14.0\bin\msbuild.exe` failed with exit code: 1
gyp ERR! stack     at ChildProcess.onExit (C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\build.js:262:23)
gyp ERR! stack     at emitTwo (events.js:126:13)
gyp ERR! stack     at ChildProcess.emit (events.js:214:7)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:198:12)
gyp ERR! System Windows_NT 10.0.17134
gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild"
gyp ERR! cwd C:\Users\BizCon\Projects\express-ticket\node_modules\argon2
gyp ERR! node -v v8.12.0
gyp ERR! node-gyp -v v3.8.0
gyp ERR! not ok
npm WARN babel-loader@8.0.5 requires a peer of @babel/core@^7.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN babel-loader@8.0.5 requires a peer of webpack@>=2 but none is installed. You must install peer dependencies yourself.
npm WARN express-server@1.0.0 No repository field.

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! argon2@0.21.0 install: `node-gyp rebuild`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the argon2@0.21.0 install script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.


问:
@Html.DisplayNameForModel() don't work when Property is nullable
If you create an underlying model with a Propery of DateTime? (nullable) using DisplayNameForModel or LabelForModel will render empty

Using DotNet Core 2.2 Example App

Index.cshtml

```<code>@model IndexPage
@{
    ViewData["Title"] = "Index";
}
<style>
    li > div, label { border: solid 1px black; padding: 0.1em; margin: 0.25em; }
    label { border-color: grey; }
    li > div:first-child:before { content: 'LabelFor: '; }
    li > div:nth-child(2):before { content: 'NameFor: '; }
    li > div:nth-child(3):before { content: 'DisplayFor: '; }
    li.editor > div:nth-child(3):before { content: 'EditorFor: '; }
</style>
<h1>Index</h1>
<ol>
    <li>
        <div>@Html.DisplayNameFor(m => m.DateTimeNonNullable)</div>
        <div>@Html.NameFor(m => m.DateTimeNonNullable)</div>
        <div>@Html.DisplayFor(m => m.DateTimeNonNullable)</div>
    </li>
    <li>
        <div>@Html.DisplayNameFor(m => m.DateTimeNullable)</div>
        <div>@Html.NameFor(m => m.DateTimeNullable)</div>
        <div>@Html.DisplayFor(m => m.DateTimeNullable)</div>
    </li>
    <li>
        <div>@Html.DisplayNameFor(m => m.DateTimeNullableWithDisplay)</div>
        <div>@Html.NameFor(m => m.DateTimeNullableWithDisplay)</div>
        <div>@Html.DisplayFor(m => m.DateTimeNullableWithDisplay)</div>
    </li>
    <li>
        <div>@Html.DisplayNameFor(m => m.DateTimeNullableWithDisplayName)</div>
        <div>@Html.NameFor(m => m.DateTimeNullableWithDisplayName)</div>
        <div>@Html.DisplayFor(m => m.DateTimeNullableWithDisplayName)</div>
    </li>
    <li class="editor">
        <div>@Html.DisplayNameFor(m => m.DateTimeNonNullable)</div>
        <div>@Html.NameFor(m => m.DateTimeNonNullable)</div>
        <div>@Html.EditorFor(m => m.DateTimeNonNullable)</div>
    </li>
    <li class="editor">
        <div>@Html.DisplayNameFor(m => m.DateTimeNullable)</div>
        <div>@Html.NameFor(m => m.DateTimeNullable)</div>
        <div>@Html.EditorFor(m => m.DateTimeNullable)</div>
    </li>
    <li class="editor">
        <div>@Html.DisplayNameFor(m => m.DateTimeNullableWithDisplay)</div>
        <div>@Html.NameFor(m => m.DateTimeNullableWithDisplay)</div>
        <div>@Html.EditorFor(m => m.DateTimeNullableWithDisplay)</div>
    </li>
    <li class="editor">
        <div>@Html.DisplayNameFor(m => m.DateTimeNullableWithDisplayName)</div>
        <div>@Html.NameFor(m => m.DateTimeNullableWithDisplayName)</div>
        <div>@Html.EditorFor(m => m.DateTimeNullableWithDisplayName)</div>
    </li>
</ol>
</code>```

IndexPage.cs

    public class IndexPage
    {
        public DateTime DateTimeNonNullable { get; set; } = DateTime.Today;
        public DateTime? DateTimeNullable { get; set; } = DateTime.Today;
        [Display(Name = "DateTimeNullableWithDisplay")]
        public DateTime? DateTimeNullableWithDisplay { get; set; } = DateTime.Today;
        [DisplayName("DateTimeNullableWithDisplayName")]
        public DateTime? DateTimeNullableWithDisplayName { get; set; } = DateTime.Today;
    }
```

<p><em>DisplayTemplates\DateTime.cshtml</em></p>

```@model DateTime
@Html.LabelForModel()
@Html.DisplayNameFor(m => m)
@Html.ValueForModel()
```

<p><em>EditorTemplates\DateTime.cshtml</em></p>

```@model DateTime
@Html.LabelForModel()
@Html.DisplayNameFor(m => m)
<input type="datetime" id="@Html.IdForModel()" name="@Html.NameForModel()" value="@Html.ValueForModel()"/>
```

The Display Name doen't render on the Nullable entries via either LabelForModel or DisplayNameForModel (However DisplayNameFor(m=>m.Field) and LabelFor(m=>m.Field) does but DisplayNameFor(m=>m) and LabelFor(m=>m) doesn't)
Result

答:
So with a bit further research it turns out the problem is @model DateTime line
The post that gave me enough of a hint to track down was this
The template gets the DateTime? as a nullable object so doesn't know it needs to Access other properties to get some of the metadata.

There are two ways to solve this the generic @model dynamic or the strongly typed @model DateTime?
This was confirmed when i found this comment in the source code here

We don't want to search for Nullable<T>, we want to search for T (which should handle both T and Nullable<T>).

Body:
If you create an underlying model with a Propery of DateTime? (nullable) using DisplayNameForModel or LabelForModel will render empty

Using DotNet Core 2.2 Example App

Index.cshtml

@model IndexPage
@{
    ViewData["Title"] = "Index";
}

Index

@Html.DisplayNameFor(m => m.DateTimeNonNullable)

@Html.NameFor(m => m.DateTimeNonNullable)

@Html.DisplayFor(m => m.DateTimeNonNullable)

@Html.DisplayNameFor(m => m.DateTimeNullable)

@Html.NameFor(m => m.DateTimeNullable)

@Html.DisplayFor(m => m.DateTimeNullable)

@Html.DisplayNameFor(m => m.DateTimeNullableWithDisplay)

@Html.NameFor(m => m.DateTimeNullableWithDisplay)

@Html.DisplayFor(m => m.DateTimeNullableWithDisplay)

@Html.DisplayNameFor(m => m.DateTimeNullableWithDisplayName)

@Html.NameFor(m => m.DateTimeNullableWithDisplayName)

@Html.DisplayFor(m => m.DateTimeNullableWithDisplayName)

@Html.DisplayNameFor(m => m.DateTimeNonNullable)

@Html.NameFor(m => m.DateTimeNonNullable)

@Html.EditorFor(m => m.DateTimeNonNullable)

@Html.DisplayNameFor(m => m.DateTimeNullable)

@Html.NameFor(m => m.DateTimeNullable)

@Html.EditorFor(m => m.DateTimeNullable)

@Html.DisplayNameFor(m => m.DateTimeNullableWithDisplay)

@Html.NameFor(m => m.DateTimeNullableWithDisplay)

@Html.EditorFor(m => m.DateTimeNullableWithDisplay)

@Html.DisplayNameFor(m => m.DateTimeNullableWithDisplayName)

@Html.NameFor(m => m.DateTimeNullableWithDisplayName)

@Html.EditorFor(m => m.DateTimeNullableWithDisplayName)

IndexPage.cs

    public class IndexPage
    {
        public DateTime DateTimeNonNullable { get; set; } = DateTime.Today;
        public DateTime? DateTimeNullable { get; set; } = DateTime.Today;
        [Display(Name = "DateTimeNullableWithDisplay")]
        public DateTime? DateTimeNullableWithDisplay { get; set; } = DateTime.Today;
        [DisplayName("DateTimeNullableWithDisplayName")]
        public DateTime? DateTimeNullableWithDisplayName { get; set; } = DateTime.Today;
    }

DisplayTemplates\DateTime.cshtml

@model DateTime
@Html.LabelForModel()
@Html.DisplayNameFor(m => m)
@Html.ValueForModel()

EditorTemplates\DateTime.cshtml

@model DateTime
@Html.LabelForModel()
@Html.DisplayNameFor(m => m)
<input type="datetime" id="@Html.IdForModel()" name="@Html.NameForModel()" value="@Html.ValueForModel()"/>

The Display Name doen't render on the Nullable entries via either LabelForModel or DisplayNameForModel (However DisplayNameFor(m=>m.Field) and LabelFor(m=>m.Field) does but DisplayNameFor(m=>m) and LabelFor(m=>m) doesn't)
Result


问:
laravel .htaccess in root folder
I am following this article.

I am using laravel 5.6.

I moved .htaccess file from public to root and renamed server.php to index.php.

.htaccess :

```<code><IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
    Options -MultiViews -Indexes
</IfModule>

RewriteEngine On

# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]

# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !^/public/
RewriteRule ^(css|js|images)/(.*)$ public/$1/$2 [L,NC]
</code>```

But css and js files are not loaded.

答:
there is another way to do that , you only need to create .htaccess file in root directory and put that in it :

```<code><IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
    Options -MultiViews -Indexes
</IfModule>

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ ^$1 [N]

RewriteCond %{REQUEST_URI} (\.\w+$) [NC]
RewriteRule ^(.*)$ public/$1

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ server.php
</IfModule>
</code>```

after that you can keep your css , js files in public folder put you can call them directrly without public

Title: laravel .htaccess in root folder

Body:
I am following this article.

I am using laravel 5.6.

I moved .htaccess file from public to root and renamed server.php to index.php.

.htaccess :

<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
    Options -MultiViews -Indexes
</IfModule>

RewriteEngine On

# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]

# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !^/public/
RewriteRule ^(css|js|images)/(.*)$ public/$1/$2 [L,NC]

But css and js files are not loaded.

Body:
there is another way to do that , you only need to create .htaccess file in root directory and put that in it :

<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
    Options -MultiViews -Indexes
</IfModule>

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ ^$1 [N]

RewriteCond %{REQUEST_URI} (\.\w+$) [NC]
RewriteRule ^(.*)$ public/$1

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ server.php
</IfModule>

after that you can keep your css , js files in public folder put you can call them directrly without public


问:
Where to store the downloaded .jar files?
As I am new to Java, I want to ask that where should I put the downloaded .jar files, so that I don't have to use -cp option in javac command to compile it?

For example, suppose I have written a java code "HelloWorld.java" to do a basic input output and I have done import java.io.*; or import java.util.*;, and doing javac HelloWorld.java compile command on it works fine, however, if I have some (for example) import com.mongodb.BasicDBObject; line in my code and it won't compile without me downloading the mongo-java-driver-3.10.2.jar and putting it's location in -cp option of javac. (Like: javac -cp "/home/shivam/Downloads/*" HelloWorld.java).

So I just want to ask that where should I store the  mongo-java-driver-3.10.2.jar file in my computer so that, using just the javac NameOfCode.java command without the -cp option will compile my code successfully?

FYI, I have Ubuntu 18.04.2 and am using Java-11.

Thank you!!

答: You can put them in JAVA_HOME/lib, where JAVA_HOME is the path to your jdk setup</p>


问:
Why can't a sub implement an interface and handle event at the same time?
Why can't a sub implement an interface and handle event at the same time?

The following gives my a syntax error:

```<code>Sub MySub() Handles MyButton.Click Implements MyInterface.MyMethod
End Sub
</code>```

I know I could handle this kind of logic with another method, but that is not the point. I just want to understand the reasoning behind this.

答:
I've never seen any detailed discussion of why this decision was made by the VB.NET team, but to be honest, I struggle to see how this makes any sense from an OOP design perspective. Event handler methods generally shouldn't be doing any work. Rather, they should call out to other methods to do the heavy lifting. The other method that they call out to would be the one that implements your interface.

But it's certainly attainable if you do something like this:

```<code>Public MustInherit Class MyParentClass
    Protected WithEvents MyButton As Button

    Protected MustOverride Sub MySub() Handles MyButton.Click
End Class

Public Class MyDerivedClass : Inherits MyParentClass : Implements IMyInterface
    Protected Overrides Sub MySub() Implements IMyInterface.MyMethod
        ' Do something here...
    End Sub
End Class
</code>```

Also remember that event handler methods generally have a distinctive signature; something like:

```<code>Public Sub MySub(ByVal sender As System.Object, ByVal e As System.EventArgs)
</code>```

which is another reason why it would be extremely uncommon for an event handler method to also be able to implement a method defined in an interface.

ContentLicense: CC BY-SA 3.0

Body:
Why can't a sub implement an interface and handle event at the same time?

The following gives my a syntax error:

Sub MySub() Handles MyButton.Click Implements MyInterface.MyMethod
End Sub

I know I could handle this kind of logic with another method, but that is not the point. I just want to understand the reasoning behind this.

Body:
I've never seen any detailed discussion of why this decision was made by the VB.NET team, but to be honest, I struggle to see how this makes any sense from an OOP design perspective. Event handler methods generally shouldn't be doing any work. Rather, they should call out to other methods to do the heavy lifting. The other method that they call out to would be the one that implements your interface.

But it's certainly attainable if you do something like this:

Public MustInherit Class MyParentClass
    Protected WithEvents MyButton As Button

    Protected MustOverride Sub MySub() Handles MyButton.Click
End Class

Public Class MyDerivedClass : Inherits MyParentClass : Implements IMyInterface
    Protected Overrides Sub MySub() Implements IMyInterface.MyMethod
        ' Do something here...
    End Sub
End Class

Also remember that event handler methods generally have a distinctive signature; something like:

Public Sub MySub(ByVal sender As System.Object, ByVal e As System.EventArgs)

which is another reason why it would be extremely uncommon for an event handler method to also be able to implement a method defined in an interface.


问:
this class is not key value coding-compliant for the key Project1.'
I am new to iOS development , can you help me anyone in bug point of you. thank you for advance.

uncaught exception 'NSUnknownKeyException', reason:
  '[ setValue:forUndefinedKey:]:
  this class is not key value coding-compliant for the key Project1.'

```<code> let  context  = appdelegate.persistentContainer.viewContext
 let proj = Project()
        let arrProj = dic.object(forKey: "Projects") as! NSArray
        for n in 0..<arrProj.count {
            let subDic = arrProj.object(at: n) as! NSDictionary
            let item = ProjectItem(dict: subDic)
            proj.arrProjs.append( item )

           let projects = NSEntityDescription.entity(forEntityName: "Projects", in: context)
            projects?.setValue(item.Project, forKey: "project1")
            projects?.setValue(item.Project2, forKey: "project2")
            projects?.setValue(item.ID, forKey: "projectid")
            projects?.setValue(item.radius, forKey: "radius")
            projects?.setValue(item.GeofenceType, forKey: "geo_Type")
            projects?.setValue(item.Geofence, forKey: "geofence")
            projects?.setValue(item.Coordinates, forKey: "coordinates")
        }
</code>```

答:
You should set values in NSManagedObject object, not in NSEntityDescription object

```<code>let entity = NSEntityDescription.entity(forEntityName: "Projects", in: context)
for n in 0..<arrProj.count {
    let projects = NSManagedObject(entity: entity!, insertInto: context)
    projects?.setValue(item.Project, forKey: "project1")
    projects?.setValue(item.Project2, forKey: "project2")
    //...
}
</code>```

Body:
I am new to iOS development , can you help me anyone in bug point of you. thank you for advance.

uncaught exception 'NSUnknownKeyException', reason:
  '[ setValue:forUndefinedKey:]:
  this class is not key value coding-compliant for the key Project1.'

 let  context  = appdelegate.persistentContainer.viewContext
 let proj = Project()
        let arrProj = dic.object(forKey: "Projects") as! NSArray
        for n in 0..<arrProj.count {
            let subDic = arrProj.object(at: n) as! NSDictionary
            let item = ProjectItem(dict: subDic)
            proj.arrProjs.append( item )

           let projects = NSEntityDescription.entity(forEntityName: "Projects", in: context)
            projects?.setValue(item.Project, forKey: "project1")
            projects?.setValue(item.Project2, forKey: "project2")
            projects?.setValue(item.ID, forKey: "projectid")
            projects?.setValue(item.radius, forKey: "radius")
            projects?.setValue(item.GeofenceType, forKey: "geo_Type")
            projects?.setValue(item.Geofence, forKey: "geofence")
            projects?.setValue(item.Coordinates, forKey: "coordinates")
        }

Body:
You should set values in NSManagedObject object, not in NSEntityDescription object

let entity = NSEntityDescription.entity(forEntityName: "Projects", in: context)
for n in 0..<arrProj.count {
    let projects = NSManagedObject(entity: entity!, insertInto: context)
    projects?.setValue(item.Project, forKey: "project1")
    projects?.setValue(item.Project2, forKey: "project2")
    //...
}


问:
unhandled exception type ParseException
I'm using this part of code in my app :

```<code>SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss'Z'");
Date qdate = new GregorianCalendar(0,0,0).getTime();
try {
    qdate = sdf.parse(dt);
} catch (ParseException e) {
    e.printStackTrace();
}
</code>```

but Eclipse throws an error saying :

Unhandled exception type ParseException

What is the problem here?
Do u need me to post the whole code ?
Thnx in advance !

答:
```<code>Calendar c = Calendar.getInstance();

SimpleDateFormat df = new SimpleDateFormat("DD-MM-YYYY");

String Currentdatestr = df.format(c.getTime());

//get current date in String

Date date = df.parse(Currentdatestr);

//String to parse Date Format
</code>```

Title: unhandled exception type ParseException

Body:
I'm using this part of code in my app :

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss'Z'");
Date qdate = new GregorianCalendar(0,0,0).getTime();
try {
    qdate = sdf.parse(dt);
} catch (ParseException e) {
    e.printStackTrace();
}

but Eclipse throws an error saying :

Unhandled exception type ParseException

What is the problem here?
Do u need me to post the whole code ?
Thnx in advance !


问:
How to send code, pressing a button and receiving output of a website?
Sorry if the title is not clear enough, English is not my main language and I have trouble writing technical stuff.

There's this website:
https://www.cleancss.com/javascript-obfuscate/index.php

I need to be able to send code to this website obfuscating input and to receive its output. I have NO idea how to to this. I was thinking on using web browser module but I'd prefer that this is done in the background, so no explorer window is opened.

Please help me approach a solution for this!

答:
The obfuscated code is inside the textarea with id packed.

Javascript obfuscate API

```<code>import requests
from bs4 import BeautifulSoup

with open('file.js') as s:
    source= s.read()
cookies = {
    'PHPSESSID': 'foln2l1v1564o66vmbs19mk0j1',
}

headers = {
    'Connection': 'keep-alive',
    'Cache-Control': 'max-age=0',
    'Origin': 'https://www.cleancss.com',
    'Upgrade-Insecure-Requests': '1',
    'Content-Type': 'application/x-www-form-urlencoded',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
    'Referer': 'https://www.cleancss.com/javascript-obfuscate/index.php',
    'Accept-Encoding': 'gzip, deflate, br',
    'Accept-Language': 'en-US,en;q=0.9,ta;q=0.8',
}

data = {
  'ascii_encoding': '62^',
  'fast_decode': 'on^',
  'src': source
}

response = requests.post('https://www.cleancss.com/javascript-obfuscate/index.php', headers=headers, cookies=cookies, data=data)

soup=BeautifulSoup(response.text,'lxml')
with open('file2.js') as f:
    print(soup.select('#packed')[0].text,file=f)
</code>```

Body:
The obfuscated code is inside the textarea with id packed.

Javascript obfuscate API

import requests
from bs4 import BeautifulSoup

with open('file.js') as s:
    source= s.read()
cookies = {
    'PHPSESSID': 'foln2l1v1564o66vmbs19mk0j1',
}

headers = {
    'Connection': 'keep-alive',
    'Cache-Control': 'max-age=0',
    'Origin': 'https://www.cleancss.com',
    'Upgrade-Insecure-Requests': '1',
    'Content-Type': 'application/x-www-form-urlencoded',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
    'Referer': 'https://www.cleancss.com/javascript-obfuscate/index.php',
    'Accept-Encoding': 'gzip, deflate, br',
    'Accept-Language': 'en-US,en;q=0.9,ta;q=0.8',
}

data = {
  'ascii_encoding': '62^',
  'fast_decode': 'on^',
  'src': source
}

response = requests.post('https://www.cleancss.com/javascript-obfuscate/index.php', headers=headers, cookies=cookies, data=data)

soup=BeautifulSoup(response.text,'lxml')
with open('file2.js') as f:
    print(soup.select('#packed')[0].text,file=f)


问:
How to drop rows with condition to match string value
I have this dataframe where one of the columns has values as either "TRUE" or "FALSE". I want to get rid of the rows having column value = "TRUE". The name of that column is "is_duplicate" and dataframe name is "z".

I have tried the following approach:

i=0
while(i<len(z)):
    check=z["is_duplicate"].iloc[i:i+1]
    check=check.to_string(index=False)
    if(check=="TRUE"):
        z=z.drop([i],axis=0)
    i=i+1
```

<p>I also tried 2 more approaches based on the threads given on the similar topic but none of them work for me.</p>

<pre class="lang-py prettyprint-override"><code>z = z.replace('TRUE', np.nan).dropna()
</code>```

z=z[z["is_duplicate"] == "FALSE"]
```

I'm new to coding and have not been able to get this done even though it looks like the most basic thing ever.

答:
I think this is what you are looking for,

```<code>z.drop(z[z['is_duplicate']==True].index, axis=0)
</code>```

Thanks

Body:
I have this dataframe where one of the columns has values as either "TRUE" or "FALSE". I want to get rid of the rows having column value = "TRUE". The name of that column is "is_duplicate" and dataframe name is "z".

I have tried the following approach:

i=0
while(i<len(z)):
    check=z["is_duplicate"].iloc[i:i+1]
    check=check.to_string(index=False)
    if(check=="TRUE"):
        z=z.drop([i],axis=0)
    i=i+1

I also tried 2 more approaches based on the threads given on the similar topic but none of them work for me.

z = z.replace('TRUE', np.nan).dropna()

z=z[z["is_duplicate"] == "FALSE"]

I'm new to coding and have not been able to get this done even though it looks like the most basic thing ever.

Body:
I think this is what you are looking for,

z.drop(z[z['is_duplicate']==True].index, axis=0)

Thanks


问:
How to read text file in react
Screenshot1
Screenshot2

I want to read from a text file within the react project, but when I try to execute and read I get a HTML sample code in the console log.

This is the function:

```<code>onclick= () =>{
 fetch('data.txt')
  .then(function(response){
    return response.text();
  }).then(function (data) {
    console.log(data);
  })
};
</code>```

And the button which calls it:

```<code><button onClick={this.onclick}>click string</button>
</code>```

答:
Simply try the below code and you may understand</p>

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

class App extends Component {

  constructor(props) {
    super(props);
  }

  showFile = async (e) => {
    e.preventDefault()
    const reader = new FileReader()
    reader.onload = async (e) => {
      const text = (e.target.result)
      console.log(text)
      alert(text)
    };
    reader.readAsText(e.target.files[0])
  }

  render = () => {

    return (<div>
      <input type="file" onChange={(e) => this.showFile(e)} />
    </div>
    )
  }
}

export default App;
</code>```

Title: How to read text file in react

Body:
Screenshot1
Screenshot2

I want to read from a text file within the react project, but when I try to execute and read I get a HTML sample code in the console log.

This is the function:

onclick= () =>{
 fetch('data.txt')
  .then(function(response){
    return response.text();
  }).then(function (data) {
    console.log(data);
  })
};

And the button which calls it:

<button onClick={this.onclick}>click string</button>

Body:
Simply try the below code and you may understand

import React, { Component } from 'react';

class App extends Component {

  constructor(props) {
    super(props);
  }

  showFile = async (e) => {
    e.preventDefault()
    const reader = new FileReader()
    reader.onload = async (e) => {
      const text = (e.target.result)
      console.log(text)
      alert(text)
    };
    reader.readAsText(e.target.files[0])
  }

  render = () => {

    return (<div>
      <input type="file" onChange={(e) => this.showFile(e)} />
    </div>
    )
  }
}

export default App;


问:
Handling multiple branches in continuous integration
I've been dealing with the problem of scaling CI at my company and at the same time trying to figure out which approach to take when it comes to CI and multiple branches. There is a similar question at stackoverflow, Multiple feature branches and continuous integration. I've started a new one because I'd like to get more of discussion and provide some analysis in the question.

So far I've found that there are 2 main approaches that I can take (or maybe some others???).

Multiple set of jobs (talking about Jenkins/Hudson here) per branch

Write tooling to manage the extra jobs

Create/modify/delete Jobs in bulk

Custom settings for each job per branch (SCM url, dep management repos duplications)

Some examples of people tackling this problem with shell tools, ant scripts and Jenkins CLI. See:

http://jenkins.361315.n4.nabble.com/Multiple-branches-best-practice-td2306578.html

http://jenkins.361315.n4.nabble.com/Is-it-possible-to-handle-multiple-branches-where-some-jobs-should-run-on-each-one-without-duplicatin-td954729.html

http://jenkins.361315.n4.nabble.com/Parallel-development-with-branches-td1013013.html

Configure or Create hudson job automatically

Will cause more load on your CI cluster

Feedback cycle for devs slows down (if the infrastructure cannot handle the new load)

Multiple set of jobs per 2 branches (dev & stable)

Manage the two sets manually (if you change the conf of a job then be sure to change in the other branch)

PITA but at least so few to manage

Other extra branches won't get a full test suite before they get pushed to dev

Unsatisfied devs. Why should a dev care about CI scaling problems. He has a simple request, when I branch I would like to test my code. Simple.

So it seems if I want to provide devs with CI for their own custom branches I need special tooling for Jenkins (API or shellscripts or something?) and handle scaling. Or I can tell them to merge more often to DEV and live without CI on custom branches. Which one would you take or are there other options?

答:
I would set up separate jobs for each branch. I've done this before and it isn't hard to manage and set up if you've set up Hudson/Jenkins correctly. A quick way to create multiple jobs is to copy from an existing job that has similar requirements and modify them as needed. I'm not sure if you want to allow each developer to setup their own jobs for their own branches, but it isn't much work for one person (i.e. a build manager) to manage. Once the custom branches have been merged into stable branches, corresponding jobs can be removed when they are no longer necessary.

If you're worried about the load on the CI server, you could set up separate instances of the CI or even separate slaves to help balance the load across multiple servers. Make sure that the server you are running Hudson/Jenkins on is adequate. I've used Apache Tomcat and just had to ensure that it had enough memory and processing power to process the build queue.

It's important to be clear on what you want to achieve using CI and then figure out a way to implement it without much manual effort or duplication. There's nothing wrong with using other external tools or scripts that are executed by your CI server that help simplify your overall build management process.


问:
Converting Swift code to Objective-C errors
Im try to convert from swift to Objective-C, but have errors

```<code>func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {

    print(url)

    let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: true)

    let host = urlComponents?.host ?? ""

    print(host)

    return true
}
</code>```

In object try:

```<code>  - (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
            options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {

    printf("%s", url);

    NSURLComponents * const urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: true);

    NSString * const host = urlComponents.host ?? ""

    printf(host);
    return true;
    }
</code>```

But have error

Implicit declaration of function 'URLComponents' is invalid in C99

答:
You can try</p>

```<code>- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
            options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {

    printf("%s", url);

    NSURLComponents *  urlComponents = [[NSURLComponents alloc] initWithURL:url resolvingAgainstBaseURL:true];

    NSString *  host = urlComponents.host;

    NSLog(host);

    return true;
}
</code>```

Body:
Im try to convert from swift to Objective-C, but have errors

func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {

    print(url)

    let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: true)

    let host = urlComponents?.host ?? ""

    print(host)

    return true
}

In object try:

  - (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
            options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {

    printf("%s", url);

    NSURLComponents * const urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: true);

    NSString * const host = urlComponents.host ?? ""

    printf(host);
    return true;
    }

But have error

Implicit declaration of function 'URLComponents' is invalid in C99

Body:
You can try

- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
            options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {

    printf("%s", url);

    NSURLComponents *  urlComponents = [[NSURLComponents alloc] initWithURL:url resolvingAgainstBaseURL:true];

    NSString *  host = urlComponents.host;

    NSLog(host);

    return true;
}


问:
Couldn't get text from a text field using selenium
I am trying to get value from a text field using selenium, but I am not able to. The value is neither present between the tags nor in the attribute "value".Please help me with this.

I have tried following ways but nothing worked.

```<code>Webelement.getAttribute("innerText");

Webelement.gettext();

Webelement.getAttribute("value");

Webelement.getAttribute("textcontent");
</code>```

Below is the HTML for the text field.

```<code><input name="quantityField_valueFieldKeyboard" id="quantityField_valueFieldKeyboard" data-mini="true" data-clear-btn="false" maxlength="61" seyctype="numeric" class="seyc-visually-important seyc-ui-input-icon-white seyc-ui-input-text">
</code>```

答:
```<code>driver.findElement(By.id("quantityField_valueFieldKeyboard")).getAttribute("value");
</code>```

is correct way. You are getting empty string is also correct because your text field has no data in it. Since this is an input field, first enter some text and once text is saved. Try to fetch the entered text you will get your desired results.

Body:
I am trying to get value from a text field using selenium, but I am not able to. The value is neither present between the tags nor in the attribute "value".Please help me with this.

I have tried following ways but nothing worked.

Webelement.getAttribute("innerText");

Webelement.gettext();

Webelement.getAttribute("value");

Webelement.getAttribute("textcontent");

Below is the HTML for the text field.

<input name="quantityField_valueFieldKeyboard" id="quantityField_valueFieldKeyboard" data-mini="true" data-clear-btn="false" maxlength="61" seyctype="numeric" class="seyc-visually-important seyc-ui-input-icon-white seyc-ui-input-text">

Body:
driver.findElement(By.id("quantityField_valueFieldKeyboard")).getAttribute("value");

is correct way. You are getting empty string is also correct because your text field has no data in it. Since this is an input field, first enter some text and once text is saved. Try to fetch the entered text you will get your desired results.


问:
Android - Make an envelope shape background in xml/vector
I'm trying to do a shape as this one in xml:

It is a simple rectangle, with a solid color and a little transparent triangle in the top-center, from the inner side.

Can this be achieved using vectors?

答:
In general, a good starting point when looking for icons for your Android project is the icons section of the Material Design website.
In particular, for the icon you are looking for you can try to find something very similar and worst case you can adapt it and tweak it a bit.
Check the mail icon, is a very fine drawn envelope: https://material.io/tools/icons/?icon=mail&style=baseline

Select Android from the options, and press the SVG Button to obtain your vector asset.

For adding a different color, you can apply a tint on your vector directly on the xml:

```<code>android:tint="@color/your_color"
</code>```

Body:
In general, a good starting point when looking for icons for your Android project is the icons section of the Material Design website.
In particular, for the icon you are looking for you can try to find something very similar and worst case you can adapt it and tweak it a bit.
Check the mail icon, is a very fine drawn envelope: https://material.io/tools/icons/?icon=mail&style=baseline

Select Android from the options, and press the SVG Button to obtain your vector asset.

For adding a different color, you can apply a tint on your vector directly on the xml:

android:tint="@color/your_color"


问:
How to access contact on Android for API 17
I want to be able to read from contacts to my on my Android application but it doesn't seem achievable for APIs below 23. I intend to use this for API 17. How can I achieve this?</p>

答:
This code should work in API5 and above, using the enum ContactsContract.CommonDataKinds you have access to all field.

```<code> ContentResolver resolver = context.getContentResolver();
    Cursor contacts = null;
    try {
        contacts = resolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
        if (contacts.moveToFirst()) {
            do {
                String contactId = contacts.getString(contacts.getColumnIndex(ContactsContract.Contacts._ID));

                Cursor emails = null;
                Cursor phones = null;
                try {
                    emails = resolver.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, ContactsContract.CommonDataKinds.Email.CONTACT_ID
                            + " = " + contactId, null, null);
                    while (emails.moveToNext()) {
                        String email = emails.getString(emails.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
                       object
                    }
                    phones = resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                            ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, null, null);
                    while (phones.moveToNext()) {
                        String number = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                        String displayName = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                       phoneContact object
                    }
                } finally {
                    if (emails != null) {
                        emails.close();
                    }
                    if (phones != null) {
                        phones.close();
                    }
                }

            } while (contacts.moveToNext());
        }
    } finally {
        if (contacts != null) {
            contacts.close();
        }
    }
</code>```

Body:
This code should work in API5 and above, using the enum ContactsContract.CommonDataKinds you have access to all field.

 ContentResolver resolver = context.getContentResolver();
    Cursor contacts = null;
    try {
        contacts = resolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
        if (contacts.moveToFirst()) {
            do {
                String contactId = contacts.getString(contacts.getColumnIndex(ContactsContract.Contacts._ID));

                Cursor emails = null;
                Cursor phones = null;
                try {
                    emails = resolver.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, ContactsContract.CommonDataKinds.Email.CONTACT_ID
                            + " = " + contactId, null, null);
                    while (emails.moveToNext()) {
                        String email = emails.getString(emails.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
                       object
                    }
                    phones = resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                            ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, null, null);
                    while (phones.moveToNext()) {
                        String number = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                        String displayName = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                       phoneContact object
                    }
                } finally {
                    if (emails != null) {
                        emails.close();
                    }
                    if (phones != null) {
                        phones.close();
                    }
                }

            } while (contacts.moveToNext());
        }
    } finally {
        if (contacts != null) {
            contacts.close();
        }
    }


问:
How to delay re-delivery message?
I am using the asynchronous pull of Cloud Pub/Sub

For now, when I call message.nack() method, it will re-delievery this message immediately.

subscription.on('message', (message) => {
  message.nack();
})
```

How to delay the re-delivery?

For example, I got a message with publishTime: '2019-05-28T10:24:31.055Z'

I want to let this message re-delivery 20 seconds(computed) later from last delivery.

答: There is currently no way in Cloud Pub/Sub to delay the redelivery of a message. When a message is nacked, it is immediately a candidate for redelivery to the same subscriber or to another subscdriber.</p>

Title: How to delay re-delivery message?

Body:
I am using the asynchronous pull of Cloud Pub/Sub

For now, when I call message.nack() method, it will re-delievery this message immediately.

subscription.on('message', (message) => {
  message.nack();
})

How to delay the re-delivery?

For example, I got a message with publishTime: '2019-05-28T10:24:31.055Z'

I want to let this message re-delivery 20 seconds(computed) later from last delivery.


问:
Div with margin-left and width:100% overflowing on the right side
I have 2 nested div's that should be 100% wide. Unfortunately the inner div with the Textbox overflows and is actually larger than the outer div. It has a left margin and overflows by about the size of the margin.

How can I fix that?

```<code><div style="width:100%;">
    <div style="margin-left:45px; width:100%;">
    <asp:TextBox ID="txtTitle" runat="server" Width="100%"></asp:TextBox><br />
    </div>
</div>
</code>```

If I don't do the 100%, then the textbox is not 100% wide.

答:
```<code><div style="width:100%;">
    <div style="margin-left:45px;">
       <asp:TextBox ID="txtTitle" runat="server" Width="100%"></asp:TextBox><br />
    </div>
</div>
</code>```

Body:
I have 2 nested div's that should be 100% wide. Unfortunately the inner div with the Textbox overflows and is actually larger than the outer div. It has a left margin and overflows by about the size of the margin.

How can I fix that?

    <asp:TextBox ID="txtTitle" runat="server" Width="100%"></asp:TextBox>

If I don't do the 100%, then the textbox is not 100% wide.


问:
How to display a worksheet blank by default and only display result after a click action ? Tableau
I would like to display a worksheet only after an action has been made. For example: Click from a button on another worksheet.

答:
Create a parameter with 4 values and select default value as blank

Place all sheets on a dashboard and add the parameter as a filter in all worksheets.

Create one more worksheet with 3 options and add action filters to other worksheets.

Now place all on dashboard, change parameter value and the check the data.


问:
Why can't make_shared construct this object?
When trying to create a shared pointer to an object I come across this error

```<code>#include <iostream>
#include <vector>

class Foo {
public:
    std::shared_ptr<Foo> getFoo(int i) {
        auto foo = std::make_shared<Foo>(i);
        //auto foo = std::shared_ptr<Foo>(new Foo(i)); "works"
        return foo;
    }
protected:
    Foo(int i) {std::cout << "foo" << std::endl; }
};

int main(int argc, const char * argv[]) {

}
</code>```

I get the buildtime error

```<code> Static_assert failed due to requirement 'is_constructible<Foo, int &>::value' "Can't construct object in make_shared"
</code>```

I can avoid this by making the constructor private, But I would like to know why make_shared fails and and shared_ptr(new) works?

答:
```<code>//auto foo = std::shared_ptr<Foo>(new Foo(i)); "works"
</code>```

Here you access Foo's constructor from inside Foo and then pass this pointer to std::shared_ptr, which is fine.

```<code>auto foo = std::make_shared<Foo>(i);
</code>```

Here std::make_shared tries to access Foo's constructor which is protected and thus not allowed.

Body:
When trying to create a shared pointer to an object I come across this error

#include <iostream>
#include <vector>

class Foo {
public:
    std::shared_ptr<Foo> getFoo(int i) {
        auto foo = std::make_shared<Foo>(i);
        //auto foo = std::shared_ptr<Foo>(new Foo(i)); "works"
        return foo;
    }
protected:
    Foo(int i) {std::cout << "foo" << std::endl; }
};

int main(int argc, const char * argv[]) {

}

I get the buildtime error

 Static_assert failed due to requirement 'is_constructible<Foo, int &>::value' "Can't construct object in make_shared"

I can avoid this by making the constructor private, But I would like to know why make_shared fails and and shared_ptr(new) works?

Body:
//auto foo = std::shared_ptr<Foo>(new Foo(i)); "works"

Here you access Foo's constructor from inside Foo and then pass this pointer to std::shared_ptr, which is fine.

auto foo = std::make_shared<Foo>(i);

Here std::make_shared tries to access Foo's constructor which is protected and thus not allowed.


问:
aws lambda function triggering multiple times for a single event
I am using aws lambda function to convert uploaded wav file in a bucket to mp3 format and later move file to another bucket. It is working correctly. But there's a problem with triggering. When i upload small wav files,lambda function is called once. But when i upload a large sized wav file, this function is triggered multiple times.

I have googled this issue and found that it is stateless, so it will be called multiple times(not sure this trigger is for multiple upload or a same upload).

https://aws.amazon.com/lambda/faqs/

Is there any method to call this function once for a single upload?

答:
Any event Executing Lambda several times is due to retry behavior of Lambda as specified in AWS document.

Your code might raise an exception, time out, or run out of memory. The runtime executing your code might encounter an error and stop. You might run out concurrency and be throttled.

There could be some error in Lambda which makes the client or service invoking the Lambda function to retry.

Use CloudWatch logs to find the error and resolving it could resolve the problem.

I too faced the same problem, in my case it's because of application error, resolving it helped me.

Recently AWS Lambda has new property to change the default Retry nature. Set the Retry attempts to 0 (default 2) under Asynchronous invocation settings.


问:
how to override django save method to update some field dynamically?
Here i have two models.In these models i want to make the value of amount_to_pay dynamic in Ledger model.For Example i have two different forms for these two models and while saving expense form if the user select the payment_option which comes from ledger model and gives some value for the amount_to_pay field  then if only ledger.id and expense.payment_option_id are same then the value of amount_to_pay in ledger model should be replaced with that value.how can i do it ?

models.py

```<code>     class Expense(models.Model):
        pay_from = models.CharField(max_length=200)
        payment_option = models.ForeignKey('Ledger', on_delete=models.CASCADE)
        amount_to_pay = models.IntegerField(default=0)
        expense_date = models.DateField(default=datetime.date.today)
        expense_type = models.ForeignKey(ExpenseType, on_delete=models.CASCADE)
        note = models.TextField()
        created = models.DateTimeField(auto_now_add=True)
        updated = models.DateTimeField(auto_now=True)
        slug = AutoSlugField(unique_with='id', populate_from='expense_type')

        def get_amount_to_pay(self):
            return self.amount_to_pay

    class Ledger(models.Model):
        name = models.CharField(max_length=200)
        account_number = models.CharField(max_length=250, unique=True)
        account_type = models.CharField(max_length=200)
        opening_balance = models.IntegerField(default=0)
        amount_to_pay = models.IntegerField(default=0, blank=True, null=True)
        current_balance = models.IntegerField(default=0, blank=True, null=True)
        created = models.DateTimeField(auto_now_add=True)
        updated = models.DateTimeField(auto_now=True)
        slug = AutoSlugField(unique_with='id', populate_from='name')

        def save(self, *args, **kwargs):
             self.amount_to_pay = Expense.get_amount_to_pay(self)

# here how can i save the amount_to_pay from expense form if the ledger.id and expense.payment_option.id matches??
#i got stuck here.
 self.current_balance = self.opening_balance - self.amount_to_pay

            super(Ledger, self).save(*args, **kwargs)
</code>```

答:
Solution One:

I think instead of changing in Ledger model, you should change in Expense model, like this:

```<code>class Expense(models.Model):
    ...
    def save(self, *args, **kwargs):
       self.payment_option.amount_to_pay = self.payment_option.amount_to_pay + self.amount_to_pay
       self.payment_option.save()
       super(Expense, self).save(*args, **kwargs)
</code>```

Solution Two:

But to be honest, Solution One does not seem good to me. Reason is that you are saving same data in 2 places(in both expense and ledger). Instead, it should be once, then the amount_to_pay value in Ledger should be calculated dynamically. Like this:

```<code>from django.db.models import Sum

class Ledger(...):

     @property
     def amount_to_pay(self):
         # I am using a property method to show the amount_to_pay value.
         # FYI: in this way, you need to remove amount_to_pay field from Ledger model
         return self.opening_balance - self.expense_set.all().aggregate(a_sum=Sum('amount_to_pay')).get('a_sum', 0)
</code>```

In that way, with each ledger, the value amount_to_pay will be dynamically calculated at runtime. For example:

```<code> for l in Ledger.objects.all():
     l.amount_to_pay
</code>```

Solution Three:

If you are wary of making DB hits with each l.amount_to_pay(as it calculates amount_to_pay from DB dynamically) from previous solution, then you can always annotate the value. Like this:

For this solution, you need to change your Expense model and add a related_name:

```<code>class Expense(models.Model):
    pay_from = models.CharField(max_length=200)
    payment_option = models.ForeignKey('Ledger', on_delete=models.CASCADE, <b>related_name='expenses'</b>)</code>```

Then use that related_name in query like this(FYI: You can't keep def amount_to_pay(...) method in Ledger model for the following usage example):

```<code>from django.db.models import Sum, F, ExpressionWrapper, IntegerField

ledgers = Ledger.objects.all().annotate(expense_sum=Sum(<b>'expenses__amount_to_pay'</b>)).annotate(<b>amount_to_pay=ExpressionWrapper(F('opening_balance') - F('expense_sum'), output_field=IntegerField())</b>)

# usage one
for l in ledgers:
   l.amount_to_pay

# usage two
ledgers.values('amount_to_pay')</code>```

Body:
Here i have two models.In these models i want to make the value of amount_to_pay dynamic in Ledger model.For Example i have two different forms for these two models and while saving expense form if the user select the payment_option which comes from ledger model and gives some value for the amount_to_pay field  then if only ledger.id and expense.payment_option_id are same then the value of amount_to_pay in ledger model should be replaced with that value.how can i do it ?

models.py

     class Expense(models.Model):
        pay_from = models.CharField(max_length=200)
        payment_option = models.ForeignKey('Ledger', on_delete=models.CASCADE)
        amount_to_pay = models.IntegerField(default=0)
        expense_date = models.DateField(default=datetime.date.today)
        expense_type = models.ForeignKey(ExpenseType, on_delete=models.CASCADE)
        note = models.TextField()
        created = models.DateTimeField(auto_now_add=True)
        updated = models.DateTimeField(auto_now=True)
        slug = AutoSlugField(unique_with='id', populate_from='expense_type')

        def get_amount_to_pay(self):
            return self.amount_to_pay

    class Ledger(models.Model):
        name = models.CharField(max_length=200)
        account_number = models.CharField(max_length=250, unique=True)
        account_type = models.CharField(max_length=200)
        opening_balance = models.IntegerField(default=0)
        amount_to_pay = models.IntegerField(default=0, blank=True, null=True)
        current_balance = models.IntegerField(default=0, blank=True, null=True)
        created = models.DateTimeField(auto_now_add=True)
        updated = models.DateTimeField(auto_now=True)
        slug = AutoSlugField(unique_with='id', populate_from='name')

        def save(self, *args, **kwargs):
             self.amount_to_pay = Expense.get_amount_to_pay(self)

# here how can i save the amount_to_pay from expense form if the ledger.id and expense.payment_option.id matches??
#i got stuck here.
 self.current_balance = self.opening_balance - self.amount_to_pay

            super(Ledger, self).save(*args, **kwargs)

Body:
Solution One:

I think instead of changing in Ledger model, you should change in Expense model, like this:

class Expense(models.Model):
    ...
    def save(self, *args, **kwargs):
       self.payment_option.amount_to_pay = self.payment_option.amount_to_pay + self.amount_to_pay
       self.payment_option.save()
       super(Expense, self).save(*args, **kwargs)

Solution Two:

But to be honest, Solution One does not seem good to me. Reason is that you are saving same data in 2 places(in both expense and ledger). Instead, it should be once, then the amount_to_pay value in Ledger should be calculated dynamically. Like this:

from django.db.models import Sum

class Ledger(...):

     @property
     def amount_to_pay(self):
         # I am using a property method to show the amount_to_pay value.
         # FYI: in this way, you need to remove amount_to_pay field from Ledger model
         return self.opening_balance - self.expense_set.all().aggregate(a_sum=Sum('amount_to_pay')).get('a_sum', 0)

In that way, with each ledger, the value amount_to_pay will be dynamically calculated at runtime. For example:

 for l in Ledger.objects.all():
     l.amount_to_pay

Solution Three:

If you are wary of making DB hits with each l.amount_to_pay(as it calculates amount_to_pay from DB dynamically) from previous solution, then you can always annotate the value. Like this:

For this solution, you need to change your Expense model and add a related_name:

class Expense(models.Model):
    pay_from = models.CharField(max_length=200)
    payment_option = models.ForeignKey('Ledger', on_delete=models.CASCADE, related_name='expenses')

Then use that related_name in query like this(FYI: You can't keep def amount_to_pay(...) method in Ledger model for the following usage example):

from django.db.models import Sum, F, ExpressionWrapper, IntegerField

ledgers = Ledger.objects.all().annotate(expense_sum=Sum('expenses__amount_to_pay')).annotate(amount_to_pay=ExpressionWrapper(F('opening_balance') - F('expense_sum'), output_field=IntegerField()))

# usage one
for l in ledgers:
   l.amount_to_pay

# usage two
ledgers.values('amount_to_pay')


问:
How to fix - Promise { <pending> } in Node.js and use it as variable anywhere
I'm accessing google API for converting coordinates into detailed objects using node-geocoder library from npmjs. Everything went well and I'm getting the expected object from geocoder API. The problem started the moment when I thought of using the data outside the promise function. I want to use the values outside the promise/async-await function.
Below is the code I've tried, Pls take a look and help me. TIA...

```<code>function goecoderPromiseFunction() {

    return new Promise(function (resolve, reject) {

        geocoder.reverse({ lat: 45.767, lon: 4.833 })

            .then(data => {

                cityName = data[0].city;

                resolve(cityName);

            })
            .catch(err => {

                console.log(err);

            });
    });

}

async function app() {

    var a = await goecoderPromiseFunction();
    return a;

}

var a = app();

console.log("a->", a);
</code>```

I expect the variable "a" should print the city name "Lyon", but it prints

a-> Promise { < pending > }

答:
The promise returned by the app function is never consumed, that is why it remains in a pending state.

Call then on the app function to get the result :

```<code>app().then(a => console.log("a->", a));
</code>```

You can also use async/await :

```<code> (async function() {
   var a = await app();
   console.log("a->", a);
 })();
</code>```

Body:
I'm accessing google API for converting coordinates into detailed objects using node-geocoder library from npmjs. Everything went well and I'm getting the expected object from geocoder API. The problem started the moment when I thought of using the data outside the promise function. I want to use the values outside the promise/async-await function.
Below is the code I've tried, Pls take a look and help me. TIA...

function goecoderPromiseFunction() {

    return new Promise(function (resolve, reject) {

        geocoder.reverse({ lat: 45.767, lon: 4.833 })

            .then(data => {

                cityName = data[0].city;

                resolve(cityName);

            })
            .catch(err => {

                console.log(err);

            });
    });

}

async function app() {

    var a = await goecoderPromiseFunction();
    return a;

}

var a = app();

console.log("a->", a);

I expect the variable "a" should print the city name "Lyon", but it prints

a-> Promise { < pending > }

Body:
The promise returned by the app function is never consumed, that is why it remains in a pending state.

Call then on the app function to get the result :

app().then(a => console.log("a->", a));

You can also use async/await :

 (async function() {
   var a = await app();
   console.log("a->", a);
 })();


问:
Hide element with JQuery and activate button
I am making a product with 3 variables. A customer can pickup the products at our place, or we can deliver the products. Because of practical things, we choose to sell products there should be delivered as packages with 30, 60 or 90 products in.

Before a price can be shown, all 3 variables need to get selected. So here comes the problem. If a person wants to pickup the products at our place only 2 variables need to be selected: Length in m and Pickup or Delivery. But that will not give a price. Therefore I need to insert "Pickup" in "Packages" again to get a price.

But I would like to hide "pickup" in packages, so I do not confuse the visitor to much. The image describes what I am looking for:

The page can [be seen here][2]

This is the code I have until now, but as I see it either my code is not executed or the code is simply wrong. The page is looking excact the same as before I added my code to functions.php, and none of the functions are executed.

Based on my description does anybody have a good idea to what is wrong with my code?

HTML:

```<code><ul class="variable-items-wrapper button-variable-wrapper" data-attribute_name="attribute_pa_packages">
    <li data-wvstooltip="pickup" class="variable-item button-variable-item button-variable-item-pickup" title="pickup" data-value="pickup">
        <span class="variable-item-span variable-item-span-button">pickup</span>
    </li>
</ul>

<ul class="variable-items-wrapper button-variable-wrapper" data-attribute_name="attribute_pa_packages">
    <li data-wvstooltip="pickup" class="variable-item button-variable-item button-variable-item-pickup selected" title="pickup" data-value="pickup">
        <span class="variable-item-span variable-item-span-button">pickup</span></li>
    </li>
</ul>
</code>```

PHP and script:

```<code>function custom_script_name(){
    ?>
    <script>
    jQuery("ul[data-attribute_name=attribute_pa_pickup-og-delivery] li").click(function(){
        var selectedDelivery = jQuery("ul[data-attribute_name=attribute_pa_pickup-og-delivery]").find("li.selected").attr("data-value");
        if (selectedDelivery == "pickup"){
            jQuery("ul[data-attribute_name=attribute_pa_packages] li[data-value=pickup] span").click();
            jQuery("ul[data-attribute_name=attribute_pa_packages] li[data-value=pickup]").hide(); // hide the "pickup" option in "Packages" if you like
        }
    });
    </script>
    <?php
    }
    add_action('wp_head', 'custom_script_name');
</code>```

答:
If I understand the question correct:

you wanna hide the PickUp button in "Pickup or Delivery" on page load

Show the Pickup button in "Packages" when User clicks Pickup from "Pickup or Delivery".

Here's a JS way of doing it:

Disable the Pickup button in "Packages" on page load.

Enable Pickup button in "Packages" when user clicks on Pickup button in "Pickup or Delivery"

Disable Pickup button in "Packages" when user clicks on Delivery button in "Pickup or Delivery"

Here's a sample codewith simpler HTML(Live stackblitz: https://stackblitz.com/edit/js-l9ddiq):

```<code><div>
  <span>Length</span>
  <button>4.2m</button>
  <button>5.1m</buton>
</div>

<div>
  <span>Pickup or delivery</span>
  <button id="pickup-button">Pickup</button>
  <button id="delivery-button">Delivery</buton>
</div>

<div id="packages">
  <span>Packages</span>
  <button class="toggle-button" style="display: none;">Pickup</button>
  <button>30</button>
  <button>60</button>
  <button>90</button>
</div>
</code>```

JS:

```<code>const pickUpButton = document.getElementById('pickup-button');
pickUpButton.addEventListener('click', event => {
  const packageButtons = document.querySelector('#packages').querySelectorAll('button');
  packageButtons.forEach(button => {
    if (button.classList.contains('toggle-button')) {
      button.style.display = 'block';
    } else {
      button.disabled = true;
    }
  });
});

const deliveryButton = document.getElementById('delivery-button');
deliveryButton.addEventListener('click', event => {
  const packageButtons = document.querySelector('#packages').querySelectorAll('button');
  packageButtons.forEach(button => {
    if (button.classList.contains('toggle-button')) {
      button.style.display = 'none';
    } else {
      button.disabled = false;
    }
  });
});
</code>```

Body:
I am making a product with 3 variables. A customer can pickup the products at our place, or we can deliver the products. Because of practical things, we choose to sell products there should be delivered as packages with 30, 60 or 90 products in.

Before a price can be shown, all 3 variables need to get selected. So here comes the problem. If a person wants to pickup the products at our place only 2 variables need to be selected: Length in m and Pickup or Delivery. But that will not give a price. Therefore I need to insert "Pickup" in "Packages" again to get a price.

But I would like to hide "pickup" in packages, so I do not confuse the visitor to much. The image describes what I am looking for:

The page can [be seen here][2]

This is the code I have until now, but as I see it either my code is not executed or the code is simply wrong. The page is looking excact the same as before I added my code to functions.php, and none of the functions are executed.

Based on my description does anybody have a good idea to what is wrong with my code?

HTML:

        pickup

        pickup

PHP and script:

function custom_script_name(){
    ?>

    <?php
    }
    add_action('wp_head', 'custom_script_name');

Body:
If I understand the question correct:

you wanna hide the PickUp button in "Pickup or Delivery" on page load

Show the Pickup button in "Packages" when User clicks Pickup from "Pickup or Delivery".

Here's a JS way of doing it:

Disable the Pickup button in "Packages" on page load.

Enable Pickup button in "Packages" when user clicks on Pickup button in "Pickup or Delivery"

Disable Pickup button in "Packages" when user clicks on Delivery button in "Pickup or Delivery"

Here's a sample codewith simpler HTML(Live stackblitz: https://stackblitz.com/edit/js-l9ddiq):

<div>
  <span>Length</span>
  <button>4.2m</button>
  <button>5.1m</buton>
</div>

<div>
  <span>Pickup or delivery</span>
  <button id="pickup-button">Pickup</button>
  <button id="delivery-button">Delivery</buton>
</div>

<div id="packages">
  <span>Packages</span>
  <button class="toggle-button" style="display: none;">Pickup</button>
  <button>30</button>
  <button>60</button>
  <button>90</button>
</div>

JS:

const pickUpButton = document.getElementById('pickup-button');
pickUpButton.addEventListener('click', event => {
  const packageButtons = document.querySelector('#packages').querySelectorAll('button');
  packageButtons.forEach(button => {
    if (button.classList.contains('toggle-button')) {
      button.style.display = 'block';
    } else {
      button.disabled = true;
    }
  });
});

const deliveryButton = document.getElementById('delivery-button');
deliveryButton.addEventListener('click', event => {
  const packageButtons = document.querySelector('#packages').querySelectorAll('button');
  packageButtons.forEach(button => {
    if (button.classList.contains('toggle-button')) {
      button.style.display = 'none';
    } else {
      button.disabled = false;
    }
  });
});


答:
Try this function. This will give you all the contacts saved in phone</p>

```<code> private void getContactList() {
            ContentResolver cr = getContentResolver();
            Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
                    null, null, null, null);

            if ((cur != null ? cur.getCount() : 0) > 0) {
                while (cur != null && cur.moveToNext()) {
                    String id = cur.getString(
                            cur.getColumnIndex(ContactsContract.Contacts._ID));
                    String name = cur.getString(cur.getColumnIndex(
                            ContactsContract.Contacts.DISPLAY_NAME));

                    if (cur.getInt(cur.getColumnIndex(
                            ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0) {
                        Cursor pCur = cr.query(
                                ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                                null,
                                ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
                                new String[]{id}, null);
                        while (pCur.moveToNext()) {
                            String phoneNo = pCur.getString(pCur.getColumnIndex(
                                    ContactsContract.CommonDataKinds.Phone.NUMBER));
                            Log.i(TAG, "Name: " + name);
                            Log.i(TAG, "Phone Number: " + phoneNo);
                        }
                        pCur.close();
                    }
                }
            }
            if (cur != null) {
                cur.close();
            }
        }
</code>```

Title: How to access contact on Android for API 17

Body: I want to be able to read from contacts to my on my Android application but it doesn't seem achievable for APIs below 23. I intend to use this for API 17. How can I achieve this?

Body:
Try this function. This will give you all the contacts saved in phone

 private void getContactList() {
            ContentResolver cr = getContentResolver();
            Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
                    null, null, null, null);

            if ((cur != null ? cur.getCount() : 0) > 0) {
                while (cur != null && cur.moveToNext()) {
                    String id = cur.getString(
                            cur.getColumnIndex(ContactsContract.Contacts._ID));
                    String name = cur.getString(cur.getColumnIndex(
                            ContactsContract.Contacts.DISPLAY_NAME));

                    if (cur.getInt(cur.getColumnIndex(
                            ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0) {
                        Cursor pCur = cr.query(
                                ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                                null,
                                ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
                                new String[]{id}, null);
                        while (pCur.moveToNext()) {
                            String phoneNo = pCur.getString(pCur.getColumnIndex(
                                    ContactsContract.CommonDataKinds.Phone.NUMBER));
                            Log.i(TAG, "Name: " + name);
                            Log.i(TAG, "Phone Number: " + phoneNo);
                        }
                        pCur.close();
                    }
                }
            }
            if (cur != null) {
                cur.close();
            }
        }