text:
Q: Everytime I have to change something to reflect In my chat App FriendsFragment is shwoing blank. If I want to reflect that then, I have run the app, open the Friends tab in my app and after Instant run in Android studio and it will reflect. If it will not, then I have to add Log statement anywhere in my FriendsFragment, and run Instant run with exctly the open tab of friendsfragmet.
Why I'm telling you to add Log statement is necessary because I found this bug that whenever I change something on my Friends Fragment and then run Instant run, then only it will show the Fragment part. And I have to do this every time, otherwise it won't show. Add Log statement and remove second time, or change tag or change message, do something that makes the changes, and must run Instant run (that Yellow symbol like booster).
NOTE: I'm still doing this thing, I observe this problem by myself and I also don't know why I have to change something every time to show this Fragment? I also built the similar fragment in this same app, but for that there is no problem!
FriendFragment
package com.jimmytrivedi.lapitchat;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import com.squareup.picasso.Picasso;

import de.hdodenhof.circleimageview.CircleImageView;

public class FriendsFragment extends Fragment {

    private RecyclerView FriendRecyclerView;
    private DatabaseReference databaseReference, UsersDatabaseReference;
    private FirebaseAuth mAuth;
    private String currentUID;
    private View MainView;

    public FriendsFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        MainView = inflater.inflate(R.layout.fragment_friend, container, false);
        FriendRecyclerView = MainView.findViewById(R.id.FriendRecyclerView);
        mAuth = FirebaseAuth.getInstance();

        if (mAuth.getCurrentUser() != null) {
            currentUID = mAuth.getCurrentUser().getUid();
            databaseReference = FirebaseDatabase.getInstance().getReference().child("Friends").child(currentUID);
            databaseReference.keepSynced(true);
            UsersDatabaseReference = FirebaseDatabase.getInstance().getReference().child("Users");
            UsersDatabaseReference.keepSynced(true);
        }

        FriendRecyclerView.setHasFixedSize(true);
        FriendRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
           Log.d("wihddiewd", "Is it going?");
        return MainView;
    }

    @Override
    public void onStart() {
        super.onStart();

        Query query = FirebaseDatabase.                                                                                getInstance()
                .getReference()
                .child("Friends")
                .limitToLast(50);

        FirebaseRecyclerOptions<Friends> options = new FirebaseRecyclerOptions.Builder<Friends>()
                .setQuery(query, Friends.class)
                .build();

        final FirebaseRecyclerAdapter<Friends, FriendsViewHolder> FriendsRecyclerViewAdapter = new
                FirebaseRecyclerAdapter<Friends, FriendsViewHolder>(options) {
                    @Override
                    protected void onBindViewHolder(@NonNull final FriendsViewHolder holder, int position, @NonNull Friends model) {
                        holder.setDate(model.getDate());

                        final String listUID = getRef(position).getKey();
                        UsersDatabaseReference.child(listUID).addValueEventListener(new ValueEventListener() {
                            @Override
                            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                                final String userName = dataSnapshot.child("Name").getValue().toString();
                                String thumbImage = dataSnapshot.child("thumbImage").getValue().toString();
                                String userOnline = dataSnapshot.child("Online").getValue().toString();

                                holder.setName(userName);
                                holder.setThumbImage(thumbImage, getContext());
                                holder.setUserOnline(userOnline);
                                holder.mView.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        CharSequence options[] = new CharSequence[]{"Open profile", "Send message"};

                                        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
                                        builder.setTitle("Select Options");
                                        builder.setItems(options, new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                if (which == 0) {
                                                    Intent intent = new Intent(getContext(), ProfileActivity.class);
                                                    intent.putExtra("userID", listUID);
                                                    startActivity(intent);
                                                }

                                                if (which == 1) {
                                                    Intent intent = new Intent(getContext(), ChatActivity.class);
                                                    intent.putExtra("userID", listUID);
                                                    intent.putExtra("userName", userName);
                                                    startActivity(intent);
                                                }
                                            }
                                        });

                                        builder.show();
                                    }
                                });

                            }

                            @Override
                            public void onCancelled(@NonNull DatabaseError databaseError) {

                            }

                        });
                    }

                    @NonNull
                    @Override
                    public FriendsViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.users_single_layout, parent, false);
                        return new FriendsViewHolder(view);
                    }
                };

        FriendRecyclerView.setAdapter(FriendsRecyclerViewAdapter);
        FriendsRecyclerViewAdapter.startListening();

    }

    public static class FriendsViewHolder extends RecyclerView.ViewHolder {

        View mView;

        public FriendsViewHolder(View itemView) {
            super(itemView);
            mView = itemView;
        }

        public void setDate(String date) {
            TextView userStatusView = mView.findViewById(R.id.userStatus);
            userStatusView.setText(date);
        }

        public void setName(String name) {
            TextView userNameView = mView.findViewById(R.id.userName);
            userNameView.setText(name);
        }

        public void setThumbImage(String thumbImage, Context context) {
            CircleImageView circleImageView = mView.findViewById(R.id.userImage);
            Picasso.get().load(thumbImage).placeholder(R.drawable.defaultimage)
                    .into(circleImageView);
        }

        public void setUserOnline(String online) {
            ImageView userOnline = mView.findViewById(R.id.online);
            if (online.equals("true")) {
                userOnline.setVisibility(View.VISIBLE);
            } else {
                userOnline.setVisibility(View.INVISIBLE);
            }
        }
    }
}

Update
I know this is weird bug. But basically when I open my app and in app firends tab (which is FriendsFragment.java), it is showing blank. So I tried to debug that is there any mistake on my code or not? But I didn't find. But while debugging time, when I go to my firends tab in my mobile app, and put any log statement in Android Studio (because when I add/remove something so Android Studio will understand that some changes made happen, and then I run Instant run(not normal run) then FriendFragment will reflect and it shows the user list.
And I have to do this every time, (means I have to add something/remove something, that consider changes for Android Studio) then only FriendsFragment will show the users list. And even if I not open my Friends tab, but open something else in app and than run (instant run) that is also not work! Only when I just go to friends tab (that time it is showing blank, but that is okay) and run Instant run, then only it will reflect.
fragment_friends.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".FriendsFragment">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/FriendRecyclerView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    </android.support.v7.widget.RecyclerView>

</RelativeLayout>

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

    <de.hdodenhof.circleimageview.CircleImageView
        android:id="@+id/userImage"
        android:layout_width="64dp"
        android:layout_height="64dp"
        android:layout_marginBottom="15dp"
        android:layout_marginLeft="15dp"
        android:layout_marginTop="15dp"
        android:src="@drawable/defaultimage" />

    <TextView
        android:id="@+id/userName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignTop="@+id/userImage"
        android:layout_marginStart="99dp"
        android:text="Display Name"
        android:textColor="#000000"
        android:textSize="18dp" />

    <TextView
        android:id="@+id/userStatus"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignStart="@+id/userName"
        android:layout_below="@+id/userName"
        android:text="User default Status"
        android:textSize="15dp" />

    <ImageView
        android:id="@+id/online"
        android:layout_width="8dp"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/userName"
        android:layout_marginLeft="10dp"
        android:layout_toEndOf="@+id/userName"
        android:visibility="invisible"
        android:src="@drawable/online" />

</RelativeLayout>

Another Fragment ChatFragment, which is similar to this and working pretty fine).
ChatFragment.java
package com.jimmytrivedi.lapitchat;

import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import com.squareup.picasso.Picasso;

import de.hdodenhof.circleimageview.CircleImageView;

public class ChatFragment extends Fragment {

    private RecyclerView ConversationList;
    private DatabaseReference ConversationRef, MessageRef, UserRef;
    private FirebaseAuth mAuth;
    private String currentUID;
    private View MainView;

    public ChatFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        MainView = inflater.inflate(R.layout.fragment_chat, container, false);
        ConversationList = MainView.findViewById(R.id.ConversationList);
        mAuth = FirebaseAuth.getInstance();
        currentUID = mAuth.getCurrentUser().getUid();

        ConversationRef = FirebaseDatabase.getInstance().getReference().child("Chat").child(currentUID);
        ConversationRef.keepSynced(true);

        UserRef = FirebaseDatabase.getInstance().getReference().child("Users");
        UserRef.keepSynced(true);

        MessageRef = FirebaseDatabase.getInstance().getReference().child("Messages").child(currentUID);

        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        layoutManager.setReverseLayout(true);
        layoutManager.setStackFromEnd(true);

        ConversationList.setHasFixedSize(true);
        ConversationList.setLayoutManager(layoutManager);

        return MainView;
    }

    @Override
    public void onStart() {
        super.onStart();
        Query conversationQuery = ConversationRef.orderByChild("timestamp");

        Query query = FirebaseDatabase.getInstance()
                .getReference()
                .child("Chat")
                .limitToLast(50);

        FirebaseRecyclerOptions<Conversation> options = new FirebaseRecyclerOptions.Builder<Conversation>()
                .setQuery(query, Conversation.class)
                .build();

        FirebaseRecyclerAdapter<Conversation, ConversationViewHolder> ConversationRecyclerViewAdapter = new
                FirebaseRecyclerAdapter<Conversation, ConversationViewHolder>(options) {
                    @Override
                    protected void onBindViewHolder(@NonNull final ConversationViewHolder holder, int position, @NonNull final Conversation model) {
                        final String listUID = getRef(position).getKey();

                        Query lastMessageQuery = MessageRef.child(listUID).limitToLast(1);

                        lastMessageQuery.addChildEventListener(new ChildEventListener() {
                            @Override
                            public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
                                String data = dataSnapshot.child("message").getValue().toString();
                                holder.setMassage(data, model.isSeen());
                            }

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

                            }

                            @Override
                            public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {

                            }

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

                            }

                            @Override
                            public void onCancelled(@NonNull DatabaseError databaseError) {

                            }
                        });

                        UserRef.child(listUID).addValueEventListener(new ValueEventListener() {
                            @Override
                            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                                final String userName = dataSnapshot.child("Name").getValue().toString();
                                String userThumb = dataSnapshot.child("thumbImage").getValue().toString();

                                if (dataSnapshot.hasChild("Online")) {
                                    String userOnline = dataSnapshot.child("Online").getValue().toString();
                                    holder.setUserOnline(userOnline);
                                }

                                holder.setName(userName);
                                holder.setUserImage(userThumb, getContext());

                                holder.mView.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        Intent intent = new Intent(getContext(), ChatActivity.class);
                                        intent.putExtra("userID", listUID);
                                        intent.putExtra("userName", userName);
                                        startActivity(intent);
                                    }
                                });
                            }

                            @Override
                            public void onCancelled(@NonNull DatabaseError databaseError) {

                            }
                        });

                    }

                    @NonNull
                    @Override
                    public ConversationViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.users_single_layout, parent, false);
                        return new ConversationViewHolder(view);
                    }
                };

        ConversationList.setAdapter(ConversationRecyclerViewAdapter);
        ConversationRecyclerViewAdapter.startListening();
    }

    public static class ConversationViewHolder extends RecyclerView.ViewHolder {

        View mView;

        public ConversationViewHolder(View itemView) {
            super(itemView);
            mView = itemView;
        }

        public void setMassage(String message, boolean isSeen) {
            TextView userStatusView = mView.findViewById(R.id.userStatus);
            userStatusView.setText(message);

            if (!isSeen) {
                userStatusView.setTypeface(userStatusView.getTypeface(), Typeface.BOLD);
            } else {
                userStatusView.setTypeface(userStatusView.getTypeface(), Typeface.NORMAL);
            }
        }

        public void setUserOnline(String online) {
            ImageView userOnlineView = mView.findViewById(R.id.online);

            if (online.equals("true")) {
                userOnlineView.setVisibility(View.VISIBLE);
            } else {
                userOnlineView.setVisibility(View.INVISIBLE);
            }
        }

        public void setName(String userName) {
            TextView userNameView = mView.findViewById(R.id.userName);
            userNameView.setText(userName);
        }

        public void setUserImage(String userThumb, Context context) {
            CircleImageView userImageView = mView.findViewById(R.id.userImage);
            Picasso.get().load(userThumb).placeholder(R.drawable.defaultimage).into(userImageView);
        }
    }
}

Friends.java
package com.jimmytrivedi.lapitchat;

public class Friends {

    public String date;

    public Friends() {
    }

    public Friends(String date) {
        this.date = date;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }
}

SectionPagerAdapter.java
package com.jimmytrivedi.lapitchat;

import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

class SectionsPagerAdapter extends FragmentPagerAdapter {
    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {

        switch (position) {
            case 0:
                RequestFragment requestFragment = new RequestFragment();
                return requestFragment;

            case 1:
                ChatFragment chatFragment = new ChatFragment();
                return chatFragment;

            case 2:
                FriendsFragment friendFragment = new FriendsFragment();
                return friendFragment;

            default:
                return null;
        }

    }

    @Override
    public int getCount() {
        return 3;
    }

    @Nullable
    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return "Requests";

            case 1:
                return "Chats";

            case 2:
                return "Friends";

            default:
                return null;
        }
    }
}

MainActivity.java
package com.jimmytrivedi.lapitchat;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;

import com.facebook.login.LoginManager;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ServerValue;

public class MainActivity extends AppCompatActivity {

    private FirebaseAuth mAuth;
    private FirebaseUser currentUser;
    private Toolbar toolbar;
    private ViewPager viewPager;
    private SectionsPagerAdapter sectionsPagerAdapter;
    private TabLayout tabLayout;
    private DatabaseReference UserDatabaseReference;

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

        mAuth = FirebaseAuth.getInstance();
        currentUser = mAuth.getCurrentUser();

        if (currentUser == null) {
            sendTostart();
        } else {
            UserDatabaseReference = FirebaseDatabase.getInstance().getReference().child("Users").child(mAuth.getCurrentUser().getUid());
            UserDatabaseReference.child("Online").setValue("true");
        }

        viewPager = findViewById(R.id.viewPager);
        sectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        viewPager.setAdapter(sectionsPagerAdapter);

        toolbar = findViewById(R.id.mainToolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setTitle("Home");

        tabLayout = findViewById(R.id.tabLayout);
        tabLayout.setupWithViewPager(viewPager);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (currentUser != null) {
            UserDatabaseReference.child("Online").setValue(ServerValue.TIMESTAMP);
        }
    }

    private void sendTostart() {
        startActivity(new Intent(MainActivity.this, StartActivity.class));
        finish();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        getMenuInflater().inflate(R.menu.main_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        super.onOptionsItemSelected(item);

        if (item.getItemId() == R.id.logout) {
            FirebaseAuth.getInstance().signOut();
            LoginManager.getInstance().logOut();
            sendTostart();
        }

        if (item.getItemId() == R.id.settings) {
            startActivity(new Intent(MainActivity.this, SettingsActivity.class));
        }

        if (item.getItemId() == R.id.allUsers) {
            startActivity(new Intent(MainActivity.this, UsersActivity.class));
        }

        return true;
    }
}

A: Use
`viewPager.setOffscreenPageLimit(3);`

after
viewPager.setAdapter(sectionsPagerAdapter);

inside MainActivity.

A: Use notifyDataSetChanged() after setting adapter to recyclerview.
 FriendRecyclerView.setAdapter(FriendsRecyclerViewAdapter);
 FriendsRecyclerViewAdapter.notifyDataSetChanged();


text:
Q: Trouble with SUM(IF) condition in mysql Can anyone help me to fix the query below? I need to produce a report that is able to count how many TOB is sent & signed without certain period. There are 3 different TOB tables. Below is my SQL query:
select cl.name, con.name,
    COUNT(IF(DATE( tp.sent_on ) between '2012-01-01' AND '2012-12-31', 1, 0))  as "TOB Perm Sent",
    COUNT(IF(DATE( tp.signed_on ) between '2012-01-01' AND '2012-12-31', 1, 0))  as "TOB Perm Signed",
    COUNT(IF(DATE( tt.sent_on ) between '2012-01-01' AND '2012-12-31', 1, 0))  as "TOB Temp Sent",
    COUNT(IF(DATE( tt.signed_on ) between '2012-01-01' AND '2012-12-31', 1, 0))  as "TOB Temp Signed",
    COUNT(IF(DATE( tc.sent_on ) between '2012-01-01' AND '2012-12-31', 1, 0))  as "TOB Contract Sent",
    COUNT(IF(DATE( tc.signed_on ) between '2012-01-01' AND '2012-12-31', 1, 0))  as "TOB Contract Signed"
FROM clients cl
    LEFT OUTER JOIN consultants con ON cl.CIC = con.con_id
    LEFT OUTER JOIN tob_perm tp ON tp.client_id = cl.client_id
    LEFT OUTER JOIN tob_temp tt ON tt.client_id = cl.client_id
    LEFT OUTER JOIN tob_contract tc ON tc.client_id = cl.client_id
WHERE cl.status IN(1) and cl.client_id = 16
GROUP BY cl.client_id
order by cl.client_id asc

Sample Data:
Consultants Table
id       name
-----------------
 1       Andy

Clients Table
id       name       con_id
----------------------------
 1     Client A        1

TOB Perm
id       client_id          sent_on          signed_on
-------------------------------------------------------
 1           1            2012-02-05         0000-00-00
 2           1            2012-10-09         2012-06-03

TOB Temp
id       client_id          sent_on          signed_on
-------------------------------------------------------
 1           1            0000-00-00         2012-08-30
 2           1            0000-00-00         2012-02-19
 3           1            2012-10-09         2012-06-03

TOB Contract
id       client_id          sent_on          signed_on
-------------------------------------------------------
 1           1            2012-08-30         0000-00-00

Table result that I want to produce is as below:
No    Client Name    Consultant     TOB perm sent     TOB perm signed     TOB temp sent       TOB temp signed      TOB contract sent       TOB contract signed
-----------------------------------------------------------------------------------------------------------------------------------------------------------
1      Client A        Andy              2                   1                  1                     3                    1                       0

Can anyone help me with my query? Thanks in advance.
UPDATE
I think there is something wrong with my IF condition:
IF(DATE( tp.sent_on ) between '2012-01-01' AND '2012-12-31', 1, 0)

Is there anyone can help me figure out the problem? Thanks

A: Replace count with sum to make it work.
count counts the records and does not care about conditions. Use for instance
SUM(DATE( tp.sent_on ) between '2012-01-01' AND '2012-12-31')

redpajama_set_name: RedPajamaStackExchange


text:
Q: Update node modules when package-lock has changed We are using git and npm in our project.
We often pull the changes made by our colleagues. Most of the time, this is enough, but if our colleague did update a dependency, just pulling the new package.json and the new package-lock.json won't be enough. We alson need to run npm install to update our node_modules.
The issue is that if we forget about the npm install, we end up with errors that will take us time to identify and finally realize: "Oh! That dependency was updated!".
So, what I would really like, is a kind of hook that would, each time the file package-lock.json is changed, run npm install.
Being totally newbie with hooks, I have some problems though:

*

*What hook should I use? Is post-update what I'm looking for? Or should it be post-receive? Or post-checkout maybe?

*How can I get the information if package-lock.json was updated in the changes I pulled?

*Is this the correct way to achieve my goal or is there another way?

Edit
I found this that seems to fix my issue perfectly. I will make it an answer once I checked that it's working fine.

A: I think this is what you are looking for: https://git-scm.com/docs/githooks#_post_merge
So, how to use it? Well, you will need to write some lines of code to handle that. The problem is that this resides inside your .git folder. You can configure it as a global "thing", but yet need to control and distribute it to all your colleagues.
I wrote a tool https://pypi.org/project/hooks4git/ to be simple enough to be used, and yet flexible enough to be used in any programming language.
It is a tool written in Python, so yes, you need python on the OS.
But after that, you can create your custom "check-if-packagejson-was-changed-and-do-npm-install.js" and link it to a .hooks4git.ini file, and that's it.
This file goes within the repository.
I just noticed that I missed a few hooks, post-merge in particular, and added support for this... It is building on Travis right now! The main idea is that I collect all data I can, and call your custom script at the right event. You code the rest on your preferred language.
Hope this helps.


text:
Q: Using a non-class new statement inside an enum creating? In Java, is it alright to do the following?
public enum MyEnum {

    FirstVariable(new nonEnumClass()),
    SecondVariable(new nonEnumClass())

    MyEnum(nonEnumClass class) {

    }
}

I'm unsure if I should do that, or if I shouldn't.
I'm sorry if the question isn't clear enough, I don't know how to further clarify it.

A: That's fine!
However, you'll have a compiler error here:
MyEnum(nonEnumClass class)

class is a keyword in Java, you can't name a parameter that.
MyEnum(nonEnumClass myClass) is fine though.
Also, typically class names in Java have every word capitalized (NonEnumClass), though that doesn't really matter.


text:
Q: updateDescription.updatedFields in Change Event From mongoDB is null I am trying to watch the updates on a specific field status in MongoDB change stream.
From the Change Event documentation page, a change stream will output this document:
{
   _id : { <BSON Object> },
   "operationType" : "<operation>",
   "fullDocument" : { <document> },
   "ns" : {
      "db" : "<database>",
      "coll" : "<collection"
   },
   "documentKey" : { "_id" : <ObjectId> },
   "updateDescription" : {
      "updatedFields" : { <document> },
      "removedFields" : [ "<field>", ... ]
   }
}

I am always getting all the fields but getting updateDescription.updatedFields as null.
Here is the Java code I'm using
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
MongoDatabase database = mongoClient.getDatabase("db");
MongoCollection<org.bson.Document> collection = database.getCollection("collection");
List<Bson> pipeline = Collections.singletonList(Aggregates.match(Filters.and(
        Document.parse("{'fullDocument.status':  { $in: [ 'DONE','ERROR'] }}"),
        Filters.exists("updateDescription.updatedFields.status",true),
        Filters.in("operationType", ("replace")))));

MongoCursor<ChangeStreamDocument<Document>> cursor = collection.watch(pipeline).iterator();

I am using these dependencies with the project
<mongo.java.driver>3.6.3</mongo.java.driver>

<spring.data.mongo.version>1.10.10.RELEASE</spring.data.mongo.version>

A: I solved the issue, the problem that I was testing using "edit document" on Robo.
The "edit document" does not update one field, it replaces all the document with a new one having the same id.


text:
Q: How can i make a function out of this so i don't have to copy paste the same piece of code? Currently in my code i am just copy and pasting blocks of code like these 20+ times, i need some help on how to make this into a function to save space
if chosenrace == "Var Human":
    randclass = random.choice(varhumanclasses)

if chosenrace == "Aasimar":
    randclass = random.choice(aasimarclasses)

if chosenrace == "Aarakocra":
    randclass = random.choice(aarakocraclasses)

if chosenrace == "Warforged":
    randclass = random.choice(warforgedclasses)

A: A possible solution would be to have create a dictionary linking the strings, to the variables. For example,
class_dict = {
"Var Human": varhumanclasses,
"Aasimar": aasimarclasses
}

Then, you could create a function that takes the chosen race string and returns a random choice using the correct class variable from the dictionary.
def random_class(race):
    return random.choice(class_dict[race])

A: like this
def pick(chosenrace): return random.choice({
    "Var Human" : varhumanclasses,
    "Aasimar"   : aasimarclasses,
    "Aarakocra" : aarakocraclasses,
    "Warforged" : warforgedclasses,
}.get(chosenrace, notfoundclasses))

A: I liked and up-voted the solution by @tintins7a6164. If you don't want to maintain a dictionary, you can consider the snippet below. It assumes that varhumanclasses etc are declared on the global scope.
import random

varhumanclasses = [1, 2, 3]
aasimarclasses = [5, 6, 7]

def get_classes_from_race(race: str):
    classes_s = race.lower().replace(" ", "") + "classes"
    if classes_s in globals():
        f = globals()[classes_s]
    else:
        raise ValueError(f"{classes_s} not found")
    if not isinstance(f, list):
        raise ValueError(f"{classes_s} is not declared as a function")
    return f

print(random.choice(get_classes_from_race("Var Human")))
print(random.choice(get_classes_from_race("Aasimar")))


text:
Q: T4MVC: Cannot use a leading .. to exit above the top directory I'm trying to use the T4MVC project from the MVCContrib project on codeplex (v2.6.13).
I'm using ASP.NET MVC 2 RTM running against .NET 4 in Visual Studio 2010.
Using the Default project template that you get when creating a new MVC 2 Web Application I modified the Home ActionLink in the Master Page to:
<%= Html.ActionLink("Home", MVC.Home.Index()) %>

Now I get an HttpException of "Cannot use a leading .. to exit above the top directory" every time I try and browse the project (F5 in VS2010).
If I remove that ActionLink then everything works just fine.
Stack Trace

[HttpException (0x80004005): Cannot use a leading .. to exit above the top directory.]
     System.Web.Util.UrlPath.ReduceVirtualPath(String path) +8774912
     System.Web.Util.UrlPath.Reduce(String path) +52
     System.Web.Util.UrlPath.Combine(String appPath, String basepath, String relative) +217
     System.Web.UI.Control.ResolveClientUrl(String relativeUrl) +258
     System.Web.UI.HtmlControls.HtmlLink.RenderAttributes(HtmlTextWriter writer) +74
     System.Web.UI.HtmlControls.HtmlLink.Render(HtmlTextWriter writer) +42
     System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +27
     System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +100
     System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +25
     System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +208
     System.Web.UI.HtmlControls.HtmlHead.RenderChildren(HtmlTextWriter writer) +21
     System.Web.UI.HtmlControls.HtmlContainerControl.Render(HtmlTextWriter writer) +31
     System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +27
     System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +100
     System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +25
     ASP.views_shared_site_master.__Render__control1(HtmlTextWriter __w, Control parameterContainer) in c:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\82809071\51b73fea\App_Web_uers1hdy.1.cs:0
     System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +109
     System.Web.UI.Control.RenderChildren(HtmlTextWriter writer) +8
     System.Web.UI.Control.Render(HtmlTextWriter writer) +10
     System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +27
     System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +100
     System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +25
     System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +208
     System.Web.UI.Control.RenderChildren(HtmlTextWriter writer) +8
     System.Web.UI.Page.Render(HtmlTextWriter writer) +29
     System.Web.Mvc.ViewPage.Render(HtmlTextWriter writer) +56
     System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +27
     System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +100
     System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +25
     System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3060

I've been banging my head on this for a while now but I don't seem to be able to find anything in the documentation or related blogs that might point to the solution.
Does anyone know where I'm going wrong?


text:
Q: Prove that $\{(x,y): W_x\text{ and }W_y\text{ are recursively separable}\}$ is $\Sigma_3$-complete
Prove that $\{(x,y): W_x\text{ and }W_y\text{ are recursively separable}\}$ is $\Sigma_3$-complete

This is a question from Soare's Recursively Enumerable Sets and Degrees. I have little idea how to construct the reduction function. I have done much simpler completeness proofs of $\Sigma_1$ level but don't really get the intuition behind completeness at higher levels of the hierarchy.


text:
Q: Colour Map on scatter plot I have three columns in a csv file which reads like this:
X,Y, Cosine efficiency
989.565,670.17,0.868684456
660.941,-1502.48,0.597998523
685.683,-1491.35,0.600137189
-1454.88,-316.582,0.666894492
-510.86,1016.79,0.870398677
-1350.21,-788.027,0.61601682
-944.034,-1342.79,0.565497692
-966.098,-1327,0.56678693
-1206.4,-1054.63,0.590095562
1004.18,648.067,0.866589585

I can read the X and Y values and make a scatter plot in the following way:
import csv
# Reading data from csv file
with open('my_file.csv') as csvfile:
readCSV = csv.reader(csvfile, delimiter=',')
    X = []
    Y = []
    C = []

for row in readCSV:
    X_coordinates = row[0]
    Y_coordinates = row[1]
    cos_eff = row[2]
    X.append(X_coordinates)
    Y.append(Y_coordinates)
    C.append(cos_eff)
Xcoordinate = [float(X[c]) for c in range(1,len(X))]
Ycoordinate=[float(Y[c]) for c in range(1,len(Y))]
CosineEff=[float(C[c]) for c in range(1,len(C))]

# Plotting the solar field
plt.figure(1)
plt.scatter(Xcoordinate,Ycoordinate, color = 'blue', s=2)
plt.title("Solar field")
plt.xlabel("Position, east-west [m]"); plt.ylabel("Position, east-west [m]")
plt.show()

Now, I want to make this scatter plot using a colour map which uses the values from the third column.
For example, the first point is : 989.565,670.17,0.868684456. I have already plotted the X and Y coordinates - in this case 989.565 and 670.17. But i want to use a colour map to put the value of 0.868684456 on this plotted X & Y value.
I want to use Brewer2mpl or pcolour but I dont know where to start.
I can make a colour map on Origin using the 'colour mapped' function but how can I do it on Python?

A: plt.scatter(x_vals, y_vals,  c = z_vals, cmap = 'rainbow')

You're going to want to play with adding s= and choosing an appropriate size for the points. There's also a beautiful colormap set called cmocean that you may want to consider installing


text:
Q: Unable to resolve path to module in VueJS I am facing Unable to resolve path to module in VueJS
when i have import SidebarContent.vue file this error has showing
This is my error
enter image description here
This is my code:
enter image description here


text:
Q: Error when using a string as a parameter I have a list of floats [234, 533, 734, 964, 623, 744, 244, 353, 264]. Then, I format it to a string like "(234, 533, 734), (964, 623, 744), (244, 353, 264)".
This is a format example of the function I'm passing it to:
cmds.curve( p=[(0, 0, 0), (3, 5, 6), (5, 6, 7), (9, 9, 9)] )

Here's what I used that returned an error:
cmds.curve( p = [ pStr ] )

Here's the error:

Line 142: Invalid arguments for flag 'p'.  Expected ( distance, distance, distance ), got [ str, str ] #

A: Try this and see if it works for you.  I have a feeling that you are converting to a string unnecessarily.
floats = [234, 533, 734, 964, 623, 744, 244, 353, 264]
groups = [tuple(floats[i:i+3]) for i in range(0, len(floats), 3]
cmds.curve(p=groups)

A: Try using zip, click here for the python docs.
>>> my_list = [234, 533, 734, 964, 623, 744, 244, 353, 264]
>>> zip(*[iter(my_list)]*3)
[(234, 533, 734), (964, 623, 744), (244, 353, 264)]


text:
Q: How do i create index column in sql? I'm using SQL-Server 2005.
I have table with many columns, rows i select have where clause which makes impossible to use identity as indexer. I want select all these row + indexer row (acting like identity).
example
2 jack

4 thomas

8 james

to
1 2 jack

2 4 thomas

3 8 james

thanks

A: Use rank function or row_number (http://www.databasejournal.com/features/mssql/article.php/3661461/New-Ranking-Functions-within-SQL-Server-2005.htm)
select rank() OVER (ORDER BY list of your columns) as Id,
your_column_1, your_column_2 ...
from your table


text:
Q: Application not configured for billing through Google Play error I have the following code that allows people to purchase subscriptions in android/kotlin. However, when people click to purchase an annual subscription sometimes they get the error Application not configured for billing through Google Play
Sometimes I get the error "Error retrieving from the server"
Here's the code https://gist.github.com/naissa12/2e52e4ac40c1f7143b44e92923913f87
I'm using RevenueCats SDK

A: implementation 'com.android.billingclient:billing:2.2.0'


text:
Q: java.nio.ByteBuffer wrap method partly working with sbt run I have an issue where I read a bytestream from a big file ~ (100MB) and after some integers I get the value 0 (but only with sbt run ). When I hit the play button on IntelliJ I get the value I expected > 0.
My guess was that the environment is somehow different. But I could not spot the difference.
// DemoApp.scala
import java.nio.{ByteBuffer, ByteOrder}

object DemoApp extends App {
  val inputStream = getClass.getResourceAsStream("/HandRanks.dat")
  val handRanks = new Array[Byte](inputStream.available)
  inputStream.read(handRanks)
  inputStream.close()

  def evalCard(value: Int) = {
    val offset = value * 4
    println("value: " + value)
    println("offset: " + offset)
    ByteBuffer.wrap(handRanks, offset, handRanks.length - offset).order(ByteOrder.LITTLE_ENDIAN).getInt
  }

  val cards: List[Int] = List(51, 45, 14, 2, 12, 28, 46)

  def eval(cards: List[Int]): Unit = {
    var p = 53
    cards.foreach(card =>  {
      println("p = " + evalCard(p))
      p = evalCard(p + card)
    })
    println("result p: " + p);
  }
  eval(cards)
}

The HandRanks.dat can be found here: (I put it inside a directory called resources)
https://github.com/Robert-Nickel/scala-texas-holdem/blob/master/src/main/resources/HandRanks.dat
build.sbt is:
name := "LoadInts"
version := "0.1"
scalaVersion := "2.13.4"

On my windows machine I use sbt 1.4.6 with Oracle Java 11
You will see that the evalCard call will work 4 times but after the fifth time the return value is 0. It should be higher than 0, which it is when using IntelliJ's play button.

A: You are not reading a whole content. This
val handRanks = new Array[Byte](inputStream.available)

allocates only as much as InputStream buffer and then you read the amount in buffer with
inputStream.read(handRanks)

Depending of defaults you will process different amount but they will never be 100MB of data. For that you would have to read data into some structure in the loop (bad idea) or process it in chunks (with iterators, stream, etc).
import scala.util.Using

// Using will close the resource whether error happens or not
Using(getClass.getResourceAsStream("/HandRanks.dat")) { inputStream =>
  def readChunk(): Option[Array[Byte]] = {
    // can be done better, but that's not the point here
    val buffer = new Array[Byte](inputStream.available)
    val bytesRead = inputStream.read(buffer)
    if (bytesRead >= 0) Some(buffer.take(bytesRead))
    else None
  }

  @tailrec def process(): Unit = {
    readChunk() match {
      case Some(chunk) =>
        // do something
        process()
      case None =>
        // nothing to do - EOF reached
    }
  }

  process()
}


text:
Q: Why is Node's process.stdin.on('readable') fire my callback once? I have the following code:
process.stdin.on('readable', () => {
  const input = process.stdin.read();
  console.log(input);
});

In a tutorial, the callback seems to fire in a loop, but when I try it, it gets called only once, then exits. Why is this happening? My Node version is 13.12.0

A: Once the readable event fires, it won't fire again until either the stream reaches the end or until you call .read() and get null back (no more data to read).  Once you get null, then it will fire again when there is more data.
That's why the sample code in the doc does this:
const readable = getReadableStreamSomehow();
readable.on('readable', function() {
  // There is some data to read now.
  let data;

  while (data = this.read()) {
    console.log(data);
  }
});

In general, this is a more difficult way to use streams.  If you use them in the flowing mode such as this:
process.stdin.on('data', (input) => {
  console.log(input);
});

Then, it will just call you whenever data arrives.


text:
Q: String#split strange behavior I observed a strange behavior of the split method on a String.
"1..2".split('..')      # => ['1', '2']
"1..2".split('..', 2)   # => ['1', '2']

"..2".split('..')       # => ['', '2']
"..2".split('..', 2)    # => ['', '2']

Everything like expected, but now:
"1..".split('..')       # => ['1']
"1..".split('..', 2)    # => ['1', '']

I would expect the first to return the same that the second.
Does anyone have a good explanation, why "1..".split('..') returns an array with just one element? Or is it an inconsistency in Ruby? What do you think about that?

A: According to the Ruby String documentation for split:
If the limit parameter is omitted, trailing null fields are suppressed.
Regarding the limit parameter, the Ruby documentation isn't totally complete. Here is a little more detail:

*

*If limit is positive, split returns at most that number of fields. The last element of the returned array is the "rest of the string", or a single null string ("") if there are fewer fields than limit and there's a trailing delimiter in the original string.

Examples:
"2_3_4_".split('_',3)
=> ["2", "3", "4_"]

"2_3_4_".split('_',4)
=> ["2", "3", "4", ""]

*

*If limit is zero [not mentioned in the documentation], split appears to return all of the parsed fields, and no trailing null string ("") element if there is a trailing delimiter in the original string. I.e., it behaves as if limit were not present. (It may be implemented as a default value.)

Example:
"2_3_4_".split('_',0)
=> ["2", "3", "4"]

*

*If limit is negative, split returns all of the parsed fields and a trailing null string element if there is a trailing delimiter in the original string.

Example:
"2_3_4".split('_',-2)
=> ["2", "3", "4"]

"2_3_4".split('_',-5)
=> ["2", "3", "4"]

"2_3_4_".split('_',-2)
=> ["2", "3", "4", ""]

"2_3_4_".split('_',-5)
=> ["2", "3", "4", ""]

It would seem that something a little more useful or interesting could have been done with the negative limit.


text:
Q: How to classify edge-images which belong to two highly changeable but distinguishable classes according to edges (contours) "curviness" Introduction
I am working on a project in OpenCV in C++ and I am trying to classify a small image (a frame from a video) containing many edges into two groups. I would also like to retain the information of how close the image is to class A or to class B, because this classification does not seem to be simply a binary problem - sometimes the images is a mixture of class A and B.
Class A can be roughly determined by existence of curvy/smooth edges, similar to arches or parts of elliptic structures, which often are oriented into some kind of center (like in a tunnel).
The other class, class B is usually very chaotic and the edges on such image are definitely less curvy, they are often winding and usually don't have any kind of "center of attention".
Classes:
The images from both classes are in following links:
Group A
Group B
Previous approaches and ideas
I was trying to separate each sufficiently long contour and then calculate some kind of curvature/curviness coefficient - basically I downsampled the contour (by 10), then I traversed along the new contour and calculated the average value of absolute angle between two segments created by 3 consecutive points. Then based on this value I determined whether a current contour is "curvy" or not. According to that I calculated a few features:

*

*total length of curvy contours / total length of all contours

*number of curvy contours / number of all contours

*etc.

However, the very curvature calculation seems to be not working very robustly (in one frame a contour is considered to be curvy, in second the same contour with slighly changed shape is not etc.) and also setting the threshold to determine which contour is curvy and which is not (based on "avereage curvines of single contour") is difficult to set properly. Also, such approach in no way takes into account the specific "shape" of class A and therefore classification results are very poor.
I was thinking about some kind of ellipse fitting, but as you can see, the class A is more like a group of arches than actual ellipse or circle.
I was reading about some ways of comparing edge maps such as Hausdorff matching, but it does not seem to be very helpful in my case. Also, it is important, that I want to keep the algorithm simple, because it has to be able to work in real time and also it is only a part of bigger software.
Finally, my question is:
Do you have any ideas of any other, better features and calculations that I can use to describe and then classify such edges/images? Is there a robust solution to describe my classes?


text:
Q: Socket.io отключается Я прикидываю код на сервере и клиенте, после чего в putty пишу node code.js, и работа скрипта начинается, но как я закрываю putty, код перестает работать? Что за хрень?
A: Вопрос на самом деле Руткодовский и касается исключительно администрирования *никсов. Вы отключаетесь, ваш сеанс закрывается и запущенные в нем процессы.
Вам же нужно запустить node.js' в режиме демона/в фоновом режиме. Варианты:

*

*Воспользоваться довольно удобной оберткой для запуска ноды - модулем forever. Установите через npm (npm install forever) и пользуйтесь на здоровье (forever start code.js). Он вам и несколько приложений запустит/остановит и логи аккуратно сложит.

*Решить вопрос по-никсовому, как-то так: nohup node code.js >/dev/null 2>&1 &

A: Установи pm2 глобально и запусти pm2 start code.js --name=sockets.
По окончанию пропиши pm2 stop sockets


text:
Q: Why does voltage reading increase the greater the resistance load? I'm new to electronics. So basically I already understand Ohm's law and the math behind why this is the case. What I don't get is the idea behind it.
Shouldn't the greater the load resistance be, the smaller the voltage? The resistance should 'resist' and thus lower the voltage. I hope I'm making sense.
Right here is a battery's open circuit voltage:

In this other scenario, I've placed a shunt of 2 ohms which should run parallel to the shunt present in the voltmeter. Which means, in my understanding, that the lower the value of your resistance, the lower the voltage drawn from the battery.

A: Your circuit is a voltage divider and behaves exactly as expected. Nothing special about one resistance being called "internal battery resistance". The circuit theory doesn't care very much about names, only about behaviors.

simulate this circuit – Schematic created using CircuitLab
R1 and R2||R3 form the voltage divider. Since R3>>R2, R3 can be ignored without introducing much error. Thus you have a voltage divider R1 and R2, whose output voltage is \$ V_1 \cdot R_2/(R_1+R_2) \$.

Shouldn't the greater the load resistance be, the smaller the voltage?

Your intuition is backwards. You should think: the greater the load conductance, the smaller the voltage, since the better the load conducts, the more it behaves like a short circuit, and a voltage across an ideal short circuit is zero.
Here, the short circuit - just like open circuit - is an abstract concept. Real short circuits never have zero resistance, unless they are superconductors that is. And even superconductors aren't ideal -  they stop working when the current is too high or when they get too warm, and then "stops working" means that things go boom or that things get real expensive real quick.
Notation:

*

*R2||R3 means "resistance of R2 in parallel with R3", numerically: \$ (1/R_2+1/R_3)^{-1} \$.

*R3>>R2 means "R3 much larger than R2", typically \$ R_3 \ge 32R_2 \$, although some people are fine with a factor of 10 - it depends on how accurate your models needs to be.

A: If you had an ideal battery (ie without R1), then you would measure the same voltage whatever the load (resistors R4 and R5).
For a real battery, with an internal resistance, you can think of it as an ideal voltage source (that will always stay at 10V) and an internal resistor R1. The greater the current, the more voltage you loose in R1, therefore the voltage across the real battery decreases. And if you decrease the resistance of the load, then you increase the current (if electrons have less trouble traveling, more will do so). So the lower R4 and R5, the more current, and therefore the more voltage loss in R1, which means less apparent voltage on the battery.
Another way to see it is that you have 2 resistors in series (R1 and {R4, R5}). You split the voltage of the battery (10V) into the 2 resistors : the bigger resistor in proportion gets the biggest share. So if you decrease {R4, R5} then you have less voltage on them (and more in R1, in such way that the sum remains 10V)

A:
Because the resistance, should 'resist' and thus lower the voltage... Which means, in my understanding, that the lower the value of your resistance, the lower the voltage drawn from the battery.

Your assumption is true if the resistance is connected in series to the load and you are interested in the voltage across the load.
The voltage across the resistor is a loss (drop) that is subtracted from the input voltage; the rest is a useful voltage across the load. From this point of view, the loss (voltage drop) increases when the resistance increases; the gain decreases and this corresponds to your view. The network of the two elements in series forms a "voltage divider" that can be seen everywhere in this world.
In your case, the resistance is connected in parallel to the load and the relation is the opposite. Now the voltage across the resistor is useful since it is the load voltage. The network of the two elements in parallel forms a "current divider".

A:
Shouldn't the greater the load resistance be, the smaller the voltage? Because the resistance, should 'resist' and thus lower the voltage.

Josh pushing the car. Image source: Omegaman on Flickr. Creative Commons licence Attribution-NonCommercial-ShareAlike 2.0 Generic (CC BY-NC-SA 2.0).
Voltage and pressure or force are somewhat analogous. In the photo we can see that Josh is leaning at quite an angle to apply force to the car to get it to move. The more resistance the more he can lean. The higher the load, the higher the rolling resistance and the more pressure can be applied.
Similarly in an electrical circuit the higher the resistance the higher the voltage that must be applied to achieve a certain current.


text:
Q: How to prove that this integral converges absolutely? $f:[a,{\infty}[\to\mathbb{R}\ $ is  bounded and suppose that $f$ is integrable on each interval of the form $[a,b[$. Prove that
$$\int_0^\infty \frac { f(x) }{ x^p } \ \, dx$$ converges absolutely for $p>1$. Conclude that, if $x^pf(x)$is bounded for some $p>1$, then $$\int_a^\infty f\ \, dx$$ converges absolutely.


text:
Q: Jest mock document.activeElement I have a function that uses the DOM
const trap = {
  // ...
  init() {
    if (document.activeElement === this.firstTabStop) {
      return this.lastTabStop.focus();
    }
  }
}

module.exports = trap.init;

I try to mock document.activeElement but it throws an error.
global.document.activeElement = mockFirstTabStop;

mockFirstTabStop is just function mock, but whatever I put there, the error is the same.

TypeError: Cannot set property activeElement of [object Object] which has only a getter

So, how can I test that conditional to expect this.lastTabStop.focus() was called?

A: The solution is to create a mocked DOM and use it as scenario:
trap.js
const trap = {
  // ...
  init() {
    if (document.activeElement === this.firstTabStop) {
      return this.lastTabStop.focus();
    }
  }
}

module.exports = trap.init;

trap.test.js
const trap = require('./trap.js');

// Mock a DOM to play around
document.body.innerHTML = `
    <div>
        <button id="btn1">btn 1 </button>
        <button id="btn2">btn 2 </button>
        <button id="btn3">btn 3 </button>
    </div>
`;

// Mock Jest function
const mockBtnFocus = jest.fn();
const mockBtnFirst = document.getElementById('btn1');
const mockBtnLast = document.getElementById('btn3');

it('should focus this.lastTabStop when activeElement is this.firstTabStop', () => {
    mockBtnFirst.focus(); // <<< this is what sets document.activeElement
    mockBtnLast.focus = mockBtnFocus;

    // Mock trap context to access `this`
    trap.bind({
        firstTabStop: mockBtnFirst,
        lastTabStop: mockBtnLast,
    });

    expect(mockBtnLast.focus).toHaveBeenCalledTimes(1);
});

A: An alternative solution:
const element = document.createElement('div');

Object.defineProperty(document, 'activeElement', { value: element, writable: false });


text:
Q: Is this query non compatible with php? It there a glaringly obvious syntax error because I can't get it to run So, I am currently making a dashboard for my boss, displaying data from a logistics perspective, he has sent me his own MS Access query, for the life of my I cannot make it run, in an attempt to make a table our worker can view from the data it should be pulling. Is anything glaringly wrong with it?
I'm just an apprentice, but my seniors have suggested that everything with ORDER requires [] around it to run through PHP and codeigniter, I have tried altering the syntax through a validator, yet i seem to have hit a brick wall. Below is the original.
function order_table()
    {
        $date = date("Y-m-d");
        $macsdb = $this->load->database('macs', TRUE);

$query = $macsdb->query("SELECT temp123.Hour, temp123.User, Count(temp123.[ORDER]) AS CountOfORDER, Sum(temp123.SumOfCountOfPRODUCT) AS SumOfSumOfCountOfPRODUCT, Sum(temp123.SumOfSumOfQUANTITY) AS SumOfSumOfSumOfQUANTITY
FROM (SELECT temp456.Hour, temp456.User, temp456.[ORDER], Sum(temp456.CountOfPRODUCT) AS SumOfCountOfPRODUCT, Sum(temp456.SumOfQUANTITY) AS SumOfSumOfQUANTITY
FROM (SELECT WHAUDIT.Date, Format([Time],'hh') AS [Hour], WHAUDIT.User, WHAUDIT.[ORDER], Count(WHAUDIT.PRODUCT) AS CountOfPRODUCT, Sum(WHAUDIT.QUANTITY) AS SumOfQUANTITY
FROM WHAUDIT
WHERE (((WHAUDIT.type)='I11' Or (WHAUDIT.type)=' 11'))
GROUP BY WHAUDIT.Date, Format([Time],'hh'), WHAUDIT.User, WHAUDIT.[ORDER]
HAVING (((WHAUDIT.Date)='$date')) as temp456
GROUP BY temp456.Hour, temp456.User, temp456.[ORDER]) as temp123
GROUP BY temp123.Hour, temp123.User
ORDER BY temp123.Hour DESC;");

     return $query->result();
        $macsdb->close();
    }

The query by itself is as follows:
SELECT
  temp123.Hour,
  temp123.User,
  Count(temp123.[ORDER]) AS CountOfORDER,
  Sum(temp123.SumOfCountOfPRODUCT) AS SumOfSumOfCountOfPRODUCT,
  Sum(temp123.SumOfSumOfQUANTITY) AS SumOfSumOfSumOfQUANTITY
FROM
  (
    SELECT
      temp456.Hour,
      temp456.User,
      temp456.[ORDER],
      Sum(temp456.CountOfPRODUCT) AS SumOfCountOfPRODUCT,
      Sum(temp456.SumOfQUANTITY) AS SumOfSumOfQUANTITY
    FROM
      (
        SELECT
          WHAUDIT.Date,
          Format([Time], 'hh') AS [Hour],
          WHAUDIT.User,
          WHAUDIT.[ORDER],
          Count(WHAUDIT.PRODUCT) AS CountOfPRODUCT,
          Sum(WHAUDIT.QUANTITY) AS SumOfQUANTITY
        FROM
          WHAUDIT
        WHERE
          (
            (
              (WHAUDIT.type) = 'I11'
              Or (WHAUDIT.type) = ' 11'
            )
          )
        GROUP BY
          WHAUDIT.Date,
          Format([Time], 'hh'),
          WHAUDIT.User,
          WHAUDIT.[ORDER]
        HAVING
          (((WHAUDIT.Date) = '$date')) as temp456
        GROUP BY
          temp456.Hour,
          temp456.User,
          temp456.[ORDER]
      ) as temp123
    GROUP BY
      temp123.Hour,
      temp123.User
    ORDER BY
      temp123.Hour DESC;

I have been trying to produce the results using the echo function to populate a table, I haven't gotten as far as I have yet to make it work. It seems to be a query, within a query, within a query. Any advice would be much appreciated.
I have tried square bracketing all instances of ORDER as it is apparently an essential part of it that won't be read properly without it. I have tried running it through a validator but this throws up various issues because of the brackets also. I also know that it seems to really not like the format Time section for some reason.
The goal of this query is to be able to populate a table from the results on a Codeigniter view page. Any advice would be very much appreciated.

A: Date value expressions in Access are wrapped in octothorpes, so either:
HAVING (((WHAUDIT.Date)=#$date#)) as temp456

or, if it today's date:
HAVING (((WHAUDIT.Date)=Date())) as temp456

Also, the leading space here looks weird:
Or (WHAUDIT.type) = ' 11'


text:
Q: how to calculate moving average in RxJava In finance domain, we usually need to calculate the moving-window aggregate value from a stream of time series data, use moving average as an example, say we have the following data stream(T is time stamp and V is the actual vlaue):
[T0,V0],[T1,V1],[T2,V2],[T3,V3],[T4,V4],[T5,V5],[T6,V6],[T7,V7],[T8,V8],[T9,V9],[T10,1V0],......

to calculate a moving average 3 from the stream we get:
avg([T0,V0],[T1,V1],[T2,V2]),
avg([T1,V1],[T2,V2],[T3,V3]),
avg([T2,V2],[T3,V3],[T4,V4]),
avg([T3,V3],[T4,V4],[T5,V5]),
avg([T4,V4],[T5,V5],[T6,V6]),...

To calculate the moving average, it seems like we could do it by :

*

*build a Observable from the original stream

*build a Observable from the original stream by aggregate the values into groups

*using aggregate operator to calculate the final results from Observable in step 2.

Step 1 and 3 is trivial to implement, however, for step 2 it seems like current RxJava do not have build-in operator to produce moving-windows groups, the window/groupBy operator seems not fit in this case, and I did not find a easy way to compose a solution from existing operators, can any one suggest how to do this in RxJava in a "elegantly" fashion?

A: RxJava version: 0.15.1
import java.util.List;
import rx.Observable;
import rx.util.functions.Action1;

class Bar {

    public static void main(String args[]) {

        Integer arr[] = {1, 2, 3, 4, 5, 6}; // N = 6
        Observable<Integer> oi = Observable.from(arr);

        // 1.- bundle 3, skip 1
        oi.buffer(3, 1)
        /**
         * 2.- take only the first X bundles
         * When bundle 3, X = N - 2 => 4
         * When bundle 4, X = N - 3 => 3
         * When bundle a, X = N - (a-1)
         */
          .take(4)
        // 3.- calculate average
          .subscribe(new Action1<List<Integer>>() {
            @Override
            public void call(List<Integer> lst) {
                int sum = 0;
                for(int i = 0; i < lst.size(); i++) {
                    sum += lst.get(i);
                }

                System.out.println("MA(3) " + lst +
                                   " => " + sum / lst.size());
            }
        });

    }

}

Sample output:

MA(3) [1, 2, 3] => 2
MA(3) [2, 3, 4] => 3
MA(3) [3, 4, 5] => 4
MA(3) [4, 5, 6] => 5

A: I'd do it like this:
public static Observable<Double> movingAverage(Observable<Double> o, int N) {
    return o.window(N, 1).flatMap(
        new Func1<Observable<Double>, Observable<Double>>() {
            public Observable<Double> call(Observable<Double> window) {
                return Observable.averageDoubles(window);
            }
        }
    );
}

*

*I use window (which emits Observables, which only consume a constant amount of memory) and not buffer (which emits Lists, which consume memory for each of their item).

*This is an example of how you can use combinator operators instead of writing your own loops, something that you should always consider when using Observables.

Update: If you want to filter out the windows at the end of the stream which have less than n elements, you could do it like this:
def movingAverage(o: Observable[Double], n: Int): Observable[Double] = {
  class State(val sum: Double, val n: Int)
  o.window(n, 1).flatMap(win =>
    win.foldLeft(new State(0.0, 0))((s, e) => new State(s.sum + e, s.n + 1))
       .filter(s => s.n == n)
       .map(s => s.sum/s.n))
}

(I chose Scala because it's shorter to write, but in Java, you can do the same, just note that Scala's foldLeft is called reduce in Java).


text:
Q: C++, constexpr и инициализатор синглтона Рассмотрим следующий код:
class Singleton
{
    public:
    static const Singleton& instance()
    {
        const static Singleton singleton;
        return singleton;
    }

    private:
    constexpr Singleton()
    {
        fillTable();
    }

    constexpr void fillTable()
    {
        uint64_t value = 0;
        for (auto& element : table)
        {
            element = value;
            value = value * 2 + 1;
        }
    }

    // Копирование и перемещение запретили.
    // ...

    array<uint64_t, 1024> table;
};

Действительно ли такой код заполняет таблицу синглтона на этапе компиляции?
Если да, то что происходит при вызове конструктора? Ничего? То есть, таблица уже заполнена еще до вызова конструктора?

A: Вычисления на этапе компиляции будут гарантированы только в том случае, если:

*

*вычисленное значение используется в качестве параметра шаблона
(старый стиль)

*вычисленное значение записывается в constexpr -
переменную. В остальных случаях - как повезет.
По вашему коду сделать вывод невозможно.

A: *

*На constexpr-конструкторы есть ограничения: все нестатические
члены класса должны быть инициализированы в списке
инициализатора конструктора(или при объявлении), точно также, как
и обычно инициализируются константные члены класса. Поэтому вы не
сможете вызвать constexpr_функцию в теле constexpr-конструктора для
инициализации члена table.

*Вы имеете возможность создать всего один экземпляр класса_одиночки
посредством вызова статического члена, который возвращает
статический обьект, поэтому   смысла нет содержать
нестатический член в этом классе.

Выражение constexpr void fillTable() означает, что функция ничего не возвращает, и это ничего является константным выражением. Одним словом constexpr_функция должна возвращать значение, являющимся результатом любого константного выражения.
Надеюсь я смог помочь понять, почему gbg прав в том, что

По вашему коду сделать вывод невозможно


text:
Q: Android release build failing but debug version builds OK I'm working on a small Android Wear OS app and am pretty close to a release version.
The app is built in Android Studio using the Wear OS application template and it currently has just the one Activity (MainActivity).
Up to now I have been building a debug variant without any problems. I didn't need to tweak anything to make that work.
But now I am trying to build a release variant I am getting the following error:
Error: MainActivity must extend android.app.Service [Instantiatable]

My AndroidManifest.xml is as follows and it's the <service android:name="MainActivity" that is flagging as the error in the editor with MainActivity underlined in red:
<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@android:style/Theme.DeviceDefault">
    <uses-library
        android:name="com.google.android.wearable"
        android:required="true" />

    <meta-data
        android:name="com.google.android.wearable.standalone"
        android:value="true" />

    <!-- Recommended for Android 9 (API level 28) and lower. -->
    <!-- Required for Android 10 (API level 29) and higher. -->
    <service
        android:name="MainActivity"
        android:foregroundServiceType="location" >
    <!-- Any inner elements would go here. -->
    </service>

    <activity
        android:name=".MainActivity"
        android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

My MainActivity currently extends Activity
public class MainActivity extends Activity {

I have no idea how to resolve this... it doesn't make sense to me that the debug variant builds and runs fine but the release variant doesnt.
The only release build specific stuff in my build.gradle is:
buildTypes {
    release {
        minifyEnabled true
        shrinkResources true
        proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
    }
}

When I switch back to the debug variant the app build and runs perfectly on both an AVD Wear OS device and on an actual device.


text:
Q: Intent Service derived call explicit super class constructor I am learning android and came across an example like
public static class A extends IntentService {
    public A() {
        super("AppWidget$A");
    }
}

Can someone please tell me why do we have to call constructor of the superclass(IntentService) explicitly? and what does the parameter string signify?

A: It is used only for debugging. Here is a part of IntentService source code that uses this:
public abstract class IntentService extends Service {

    ...
    private String mName;
    ...

    /**
     * Creates an IntentService.  Invoked by your subclass's constructor.
     *
     * @param name Used to name the worker thread, important only for debugging.
     */
    public IntentService(String name) {
        super();
        mName = name;
    }

    ...

    @Override
    public void onCreate() {
        super.onCreate();
        HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
        thread.start();

        mServiceLooper = thread.getLooper();
        mServiceHandler = new ServiceHandler(mServiceLooper);
    }

    ...
}

A: IntentService has a single constructor that takes a string argument
"name".I found that its only use is in naming the worker thread for the IntentService. This thread is named IntentService [name].


text:
Q: Can Bamboo deploy to a server with only an internal IP? All the Bamboo questions seem to be here, so here goes.
We have a development server that we would like to deploy to, using Bamboo OnDemand. It doesn't have an outwardly facing IP address, however. Our team cannot figure out how to get around this limitation.
Should this possible? What are the options to accomplish this?

A: This isn't much of an answer, but yes it is possible.
A VPN connection must be made from the agent(in our case EC2 and VPC) to the local network, but from what I am able to gather, it isn't too complicated.
A Note: I haven't tried this yet. We are mostly likely going with Bamboo self-hosted just for ease of setup.


text:
Q: Resizing UIPopoverController I have a UIPopoverController. I put a UINavigationController with two UITableViewcontrollers in it.
I create a subclassed UITableView, I'm able to set the size of the popover with tableView.contentSizeForViewInPopover:
if (self.myPopoverController.isPopoverVisible)
{
    [self.myPopoverController dismissPopoverAnimated:YES];
}
else
{
    MyRootTableView *rootTableView = [[MyRootTableView alloc]initWithStyle:UITableViewStyleGrouped];
    MyRootTableView.contentSizeForViewInPopover = CGSizeMake(POPOVER_SIZE.width, [self createContentHeighForTableViewController:tableView]);
    MyRootTableView.boundaryDelegate = self;

    UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:tableViewController];
    navController.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    navController.navigationBar.barStyle = UIBarStyleBlack;

    self.myPopoverController = [[UIPopoverController alloc] initWithContentViewController:navController];
    self.myPopoverController.delegate = self;

    [self.myPopoverController presentPopoverFromRect:frame inView:view permittedArrowDirections:arrowDirection animated:YES];
}

In the rootTableViewController's didSelectRowAtIndexPath:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    DetailedTableViewController *tableViewController = [[DetailedTableViewController alloc] initWithStyle:UITableViewStyleGrouped];
    tableViewController.contentSizeForViewInPopover = CGSizeMake(POPOVER_SIZE.width, [self createContentHeighForTableViewController:tableViewController]);
    tableViewController.delegate = self.boundaryDelegate;

    [self.navigationController pushViewController:tableViewController animated:TRUE];
}

createContentHeightForTableViewController: calculates the height needed to show all the cells in the table view
So for the root tableViewController, I set the content size. When I create the detailed view controller, I set the contentSizeForViewInPopover to a different size. This works great. The issue I'm having is when I navigate back to the root table view, the contentSizeForViewInPopover is still set for the detail table view.
How can I resize the pop over when the table view is displayed or appears?

A: Try to use preferredContentSize instead of contentSizeForViewInPopover on your tableViewController (contentSizeForViewInPopover is deprecated on iOS7)

A: You should set popoverContentSize on the UIPopoverController directly in the viewWillAppear method of your parent view controller (or some other appropriate place).  Wherever you want to force the popover's content size to update.


text:
Q: Multiple Inline Insert into Mysql using Ajax JQuery in PHP I am new in php. I trying to know Multiple Inline Insert into Mysql using Ajax JQuery in PHP.
Then I follow this tutorial on "webslesson". My all codes and database are Ok as like as webslesson web tutorial . But my save button doesn't work and don't send any data in my database and also not shown any error....
index.php
<!DOCTYPE html>

<title>Multiple Inline Insert into Mysql using Ajax JQuery in PHP</title>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />

Multiple Inline Insert into Mysql using Ajax JQuery in PHP

  Item Name
  Item Code
  Description
  Price

  <button type="button" name="add" id="add" class="btn btn-success btn-xs">+</button>

  <button type="button" name="save" id="save" class="btn btn-info">Save</button>

insert.php
<?php
//insert.php
$connect = mysqli_connect("127.0.0.1", "root", "", "testing4");
if(isset($_POST["item_name"]))
{
  $item_name = $_POST["item_name"];
  $item_code = $_POST["item_code"];
  $item_desc = $_POST["item_desc"];
  $item_price = $_POST["item_price"];
  $query = '';
    for($count = 0; $count<count($item_name); $count++)
   {
     $item_name_clean = mysqli_real_escape_string($connect, $item_name[$count]);
     $item_code_clean = mysqli_real_escape_string($connect, $item_code[$count]);
     $item_desc_clean = mysqli_real_escape_string($connect, $item_desc[$count]);
     $item_price_clean = mysqli_real_escape_string($connect, $item_price[$count]);
      if($item_name_clean != '' && $item_code_clean != '' && $item_desc_clean != '' && $item_price_clean != '')
     {
     $query .= '
     INSERT INTO item(item_name, item_code, item_description, item_price)
     VALUES("'.$item_name_clean.'", "'.$item_code_clean.'", "'.$item_desc_clean.'", "'.$item_price_clean.'");
      ';
      }
     }
   if($query != '')
    {
       if(mysqli_multi_query($connect, $query))
     {
    echo 'Item Data Inserted';
     }
    else
    {
      echo 'Error';
    }
   }
     else
   {
     echo 'All Fields are Required';
   }
   }
   ?>

fetch.php
 <?php
//fetch.php
 $connect = mysqli_connect("127.0.0.1", "root", "", "testing4");
 $output = '';
 $query = "SELECT * FROM item ORDER BY item_id DESC";
 $result = mysqli_query($connect, $query);
 $output = '

Item Data

  Item Name
  Item Code
  Description
  Price

   ';
   while($row = mysqli_fetch_array($result))
   {
    $output .= '

  '.$row["item_name"].'
  '.$row["item_code"].'
  '.$row["item_description"].'
  '.$row["item_price"].'

   ';
    }
  $output .= '
';
  echo $output;
  ?>

This is my database......
item.sql
--
-- Database: `testing4`
- -

-- --------------------------------------------------------

--
-- Table structure for table `item`
--

CREATE TABLE `item` (
   `item_id` int(11) NOT NULL,
    `item_name` varchar(250) NOT NULL,
    `item_code` varchar(250) NOT NULL,
    `item_description` text NOT NULL,
    `item_price` varchar(30) NOT NULL
   ) ENGINE=InnoDB DEFAULT CHARSET=latin1;


text:
Q: How can I extract a vector from a list of text files I have many different text files with the same structure (900*600 pixels). Now I would like to extract 900*600 vectors each containing one data point from each text file.
For example I would like to have a vector from the position (x1,y1) with all the data points from all the text files.
Here you can see my code I have in order to generate a list with all the text files.
file.list = list.files(pattern="*.txt", full.names=T)
df = data.frame( files= sapply(file.list, FUN = function(x)readChar(x, file.info(x)$size)), stringsAsFactors=FALSE)

Now "df" is a list containing all the text files.
How can I extract now the different vectors with values from all the files?
This is my code so far. I need to define somehow a function (FUN).
files = lapply(df, FUN, header = F, sep="\t", skip = 2, stringsAsFactors = F)

I prepared a dummy data set.
a = matrix(c(15, 12,    37, 21, 37, 26, 33, 33, 27, 38, 32, 21, 24, 18,
             20, 14, 32, 56, 16, 7, 23, 14, 34, 42), nrow = 3, ncol = 4)
b = matrix(c(14, 18,    34, 26, 37, 26, 32, 36, 21, 39, 32, 21, 22, 18,
             20, 16, 42, 50, 16, 7, 23, 12, 36, 40), nrow = 3, ncol = 4)
c = matrix(c(10, 12,    34, 29, 31, 26, 30, 30, 20, 38, 36, 21, 29, 18,
             20, 10, 32, 59, 16, 1, 23, 10, 39, 49), nrow = 3, ncol = 4)

file.list = list(a,b,c)

Here every variable corresponds to one textfile (listed in file.list). And instead of a 900*600 matrix there are 3*4 matrices.
Accordingly to your suggestions I implemented the the functions the following way.
cmbn = expand.grid(1:3, 1:4)
flen = length(file.list)
lapply(1:(nrow(cmbn)),function(t,lst,cmbn){
  return(sapply(1:flen,function(i,t1,lst1,cmbn1){
    return(lst1[[i]][cmbn1$Var1[t1],cmbn1$Var2[t1]])},t,lst,cmbn))}
  ,file.list,cmbn)

A: This should work for you:
It will take two loops. Not sure if this is the most optimized solution.
cmbn is the data.frame of co-ordinates.
cmbn  =  expand.grid(1:3,1:4)
#or `expand.grid(1:900,1:600)` in your case

flen = length(file.list)
lst will take file.list
lapply(1:(nrow(cmbn)),function(t,lst,cmbn)
                      {return(sapply(1:flen,function(i,t1,lst1,cmbn1){
                              return(lst1[[i]][cmbn1$Var1[t1],cmbn1$Var2[t1]])},t,lst,cmbn))
                      },file.list,cmbn)


text:
Q: how to do this equation? I wonder how I can do this equation in this style, I tried to make it into a matrix, but is disastrous.

\begin{equation}
\begin{matrix}
\frac{2}{3}\sinh{\frac{3}{2}t}&\longleftrightarrow&\frac{2}{3}\left[\frac{\frac{3}{2}}{s^{2}-\frac{9}{4}}\right]\\
        \downarrow e^{-3t}    &      \quad        &\downarrow s\rightarrow s-3\\
\frac{2}{3}e^{-3t}\sinh{\frac{3}{2}t}&\longleftrightarrow&\frac{1}{\left[s+\frac{1}{2}\right]^2-\frac{9}{4}}
\end{matrix}
\end{equation}

A: Something like this with tikz.
\documentclass{article}
\usepackage{mathpazo}
\usepackage{amsmath}
\usepackage{tikz}
\usetikzlibrary{matrix,arrows.meta}
\begin{document}
\begin{tikzpicture}[semithick,>=Latex]
\matrix (m)[matrix of math nodes,column sep=2cm,row sep=1cm]
{
\frac{2}{3}\sinh{\frac{3}{2}t}          &   \frac{2}{3}\left[\dfrac{\frac{3}{2}}{s^{2}-\frac{9}{4}}\right]\\
\frac{2}{3}e^{-3t}\sinh{\frac{3}{2}t}   &   \dfrac{1}{\left[s+\frac{1}{2}\right]^2-\frac{9}{4}}\\
};
\draw[<->] (m-1-1) -- (m-1-1-|m-1-2.west);
\draw[<->] (m-2-1) -- (m-2-1-|m-2-2.west);
\draw[->] (m-1-1) -- node[right] {$e^{-3t}$} (m-2-1);
\draw[->] (m-1-2) -- node[right] {$s\rightarrow s-3$} (m-2-2);
\end{tikzpicture}
\end{document}

A: It's simple with tikz-cd:
\documentclass{article}
\usepackage{mathpazo}
\usepackage{amsmath,mathtools}
\usepackage{tikz-cd}

\begin{document}
\[
\begin{tikzcd}
\frac{2}{3}\sinh{\frac{3}{2}t}
  \arrow[r,leftrightarrow]
  \arrow[d,"e^{-\frac{t}{2}}"]
&
\frac{2}{3}\left[\dfrac{\frac{3}{2}}{s^{2}-\frac{9}{4}}\right]
  \arrow[d,"s\to s+\frac{1}{2}"]
\\
\frac{2}{3}e^{-3t}\sinh{\frac{3}{2}t}
  \arrow[r,leftrightarrow]
&
\dfrac{1}{\left[s+\frac{1}{2}\right]^2-\frac{9}{4}}
\mathrlap{{}=\dfrac{1}{s^2+s+2}}
\end{tikzcd}
\hphantom{{}=\dfrac{1}{s^2+s+2}} % compensate for the rlapped fraction
\]
\end{document}


text:
Q: ASP.NET Core Entity changing history I have many controllers like this:
public class EntityController : Controller
{
    private readonly IEntityRepository _entity;

    public EntityController(IEntityRepository entity)
    {
        _entity = entity;
    }

    [Authorize]
    [HttpPut("{id}")]
    public async ValueTask<IActionResult> Put(int id, [FromBody] Entity entity)
    {
        if (entity == null || entity.Id != id) return BadRequest();
        var updated = await _entity.Update(entity);
        if (updated == null) return NotFound();
        return Ok(updated);
    }
}

I need to implement entities editing (audit) history.
And, since the method is marked as [Authorize], I need to log by which user it was edited.
I'm looking at Audit.NET, but I didn't find a way to do it.

A: The Audit.NET EF Provider allows to customize the audit entity  before saving it. This has to be done at the startup with a so-called AuditEntity Action: an action that is triggered for each entity being modified.
So, you can make this action retrieve the user name from the current HttpContext and store it in a UserName property on your audit entities.
On your asp net startup code, setup a way to obtain the current HttpContext and configure the action to retrieve the username from the context:
public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        // Add the HttpContextAccessor if needed.
        services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();

        // Get the service provider to access the http context
        var svcProvider = services.BuildServiceProvider();

        // Configure Audit.NET
        Audit.Core.Configuration.Setup()
            .UseEntityFramework(x => x
                .AuditTypeNameMapper(typeName => "Audit_" + typeName)
                .AuditEntityAction((evt, ent, auditEntity) =>
                {
                    // Get the current HttpContext
                    var httpContext = svcProvider.GetService<IHttpContextAccessor>().HttpContext;
                    // Store the identity name on the "UserName" property of the audit entity
                    ((dynamic)auditEntity).UserName = httpContext.User?.Identity.Name;
                }));
    }
}

This is assuming your audit entities have a common UserName property.
If your Audit Entities already inherits from an interface or base class including the UserName, you can use the generic AuditEntityAction<T> instead.
Audit.Core.Configuration.Setup()
    .UseEntityFramework(x => x
        .AuditTypeNameMapper(typeName => "Audit_" + typeName)
        .AuditEntityAction<IUserName>((evt, ent, auditEntity) =>
        {
            var httpContext = svcProvider.GetService<IHttpContextAccessor>().HttpContext;
            auditEntity.UserName = httpContext.User?.Identity.Name;
        }));

A: To get UserID in IOC :
var userId = httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value

how-get-current-user-in-asp-net-core


text:
Q: Is it possible to run webdriverio app tests against AWS Device Farm without uploading the test suite? We currently have a suite of webdriverio/appium tests for our react native app, with separate wdio.conf files for local, simulator, BrowserStack etc.
All of the examples I can find for device farm either involve first uploading the test suite as a zip up front, or creating a custom test runner that obtains a selenium grid url from Device Farm and then triggers the wdio command (but I can only see this being used for Selenium, nothing for appium/app testing).
Is it not possible to run tests from my local machine whilst pointing to AWS Device Farm devices?

A: Unfortunately this is not possible with AWS Device Farm, as you have already noticed that they do not have a Selenium Grid for mobile devices. In general for me it has been a huge hassle to get Appium tests to work on AWS using CI/CD - both because of the setup and the inability to easily debug since I can't run the tests locally against their devices. I would advise using another cloud farm service like Browserstack which allows you to target their grid from your local machine


text:
Q: anyone can help me how to decrypt this lua key="mikacommunityscript"local a=load((function(b,c)function bxor(d,e)local f={{0,1},{1,0}}local g=1;local h=0;while d>0 or e>0 do h=h+f[d%2+1][e%2+1]*g;d=math.floor(d/2)e=math.floor(e/2)g=g*2 end;return h end;local i=function(b)local j={}local k=1;local l=b[k]while l>=0 do j[k]=b[l+1]k=k+1;l=b[k]end;return j end;local m=function(b,c)if#c<=0 then return{}end;local k=1;local n=1;for k=1,#b do b[k]=bxor(b[k],string.byte(c,n))n=n+1;if n>#c then n=1 end end;return b end;local o=function(b)local j=""for k=1,#b do j=j..string.char(b[k])end;return j end;return o(m(i(b),c))end)({5516,8542,9551,10042,6683,9468,5746,7170,8040,8999,8665,9962,10664,7255,8728,7666,7922,6403,6223,7121,9450,5928,5362

also its actually got 50k word anyone can help me with this? or is there any program thats can help with decrypting xD


text:
Q: Finding the average, maximum, minimum value of array in c I am trying to get the smallest and the largest values of the array. An array which is created by user. I keep getting Segmentation fault (core dumped). I don't know where I am doing wrong.
#include <stdio.h>
int main(void){
    int n, i;
    double sum = 0.0, array[n], avg;
    printf("Enter the size of the array:");
    scanf("%d", &n);

    for (i=0; i<n; ++i){
        printf("Enter the number for position %d: ", i + 1);
        scanf("%i", &n);
        sum += n;
    }
    avg = (double) sum / n;
    printf("Average = %.2f\n", avg);

    double largest = array[0], smallest = array[0];

    for (i = 0; i < n; i++){
        if (array[i] > largest)
        {
            largest = array[i];
        }
        else if (array[i] < smallest)
        {
            smallest = array[i];
        }
    }
    printf("The smallest is %lf and the largest is %lf!\n", smallest, largest);
}

Edit: After solving this problem, I saw that I also can't get the smallest and largest values. I keeps giving 0.000000 for both. How do I solve it? I tried the change double to float but didn't work..

A: You wrote array[n] before initialing n. This will invoke undefined behavior for using (indeterminate) value of uninitialized non-static local variable n.
The array allocating must be after reading n. It will be like this:
    int n, i;
    double sum = 0.0, avg;
    printf("Enter the size of the array:");
    scanf("%d", &n);
    double array[n];

A: @MikeCAT is totally right...
But, if you use c89 or c90 standard you will not able to get the data from the user and then declare the array.
and probably get this message when you try to compile it:
ISO C90/C89 forbids mixed declarations and code in C

what you will able to do is to dynamically allocate it, using malloc or calloc.
i see you don't use this standard but i write it anyway so if anyone will see this it could prevent a possible question..
if you do not know which c standard you use check your compilation instructions if there is "-ansi" or "std=c99" flag that means you use the c89 or c90 standard.


text:
Q: Что за свойство необходимо присвоить блоку? Что за свойство необходимо присвоить html блоку, чтобы стала возможно с ним работать так же как с элементом input. То есть точно так же вводить текст, как с текстовым полем

A: атрибут contenteditable="true", подробнее можно почитать здесь


text:
Q: Image overwrites table cell border in iTextSharp I am trying to create a PDF using iTextSharp library (version 4.1.2.0). At the top of the document, I want to add a logo, horizontal line and - below the line - some text (title).
I'm trying to achieve this by:

*

*creating a PdfPTable with one column size

*adding to it a PdfPCell with border set to BOTTOM_BORDER containing the logo image

*adding another PdfPCell with the title text to the PdfPTable

However, in the resulting PDF the image overwrites the bottom border (which otherwise shows fine). How can I stop it from overwriting it? The only way I've been able to do it is by setting FIT parameter of the PdfPCell constructor to true, but this completely destroys the layout (the image is enormous).
The code:
        document.Open();

        Image img = Image.GetInstance("Logo.PNG");
        PdfPCell cell = new PdfPCell(img, false);
        PdfPTable table = new PdfPTable(1);
        cell.Border = PdfPCell.BOTTOM_BORDER;
        table.DefaultCell.Border = PdfPCell.NO_BORDER;
        table.WidthPercentage = 100;
        table.AddCell(cell);

        PdfPCell cell2 = new PdfPCell(new Phrase("Title"));
        cell2.Border = PdfPCell.TOP_BORDER;
        table.AddCell(cell2);
        document.Add(table);

        document.Close();

And this is how it looks like:
This is how it looks like

A: Try adding this:
cell.PaddingBottom = 5;

So the updated code would be:
PdfPTable table = new PdfPTable(1);
table.DefaultCell.Border = PdfPCell.NO_BORDER;
table.WidthPercentage = 100;

Image img = Image.GetInstance("Logo.PNG");
PdfPCell cell = new PdfPCell(img, false);
cell.Border = PdfPCell.BOTTOM_BORDER;
cell.PaddingBottom = 5;
table.AddCell(cell);

PdfPCell cell2 = new PdfPCell(new Phrase("Title"));
table.AddCell(cell2);

document.Add(table);
document.Close();

Something else to try:
cell.UseBorderPadding = true;


text:
Q: Azure worker role does not seem to start We are building webapplication with an AngularJS frontend and a Web.Api backend. Both need to be hosted in Azure. To support this we created two projects:

*

*A worker role with an endpoint on 8080 for the web.api (converted from a selfhosting web.api)

*A web role on port 80

Both roles are combined in one azure service project. When running the project local in the azure emulator we have two endpoints that are working as desired. Localhost gives back the website, localhost:8080/api gives back the api. Together a nice website is running.
When deploying it to the staging environment on azure it publishes correctly. After done publishing, when we go to the site the sites loads up. The api does not work though.
When we go to the instances tab in the azure portal, we get 2 instances running in the project. 1 for XX.Azure.Worker_IN_0 and one for XX.WebRole_IN_0.
We looked in the eventlog of the worker role, but we cannot find any problems. Is there anyplace where we should look for errors? We tried searching for it but we couldn't find a log on the server. Or are we doing things with azure that we are not supposed to do.


text:
Q: MySQL connection realization in C++ object-oriented program I have C++ object-oriented application and I want to make my several different classes to have ability to send mysql queries to database and get results. I want to have single program-lifetime connection with database.
Additionally: If connection timed out, then I program to still do it's work, but then some class tries to send query, it would get exception.
I read this page: MySQL Connector/C++ Developer Guide
But there is only iterative example, not OOP.

A: There are two solutions here:
1) Make the DatabaseConnection class, create an instance of it during the application startup and then pass into other objects, something like this:
main() {
   DatabaseConnection* connection = new DatabaseConnection('connection.string');
   Application* myapp = new Application(connection);
   myapp->run();
   ...
}

So you just pass the connection instance to other objects which need the database access.
2) Use a singleton. I don't like singletons, but in this case the connection object may be needed by many parts of your application and it can be annoying to always pass it around explicitly.
With singleton you will initialize the connection on the app startup and then will get it from the singleton like this:
//application startup
DatabaseConnection* connection = DatabaseConnection::instance()->init('connection.string');
...
// get the connection when you need it
DatabaseConnection *connection = DatabaseConnection::instance();
connection->query('my query here');
...


text:
Q: Using MHDD 4.6 to check hard drives Following on from my previous post, I have run MHDD 4.6 from Hiren's Boot CD.
1) Does anyone know which commands I should be running to check the health of a drive?
2) I have run 'scan', but about 1/3 of blocks show up as a red X. Does this mean the drive is dead, or can it be recovered?

A: Various discussion of "red" blocks here, http://forum.hddguru.com/hdd-faq-t5.html


text:
Q: How is generic type 'T constrained on this Don Syme's code? let compareOn f x (yobj: obj) =
     match yobj with
     | :? 'T as y -> compare (f x) (f y)
     | _ -> invalidArg "yobj" "cannot compare values of different types"

I don't see how 'T above relates to the type of x.
Why is not the type of x just 'a ?
Used in:
type stamp = int

[<CustomEquality; CustomComparison>]
type MyUnionType =
    | MyUnionType of stamp * (int -> int)

    static member Stamp (MyUnionType (s,_)) = s

    override x.Equals y = equalsOn MyUnionType.Stamp x y
    override x.GetHashCode() = hashOn MyUnionType.Stamp x
    interface System.IComparable with
      member x.CompareTo y = compareOn MyUnionType.Stamp x y

A: The reason why has to do with the uses of x.  The value x and y are used as arguments to the same call back: f x and f y.  The type of y in this expression is known to be T hence x must also be of a type compatible with T so F# chooses T


text:
Q: Real and Complex Analysis Rudin thm 1.41 I'm having trouble understanding the implication Rudin makes here at the last two sentences.
How do the integrals look like (1):
I was thinking they are like this:
$$ \int_X g d\mu = \sum_{k=1} ^{\infty} \int_X \chi_{E_{k}} d \mu $$
I'm having trouble how this is (1)...

A: Thus lemma is also known as the Borel–Cantelli lemma. So we want to show that $\mu(A) = 0$. First notice that by definition $x \in A$ if and only if $x \in E_k$ for infinitely many $k$. Let $x \in A$. Then as $g(x) = \sum_{k=1}^{\infty} \chi_{E_k}(x)$, we see $g(x) = \infty$ (since $x$ is in infinitely many $E_k$). Now the idea is to recall that if $\int |g(x)| < \infty$, then $g(x)$ is finite valued almost everywhere.  We omit the absolute values since $g \geq 0$
So we want to integrate $g$ and use the monotone convergence theorem(our $g$ and soon to be defined $g_n$ are non-negative and measurable, so we can apply MCT) with $g_n(x) := \sum_{k=1}^{n} g(x)$, to interswap the order of integration and summation.
So we see $\int_{\mathbb{R}^d} g(x)$ = $\int_{\mathbb{R^d}} \sum_{k=1}^{\infty} \chi_{E_k}(x)$ = $\sum_{k=1}^{\infty} \int _{\mathbb{R}^d}\chi_{E_k}(x)$ = $\sum_{k=1}^{\infty} \int_{E_k} 1$ = $\sum_{k=1}^{\infty} \mu(E_k) < \infty$ by assumption. Hence, we have $g(x)$ is finite valued almost everywhere. Therefore, as $A$ is the set where $g(x)$ is infinity, we see $\mu(A) = 0$ as desired.

A: There are two major facts employed here. The first is that we can interchange the series sign with integral sign by a suitable application of the monontone convergence theorem. The second is that $\int_{A} g = \int g1_{A}$ for all measurable $A$.