text:
Q: 1D Ising model as indpendent coin tosses : Partition function calculation My query refers to the Wikipedia article on the one-dimensional Ising model, namely the section "Comments", immediately after "Ising's exact solution".
An Ising model with Hamiltonian $$ H = -J \sum \sigma_i \sigma_j $$ is considered.
The point is made that the lowest energy state has energy $-JN$ (all spins aligned).
It is then added that the energy added by $k$ spin sign changes is $2kJ$. Then it is stated that "as the energy is additive in the number of flips, the probability $p$ of having a spin-flip at each position is independent. The ratio of the probability of finding a flip to the probability of not finding one is the Boltzmann factor"
$$ \frac{p}{1-p} = e^{-2 \beta J} $$
FIRST QUESTION: I did not find this statement obvious and I wonder how it was arrived at.
In the above statement I do not see how the energy is additive in the number of flips (the energy difference from the minimum energy state perhaps).
I can arrive at the same result in two ways, via a direct calculation, see below, but I wonder if there is a quicker way using the independence and energy additivity.
I confirmed the results as follows.
First approach: using the spin independence, I write down the partition function for a specific site, $$Z_i =   e^{-2\beta kJ} + 1$$
Then, the probabaility of haivng a flip is $p = e^{- \beta 2kJ} / Z_j $, which matches the expression for $p$ sought for. I wonder though why it would be given as a ratio, $ p / (1-p)$.
Second approach:
The average energy can be found to be
$$ U = - (N-1) J tanh(\beta J) $$
And this has to be equal to
$$ - (N-1) J + 2kJ $$ (lowest energy plus energy diffeence linear inhe number of flips)
So the average number of flips $k$ equals
$$ -\frac{N-1}{2N} [tanh (\beta J) + 1] $$
Divinding by $N$ in the large $N$ limit one gets the chance of getting a flip at a specific location
$$ p = \frac{-tanh (\beta J) + 1}{2 } $$
Which matches the previously given expression for $p$, via the identity $ (1-tanh(x))/2 = e^{-2x} / (1 + e^{-2x} )$
SECOND QUESTION
Later in the same section the partition function is calculated.
The expression is given $$ Z = \sum_{configs} e^{\sum_k S_k} = \prod_k (1+p) = (1+p)^N $$
Incidentally, I do not see the equivalence between the last two terms ($N$ is different from $k$). Most importantly, I do not see how this expression could be the partition function.
I tried to calculate the partition function myself following this route (focusing on total energy and not energy differences from the lowest energy state, so to be able to compare it with the known partition function expression). I neglect a factor of 2 (coming from summing over both the first spin possiiblities) as it goes to zero when divided by $N$ to get the free energy density.
So
 $$ Z = \sum_{configs} e^{-\beta J ( -N + \sum_k S_k)} = e^{J \beta N}  \sum_{configs} e^{ -\beta J  \sum_k S_k}
= e^{\beta J N}   \sum_k \binom{N}{k} e^{- 2 \beta J k} = e^{\beta J N }  (1 + e^{- 2 \beta J })^N $$
The free energy density $$A = -\frac{1}{\beta N} ln Z = -\frac{1}{\beta } (\beta J + ln (1 + e^{-2 \beta J}))$$
Which matches with the expression
$$A =-\frac{1}{\beta } (ln (e^{ \beta J} + e^{- \beta J}))$$ which is often presented.
But the one reported in the quoted paragraph, I cannot make sense of, it seems to give numerically different results.
Many thanks as usual

A: I think the "comments" section is just really, really  badly written with inconsistent notation. All the ideas are correct and with the right definitions each equation can be made correct (except for the final equation for free energy, which is missing a sign), but together they're totally inconsistent. What $p$ means changes, what $L$ means changes, the ground state is shifted in the equation for the partition function, which in turn screws up the free energy. It's a mess, but I will try to answer your questions and straighten it out.
Question 1
"Energy is additive in what exactly?"
"Spin flip" is an unclear way for the article to refer to it.
Indeed, if "spin flip" refers to sending a single spin to its negative, then the energy above the ground state is NOT proportional to the number of spin flips. But the text reads:

the extra energy is equal to the number of sign changes as you scan the configuration from left to right. If we designate the number of sign changes in a configuration as k, the difference in energy from the lowest energy state is 2k.

and concludes "the energy is additive in the number of flips". This is referring to a different kind of flip. If we consider the ground state (-,-,-,-,-,-,-,-), and send this to (-,-,-,-,+,+,+,+), we only have one sign "flip", and so $k=1$ (I am considering non-looping boundary conditions). You could say that "there is only one flip".
Section 3.1 of this document does a similar computation, but it refers to a boundary of a segment as a "kink" rather than a flip. The following diagram consists of two kinks, and so it is an energy $4J=2kJ$ above the ground state.

The computation in that section may be helpful for you too, and it only takes a line or three.
"Why p/(1-p)?"
I think the author of the section brings it up because it's an easy consequence of a two state system. The partition function in a two state system (ground state 0 and excited state $E$) is $Z=1+e^{-\beta E}$, so the two probabilities are $e^{-\beta E}/Z$ and $1/Z$, so their ratio is clearly $e^{-\beta E}$.
Question 2
This is where the inconsistencies are the worst. Looking at the wikipedia talk page on this section, one person who authored part of the section writes "So that if you define p=e^{J}, the sum is (1+p)^L, where L is the number of sites." J, L, and P are all inconsistent with the definitions on this page, the sign of the free energy is wrong too. It's totally mutilated. You can piece together what the author meant like this:
First, it is an important fact of statistical mechanics that the partition function of two noninteracting statistically independent systems is the product of their two partition functions.
It is easy to confirm that this rule gives the correct probabilities: if $E_1$ and $E_2$ are the energies of two configurations with partition functions $Z_1$ and $Z_2$, the probability of choosing system one with energy $E_1$ and system two with energy $E_2$ is the product of the probabilities: $$\frac{e^{-\beta E_1}}{Z_2}\frac{e^{-\beta E_1}}{Z_2}=\frac{e^{-\beta(E_1+E_2)}}{(Z_1Z_2)}=\frac{e^{-\beta E_{\text{total}}}}{Z}$$
Alternatively, you can prove this general rule by expanding with binomial coefficients and counting arguments and all that, like you did in your question. That is extra work, though.
Shifting to the point of view where to the left of any site there can either be a kink or not, we have a system of $N$ completely independent systems. If there is no kink, it contributes an energy of $-J$. If there is a kink, it contributes an energy of $+J$. Then the partition functions of the systems are each equal to $e^{-\beta J}+e^{\beta J}$, so the total partition function for $N$ sites is $(e^{-\beta J}+e^{\beta J})^N$, so the free energy density is $-\frac{1}{\beta N}\log(Z)=-\frac{1}{\beta}\log(e^{-\beta J}+e^{\beta J})$. Easy as pie!


text:
Q: Is the humanoid appearance of most alien species in the Star Trek universe ever canonically addressed? The vast majority of intelligent species in the Star Trek universe are bipedal, humanoid creatures.  From the lot I've seen of TOS, TNG, DS9, Voyager, Enterprise, and the movies, it seems that this coincidence goes largely unquestioned.
Metaknowledge grants that it is much easier to have human actors portray human-like beings, and so this was probably done due to budgetary/technological limitations.  However, I'm wondering if an in-universe reason for this was ever given or explored?

A: Yes.  In Star Trek: The Next Generation's "The Chase", the Federation, Klingons, Cardassians, and Romulans are all on what amounts to a treasure hunt:

 Representatives of all three races are together when all the pieces are put together and it turns out to be a program that takes over a tricorder and projects an image of an ancient alien who tells them that they found the galaxy empty, other than themselves, so they spread seeds of DNA throughout so there would be other races and that the existing races would be descendants of that seeding.

A: In TOS, there was a race called the Preservers in the episode The Paradise Syndrome.  They transported groups of endangered indigenous people across the galaxy and terraformed the planets as well (a possible explanation for all those earth-like planets).
TNG The Chase, was written by Ronald D Moore.  In the Star Trek TNG Companion he mentioned that he intentionally did not specify that these aliens were The Preservers and left it up to the viewer to draw the connection.
The Preservers are mentioned quite often in the trade paperbacks, and it's generally assumed that seeding is how the galaxy was populated.

A: The extraterrestrial seeding theories are all a bit suspect to me from a scientific point of view (besides the Adam and Even nonsense from Return to Tomorrow).
We already know that modern humans descended from primates which have been on earth for 65 million years, and their evolutionary roots can be traced back to the common ancestor of all mammals, the Synapsids, which lived 250 to 300 million years ago. So any exogenic explanation for the origin of humanity has to be set much earlier than half a million years ago. And the "seeds" themselves would have had to been single-celled organisms to explain what we know from modern genetic analysis of life on Earth.
A more plausible explanation is one that attempts to explain why so many species on different alien worlds have near-identical analogs on Earth (hawks, dogs, lizards, beatles, worms, etc.), and that would be convergent evolution.
It's possible that due to similar environments existing on different worlds, evolution has independently found the same "solutions" in terms of general body layout and organ function. Physics (for the most part) follows the same rules no matter what planet you're on, so that in itself is going to eliminate certain body designs while gravitating towards others.
That would explain why most complex life forms are bilateral-symmetric and only a few are radial-symmetric. It also explains why most animals have an even-number of limbs and heads are placed at the front or top of the body.
So the reason why humanoid species are so common in Star Trek is probably because the humanoid body shape is the natural upright evolution from a quadriped bodyshape, and it's one that allows one to use their hands for manipulating the environment (e.g. creating and using tools). And we don't see any sapient aliens with 2-mouths or eyes on their back because it's just inefficient to have these designs.

A: In addition to "The Chase", in the original series episode "Return to Tomorrow", Sargon says that his race had seeded other planets, and that humans and others could be their descendants.
Quoting the Wikipedia article:

Sargon repeatedly refers to the landing party as his children. When
  Kirk asks why Sargon refers to them as "my children," Sargon says it
  is probable that human beings actually are descendants of his people.
  Six thousand centuries ago, they explored and colonized the galaxy
  just as Earth people do now; he speculates that Adam and Eve were two
  of their travellers. Dr. Mulhall objects that life on Earth evolved
  independently, but Spock says the colonist idea would explain certain
  enigmas in Vulcan pre-history. Either way; Sargon can't confirm either
  legend.

All this would have happened half a million or so years ago, long after the events referenced in "The Chase".

A: My understanding - although I cannot quote particular evidence - is that the seeding argument is the reason for this. I think that the understanding is that some species was responsible at core for seeding the entire galaxy. This includes earth, and explains why many creatures have the core bipedal approach to life.
Of course, many of them have evolved in a range of ways to make them more of less humanoid. Most have forgotten that there was a seed race, some have stories that explain it. I think the question of who the initial seed race was is deliberately avoided - not that anyone actually knows for certain. It may be extinct except in its many seed forms.

A: During the Voyager episode 'Death Wish', the crew is transported back to the big bang by two Q. One Q jokes that if they did stick around their DNA would be spread through-out the universe and perhaps that is how there are so many humanoids. Then he covers his mouth, like it was a slip up that he said it.
The voyager is transported back to the future so it wasn't their DNA that was spread. But the idea seemed interesting that pieces of DNA could be spread more or less ubiquitously over the entire universe.

A: This is explained in The Paradise Syndrome, the 25th episode of Season 1 of The Original Series:

MCCOY: Were you able to make sense out of the symbols?
SPOCK: Yes. The obelisk is a marker, just as I thought. It was left by a super-race known as the Preservers. They passed through the galaxy rescuing primitive cultures which were in danger of extinction and seeding them, so to speak, where they could live and grow.
MCCOY: I've always wondered why there were so many humanoids scattered through the galaxy.
SPOCK: So have I. Apparently the Preservers account for a number of them.

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to search arraylist data in recyclerview in fragment I am creating an app I using search view in fragment to search recycler view ArrayList data but below method not showing the result
Not show my filter result in recycler view
How to show filter result in recycle view in the fragment.
anyone tell me what changes below code to fix this problem
please help me
Fragment
import in.getagf.pickuplines.Model.dataAdapter;
import in.getagf.pickuplines.Model.dataItem;

 /**
 * A simple {@link Fragment} subclass.
 */
public class LatestFragment extends Fragment {

private View myView;
private DatabaseReference RootRef, AdsRef;
private AdView adView;

private RecyclerView mRecyclerView;
dataAdapter mDataAdapter;
private RecyclerView.LayoutManager mDataLayoutManager;

public LatestFragment() {
    // Required empty public constructor
}

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

    RootRef = FirebaseDatabase.getInstance().getReference().child("App_Data");
    AdsRef = FirebaseDatabase.getInstance().getReference().child("Apps Link").child("AdsUnitID");
    mRecyclerView = (RecyclerView) myView.findViewById(R.id.latest_recyclerView);
    mDataLayoutManager = new LinearLayoutManager(getActivity());
    mRecyclerView.setLayoutManager(mDataLayoutManager);

    mDataAdapter = new dataAdapter(getDataSetLines(), getActivity());
    mRecyclerView.setAdapter(mDataAdapter);
    getResult.clear();
    //   offlinedata();

    receiverData();
    return myView;
}

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.home, menu);
    MenuItem item = menu.findItem(R.id.action_search);

    SearchView sv = (SearchView) MenuItemCompat.getActionView(item);
    sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String s) {
            return false;
        }

        @Override
        public boolean onQueryTextChange(String newtext) {
            mDataAdapter.getFilter().filter(newtext);
            return false;
        }
    });
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // handle item selection
    switch (item.getItemId()) {
        case R.id.action_search:
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

private void receiverData()
{
    RootRef.addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
            if (dataSnapshot.exists() && !dataSnapshot.child("category").getValue().toString().equals("Good Night"))
            {

                String Lines = dataSnapshot.child("lines").getValue().toString();
                String Pic = dataSnapshot.child("pic").getValue().toString();
                String visite_id = dataSnapshot.getKey();
                dataItem obj = new dataItem(visite_id, Lines, Pic);
                getResult.add(obj);
                mDataAdapter.notifyDataSetChanged();
            }
        }

        @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) {

        }
    });

    AdsRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            if (dataSnapshot.exists()) {
                String fB_Latest = dataSnapshot.child("fB_Latest").getValue(String.class);

                // Facebook Banner Ads
                adView = new AdView(getActivity(), fB_Latest, AdSize.BANNER_HEIGHT_50);
                LinearLayout adContainer = (LinearLayout) myView.findViewById(R.id.latest_facebook_ads);
                adContainer.addView(adView);
                adView.loadAd();
                // end
            }
        }

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

        }
    });
}

@Override
public void onDestroy() {
    if (adView != null) {
        adView.destroy();
    }
    super.onDestroy();
}

private ArrayList<dataItem> getResult = new ArrayList<dataItem>();
private List<dataItem> getDataSetLines() {
    return getResult;
}
}

dataAdapter
/**
 * Created by Vinay Singh on 16/02/2019.
 */

public class dataAdapter extends RecyclerView.Adapter<DataViewHolders>
implements Filterable {

private List<dataItem> myList;
private  List<dataItem> myListFull;
private Context context;

public dataAdapter(List<dataItem> myList, Context context) {
    this.myList = myList;
    this.context = context;
    myListFull = new ArrayList<>(myList);
}

@Override
public DataViewHolders onCreateViewHolder(ViewGroup viewGroup, int position) {

    View layoutView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_view, null, false);
    RecyclerView.LayoutParams lp = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    layoutView.setLayoutParams(lp);
    DataViewHolders rcv = new DataViewHolders(layoutView);

    return rcv;
}

@Override
public void onBindViewHolder(DataViewHolders holder, int position) {

    String lines = myList.get(position).getLines();
    holder.mLines.setText(myList.get(position).getLines());
    holder.mVisit_id.setText(myList.get(position).getVisite_id());
    if (myList.get(position).getPic().equals("default")) {
        Picasso.get().load(R.drawable.app_logo).into(holder.mImage);
    }else if (myList.get(position).getPic().equals("Funny"))
    {
        Picasso.get().load(R.drawable.funny).into(holder.mImage);
    }
    else if (myList.get(position).getPic().equals("Romantic"))
    {
        Picasso.get().load(R.drawable.romantic).into(holder.mImage);
    }
    else if (myList.get(position).getPic().equals("Chat Tips"))
    {
        Picasso.get().load(R.drawable.chat).into(holder.mImage);
    }
    else if (myList.get(position).getPic().equals("Good Morning"))
    {
        Picasso.get().load(R.drawable.goodmorning).into(holder.mImage);
    }
    else if (myList.get(position).getPic().equals("Motivation"))
    {
        Picasso.get().load(R.drawable.motivation).into(holder.mImage);
    }
    else if (myList.get(position).getPic().equals("Shayri"))
    {
        Picasso.get().load(R.drawable.shayari).into(holder.mImage);
    }
    else if (myList.get(position).getPic().equals("WhatsApp"))
    {
        Picasso.get().load(R.drawable.whatsapp).into(holder.mImage);
    }
    else if (myList.get(position).getPic().equals("Jokes"))
    {
        Picasso.get().load(R.drawable.jokes).into(holder.mImage);
    }
    else if (myList.get(position).getPic().equals("Good Night"))
    {
        Picasso.get().load(R.drawable.goodnight).into(holder.mImage);
    }
    else if (myList.get(position).getPic().equals("Chatting"))
    {
        Picasso.get().load(R.drawable.chatting).into(holder.mImage);
    }
    else
    {
        Picasso.get().load(R.drawable.app_logo).into(holder.mImage);
    }

}

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

@Override
public Filter getFilter() {
    return myListFilter;
}

private Filter myListFilter = new Filter() {
    @Override
    protected FilterResults performFiltering(CharSequence constraint) {
        String charString = constraint.toString();
        if (charString.isEmpty())
        {
            myListFull = myList;
        }
        else
        {
            List<dataItem> filteredList = new ArrayList<>();
            for (dataItem item : myListFull)
            {
                if (item.getLines().contains(charString)){
                    filteredList.add(item);
                }
            }
            myListFull = filteredList;
        }
        FilterResults results = new FilterResults();
        results.values = myListFull;
        return results;
    }

    @Override
    protected void publishResults(CharSequence constraint, FilterResults results) {
        myList.clear();
        myList.addAll((List) results.values);
        notifyDataSetChanged();
    }

};
}

A:     List<dataItem> filteredList = new ArrayList<>();
    for (dataItem item : myList) // myListFull wrong
    {
        if (item.getLines().contains(charString)){
            filteredList.add(item);
        }
    }
    myListFull = filteredList;

A: First Remove this code in your fragment
private ArrayList<dataItem> getResult = new ArrayList<dataItem>();
private List<dataItem> getDataSetLines() {
    return getResult;
}
}

and intialized ArrayList in above of onCreateView method and change this code in onCreateView method
mDataAdapter = new dataAdapter(getResult, getContext());

Now add this code in your Adapter
List<dataItem> filteredList = new ArrayList<>();
    for (dataItem item : myList) // myListFull wrong
    {
        if (item.getLines().contains(charString)){
            filteredList.add(item);
        }
    }
    myListFull = filteredList;

In your myListFull ArrayList to not add data of myList.
I hope this can help You!
Thank You.


text:
Q: How do you implement horizontal candlesticks using the Google Charts API? I'd like to use the Google Charts API, but they don't seem to support this (at least publicly).
This is what I'd like to replicate (for an internal report): screenshot
Edit: This is the closest thing that I've found: https://developers.google.com/chart/interactive/docs/reference#barformatter

A: There is no easy way to do exactly the same thing, but you can cheat a bit and get something like this (you can customize as needed for further fine tuning):

Basically, I make a stacked bar chart with 6 different series.

*

*Dummy (transparent) series

*Black Lines (so the error bars appear properly)

*(and 4, 5, 6) Grey, Red, Yellow, Green for the ranges

The Dummy series is transparent, and sets how far up the chart the first bar appears. The black lines series is always 0, and has error bars on it that go from 0 to 100 (the interval columns below). The others represent the data.
This is a bit complex to do by hand, but you can create a javascript function to appropriately distribute the numbers to the various series given a single value. I just put in arbitrary values.
Colors and transparency can be optimized, as can the 'height' of each bar to make it look similar. The axes base lines, and the grid lines can be hidden to make it look better. The legend can also be hidden. I didn't do those figuring you'll fiddle with the code anyhow.
Here is the code:
function drawVisualization() {
  // Create and populate the data table.
  var data = new google.visualization.DataTable();
  data.addColumn('string', 'Label');
  data.addColumn('number', 'Dummy');
  data.addColumn('number', 'Black for Lines');
  data.addColumn({type: 'number', role: 'interval'});
  data.addColumn({type: 'number', role: 'interval'});
  data.addColumn('number', 'Grey');
  data.addColumn('number', 'Red');
  data.addColumn('number', 'Yellow');
  data.addColumn('number', 'Green');
  data.addRows([
    ['Target', 65, 0, 0, 100, 15, 00, 00, 00],
    ['Test A', 85, 0, 0, 100, 00, 00, 00, 15],
    ['Test B', 70, 0, 0, 100, 10, 00, 05, 00],
    ['Test C', 10, 0, 0, 100, 00, 15, 00, 00],
  ]);

  // Create and draw the visualization.
  new google.visualization.BarChart(document.getElementById('visualization')).
      draw(data,
           {isStacked: true,
            width:600, height:400,
            series: [{color: 'transparent'}, {color: 'black'}, {color: 'grey'}, {color: 'red'}, {color: 'yellow'}, {color: 'green'}]
           }
      );
}


text:
Q: Is it possible to do data-driven tests in Testcafe Studio Is it possible to to feed data into a Testcafe Studio tests so the same test can be completed with different sets of data without having to record a new test each time?
Thanks.

A: Yes, it is possible.
[1, 2, 3].forEach(data => {
    test.only
        ('Data Driven Example', async t => {

        console.log(data);
    });
});

It will become useful when you have data in some separate file like so:
const testData = require(`../Resources/${process.env.TESTCAFE_ENV}/logIn.json`);

testData.credentials.forEach(credentials => {
    test
        ('Log Into User Account', async t => {

        await LogIn.logIn(credentials.username, credentials.password);

        await t
            .expect(PageMsg.pageMsg.innerText).eql(PageMsg.successfulLogIn)
            .expect(Selector(ProfileForm.inputObj.name.input).value).eql(credentials.name);
    });
});

All this is mentioned in the official documentation.
EDIT: This is a valid way, but the question is more focused on TestCafe Studio and how to do it in it. Havind said that, my answer doesn't really answer that.


text:
Q: Roblox Error: Attempt to index nil with 'EquippedTool' - Studio player.inventory.EquippedTool.Value = if returnValue.Inventory.EquippedTool ~= nil then returnValue.Inventory.EquippedTool else "BasicMike"

for _, tool in ipairs(player.inventory.OwnedTools:GetChildren()) do
    print(tool.Name)
    tool.Value = if returnValue.Inventory.Ownedtools[tool.Name] ~= nil then returnValue.Inventory.OwnedTools[tool.Name] else false
end

making code to save each players equipped tool data and this error came up

A: Inventory?
Do you mean
game.Players.player.Backpack

Backpack is a folder that contain all players tool that have not being equipped
and If you want to find the tool player is currently holding that will be under player's Model


text:
Q: how to set startDate to beginning of the month in bootstrap datepicker? I have two text field one for start date and one for end date.
For start date i want to set beginning of the month as default. But not getting how to accomplish that.
This is my code
<%= javascript_include_tag 'bootstrap-datepicker.js'%>

<%= form_tag '/mine', :class => "form-inline" do %>
 <%= label_tag 'start_date', 'Start Date' %>
 <%= text_field_tag 'start_date', nil, :class => 'calendar1' %>
 <%= label_tag 'end_date', 'End Date' %>
 <%= text_field_tag 'end_date', nil, :class => 'calendar' %>
<% end %>

<script>
$(".calendar").datepicker({format: "dd/mm/yyyy"});
$(".calendar1").datepicker({format: "dd/mm/yyyy"});
</script>

I tried like this by referring here
$(".calendar1").datepicker({format: "dd/mm/yyyy", startDate: Date.today.beginning_of_month});
or
$(".calendar1").datepicker({format: "dd/mm/yyyy",setDate date(Date.today.beginning_of_month)});

A: You can do like this:
<%= text_field_tag 'start_date', Date.today.beginning_of_month.strftime('%d/%m/%Y'), :class => 'calendar1' %>


text:
Q: Override SQL Server Maxrecursion? I have a table with a structure like
name    properties
x       thing1, thing2, thing3
y       otherthing1, otherthing2, otherthing3

and I would like to map this to a one to many relationship like
name  properties
x     thing1
x     thing2
x     thing3

This following solution I have works, but runs up against the Maxrecursion option in SQL Server
;with tmp(brandName, drugList, genericName) as (
select brandName, LEFT(genericName, CHARINDEX(',',genericName+',')-1),
    STUFF(genericName, 1, CHARINDEX(',',genericName+','), '')
from eeeee
where LEN(genericName) - LEN(replace(genericName,',','')) < 100
union all
select brandName, LEFT(genericName, CHARINDEX(',',genericName+',')-1),
    STUFF(genericName, 1, CHARINDEX(',',genericName+','), '')
from tmp
where genericName > ''
)
select brandName,  drugList
from tmp
order by brandName

the where clause is what let's this query run, because there are some rows in the multi-valued column that have over 100 items in the list.  Is there any way to sneak around and override SQL Server's 100 max limit on recursion?  Or will it be best to just go ahead and split the columns that have over 100 values into two and then do the recursion?

A: I could suggest more efficient solution without using recursion -
DECLARE @temp TABLE
(
      name NVARCHAR(50)
    , properties NVARCHAR(1000)
)

INSERT INTO @temp (name, properties)
VALUES
    ('x', 'thing1, thing2, thing3'),
    ('y', 'otherthing1, otherthing2, otherthing3')

SELECT
      data.name
    , property = LTRIM(data.property)
FROM (
    SELECT
          name = p.value('(./n)[1]', 'NVARCHAR(50)')
        , property = p.value('(./s)[1]', 'NVARCHAR(1000)')
    FROM (
        SELECT field = CAST('<r><s>' + REPLACE(t.properties + ',', ',', '</s><n>' + t.name + '</n></r><r><s>') + '</s></r>' AS XML)
        FROM @temp t
    ) d
    CROSS APPLY field.nodes('/r') t(p)
) data
WHERE data.name IS NOT NULL

Yes, of course. Each string in table has a fixed separator char. We replace separator char to part of XML structure. We get lines like this:
thing1, thing2, thing3 -> <r><s>thing1</s><s>thing2</s><s>thing3</s></r>

Convert string to XML date type and parse formed tree:
<r>
 <s>thing1</s>
 <n>x</n>
</r>
<r>
 <s> thing2</s>
 <n>x</n>
</r>
<r>
 <s> thing3</s>
 <n>x</n>
</r>


text:
Q: block structure of a subgroup Let $H \leq S_N$ be a transitive permutation group. A system of blocks $\Sigma = \{\Delta\}$ for $H$ is a partition of $[N]$ such that either $\Delta^h = \Delta$ or $\Delta \cap \Delta^h = \emptyset$. For primitive $H$, the only system of blocks are the trivial ones $\Delta = \{e\}$ and $\Delta = [N]$.
 It is also known that there is a one-to-one mapping between the system of blocks of $H$ and overgroups of the stabilizer $H_{n}$ for $n \in [N]$.
My question is this: what can we say about the system of blocks for a larger group $G > H$, $G \leq S_N$? We know the relationship between the stabilizers, that is $H_n < G_n$. I assume the blocks are generally not preserved (?) what more can we say?

A: There's not a lot to say here, but we can say a couple of things. We'll assume $H\le G\le S_n$ and $H$ and $G$ are both transitive. A block system is defined by a choice of a single block $\Delta\ni 1$, so let $B_H$ be the set of blocks for $H$ containing $1$ and $B_G$ be the set of blocks for $G$ containing $1$.
Immediately if $\Delta^g=\Delta$ or $\Delta^g\cap\Delta=\emptyset$ for all $g\in G$ then certainly this holds for all $g\in H$. So a block for $G$ is a block for $H$ which we can write as $B_G\le B_H$.
The inverse equality clearly doesn't always hold (e.g. $H$ any imprimitive group and $G=S_n$). One can show however that blocks of $G$ containing $1$ are in one-to-one correspondence with subgroups of $G$ containing the point stabiliser $G_1$ (specifically $\Delta$ corresponds to $G_\Delta$ the setwise stabiliser of $\Delta$). I claim that a block $\Delta$ of $H$ containing $1$ is a block for $G$ if and only if $G_\Delta\ge G_1$. This means $B_G=\{\Delta\in B_H|G_1\le G_\Delta\}$ - that is a block of $G$ containing $1$ is any block of $H$ containing $1$ fixed by $G_1$.
Proof of Claim:
"Prove $\Delta$ is a block of $G$ implies $G_1\le G_\Delta$" is a standard exercise, so I will only do the reverse implication.
Assume $G_\Delta\ge G_1$ where $\Delta$ is a block for $H$.
Let $g\in G$ and suppose $x\in\Delta\cap\Delta^g$.
Relabelling if necessary we may assume $x=1$.
As $1\in\Delta^g$ there is some $y\in\Delta$ with $y^g=1$.
As $H$ is transitive there is some $h\in H$ with $1^h=y$ so $1^{hg}=1$.
That is $hg\le G_1\le G_\Delta$.
As $\Delta$ is a block for $H$, $h\le H_\Delta\le G_\Delta$.
Hence $g=h^{-1}(hg)\le G_\Delta$, so $\Delta^g=\Delta$ completing the proof.


text:
Q: how to get year month day from date type in typescript I am using Angular 7 and I find difficult to get the year month and day in Date type variable. Also i am using Bootstrap 4. Can you help me please
My html code is

      Check date
      <input type="date" id="user1" formControlName="search_date" class="form-control" placeholder="Enter date">

and .ts file is
ngOnInit() {
this.searchForm = this.formBuilder.group({
  emp_type: '',
  designation: '',
  week_month: '',
  search_date: Date
});

}
var yer = this.searchForm.value.search_date
console.log(yer.getUTCMonth())

then it will show en error
TypeError: yer.getUTCMonth is not a function
at HomeComponent.push../src/app/home/home.component.ts.HomeComponent.onsubmit (home.component.ts:53)

A: try :
var day = yer.getDay();
var month = yer.getMonth();
var year = yer.getFullYear();

A: The value in input is not a Date type. You need to create one.
Try this:
var yer = new Date(this.searchForm.value.search_date)
console.log(yer.getUTCMonth())


text:
Q: Which is correct: "not less than" or "no less than"? Which is the correct idiom: "not less than" or "no less than"?
Example (edited):

There were no less than fifty people at the meeting.
There were not less than fifty people at the meeting.

A: It depends on the context. Both can be fine depending on what you want to say.
No less than
This is normally used to give emphasis. There are no less than 5 different ways to do this. It is by far the commonest form and the only one regularly used outside academic or technical literature (image generated by searching COCA  and BNC for no less than):
COCA:

BNC:

Not less than
This is indeed far less common but can also be used. I would use it in cases where I want to specify that the minimum required number is X. For example, Use as many eggs as you like but not less than 5. It is more common in technical literature than everyday speech though (image generated by searching COCA and BNC for not less than):
COCA:

BNC:

As you can see from the images above, no less than is far more common. However, not less than is also used and perfectly correct in some contexts, especially academic literature and on both sides of the Atlantic. Interestingly, it is also relatively common in the "misc" category in the British corpus, which includes religious and administrative literature.

A: Cambridge Dictionaries Online has an entry for no less than:

used to show your surprise at a large number: There were no less than
  a thousand people there buying tickets.

In the electronic version of the Oxford Hachette Dictionary, under the entry of "less" as an adverb, I read:

no less than 85% au moins 85%

A: Example 3 is a different construction altogether, so it is a red herring I will not be addressing.
In example 1 and 2, the variant with not strikes me personally as unidiomatic at best, and outright ungrammatical at worst. It is not something any native speaker I know would produce. It is worth noting that both examples, as well as this question here, were all asked by non-native speakers. Three out of three. So while it does seem to be a popular question among learners of the language, I do not feel it is a choice a native speaker ever feels presented with.
COCA and BNC are not quite as radical as myself, but they do generally back me up:
                              COCA    BNC

there are no/not less than     8/1    5/0
there were no/not less than    7/1    8/0
there are no/not more than    21/4    8/3
there were no/not more than   23/1    5/1

The verdict seems to be rather clear, on both sides of the pond.


text:
Q: How to return all data from one column Android SQL I have an SQLite Database in my application. It has three columns. being _id, TEXT, and Location. If I want to return all the data from, say, the TEXT column should I use cursor.getColumnIndex(2)? I am obviously new to SQLite. And and all help is appreciated. Thanks everyone!

A: Yes, friend, you are new.
First off, your database doesn't have three columns, but rather, your table does. Databases have tables, tables of columns (fields) and rows (records).
Secondly, TEXT is not a valid name for a column, as it's a datatype. Let's say you called the three columns id, theText, and location -- then if you selected all three columns to be returned, the second one would be accessible through:
cursor.getString(1); // that's the second column returned

or
cursor.getString(cursor.getColumnIndex( "theText" ) );

However, you can have sqlite do most of the work for you by selecting only the column you're interested in, so then you'd cursor.getString(0) as it's the only column returned.
For more pertinent explanations, please post your code in the question.

A: simply apply the query of getting all contacts and take an array of string type and then add the required record in that array as shown below
I hope this code help u

*

*in DBHelper getting record of particular column :
public ArrayList<String> getAllCotactsEmail() {

    ArrayList<String> arrayList=new ArrayList<>();

    SQLiteDatabase db = this.getReadableDatabase();
    Cursor res =  db.rawQuery( "select * from contacts", null );
    res.moveToFirst();

    if (res != null)
    {
        while(res.isAfterLast() == false){
            arrayList.add(res.getString(res.getColumnIndex(CONTACTS_COLUMN_EMAIL)));
            Log.d("emailssinlisttt",arrayList.toString());

            res.moveToNext();
        }}
    return arrayList;

}

*retrieve :
email=mydb.getAllCotactsEmail();

Log.d("emaillllll",email.toString());

A: You need to query your Database to get your data. This query will return a Cursor with the column you specified in the query.
To make query, you need to call query() method from ContentResolver. To get your ContentResolver, you can use getContentResolver() from a Context like Activity :
getContentResolver.query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder);
To understand all parameters, see : ContentResolver
In your case, you want only TEXT column so pass a String array with your TEXT column name for projection parameters.
You want all rows so your selection and selectionArgs parameters must be null.
If you don't care about order, pass null for sortOrder (rows will be sort by ID) :
Cursor c = getContentResolver.query(yourUri, new String[]{"TEXT"}, null, null, null)

This query will return a cursor, to extract your values from the cursor, make a loop like :
if(c.moveToFirst()) {
            do {
                final String text = c.getString(c.getColumnIndex("TEXT"));
            } while (c.moveToNext());
        }

Hope this will help you :)


text:
Q: How i can close all parents and classes in python tkinter I'm trying to make this code close all windows which are opened on windows class. At this moment it only closes few of them. Code works perfectly, but it just dont remove all windows which needs to be removed. Can someone please help me to make this script working?
import tkinter as tk
from tkinter import *
from PIL import Image, ImageTk
import webbrowser
import time
import random

def closeall():
    global close
    close = True
    self = selfstr
    parent = parentstr
    Window.__init__(self, parent)

class Window(tk.Toplevel):

    def __init__(self, parent):
        if close == True:
            self.destroy()
        else:
            global selfstr
            selfstr = self
            global parentstr
            parentstr = parent

            plusminus_list = ["+", "-"]
            plusminus = random.choice(plusminus_list)
            plusminus2 = random.choice(plusminus_list)
            location = random.randint(1, 1000)
            location2 = random.randint(1, 1000)

            super().__init__(parent)

            self.geometry(f'256x256{plusminus}{location}{plusminus2}{location2}')
            self.title('NOESCAPE')

            frame = Frame(self, width=256, height=256)
            frame.pack()
            frame.place(anchor='center', relx=0.5, rely=0.5)

            img_list = ["jeff2", "jeff3", "jeff4", "jeff5", "jeff6"]
            randomimg = random.choice(img_list)
            img = ImageTk.PhotoImage(Image.open(f"{randomimg}.jpg"))

            label = Label(frame, image = img)
            label.pack()

            def on_closing():
                plusminus_list = ["+", "-"]
                onlywayout()

                plusminus = random.choice(plusminus_list)
                plusminus2 = random.choice(plusminus_list)
                location = random.randint(1, 1000)
                location2 = random.randint(1, 1000)
                img_list = ["jeff2", "jeff3", "jeff4", "jeff5", "jeff6"]
                randomimg = random.choice(img_list)
                img = ImageTk.PhotoImage(Image.open(f"{randomimg}.jpg"))
                Window(self)

            self.protocol("WM_DELETE_WINDOW", on_closing)
            self.mainloop()

A: So you cannot access all Window instances you created for some reason? Then you could save a list with all instances in the Window class as a class attribute. With this list you should be able to destroy all Window instances. Your approach with using the constructor and global variables is a very bad coding style and you shouldn't do anything like this.
Here I created a classmethod so that you don't need the extra function closeall():
import tkinter

class Window(tkinter.Toplevel):
    instances = []  # class attribute

    def __init__(self, parent):
        super().__init__(parent)
        self.instances.append(self)  # save current instance to the list

        # ...

    @classmethod
    def destroy_all_instances(cls):
        for window in cls.instances:
            window.destroy()

# Destroy all Window instances:
Window.destroy_all_instances()


text:
Q: What does it mean when an account is suspended due to plagiarism? I stumbled upon a user who seems to have been suspended for plagiarism:

What is plagiarism and why can it get an account suspended?

A: Plagiarism is the copying of content (text, images etc...) without attribution.
The user seems to have copied the contents of their answers from elsewhere without saying so.
Wikipedia says this:

Plagiarism is the "wrongful appropriation" and "purloining and publication" of another author's "language, thoughts, ideas, or expressions," and the representation of them as one's own original work.


text:
Q: Insert time stamp in file name with extension intact I get full path of an Excel file from a cell and use a function to retrieve the file name. I have final result as "abc.xlsx"
I need to insert a time stamp in the file name like "abc_02_11_19.xlsx".
I am able to generate the time stamp, the problem is appending it. The best I could think of was to remove the last five letters from the file name i.e. ".xlsx", append the time stamp and then append the ".xlsx".
The ending might also be ".xlsm", ".xlsb" or ".xls". I would need to extract everything after the dot.
Any better way to do this or if not, how best to do it elegantly?
Snippet of code, I am using-
oldname = FunctionToGetName(ThisWorkbook.Sheets("Sheet1").Range("B10").Text)

newname = FileDateTime(ThisWorkbook.Sheets("Sheet1").Range("B10").Text) & " " & oldname

newname = Replace(Replace(Replace(newname, ":", "_"), "/", "_"), "*", "_")

This inserts the time stamp before the file name. I need to append it after.

A: I've not tested this with your functions as I don't know what they do. But if I'm correct, the FunctionToGetName will return the filename as "filename.extention" and FileDateTime will return the date stamp you wish to attach.
With this you can get the filename by cutting everything after the "." with Left$(filename, InStr(oldname, ".") - 1). Then you can do the reverse of that and add the file extention back with Right$(oldname, Len(oldname) - InStr(oldname, ".")). And as per below, you can put pretty much anything in between.
Sub what()
Dim filename As String
Dim oldname As String

oldname = FunctionToGetName(ThisWorkbook.Sheets("Sheet1").Range("B10").Text)

Newname = Left$(filename, InStr(oldname, ".") - 1) & " " & FileDateTime(ThisWorkbook.Sheets("Sheet1").Range("B10").Text) & "." & Right$(oldname, Len(oldname) - InStr(oldname, "."))
End Sub

A: Check out FSO
Dim fso as object
Set fso = CreateObject("Scripting.FileSystemObject")
Dim oldname As String
Dim newname As String
oldname = "abc.xlsx"
newname = fso.GetBaseName(oldname) & "_" & Format(Now(), "mm_dd_yy") & "." & fso.GetExtensionName(oldname)
Debug.Print newname

https://learn.microsoft.com/en-us/office/vba/language/reference/user-interface-help/filesystemobject-object


text:
Q: max function for the current time How do I create a column with the current high of the day following the time? I used pmax but it wasn't helpful.
> df
             date_time  Price
1 2018-02-01 18:13:17 3178.5
2 2018-02-01 18:13:13 3179.0
3 2018-02-01 18:13:13 3178.5
4 2018-02-01 18:13:13 3178.5
5 2018-02-01 18:13:09 3178.5
6 2018-02-01 18:13:00 3178.5
7 2018-02-01 18:12:54 3179.5
8 2018-02-01 18:12:43 3179.5

I'm trying to do this.
> mutate(df, high_day = ?)
            date_time  Price high_day
1 2018-02-01 18:13:17 3179.5   3179.5
2 2018-02-01 18:13:13 3179.0   3179.0
3 2018-02-01 18:13:13 3178.5   3179.0
4 2018-02-01 18:13:13 3179.0   3179.0
5 2018-02-01 18:13:09 3178.5   3178.5
6 2018-02-01 18:13:00 3178.5   3178.5
7 2018-02-01 18:12:54 3178.5   3178.5
8 2018-02-01 18:12:43 3178.5   3178.5

for reproduction:
structure(list(data_hora = structure(c(1517508797, 1517508793,
1517508793, 1517508793, 1517508789, 1517508780, 1517508774, 1517508763,
1517508763, 1517508763, 1517508763, 1517508757, 1517508756), class = c("POSIXct",
"POSIXt"), tzone = ""), Preco = c(3178.5, 3179, 3178.5, 3178.5,
3178.5, 3178.5, 3179.5, 3179.5, 3179.5, 3179.5, 3179, 3179, 3179.5
)), row.names = 38:50, class = "data.frame")

A: How's this:
library(lubridate)
df %>%
  arrange(date_time) %>%
  group_by(date = as.Date(date_time)) %>%
  mutate(day_high = cummax(Price))


text:
Q: Sorting an array object with lodash along with date Here I am trying to sort the priority_level such that first the alphabet comes and then number, Also along with that I am trying to sort priority_date such that oldest first along with priority_date but still it has to show the Alphabet first
example result I expect :
            priority level: P Date: 1980-02-08T00:00:00.000Z
            priority level: C Date: 2004-06-29T00:00:00.000Z
            priority level: 1 Date: 2004-06-29T00:00:00.000Z
            priority level: 1 Date: 2014-09-03T00:00:00.000Z
            priority level: 5 Date: 2005-02-15T00:00:00.000Z

[Here Like for same level 1 it should show the old date first like above.]
 Below is the object array I am getting, and want to perfrom this entire logic operation on this.
            I am using lodash orderby but not sure it it helps with this
   const input =   [{
        priority_level: 'P ',
        comments: '',
        withdraw_granted_conditions: 'false',
        condition: '',
        _id: 5db00ad95399ab5cad9e6d44,
        company: 5db00a135399ab5cad9e0049,
        priority_date: 1980-02-08T00:00:00.000Z,
        registration_type: 5db00a125399ab5cad9dfe4b,
        sequence: 6835,
        waiver_request: false,
        waiver_granted: false,
        waiver_letter_date: null,
        letter_date: null,
        waiver_sent: null,
        no_extention_letter: false,
        mpaa_extention_granted: false
      },
      {
        priority_level: '1 ',
        comments: '',
        withdraw_granted_conditions: 'false',
        condition: '',
        _id: 5db00ad95399ab5cad9e6d43,
        company: 5db00a145399ab5cad9e0096,
        priority_date: 2004-06-29T00:00:00.000Z,
        registration_type: 5db00a125399ab5cad9dfe4a,
        sequence: 13505,
        waiver_request: false,
        waiver_granted: false,
        waiver_letter_date: null,
        letter_date: null,
        waiver_sent: null,
        no_extention_letter: false,
        mpaa_extention_granted: false
      },
      {
        priority_level: 'C ',
        comments: '',
        withdraw_granted_conditions: 'false',
        condition: '',
        _id: 5db00ad95399ab5cad9e6d42,
        company: 5db00a135399ab5cad9dff5c,
        priority_date: 2004-06-29T00:00:00.000Z,
        registration_type: 5db00a125399ab5cad9dfe4a,
        sequence: 13506,
        waiver_request: false,
        waiver_granted: false,
        waiver_letter_date: null,
        letter_date: null,
        waiver_sent: null,
        no_extention_letter: false,
        mpaa_extention_granted: false
      },
      {
        priority_level: '5 ',
        comments: '',
        withdraw_granted_conditions: 'false',
        condition: '',
        _id: 5db00ad95399ab5cad9e6d41,
        company: 5db00a135399ab5cad9dff5a,
        priority_date: 2005-02-15T00:00:00.000Z,
        registration_type: 5db00a125399ab5cad9dfe4a,
        sequence: 13508,
        waiver_request: false,
        waiver_granted: false,
        waiver_letter_date: null,
        letter_date: null,
        waiver_sent: null,
        no_extention_letter: false,
        mpaa_extention_granted: false
      },

{
            priority_level: '1 ',
            comments: '',
            withdraw_granted_conditions: 'false',
            condition: '',
            _id: 5db00ad95399ab5cad9e6d41,
            company: 5db00a135399ab5cad9dff5a,
            priority_date: 2005-02-15T00:00:00.000Z,
            registration_type: 5db00a125399ab5cad9dfe4a,
            sequence: 13508,
            waiver_request: false,
            waiver_granted: false,
            waiver_letter_date: null,
            letter_date: null,
            waiver_sent: null,
            no_extention_letter: false,
            mpaa_extention_granted: false
          }]

    const result = input.sort((a, b) => {

      const aNumericPriorityLevel = Number.isInteger(Number.parseInt(a.priority_level));
      const bNumericPriorityLevel = Number.isInteger(Number.parseInt(b.priority_level));

      // If one items has letter priority level, and the other does not, sort
      // a/b pair based on if a or b was the number
      if (aNumericPriorityLevel !== bNumericPriorityLevel) {
        return aNumericPriorityLevel ? 1 : -1;
      }

      // If a/b pair are both number or both letter, then sort in descending
      // order based on date
      return Date.parse(a.priority_date) - Date.parse(b.priority_date);
    });

    console.log(result)

The above works fine, but do not refine date with same priority_level, it messed up with that senario.
Like want to sort normally with alphabet and numeric works fine but date logic will be like if data is same then it should arrange by descending date.
Here if I want numbers sorting like 1,2,3,3,4,5 and so on but if any number has 2 entires like 1,2,2,3,3,3,1 then it should be be kept as date descending date entry for numeric which has more than one entries.

A: One approach would be as follows:

// I've stripped out the extra data to give the answer more clarity
const input = [{
    priority_level: 'P ',
    priority_date: "1980-02-08T00:00:00.000Z"
  },
  {
    priority_level: '1 ',
    priority_date: "2004-06-29T00:00:00.000Z"
  },
  {
    priority_level: '1 ',
    priority_date: '1985-02-15T00:00:00.000Z'
  },
  {
    priority_level: 'C ',
    priority_date: "2004-06-29T00:00:00.000Z"
  },
  {
    priority_level: '5 ',
    priority_date: "2005-02-15T00:00:00.000Z"
  }
]

const result = input.sort((a, b) => {

  const aNumericPriorityLevel = Number.isInteger(Number.parseInt(a.priority_level));
  const bNumericPriorityLevel = Number.isInteger(Number.parseInt(b.priority_level));

  // If one items has letter priority level, and the other does not, sort
  // a/b pair based on if a or b was the number
  if (aNumericPriorityLevel !== bNumericPriorityLevel) {
    return aNumericPriorityLevel ? 1 : -1;
  }
  else if(aNumericPriorityLevel === true) {
    return bNumericPriorityLevel - aNumericPriorityLevel;
  }

  // If a/b pair are both number or both letter, then sort in descending
  // order based on date
  return Date.parse(b.priority_date) - Date.parse(a.priority_date);
});

console.log(result)

Here, Array#sort is used with a custom callback that sorts input pairs based on two criteria:

*

*The primary sort criteria depends on the value(s) of priority_level
on each input object a and b. If only one value is parsable as an integer, then we give prescendnce to this as a sorting crteria, and return a sorting direction for this pair based on which item had a the numeric string value for the priority_level field.

*Otherwise, if both a and b have numeric (or non-numeric) string values for priority_level, then the pair is sorted based on their priority_date values. Here, the Date.parse() method can be used to convert your date strings to integers, and the difference of the parsed integers are used to direct the sorting

Hope that helps!

A: Please have a look as below:

const dataObj = [{
      priority_level: 'P ',
      comments: '',
      withdraw_granted_conditions: 'false',
      condition: '',
      _id: '5db00ad95399ab5cad9e6d44',
      company: '5db00a135399ab5cad9e0049',
      priority_date: '1980-02-08T00:00:00.000Z',
      registration_type: '5db00a125399ab5cad9dfe4b',
      sequence: 6835,
      waiver_request: false,
      waiver_granted: false,
      waiver_letter_date: null,
      letter_date: null,
      waiver_sent: null,
      no_extention_letter: false,
      mpaa_extention_granted: false,
    },
    {
      priority_level: '1 ',
      comments: '',
      withdraw_granted_conditions: 'false',
      condition: '',
      _id: '5db00ad95399ab5cad9e6d43',
      company: '5db00a145399ab5cad9e0096',
      priority_date: '2004-06-29T00:00:00.000Z',
      registration_type: '5db00a125399ab5cad9dfe4a',
      sequence: 13505,
      waiver_request: false,
      waiver_granted: false,
      waiver_letter_date: null,
      letter_date: null,
      waiver_sent: null,
      no_extention_letter: false,
      mpaa_extention_granted: false,
    },
    {
      priority_level: 'C ',
      comments: '',
      withdraw_granted_conditions: 'false',
      condition: '',
      _id: '5db00ad95399ab5cad9e6d42',
      company: '5db00a135399ab5cad9dff5c',
      priority_date: '2004-06-29T00:00:00.000Z',
      registration_type: '5db00a125399ab5cad9dfe4a',
      sequence: 13506,
      waiver_request: false,
      waiver_granted: false,
      waiver_letter_date: null,
      letter_date: null,
      waiver_sent: null,
      no_extention_letter: false,
      mpaa_extention_granted: false,
    },
    {
      priority_level: '5 ',
      comments: '',
      withdraw_granted_conditions: 'false',
      condition: '',
      _id: '5db00ad95399ab5cad9e6d41',
      company: '5db00a135399ab5cad9dff5a',
      priority_date: '1985-02-15T00:00:00.000Z',
      registration_type: '5db00a125399ab5cad9dfe4a',
      sequence: 13508,
      waiver_request: false,
      waiver_granted: false,
      waiver_letter_date: null,
      letter_date: null,
      waiver_sent: null,
      no_extention_letter: false,
      mpaa_extention_granted: false,
    }];
    const getAlphabet = [];
    const getNumber = [];
    const alphabetCheck = /^[a-zA-Z]/g;
    dataObj.map((item) => {
      if (item.priority_level.match(alphabetCheck)) {
        return getAlphabet.push(
          { priority_level: item.priority_level, priority_date: item.priority_date }
        );
      }
      return getNumber.push(
        { priority_level: item.priority_level, priority_date: item.priority_date }
      );
    });
    const getSortedAlphabet = getAlphabet.sort((a, b) => ((a.priority_date > b.priority_date) ? 1 : ((b.priority_date > a.priority_date) ? -1 : 0)));
    const getSortedDate = getNumber.sort((a, b) => ((a.priority_date > b.priority_date) ? 1 : ((b.priority_date > a.priority_date) ? -1 : 0)));
    const tempCombine = [...getSortedAlphabet, ...getSortedDate];
    console.log('tempCombine', tempCombine);


text:
Q: Qt windows libmysql.dll I have installed MySQL 5.1.49 and the binary QT 4.6.2 for Visual Studio 2008. I configured Qt as follow:
C:\Qt>configure -static -no-webkit -plugin-sql-sqlite -plugin-sql-mysql -I C:\mysql\include -L C:\mysql\lib\optC:\Qt\src\plugins\sqldriver

Everything went fine, no errors. When I run nmake on my application everything runs fine, no errors as well. However when I execute my application under the debug folder I get a popup saying "Driver not loaded" (I have QT += sql under my project.pro)
If I goto C:\Qt\plugins\sqldrivers I dont see any libmysql, or any *mysql.dll only qsqlmysql.obj and qsqlmysqld.obj (there are files such as: qsqlite4.dll, qsqlpsql4.dll etc.)
I did try to build it manually by doing:
cd %QTDIR%\src\plugins\sqldrivers\mysql
C:\Qt\src\plugins\sqldrivers\mysql>qmake "INCLUDEPATH+=C:\mysql\include" "LIBS+=C:\mysql\lib\opt\libmysql.lib" mysql.pro
nmake

Everything compiles fine, no errors. However, I still don't find any libmysql.dll generated. Only file found is under C:\mysql\bin\libmySQL.dll
I have all the includes for MySQL under C:\mysql\include and the libraries under C:\mysql\lib\opt
Any ideas what could be the problem? Thanks

A: Using -static prevents you from using plugins at runtime. You will need to change
-plugin-sql-mysql

to
-qt-sql-mysql

and have it compiled in.
B1.

A: Have you tried using qt source instead of the binary one? I had a similar issue, however I was getting compile errors.


text:
Q: Leaflet Draw Plugin: How to hide/show drawing tools by Layer Type dynamically I'm using draw plugin in my project and I would like to know how can I hide/show drawing tools by layer type?
For example, let's say I have 2 layers one of them type is Polygon and the other one is Line.
If user select Polygon layer, I want to hide Line drawing tool.
After that, If user select Line layer, I want to hide Polygon drawing tool. I've looked here but this example is making tools static, I want to change dynamically. How can I do that?
Every suggestion will be appreciated.

A: It appears you can't do that with the plugin, but you can use CSS to show/hide certain drawing tools when you switch layers.
The buttons have classes like leaflet-draw-draw-polyline, leaflet-draw-draw-polygon, etc.

A: I solved it myself. I'm adding this draw control when map initialized.
 drawControl = new L.Control.Draw({
    draw : {
        position : 'topleft',
        polygon : false,
        polyline : false,
        rectangle : false,
        circle : false

    },
    edit : false
});

map.addControl(drawControl);

After that, i wrote a function for resetting drawing tools.
  function setDrawingTools(layerType) {

    map.removeControl(drawControl);

    if (layerType == 'Polygon') {

        drawControl = new L.Control.Draw({
            draw : {
                position : 'topleft',
                polygon : {
                    title : 'Draw a sexy polygon!',
                    allowIntersection : false,
                    drawError : {
                        color : '#b00b00',
                        timeout : 1000
                    },
                    shapeOptions : {
                        color : '#bada55'
                    },
                    showArea : true
                },
                polyline : false,
                rectangle : false,
                circle : false,
                marker : false
            },
            edit : false
        });
    } else if (layerType == 'Line') {

        drawControl = new L.Control.Draw({
            draw : {
                position : 'topleft',
                polygon : false,
                polyline : {
                    metric : false
                },
                rectangle : false,
                circle : false,
                marker : false
            },
            edit : false
        });
    } else if (layerType == 'Point') {

        drawControl = new L.Control.Draw({
            draw : {
                position : 'topleft',
                polygon : false,
                polyline : false,
                rectangle : false,
                circle : false

            },
            edit : false
        });

    }
    map.addControl(drawControl);
}

A: It sounds like you are trying to gain better control of you layers. Difficult to say without any code posted. Have you considered adding and removing your layers upon user selection? Here is some documentation on manipulating layers. And the syntax would be something like:
map.addLayer(layer_in_question);

or
map.removeLayer(layer_in_question);


text:
Q: SAS CATX Error: Null Parameters for CATX are invalid I am trying to concatenate some variables in SAS Enterprise guide.
I start with a SAS_table, which looks something like (note the empty column plums and the empty observation for pears:
id      farm         apples        pears           cherries          plums
1       'Munich'     'Granny'      'Williams'      'RedDelight'
2       'Amsterdam'  'PinkLady'                    'Scrumptious
3       'Moscow'     'Braeburn'    'Williams'      'RedDelight'

Then I create global variables as follows:
%do i = 1 %to 3;
    %global farm_&i., apples_&i., pears_&i., cherries_&i., plums_&i.;
%end;

And I store the above table in the global variables as follows:
data _NULL_;
    set SAS_table;
    %do i = 1 %to 3;
        if id = &i. then do;
            call symput("farm_&i.", farm);
            call symput("apples_&i.", apples);
            call symput("pears_&i.", pears);
            call symput("cherries_&i.", cherries);
            call symput("plums_&i.", plums);
        end;
    %end;
run;

All of the above seems to work smoothly. In a next step I want to the individual variables to get the following output (please note that empty values are just skipped - no extra delimiter (" :: ") is set for these cases):
concat_1:      Munich :: Granny :: Williams :: RedDelight
concat_2:      Amsterdam :: PinkLady :: Scrumptious
concat_3:      Moscow :: Braeburn :: Williams :: RedDelight

To do this, I use the following code:
data _NULL_;
    %do i = 1 %to 3;
         call_symput("concat_&i",catx(" :: ", &&farm_&i., &&apples_&i.., &&pears_&i..,
             &&cherries_&i.., &&plums_&i..));
    %end;
run;

However, when I run this code I get the error:
ERROR 159-185: Null parameters for CATX are invalid.

My assumption here is that SAS is unhappy because some of the variables can be empty values. But how do I fix this? I've messed around loads and just can't seem to find a good answer.

A: It looks to me like your macro variables will have values like Munich in them. So the SAS code that your macro is generating needs to generate a string literal like "Munich" otherwise SAS will look for a variable with that name.  This also explains the error about null values since without the quotes to make the null value into a string literal you end up with a CATX() call with adjacent delimiters.
data _NULL_;
%do i = 1 %to 3;
  call_symput("concat_&i",catx(" :: ", "&&farm_&i.", "&&apples_&i.."
             , "&&pears_&i..", "&&cherries_&i..", "&&plums_&i.."))
  ;
%end;
run;

You could instead generate the macro variables with the quotes, but they would probably be much less useful as macro variables in that form.  So instead of changing the last call symput() statement you could change the earlier ones that make the macro variables.  You could also remove the unneeded macro code from that step.
data _NULL_;
  set SAS_table;
  call symput(cats("farm_",id), quote(farm));
  call symput(cats("apples_",id), quote(apples));
  call symput(cats("pears_",id), quote(pears));
  call symput(cats("cherries_",id), quote(cherries));
  call symput(cats("plums_",id), quote(plums));
run;


text:
Q: How to convert Spark R dataframe into R list This is my first time to try Spark R to do the same work I did with RStudio, on Databricks Cloud Community Edition. But met some weird problems.
It seems that Spark R do support packages like ggplot2, plyr, but the data has to be in R list format. I could generate this type of list in R Studio when I am using train <- read.csv("R_basics_train.csv"), variable train here is a list when you use typeof(train).
However, in Spark R, when I am reading the same csv data as "train", it will be converted into dataframe, and this is not the Spark Python DataFrame we have used before, since I cannot use collect() function to convert it into list.... When you use typeof(train), it shows the type is "S4", but in fact the type is dataframe....
So, is there anyway in Spark R that I can convert dataframe into R list so that I can use methods in ggplot2, plyr?
You can find the origional .csv training data here:
train

A: Later I found that using r_df <- collect(spark_df) will convert Spark DataFrame into R dataframe, although cannot use R summary() on its dataframe, with R dataframe, we can do many R operations.

A: It looks like they changed SparkR, so you now need to use
r_df<-as.data.frame(spark_df)

A: Not sure if you call this as the drawback of sparkR, but in order to leverage many good functionalities which R has to offer such as data exploration, ggplot libraries, you need to convert your pyspark data frame into normal data frame by calling collect
df <- collect(df)


text:
Q: Random XML Questions Using Fisher-Yates Shuffle I am making a Quiz/Trivia Game and have questions stored in XML file and it gets a random question. Everything works fine, but I want to stay random but not show the same question until every question has been shown.
 public struct Question {
 public string questionText;
 public string answerA;
 public string answerB;
 public string answerC;
 public string answerD;
 public int correctAnswerID;
 }

[XmlRoot("QuestionsRoot")]
public class QuestionData {
[XmlArray("Questions")]
[XmlArrayItem("Question")]
public List<Question>questions = new List<Question>();

 public static QuestionData LoadFromText(string text) {
 try {
     XmlSerializer serializer = new XmlSerializer(typeof(QuestionData));
     return serializer.Deserialize(new StringReader(text)) as QuestionData;
 } catch (Exception e) {
     UnityEngine.Debug.LogError("Exception loading question data: " + e);
     return null;
 }
}

And I use this in my other script to get a random question:
 questionData = QuestionData.LoadFromText(questionDataXMLFile.text)
 q = Random.Range(0, questionData.questions.Count);
 currentQuestion = questionData.questions[q];

A: Do something along the following lines:
create another list with available questions - initialise it to the list of all questions:
 questionData = QuestionData.LoadFromText(questionDataXMLFile.text)

 var available = new List<Question>(questionData.question);
 ...
 }

 public Question GetNextQuestion()
 {
     if (available.Count == 0)
        available.AddRange(questionData.question);

    q = Random.Range(0, available.Count);
    currentQuestion = available[q];
    available.RemoveAt(q);

    return currentQuestion;
 }


text:
Q: Static 404 pages with WordPress I would like to redirect all 404 errors to a static html page. This should be done outside of WordPress via .htaccess so it doesn't use any WordPress resources. The standard WordPress mod_rewrite rules are as follows:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

I have tried adding ErrorDocument 404 /static.html to the top of the .htaccess file, but no luck. How can I catch 404 errors and redirect to static.html?

A: Try this in your htaccess,
ErrorDocument 404 /404.html

A: The best option I found was to place the following in .htaccess:
ErrorDocument 404 /index.php?error=404
It will load a 404.php page found in your theme directory.


text:
Q: Why slider start at wrong place? I'm trying to pass the slider value to span and dynamically change it. It works fine, but when i start page, the slider button displaced on the wrong value. How can I fix that?
This is my HTML

Slider Control

            Points:
            <input type="range" data-highlight="true"  data-bind="attr: {'id': id, 'min': min, 'max': max}, value: value, valueUpdate: 'input'" />
            Net:

This is my fiddle
EDIT
This is example of slider, where slider starts on its place.
Fiddle

A: Looks like jQuery mobile initializes the slider before knockout sets its value.
Quick and dirty solution: (not recommended) manually trigger an update after applying bindings.
ko.applyBindings(viewModel);
$("input").trigger("change");

https://jsfiddle.net/avk9dyw4/
Real solution: apply bindings before jquery mobile initializes or create a custom binding handler that takes care of the order of initializing widgets and setting attributes.


text:
Q: linq to json target specific items to deserialize So here's my code:
        // converts JSON data to an object I can use to pull select data out of
        JObject o = JObject.Parse(data);

        // this works fine. I can go one layer deep for a single piece of data
        int count = (int)o["count"];
        Console.WriteLine("This: {0} should say 30", count);

        // this also works. I can go multiple layers deep for SINGLE pieces of data...
        string publisherOne = (string)o["recipes"][0]["publisher"];
        Console.WriteLine("This: {0} should say Closet Cooking", publisherOne);

        // this is where the issue is... I can't go multiple layers deep and
        // get single pieces of data from each JSON object
        List<string> allPublishers = o["recipes"]["publisher"].Select(t => (string)t).ToList();
        Console.WriteLine(allPublishers[2] + "should say picky palate");

data is a string of JSON, which here is a sample of what I'm using: (It's longer, but this is enough)
{
  "count": 30,
  "recipes": [
{
  "publisher": "Closet Cooking",
  "f2f_url": "http://food2fork.com/view/35186",
  "title": "Caprese Grilled Cheese Sandwich",
  "source_url": "http://www.closetcooking.com/2011/09/caprese-grilled-cheese-sandwich.html",
  "recipe_id": "35186",
  "image_url": "http://static.food2fork.com/Caprese2BGrilled2BCheese2BSandwich2B5002B21616ce448f5.jpg",
  "social_rank": 99.99999999999993,
  "publisher_url": "http://closetcooking.com"
},
{
  "publisher": "Closet Cooking",
  "f2f_url": "http://food2fork.com/view/35596",
  "title": "Spinach Pesto Grilled Cheese Sandwich",
  "source_url": "http://www.closetcooking.com/2010/05/spinach-pesto-grilled-cheese-sandwich.html",
  "recipe_id": "35596",
  "image_url": "http://static.food2fork.com/SpinachPestoGrilledCheeseSandwich50053b8a9a0.jpg",
  "social_rank": 99.99999999999862,
  "publisher_url": "http://closetcooking.com"
},
{
  "publisher": "Picky Palate",
  "f2f_url": "http://food2fork.com/view/484d98",
  "title": "Crock Pot Pesto Ranch Chicken Thighs",
  "source_url": "http://picky-palate.com/2012/09/20/pesto-ranch-crock-pot-chicken-thighs/",
  "recipe_id": "484d98",
  "image_url": "http://static.food2fork.com/CrockPotPestoRanchChickenThighs1text1300x248ca0b.jpg",
  "social_rank": 99.99999999941502,
  "publisher_url": "http://picky-palate.com"
},

The first two (count and publisherOne) work absolutely fine.
allPublishers is supposed to be a list of all the publishers, but it's causing me trouble because the publisher info is just a single piece of data within the array of recipes. This is what I'm using for reference in trying to do this:
http://www.newtonsoft.com/json/help/html/LINQtoJSON.htm
Thanks in advance!

A: I would use these classes
public class Recipe
{
    public string publisher { get; set; }
    public string f2f_url { get; set; }
    public string title { get; set; }
    public string source_url { get; set; }
    public string recipe_id { get; set; }
    public string image_url { get; set; }
    public double social_rank { get; set; }
    public string publisher_url { get; set; }
}

public class RootObject
{
    public int count { get; set; }
    public List<Recipe> recipes { get; set; }
}

and
deserialize as
var obj = JsonConvert.DeserializeObject<RootObject>(json)

Now you can write your linq in a compile-time safe way
PS: See http://json2csharp.com/


text:
Q: Register FiddlerCore as a ProxyInProcess and modify https traffic calling CreateProxyEndpoint. I have a issue using FiddlerCore to modify https traffic after starting fiddler with the following. I pass in the port, upstream proxy and bypassAddress if set.
I have tried passing in "*" and "127.0.0.1" and even the certificate by calling CertMaker.GetRootCertificate() and passing in the certificate in FiddlerApplication.CreateProxyEndpoint and the result is not null, but my https traffic isnt logged.
    internal static void StartProxyWithSecureEndPoint(int proxyPort, string upstreamProxy, string bypassAddress)
    {
        ProxyPort = proxyPort;
        UpstreamProxy = upstreamProxy;
        BypassAddress = bypassAddress;

        _upstreamProxy = upstreamProxy;
        URLMonInterop.SetProxyInProcess("127.0.0.1:" + proxyPort, bypassAddress);
        CONFIG.IgnoreServerCertErrors = true;
        CONFIG.bCaptureCONNECT = false;

        if (_upstreamProxy == null)
        {
            _fiddlerOptions = (FiddlerCoreStartupFlags.Default & ~FiddlerCoreStartupFlags.RegisterAsSystemProxy  & ~FiddlerCoreStartupFlags.CaptureFTP & ~FiddlerCoreStartupFlags.ChainToUpstreamGateway);
        }
        else
        {
            _fiddlerOptions = (FiddlerCoreStartupFlags.Default & ~FiddlerCoreStartupFlags.RegisterAsSystemProxy & ~FiddlerCoreStartupFlags.CaptureFTP);
        }

        FiddlerApplication.BeforeRequest += FiddlerApplication_BeforeRequest;
        FiddlerApplication.BeforeResponse += FiddlerApplication_BeforeResponse;
        FiddlerApplication.ResponseHeadersAvailable += FiddlerApplication_ResponseHeadersAvailable;
        FiddlerApplication.OnValidateServerCertificate += FiddlerApplication_OnValidateServerCertificate;

        FiddlerApplication.Startup(proxyPort, _fiddlerOptions);
        _secureEndpoint = FiddlerApplication.CreateProxyEndpoint(proxyPort, false, "*");

    }

A: *

*"*" isn't a valid value for a certificate hostname in your call to CreateProxyEndpoint.

*When you call CreateProxyEndpoint and pass a certificate hostname, the listener you create doesn't behave like a proxy, it behaves like a HTTPS server. As a consequence, if you use SetProxyInProcess to force WinINET callers in your process to send traffic to that endpoint, the requests will all fail because the client will send a CONNECT to something that's expecting a HTTPS ClientHello.

*When you set bCaptureCONNECT to false, you prevent the client from trying to proxy its secure traffic.

From your textual description of what you're trying to do, you shouldn't be calling CreateProxyEndpoint at all, and you should not be setting bCaptureCONNECT either. And just to confirm, because you're not setting RegisterAsSystemProxy, you'll only be capturing traffic from WinINET callers (e.g. a WebBrowserControl) inside your own process.
Have you had a look at the Program.cs demo that ships with the FiddlerCore download?


text:
Q: Need help defining a Quadratic Programming problem I have an optimization problem which should be solvable with Quadratic Programming:

There are $n$ multiplication coefficients $c_i$ for which optimized values are searched.
The coefficients are multiplied by an individual vector and summed up to a new vector:
$\pmb v^{sum} = \sum_{i =0}^n c_i \cdot \pmb v_i$
Finally, the mean squared error between $\pmb v^{sum}$ and a vector $\pmb u$ is formed:
$mse = \frac{1}{m}\sum_{i = 0}^m (u_i - v^{sum}_i)^2$
The restrictions for values in the $\pmb c$ vector are:

*

*They are not allowed to be negative:
$c_i \ge 0.0$

*They must have a sum of $1.0$:
$\sum_{i =0}^n c_i = 1.0$
So I want to find optimized $c_i$ values for which the $mse$ is minimized while considering the restrictions.

The minimization should be done with Quadratic Programming:
$minimize\ \ \ \frac{1}{2}\pmb x^T \pmb P\pmb x+\pmb q^T\pmb x$
$subject\ to\ \ \ \pmb{Gx} \leq \pmb h$
$\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \pmb{Ax} = \pmb b$
Can someone help me translate the problem into the Quadratic Programming form so I can put it into a solver?

A: Some high level tools allow you to input the model almost as you stated it. After substituting out ${\pmb v}^{sum}$, we can write using cvxpy:
import numpy as np
import cvxpy as cp

n = 10 # number of vectors v[i]
m = 20 # length of each vector

# random data
V = np.random.random_sample((m,n))
u = np.random.random_sample((m,1))

# optimization model
c = cp.Variable((n,1),nonneg=True)
prob = cp.Problem(cp.Minimize((1/m)*cp.sum_squares(u-V@c)),
                  [sum(c) == 1])
prob.solve(verbose=True)
print("status:",prob.status)
print("mse:",prob.value)
print("values for c:")
print(c.value)

A: Define $\mathbf x$ as the vector $\mathbf x:=(c_1,c_2,\dots,c_n)^T$ and $\mathbf V$ as the matrix whose columns are $\pmb v_i$, i.e., $\mathbf V=(\pmb v_1, \pmb v_2, \dots, \pmb v_n)$. Then, $\pmb v^{sum}=\mathbf{Vx}$. Then, your $mse$ can be written as $$mse = (\pmb u - \mathbf{Vx})^T(\pmb u-\mathbf{Vx}).$$ (Please double-check this by taking into account my comment to make sure that I understood your notation correctly -- I ignored the constant $\frac{1}{m}$ as it is irrelevant for minimization).
Then, we have that $$(\pmb u-\mathbf{Vx})^T (\pmb u-\mathbf{Vx}) = \pmb u^T \pmb u - 2\pmb{u}^T\mathbf{Vx}+\mathbf{x}^T \mathbf V^T \mathbf V \mathbf x.$$
$ \pmb u^T \pmb u $ is constant so you can ignore it for minimization purposes. Now define $\mathbf P:=2 \mathbf V ^T \mathbf V$ and $\mathbf q := -\frac{1}{2}\pmb u^T \mathbf V$ and you have formulated your minimization function appropriately. This is a convex problem because $\mathbf P$ is nonnegative-definite, since it is the multiplication of the transpose of a matrix with the matrix itself.
As for the constraints, define $\mathbf G$ as the $n\times n$ diagonal matrix whose diagonals are all $-1$, i.e., $\mathbf G:=\text{diag}(-1,-1, \dots, -1)$, $\mathbf h$ as the $n$-dimensional column vector $\mathbf h:=(0,0\dots,0)^T$, $\mathbf A$ as the $n$-dimensional row vector $\mathbf A:=(1,1,\dots,1)$ and $\mathbf b$ simply as the scalar $\mathbf b:=1$. This should complete the formulation of the problem, but please double-check everything if you are going to use this solution.


text:
Q: Whats the best way to deprecate a field in Protocol Buffer v3, reserved vs deprecated=true? When using Protocol Buffers version 3, from what I can see, there are 2 ways you can deprecate a field:
Either using the deprecate field using tags:
message MyMessage {
    string deprecated_my_field = 1 [deprecated=true];
}

Or creating a reserved field ID:
message MyMessage {
    reserved 1; // Deprecated "my_field"
}

I am leaning towards reserved since then no one will be able to use the field.
Is this a bad idea?

A: Both will work; the first option keeps the definition in the model, so it can still be accessed and queried - but it may generate a build warning when available (for clients who update from the schema). This may have useful applications in some cases.
The second option completely removes the field from the model, so any existing usages will break at build when clients update from the schema. Again, this could be good or bad, depending on how "done" you are with the field.
In some cases, the softer "mark it as a build warning, but allow access" may be preferred; in others, the hard "that doesn't exist!" approach is cleaner. It is subjective.
Either will fundamentally get the job done.

A: One way to view this is that using [ deprecated = true ] actually deprecates the field while using reserve actually obsoletes the field. A big difference between the two is that the latter introduces a backwards-incompatible change and, pedantically, warrants a new version of the proto.
It might also be a good idea to document the deprecated/obsoleted field (including what to use instead if applicable) with something like:
  [
    deprecated = true,
    (grpc.gateway.protoc_gen_openapiv2.options.openapiv2_field) = {
      description: "Recipient's name"
    }
  ]


text:
Q: Updating from a select query with a left join I ask this with limited SQL understanding, apologies in advance if it's obvious.  I have a select query that returns a result set of 'unread' messages and matches the sender ID from a table of users (called authors) for a simple web application I am working on. The tables are described below:
Authors:
aId int(20) NO  PRI NULL    auto_increment
aUser   varchar(30) NO  UNI NULL
aPass   varchar(40) NO      NULL
aEmail  varchar(30) NO  UNI NULL
aBio    mediumtext  YES     NULL
aReg    datetime    NO      NULL

Messages:
msgId   int(20) NO  PRI NULL    auto_increment
mSender int(20) NO  MUL NULL
mReciever   int(20) NO  MUL NULL
mTitle  tinytext    NO      NULL
mBody   mediumtext  NO      NULL
mRead   tinyint(4)  NO      NULL
mDate   datetime    NO      NULL

The select query is I am using is (Tks martina):
 SELECT messages.mTitle, messages.mBody, messages.mDate, authors.aUser
 FROM messages LEFT JOIN authors on aId=mSender WHERE mReciever = '$aId' AND mRead = '0'

$aId is a php session variable that contains the userID of the active user. My php application will assume since this 'unread' message has been processed it is now read, could anyone assist with modification of the above query to also update mRead to 1, indicating it is read, from an existing post on here i read you can't SELECT with UPDATE in the same SQL statement, would there be another way around this, am i miles away from the correct solution?.any help much appreciated.
Many thanks in advance.

A: What you heard is correct.  You cannot SELECT and UPDATE in one statement.  Your PHP code has to execute two different SQL commands.  After selecting, use PHP with your result to figure out the IDs of the messages you're returning, and then execute an UPDATE statement on the messages table, something like "UPDATE messages SET mRead=1 WHERE msgId IN (?)".

A: You can JOIN the table during UPDATE:
UPDATE table1
LEFT JOIN table2 ON(table1.id = table2.id)
SET ...
WHERE ...

and select the records in WHERE statement.
Related: https://stackoverflow.com/a/806925/1815881
My blog post: http://athlan.pl/mysql-update-join/
The second way is select ID's of records to update and execute:
UPDATE table
SET ...
WHERE id IN( ...your select... )


text:
Q: bootstrap 2.3 fluid row spacing I'm trying to create a row of divs (one per day of the week) that each contain a set of buttons for a user's availability for that time slot. However, no matter what I try I can't get the Bootstrap grid to space it evenly. Since there's seven days, I can't evenly divide the 12-space span, so each div is span1. However, in the Bootstrap docs they show this evenly filling the available space. In my example, it always crowds the divs to the left, so everything is cramped instead of taking up the available space.
I have a fiddle here: http://jsfiddle.net/usrwvreL/
Can someone point out the right way to use the grid / fluid row to space these items appropriately?

A: Bootstrap uses a 12 box grid system so if you need to divide by seven you could add a custom grid division,
so you can make a selector like .col-seventh{width:  calc (100% / 7)}
to extend that you can make a new grid type:
 .col-seventh-1{width: 14.285714%;}
 .col-seventh-2{width: 28.571428%;}
 .col-seventh-3{width: 42.857142%;}
 .col-seventh-4{width: 57.142857%;}
 .col-seventh-5{width: 71.428571%;}
 .col-seventh-6{width: 85.714285%;}
 .col-seventh-7{width: 100%;}

Instead you could also use flexboxes css3 property layout (non-bootstrap) to do all this for you!!

A: I find that an easy way to defeat the grid system when faced with this type of challenge is to take advantage of nested rows. Create three columns of size 4,
inside of which you could create three columns of four.
In the first parent column, you could have two child columns. The first child column would be offset using the .col-size-offset-4, which would then be proceeded by a .col-size-4.
The center parent column would have three child columns of size four, and the final parent column would have two child columns of size 4.


text:
Q: Wireless on Acer Aspire V3-371 very poor or not working at all. What can I do? I bought an Acer Aspire V3-371 a while ago and istalled Kubuntu 14.04 on it. Most things work fine, just that I often can't connect to wifi.
At home the connection is so bad that I can't use it at all even if I'm sitting right next to the router. However, it works fine when I'm in college where there are many routers and as far as I know it's a public network.
It seems that I can't get a proper connection to the router at home.
Does anyone has any tips or links that could help?
sudo lspci -nn gives:
00:00.0 Host bridge [0600]: Intel Corporation Broadwell-U Host Bridge -OPI [8086:1604] (rev 09)
00:02.0 VGA compatible controller [0300]: Intel Corporation Broadwell-U Integrated Graphics [8086:1616] (rev 09)
00:03.0 Audio device [0403]: Intel Corporation Broadwell-U Audio Controller [8086:160c] (rev 09)
00:14.0 USB controller [0c03]: Intel Corporation Wildcat Point-LP USB xHCI Controller [8086:9cb1] (rev 03)
00:16.0 Communication controller [0780]: Intel Corporation Wildcat Point-LP MEI Controller #1 [8086:9cba] (rev 03)
00:1b.0 Audio device [0403]: Intel Corporation Wildcat Point-LP High Definition Audio Controller [8086:9ca0] (rev 03)
00:1c.0 PCI bridge [0604]: Intel Corporation Wildcat Point-LP PCI Express Root Port #3 [8086:9c94] (rev e3)
00:1c.3 PCI bridge [0604]: Intel Corporation Wildcat Point-LP PCI Express Root Port #4 [8086:9c96] (rev e3)
00:1d.0 USB controller [0c03]: Intel Corporation Wildcat Point-LP USB EHCI Controller [8086:9ca6] (rev 03)
00:1f.0 ISA bridge [0601]: Intel Corporation Wildcat Point-LP LPC Controller [8086:9cc3] (rev 03)
00:1f.2 SATA controller [0106]: Intel Corporation Wildcat Point-LP SATA Controller [AHCI Mode] [8086:9c83] (rev 03)
00:1f.3 SMBus [0c05]: Intel Corporation Wildcat Point-LP SMBus Controller [8086:9ca2] (rev 03)
00:1f.6 Signal processing controller [1180]: Intel Corporation Wildcat Point-LP Thermal Management Controller [8086:9ca4] (rev 03)
01:00.0 Ethernet controller [0200]: Realtek Semiconductor Co., Ltd. RTL8111/8168/8411 PCI Express Gigabit Ethernet Controller [10ec:8168] (rev 0c)
02:00.0 Network controller [0280]: Intel Corporation Wireless 7265 [8086:095a] (rev 48)

ifconfig gives:
eth0 Link encap:Ethernet HWaddr 20:6a:8a:e2:ce:4c
UP BROADCAST MULTICAST MTU:1500 Metric:1
RX packets:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:0 (0.0 B) TX bytes:0 (0.0 B)

lo Link encap:Local Loopback
inet addr:127.0.0.1 Mask:255.0.0.0
inet6 addr: ::1/128 Scope:Host
UP LOOPBACK RUNNING MTU:65536 Metric:1
RX packets:247 errors:0 dropped:0 overruns:0 frame:0
TX packets:247 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:31021 (31.0 KB) TX bytes:31021 (31.0 KB)

wlan0 Link encap:Ethernet HWaddr 60:57:18:1c:41:20
inet addr:192.168.192.35 Bcast:192.168.192.255 Mask:255.255.255.0
inet6 addr: fe80::6257:18ff:fe1c:4120/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:59 errors:0 dropped:0 overruns:0 frame:0
TX packets:122 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:7044 (7.0 KB) TX bytes:16003 (16.0 KB)

Hopefully that helps.

A: I have the same computer.
You have to edit /etc/modprobe.d/ath9k.conf (or create it)
sudo nano /etc/modprobe.d/ath9k.conf

and add this line:
options ath9k nohwcrypt=1

Then reboot your computer.


text:
Q: Upgrading pandas on linux So, Currently I have Python 2.7.6 in my linux system and pandas version '0.13.1' so I was using dt accesor in my code which wasnt working.After some google I came to know it requires higher version of pandas. I tried a couple of things. It is giving me warning #warning "Using deprecated NumPy API, disable it by " \ . Any help on this how can I upgrade this?

A: Looking at the log, the two interesting lines are

copying build/lib.linux-x86_64-2.7/pandas/_period.so -> /usr/local/lib/python2.7/dist-packages/pandas
error: could not delete '/usr/local/lib/python2.7/dist-packages/pandas/_period.so': Permission denied

The problem is obvious: You have a system version of pandas installed in /usr/lib/python2.7, and an old versions of pandas installed in /usr/local/lib/python2.7/. /usr/local/bin is a system-wide directory, so you need superuser rights to write to it. However, your user does not have these rights.
There are a number of options to rectify the problem:

*

*Use a virtualenv or another way of installing panda in a local directory. In order to avoid confusion, it may be a good idea to remove the system-wide installations in /usr/local/ and the one in /usr/lib.

*Call pip install with the --user option to install pandas for your current user. Again, it depends on your system setup, but it may be a good idea to remove the system-wide installations.

*Update the system-wide pip installation. You'll need superuser rights (typically acquired by prefixing the command with sudo, as in sudo pip install -U pandas). It may be a good idea to remove the OS version.

*Find a way to update the OS version (in /usr/lib). Again, remove all others.

To remove the installation in /usr/local/lib/python2.7/pandas/, run sudo pip uninstall pandas or remove the directory outright.
It depends on the linux distribution how you get rid of your operating system version. In most releases, something along the lines of sudo apt-get remove -y python-pandas should work.
Everything before these messages is just warnings. The UnicodeDecodeError is a red herring, since it only occurs after the installation has failed.
To find out which pandas version you are using, you can examine the Python path (print(sys.path)) or more cleverly, simply run
import pandas as pd
print(pd.__file__)


text:
Q: how to supress the below banner,Authentication (publickey) successful! and Connected version 2.0, client OpenSSH_6.6.1 on Python 2.7 My function to perform ssh using paramiko and and log file will be generated with below info.
def node():
    ssh=paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    ssh.connect(SelfIP,SSHport)
    stdin,stdout,stderr=ssh.exec_command('ls -lrt')
    outlines=stdout.readlines()
    resp=''.join(outlines)
    cmd = "exit"
    print("RESP",resp)
    logging.info(resp)

node()

How do we suppress or make sure the below lines should not appear in log file, any suggestions?
2019-03-18 15:30:41,226 INFO Connected (version 2.0, client OpenSSH_6.6.1)
2019-03-18 15:30:41,444 INFO Auth banner:
Attention! Unauthorized remote access is strictly prohibited!

2019-03-18 15:30:41,445 INFO Authentication (publickey) successful!


text:
Q: Getting the following error: Unable to resolve "../assets/icon.png" from "app\assets\screens\WelcomeScreen.js" When I try to run my app I get the error
Unable to resolve "../assets/icon.png" from "app\assets\screens\WelcomeScreen.js"
Error: Problems validating asset fields in app.json. See https://docs.expo.io/
• Field: icon - cannot access file at './assets/icon.png'.
I created a screens folder and input my homescreen into it as I heard that the majority of the react native community does things that way. Attached is a picture of my filesenter image description here
I think that the image path is off, however I had changed it multiple times and am still getting the same error.
Any help would be appreciated.

A: try the following:  ../icon.png
Cause that's what I can see from your file structure.
If you use visual studio code as dev tool, when you type path cue, correct path will be appeared. so you can avoid to make mistake in path of image.