text:
Q: Unit testing class with doubles I have a class that contains (one or more...) doubles. For example:
public class TestFloatClass{
 public double Double1{get;set;}
 public double Double2{get;set;}

 public void SetDoubleByCalculation(double value){
  Double1 = //Some calculations here;
  Double2 = //Some calculations here;
 }
}

I want to test the SetDoubleByCalculation(double value) method, so I start writing unit tests.
TestFloatClass expected = new TestFloatClass();
expected.Double1 = 100.10;
expected.Double2 = 200.24554;

TestFloatClass actual = new TestFloatClass();
actual.SetDoubleByCalculation(Math.PI); //Just using something random here.

In this case, expected.Double1 and actual.Double1 are approximately the same. But not exactly due to floating point accuracy.
However, I'm not sure how to unit test this correctly. These are the things I have tried so far.
Including a certain delta in the equals operator
My first intuition said, well, just include the logic in the equals operator like so:
public override bool Equals(object obj){
  return Math.Abs(this.Double1 - obj.Double1) <= 0.00001 &&
              Math.Abs(this.Double1 - obj.Double1)  <= 0.00001;
}

But as said in this Hashcode implementation double precision topic, it's just practice to do so.
Just using the Assert override
I can go on by testing it as follows:
Assert.Equals(expected.Double1, actual.Double1, 0.0000001); //Or just some precision
Assert.Equals(expected.Double2, acutal.Double2, 0.0000001);

But then again, then I have to do this for EVERY property in this class. If the TestFloatClass also had two properties VeryComplicatedClass vcc & int integer then I'd have to add those too.
Assert.Equals(expected.Double1, actual.Double1, 0.0000001); //Or just some precision
Assert.Equals(expected.Double2, actual.Double2, 0.0000001);
Assert.Equals(expected.vcc, actual.vcc);
Assert.Equals(expected.integer, actual.integer);

And it would keep growing if the class gets bigger...
So my question
What is the best way to test this class?

A: You should split the tests:
Assert.Equals(expected.Double2, acutal.Double2, 0.0000001);
Assert.Equals(expected.vcc, actual.vcc);

Make (separate) unit Tests for  the Double2 and vcc properties on the class of actual/expected.

A: Note that my response to your other question mainly criticized the use of a thusly modified Equals() together with GetHashCode() for use in a Hashtable - that just won't work, which is a good example why it's problematic to override Equals() in a way that breaks its contract. If you only use it for direct comparisons in tests, that would be OK. But it might be a better idea to have a separate comparison method (perhaps called FuzzyEquals()) for use in tests to avoid confusion.
Additionally, comparing with a fixed epsilon is problematic if your values can be very small or very large - read The Floating-Point Guide for details .


text:
Q: Cannot get value from cookie in Java. Value contains commas. I have problem with getting value from cookie that contains commas. It returns not full string but string cut off to first comma. For example:
// cookie value = var1,var2,var3
String cookieVal = cookie.getValue();
//cookieVal now is "var1" instead of "var1,var2,var3"

and
// cookie value = var1=var2=var3
String cookieVal = cookie.getValue();
//cookieVal now is "var1=var2=var3"

What am i doing wrong.

A: Take a look at the Cookie Documentation. It says :

This class supports both the Version 0
  (by Netscape) and Version 1 (by RFC
  2109) cookie specifications. By
  default, cookies are created using
  Version 0 to ensure the best
  interoperability.

And if you see the setValue method you will find this

With Version 0 cookies, values should not contain white space, brackets, parentheses, equals signs, commas, double quotes, slashes, question marks, at signs, colons, and semicolons. Empty values may not behave the same way on all browsers.

EDIT: Just read the google thing. Maybe try setting the version to 1 and see how it works.

A: The comma is part of the http-header value definition, so url-encode commas in your cookie value.
URLEncoder.encode(cookieValue);

I found this:

"This [cookie value] string is a sequence of characters excluding
  semi-colon, comma and white space. If there is a need to place such
  data in the name or value, some encoding method such as URL style %XX
  encoding is recommended, though no encoding is defined or
  required"

The RFC says:

Informally, the Set-Cookie response header comprises the token Set-
     Cookie:, followed by a comma-separated list of one or more cookies.
     Each cookie begins with a NAME=VALUE pair, followed by zero or more
     semi-colon-separated attribute-value pairs.

Update: After you clarified that you are parsing a cookie from google: I looked through all my __utmX cookies and none of them contains commas. The delimiter there is | or url-encoded :

A: Are you sure you need to store a set in the cookie? IMHO cookies should not be used to store data apart from identifiers. Data storage should be done on the server-side whenever possible.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Chrome not trusting Fiddler certificates Similar to this question:
Chrome Doesn't Trust Fiddler Root Certificate
But the upvoted answer (https://stackoverflow.com/a/33818661/1250301) doesn't seem to be working for me in fiddler v 5.0.
If I load a site with https in chrome I get NET::ERR_CERT_AUTHORITY_INVALID message. If I "reset all certificates" under the HTTPS tab of the options dialog (as per the suggestion in the answer) then I no longer get the certificate errors in Chrome, but Fiddler will only intercept the "Tunnel to" requests and nothing else. If I close fiddler and restart it, then my certificate is no good again for some reason!


text:
Q: Error while installing `XML::Parser` Perl module I'm trying to install some Perl module, but I got a strange error:
sudo cpanm XML::Parser

cp Parser/Encodings/iso-8859-5.enc blib/lib/XML/Parser/Encodings/iso-8859-5.enc
make[1]: Entering directory `/root/.cpanm/work/1383241509.7912/XML-Parser-2.41/Expat'
cp Expat.pm ../blib/lib/XML/Parser/Expat.pm
/usr/bin/perl /usr/share/perl/5.14.2/ExtUtils/xsubpp -noprototypes -typemap /usr/share/perl/5.14/ExtUtils/typemap -typemap typemap  Expat.xs > Expat.xsc && mv Expat.xs$
cc -c   -D_REENTRANT -D_GNU_SOURCE -DDEBIAN -fstack-protector -fno-strict-aliasing -pipe -I/usr/local/include -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -O2 -g   -DVER$
Expat.xs:12:19: fatal error: expat.h: No such file or directory
compilation terminated.
make[1]: *** [Expat.o] Error 1
make[1]: Leaving directory `/root/.cpanm/work/1383241509.7912/XML-Parser-2.41/Expat'
make: *** [subdirs] Error 2
-> FAIL Installing XML::Parser failed. See /root/.cpanm/work/1383241509.7912/build.log for details. Retry with --force to force install it.

How can I fix this problem?

A: I found a solution with this apt-get command:
sudo apt-get install expat
sudo apt-get install libexpat1-dev


text:
Q: Why is the intake of students for Hogwarts so small compared to the number of witches and wizards in Britain? If we assume that Harry's year in Hogwarts is an average size, and that each house gets roughly a quarter of the amount of new students each year, then it seems to me that Hogwarts doesn't house anywhere near enough students to cater for the wizarding population of Britain.
In Harry's school year, the male portion of Gryffindor consists of Harry, Ron, Neville, Seamus and Dean. If there are roughly that many girls in that years Gryffindor (I can't remember anyone other than Hermionie right now), then that makes roughly 10 in each house each year, which makes roughly 40 students a year. Over the 7 years, that makes about 280 students in Hogwarts at any one time, roughly 70 students per house.
This doesn't anywhere near high enough to teach all of the wizarding populations children, which although considerably smaller than the Muggle population, is still considerable, as evidenced by the size of the Ministry of Magic and how full Diagon Alley always seems to be.
Has this ever been explained? Out of universe, it seems that J K Rowling is just bad at maths, but in universe?

A: For this we need to look at the following things -

*

*Is Harry's class size indicative of average number of annual wizardly births?

*How large is the population of Wizarding UK anyway?

*Why does Diagon Alley always seem to be full?

*What's with the number of people in the Ministry?

Is Harry's class size indicative of average number of annual wizardly births?
This seems unlikely. Since Harry was born smack in the middle of one of the worst conflicts Wizarding UK faced. We know that people were disappearing every week for around 11 years, for a low estimate of around a 1000 adults people dead - which would be at least 10% (but more likely a lot more) of the population. Not only people too dead to spawn kidlets, but also not exactly an ideal time to be deciding to have babies (or be pregnant) anyway.
How large is the population of Wizarding UK anyway?
We have reason to believe average wizarding lifespan to be around 150 years; and assuming a conservative average annual birthrate over those 150 years to be around 50 gives us a population size of 7500. Which is not a huge number, but not exactly a tiny one either. Also consistent with comments by JKR.
Why does Diagon Alley always seem to be full?
Diagon Alley seems to be a street market style affair - and it definitely doesn't seem to be very large from what is described in the books. It wouldn't really take a very large number of people for such a place to appear crowded. But in addition to that, there's also the fact that Harry (and hence the readers) tend to see DA during what would possibly be one of the busier portions of the year for the market - the back-to-school shopping season. All those kids buying school supplies has got to create a bit of a crush.
What's with the number of people in the Ministry?
There seems a very large number of people in the Ministry compared to the total population, that's fairly true. But our window into the Ministry is through the Weasleys and the OoTP. Given that Arthur is a prominent civil servant and the OotP by its very nature would be made up of people likely to be Aurors or involved in politics, that seems at least one easy way to answer why so many of the adults we see, have something or other to do with the Ministry.
But in addition to that, there's also the question of the makeup of wizarding society. It's not a completely isolated population - it's a secret population within a much larger one. Most of the functions of the MoM seem to do with maintaining secrecy - so that's an extra function of the government that soaks up numbers - most of the Department of Magical Law Enforcement and Department of Magical Accidents and Catastrophes. Then there's also the Department for the Regulation and Control of Magical Creatures - given that these people need to deal and liase with whole societies of sapient magical people in addition to regulate dragons and other non-sapient magical creatures of that sort - their numbers being more significant than their Muggle counterparts doesn't seem too far fetched either.
Edited to add some numbers on Hogwarts and Wizarding Britain numbers from Jo: I found this interview from JKR regarding Hogwarts numbers:

Then I've been asked a few times how many people and because numbers are not my strong point, one part of my brain knew 40 [original characters she had created for Harry's year], and another part of my brain said, "Oh, about 600 sounds right."

600 in Hogwarts doesn't seem so small after all. But that paints Harry's year as being more than half the usual yearly intake ((600-40)/6) of around 90, which then goes on to give up a total population size of 13,500, take around a couple of thousand for the casualties of the two Wizarding Wars in the last century, and that's still a fairly decent number.
But then that same interview goes on to say (in the very next line):

Let's say three thousand [wizards/witches in Britain], actually...

What?! That means a Hogwarts year should have no more than 20 students at most! Harry's year is overpopulated; and total Hogwarts population should be something like a 150; and casualties under Grindelwald and Voldemort were massive percentage chunk of population. Or maybe most Wizards only live up to a 70-ish, same as Muggles, except a lucky few. That's the only way to explain those numbers.
Thankfully, JKR gives us an out and ask that we: "don't hold me to these figures, because that's not how I think."
In Conclusion: A 'corrected' average Hogwarts size of around 400-450 might be a good compromise between JKR and McNumbers. Harry's year in pretty small with 40 students, but the average yearly intake is 60-65 (two dorms per year per house per gender with 3-4 kids each (explains MWPP), instead of one with 5); leading to a total British Wizarding population of around 10000. The rest of the points in my answer still apply, I think.
And the explanation for this, as given by JKR herself:

Oh, Emerson, my maths is so bad.

A: There was a presumed baby boom after and during the early stages of the First War with Voldemort, thus the number of student would be disproportionate to the number of adult wizards. Including muggleborns, the student body is not a guaranteed comparison to the adult population.


text:
Q: Template as parameter in class I have header file and in my header file I make a template and I want to use the template just on one function and not force all other functions.  Is it possible to get the type before the function like i did in main?
This is an example:
TestTemp.h
// TestTemp.h
#ifndef _TESTTEMP_H_
#define _TESTTEMP_H_
template<class T>
class TestTemp
{
public:
    TestTemp();
    void SetValue( int obj_i );
    int Getalue();
    void sum(T b, T a);

private:
    int m_Obj;
};
#include "TestTemp.cpp"

#endif

TestTemp.cpp
//TestTemp.cpp
include<TestTemp.h>
TestTemp::TestTemp()
{
}
void TestTemp::SetValue( int obj_i )
{
    m_Obj = obj_i ;
}

int TestTemp::GetValue()
{
    return m_Obj ;
}

template<class T>
void TestTemp<T>::sum(T b, T a)
{
    T c;
    c = b + a;
}

main.cpp
//main.cpp
include<TestTemp.h>
void main()
{
    TestTemp t;
    t.sum<int>(3,4);
}

Have any ideas?

A: Your TestTemp is a template class already, no need to make sum template function.
TestTemp<int> t;
t.sum(3, 4);

If you really want to make sum function a template function of TestTemp:
template<class T>
class TestTemp
{
public:
    //....
    template<typename U>
    void sum(U b, U a);

private:
    int m_Obj;
};

To implement it outside template class:
template<class T>
template<typename U>
void TestTemp<T>::sum(U b, U a)
{
    T c;
    c = b + a;
}

int main()
{
    TestTemp<int> t;
    t.sum<int>(3, 4);
}

However, I feel you just need a free template function
template<typename T>
T sum(T a, T b)
{ return a + b; }

A: // TestTemp.h

#ifndef _TEST_TEMP_H_
#define _TEST_TEMP_H_

class TestTemp
{
public:
    TestTemp();
    void SetValue( int obj_i );
    int Getalue();

    template<class T>
    void sum(T b, T a);

private:
    int m_Obj;
};

TestTemp::TestTemp() {}

void TestTemp::SetValue( int obj_i )
{
   m_Obj = obj_i ;
}

int TestTemp::Getalue()
{
    return m_Obj ;
}

template<class T>
void TestTemp::sum(T b, T a)
{
   T c;
   c = b + a;
}

#endif

//main.cpp
#include <TestTemp.h>

int main()
{
    TestTemp t;
    t.sum<int>(3,4);
    return 0;
}

What you need is a normal class which has a template member function.
It's not a god idea to include an cpp file in header file. For template functions, just put it in header file.

A: You should take a look here. There are many examples.
I think it should work as you expect it if you just remove
template<class T>

from the
#ifndef _TESTTEMP_H_
#define _TESTTEMP_H_
--> template<class T> <--
class TestTemp

block. You don't have to define the whole class as templated when you just want a method to have template parameters.

A: You just need to define TestTemp as normal class of which "sum" is a template function. Then in your function "main" (i.e. the caller), the template argument will be deduced from the function arguments.
class TestTemp
{
public:
    TestTemp();
    void SetValue(int obj_i);
    int Getalue();

    template<class T>
    void sum(T b, T a);

private:
    int m_Obj;
};

TestTemp::TestTemp() {}

void TestTemp::SetValue(int obj_i)
{
    m_Obj = obj_i;
}

int TestTemp::Getalue()
{
    return m_Obj;
}

template<class T>
void TestTemp::sum(T b, T a)
{
    T c;
    c = b + a;
}

//main.cpp

int main()
{
    TestTemp t;
    t.sum(3, 4);
    return 0;
}


text:
Q: jQuery Selector set select value not working I have a bootstrap modal, that is offers users to add or edit bank account data.
When I click "Edit" Btn to edit bank data, the modal will set the value to the input value and select the option.
But in the modal, I have two select options, top of the select is to choose bank code,
and when the select changes, it will trigger change function to use ajax to get branch bank list.
So if I want to set the value to the modal, the top select option (bank) can successfully set value,
but the bottom select option (branch) will not successfully set the value to the modal.
My code is:
// Set top select option
$('#selectBankList option[value='+bankName[0]+']').attr('selected','selected');

// Show Modal
addBankModal.show();

// getBranchList
f_getBranchList(bankName[0]);

$(document).ready(function() {
  // Set bottom select option
  $('#selectBranchName option[value='+branchName+']').attr('selected','selected');
});

I've to try putting the set #selectBranchName value to anywhere, but still not working.
So, where is my code wrong?

A: $('#selectBankList ').on('change', function(){
    $('#selectBranchName option[value="'+$(this).val()+'"]').attr('selected', 'selected').addClass('active');
});

A: $('#id attribute[foo="bar"]');

you have not added inner quotes


text:
Q: How to get the image and text from a view in the recyclerView? I researched around 20 - 30 answers and still not found a working way to:

*

*get the image and text from --> view --> viewHolder --> recyclerview --> Fragment
( one image and one text fills 1 screen). ( NullPointerException)

*I need them as quote: String and imgRes: Int to input them in a viewModel DAO method to save them to favourites.

*Ideally if the user clicks the heart button, the present image + text goes in the favourites. If it is not possible, or overly complicated, then if the user clicks anywhere in the screen the image + text should go to favourites.

*In the adapter I need the context to get a random quote from the database  (I understand that Context in Adapter is a big no-no) - can you recommend a cleaner way to do it?

*Please advise on how to implement the clicklistener so it gets the image and text!
Thank you!

Adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.example.data.DataSource
import com.example.data.DataSource.prepareManualQuote
import com.example.databinding.SlidingItemBinding

class SlidingItemAdapter(context: Context) :
    RecyclerView.Adapter<SlidingItemAdapter.SlidingItemViewHolder>() {
    //    does NOT WORK TO PASS CONTEXT HERE, NEITHER IN DATABASE, OR VIEWMODEL,
    // but it is needed to get the drawable resources programatically
    // that is why we pass a private constructor
    private var imgList: MutableList<Int> = DataSource.getThemAll(context)

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SlidingItemViewHolder {
        val binding = SlidingItemBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return SlidingItemViewHolder(binding)
    }

    //     the prepareManualQuote is still a random quote - but passed through Database this time,
   // not viewmodel
    override fun onBindViewHolder(holder: SlidingItemViewHolder, position: Int) {

        // we take a random quote and a random image
        val randomPos: Int = (imgList.indices).random()
        val imgRes: Int = imgList[randomPos]
        val manualQuote: String = prepareManualQuote(holder.itemView.context)

        holder.binding.imageViewManual.setImageResource(imgRes)
        holder.binding.quoteManual.setText(manualQuote)

    }

    class SlidingItemViewHolder(val binding: SlidingItemBinding):
        RecyclerView.ViewHolder(binding.root)

    override fun getItemCount(): Int {
        return imgList.size
    }

}

SlidingFragment

class SlidingPhotosFragment : Fragment() {

    private var _bindingManual: FragmentManualSlidingRecyclerviewBinding? = null
    private val bindingManual get() = _bindingManual!!

    // Anything used in onCreate and OnviewCreated, etc - declare it here
    lateinit var isAuto: String

    /*** Standard implementation to work with databases */
    private val viewModel: SpiritViewModel by activityViewModels {
        SpiritViewModelFactory(
            (requireActivity().application as ConnectRoomDatabaseApplication).roomDatabase.itemDao()
        )
    }
    var randomPos: Int = 5
    var quote: String = ""

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
      _bindingManual = FragmentManualSlidingRecyclerviewBinding.inflate(inflater, container,false)
      return bindingManual.root
        }
    }

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
    bindingManual.lifecycleOwner = viewLifecycleOwner

    // slidesrecyclerView is the binding name gave to recyclerview id in  fragment_manual_sliding_recyclerview
    bindingManual.slidesRecyclerview.adapter = context?.let { SlidingItemAdapter(it) }

    // Extracting stuff from the recyclerview
    val linearManager = LinearLayoutManager(context)

    bindingManual.heartFavouriteButton.setOnClickListener {
        val position: Int = linearManager.findFirstCompletelyVisibleItemPosition()

        val row: View? = bindingManual.slidesRecyclerview.layoutManager!!.findViewByPosition(position)
        val quoteManual: TextView = row!!.findViewById(R.id.quoteManual)
        val imageViewManual: ImageView = row.findViewById(R.id.imageViewManual)
        println("dra in manual sliders were extracted this quote and this imageViewId" + quoteManual.text + imageViewManual.getDrawable())
            }

        // Snap implementation
        val pgSnaphelper: SnapHelper = PagerSnapHelper()

            // By using a pagerSnap Helper the snap goes strictly to only 1 slide - not scrolling through many more
        bindingManual.slidesRecyclerview.layoutManager?.let {
            bindingManual.slidesRecyclerview.layoutManager!!.getChildAt(0)
                ?.let { it1 -> pgSnaphelper.calculateDistanceToFinalSnap(it, it1) }
            }
        pgSnaphelper.attachToRecyclerView(bindingManual.slidesRecyclerview)
        }
    }

XML fragment_manual_sliding_recyclerview
<?xml version="1.0" encoding="utf-8"?>

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/black"
        android:navigationBarColor="@color/nav_icons_default"
        tools:context=".ui.fragments.SlidingPhotosFragment">

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/slides_recyclerview"
            android:clipToPadding="false"
            android:layout_width="0dp"
            android:layout_height="0dp"
            app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <ImageButton
            android:id="@+id/heartFavouriteButton"
            style="@android:style/Widget.Holo.ImageButton"
            android:layout_width="33dp"
            android:layout_height="32dp"
            android:layout_marginEnd="250dp"
            android:adjustViewBounds="true"
            android:background="@color/material_on_primary_disabled"
            app:layout_constraintBottom_toTopOf="@+id/heartRedFavouriteButton"
            app:layout_constraintEnd_toEndOf="parent"
            app:srcCompat="@drawable/ic_heart_svgrepo_com"
            android:contentDescription="@string/save_slider_to_favourites" />

        <ImageButton
            android:id="@+id/heartRedFavouriteButton"
            style="@android:style/Widget.Holo.ImageButton"
            android:layout_width="33dp"
            android:layout_height="32dp"
            android:layout_marginEnd="250dp"
            android:layout_marginBottom="100dp"
            android:adjustViewBounds="true"
            android:background="@color/material_on_primary_disabled"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:srcCompat="@drawable/ic_heart_svgrepo_com2"/>
<!--            tools:visibility="visible" />-->

    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

<!--    tools:visibility="visible"-->

A: Like Tenfour04 says in the comments, really your Adapter is just there to display a set of data and pass back UI events to a listener. It shouldn't need to be compiling stuff like text, image URLs etc - that information should already be part of the data that was passed to the Adapter for display.
It should be enough to just pass that item to the "hey this item was clicked" listener. That could call a setFavourite(item) function in your ViewModel, which can pass it to the DAO for handling. Since there's a database involved, you probably need some kind of itemId in Item so you can tell which item in the database it corresponds to. If you're just passing that Item around, everything has all the info it needs by looking at it.

Nobody can write you a full implementation for all this, but here's the basics to get you started:
// In your adapter

var favClickedListener: ((Item) -> Unit)? = null

// In onBindViewHolder

val item = items[position]
holder.favButton.setOnClickListener {
    favClickedListener?.invoke(item)
}

// In your fragment or whatever

adapter.favClickedListener = { item ->
    // or maybe this should be a toggle - click the button, flip its status
    viewModel.setFavourite(item)
}

and then your ViewModel handles setting that favourite status, maybe pushing a new set of items with this changed status so it can be redisplayed, etc


text:
Q: Query ElasticSearch after the index operation I have the eservice A that executes some text processing. After it, service B has to execute some set of Elasticsearch queries on the document. The connectivity between the services provided by Kafka. The solution is tightly coupled to ES free text search capabilities, so I can't query in another way.
Possible solution:
To store the document in ES and query it. The problem is that ES is eventually consistent and I don't know if the document already indexed or not.
Is there some API to ensure that the document is already indexed?
Another option is to publish a message from service A with delay X+5 seconds, where X is the refresh interval of the index, where the document should be stored. Seems to me an unreliable solution. What do you think?
Another direction that I thought about, is some way to query the document with ES queries where the document is in memory. For example, if I will have some magic way to convert the ES query to Luciene DSL, so I don't need to deal with the eventual consistent behavior of Elasticsearch and I can query Lucine directly.
Maybe there are some other solutions?

A: take a look at the ?refresh flag so that an indexing request will only return once a refresh has happened. otherwise you can use the GET API to see if the document exists or not
however there is no magic options here, Elasticsearch is eventually consistent and you need to factor that in


text:
Q: Alias column name for Use in CASE Statement I have SQL query as below:
SELECT a.ID as AID, a.Amt as AAmt
FROM
     (SELECT
          ID,
          CASE
              WHEN Col1 = 0
                 THEN SUM (Col2 + Col3)
                 ELSE 0
          END AS Amt
      FROM  table1
      GROUP BY ID, Amt) AS a

I get an error:

Invalid column name 'Amt'.

(note: this applies to the GROUP BY clause).

A: You cannot GROUP BY the alias,
Try
SELECT a.ID as AID, a.Amt as AAmt
FROM
     (SELECT
          ID,
          CASE
              WHEN Col1 = 0
                 THEN SUM (Col2 + Col3)
                 ELSE 0
          END AS Amt
      FROM  table1
      GROUP BY ID, Col1) AS a

If you have a look at SQL Query Order of Operations you will note the the order of operations are
1.FROM clause
2.WHERE clause
3.GROUP BY clause
4.HAVING clause
5.SELECT clause
6.ORDER BY clause

This means that the GROUP BY is processed before the SELECT, which is where you defined the alias.
This also explains why you can order by an alias.

A: Your query seems a bit overly complicated, and the intention doesn't fully make sense.  I suspect you want conditional aggregation:
SELECT ID,  SUM(CASE WHEN col1 = 0 THEN col2 + col3 ELSE 0 END)
FROM  table1
GROUP BY ID;


text:
Q: htaccess conflicting with wordpress htaccess I have the following code in my htaccess file:
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www.example.com$
RewriteRule ^(.*)$ http://www.example.com/$1 [R=301]
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

I avoid editing the automated code by Wordpress because the changes may be erased and I'll have to do it all again. I have another site running the first three lines of code and it's working perfectly to replace example.com for www.example.com. That's all I really need for this example.com site but still preserving the Wordpress properties.
The problem
example.com is not redirecting to www.example.com but instead displaying a 301 error.

A: I'm using the following lines in all my WordPress-Sites before the # BEGIN WordPress. This should solve your problem. The L (for last) is the solution
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} !^www\.example\.com$
RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301]

A:
"I avoid editing the automated code by Wordpress because the changes
  may be erased and I'll have to do it all again."

You can avoid a WordPress installation from modifying its root .htaccess file.
Simply connect via FTP, or other means and chmod your WordPress root .htaccess file properties to 0444.

A: Where is the conflict? I can't see any conflict. WordPress only touches the lines after # BEGIN WordPress


text:
Q: "The Install OS X Mavericks application can't be used from this disk" OS X 10.9 Installation Error
I am trying to install OS X Mavericks on my Mid-2011 iMac. Before you tell me to upgrade, Mavericks is my favorite version and anything after it runs like crap.
Please help me fix this!

A: UPDATE: I have successfully been able to fix my problem. I started off by making a Mavericks USB installer, then I made a disk image from the drive. My mistake was making a .cdr file and burning it. I tried again by making a .dmg file instead. I now have Mavericks installed. It also took significantly quicker to get into the recovery menu.


text:
Q: C++ date Type class .. after compilation some function work well but the other not in below there is the Header File for dateType.
h class. after debug it showing in consul windows this :
Consul Image
Header File : dateType.h
#ifndef dateType_H
#define dateType_H

class dateType
{
public:
    void setDate(int, int, int);
    void setMonth(int);
    void setDay(int);
    void setYear(int);

    void print() const;

    int numberOfDaysPassed();

    int numberOfDaysLeft();

    void incrementDate(int nDays);

    int getMonth();
    int getDay();
    int getYear();

    int getDaysInMonth();

    bool isLeapYear();

    dateType(int = 1, int = 1, int = 1900);

private:
    int dMonth;
    int dDay;
    int dYear;
};

#endif

main() Function :
#include <iostream>
#include<time.h>
#include "dateType.h"

using namespace std;
int main ()
{
    cout <<" Program work with data type"<<endl;

    dateType myDate(1,1,1900);

    cout << "\n\n The current Date is : "<<endl;
    myDate.print();
    cout <<endl;

    cout <<"\n\n days in this year are :" <<endl;
    myDate.getDaysInMonth();
    cout <<endl;

    cout <<"\n\n Days passed in this year are :"<<endl;
    myDate.numberOfDaysPassed();
    cout <<endl;

    cout <<"\n\n Days remaining in this year are :"<<endl;
    myDate.numberOfDaysLeft();
    cout <<endl;

    myDate.incrementDate(7);
    cout <<"\n\n New date after adding days is "<<endl;
    cout <<endl;

    myDate.print();
    cout <<endl;

    system("pause");
    return 0;
}

Implementation file .cpp :
#include <iostream>
#include "dateType.h"

using namespace std;

void dateType::setDate(int month,int day,int year)
{
    setYear(year);
    setMonth(month);
    setDay(day);
}

void dateType::setMonth(int month)
{
    if(month > 0 && month < 13)
        dMonth =month;
    else
        dMonth = 1;
}

void dateType::setDay(int day)
{
    int days[12]= {31,28,31,30,31,30,31,31,30,31,30,31};
    if (isLeapYear())
        days[1]++;
    if(day >= 1 && day <=days [dMonth -1])
        dDay =day;
    else
        dDay =1;
}

void dateType::setYear(int year)
{

    if (((int)log10((double)year) + 1)!=4)
        dYear = 1990;
        else dYear = year;
}

int dateType::getDaysInMonth()
{
    int days[12]= {31,28,31,30,31,30,31,31,30,31,30,31};
        if (isLeapYear())
        days[1]++;
        return days[ dYear -1 ];
}
int dateType::numberOfDaysPassed()
{
    int days[12]= {31,28,31,30,31,30,31,31,30,31,30,31};
    int m, daysPassed;
        if (isLeapYear())
        days[1]++;
        m = dYear-1;
        daysPassed=0;
        while(m>0)
        {
            daysPassed+= days[m-1];
            m--;
        }
        daysPassed+= dDay;
        return daysPassed;
}
int dateType::numberOfDaysLeft()
{
    int daysRemaining=365;
    if (isLeapYear())
        daysRemaining++;
    daysRemaining-= numberOfDaysPassed();
    return daysRemaining;
}

void dateType::incrementDate(int nDays)
{
    while ((nDays + dDay) > dateType::getDaysInMonth())
    {
        nDays -= dateType::getDaysInMonth();
        if (dMonth == 12)
        {
            dMonth = 0;
            dYear++;
        }
        dMonth++;
    }
    dDay += nDays;
}

int dateType::getDay()
{
    return dDay;
}

int dateType::getMonth()
{
    return dMonth;
}
int dateType::getYear()
{
    return dYear;
}

void dateType::print() const
{
    cout <<"\n\t"<<dMonth<<"-"<<dDay<<"-"<<dYear;
}
dateType::dateType(int month, int day, int year)
{
    setDate(month,day,year);
}

bool dateType::isLeapYear()
{
    if (dYear % 400 == 0 || ( dYear % 100 !=0 && dYear % 4 ==0))
        return true;
    else
        return false;
}

I am not sure about calculating I thing i did wrong with these :
days in this year are :
Days passed in this year are :
Days remaining in this year are :

A: The functions getDaysInMonth, numberOfDaysPassed and numberOfDaysLeft don't print anything, they only return a value.
You have to print the value, so something like std::cout << myDate.getDaysInMonth() << '\n';

You print days in this year are :, but the function you call is getDaysInMonth. I don't know which one you need, but the logic is for both wrong.

*

*If you need the days in the year, then you only need to return 365 or 366, depending if it is a leap year or not.

*If you need the days in the month, you should decrement dMonth instead of dYear, as you want the month, and not the year (because you are currently use the year as index, you're accessing memory you don't own, which will result in an access violation exception or some random value).
The function numberOfDaysPassed calculates m as follows m = dYear - 1;, but again, you should be using dMonth. You should also consider using a for loop instead of a while:
for (int i = dMonth - 1; i > 0; --i)
    daysPassed += days[i - 1];


text:
Q: Django-compressor: Enable BrotliCompressorFileStorage with offline compression mode I'm using offline compression in conjunction with whitenoise on heroku and everything works fine before I overrode COMPRESS_STORAGE to enable broli compression as below:
INSTALLED_APPS += ['compressor', ]
STATICFILES_FINDERS += ['compressor.finders.CompressorFinder',]
COMPRESS_STORAGE = 'compressor.storage.BrotliCompressorFileStorage'
COMPRESS_ENABLED = env.bool('COMPRESS_ENABLED', default=True)
COMPRESS_OFFLINE = env.bool('COMPRESS_OFFLINE', default=True)

I have brolipy installed and added to requirements.txt.
But django-compressor gives me this error message:
module "compressor.storage" does not define a "BrotliCompressorFileStorage" attribute/class
Any idea why? The spelling seems correct. I checked the source code, and there is indeed a class named BrotliCompressorFileStorage in the compressor.storage module.
https://github.com/django-compressor/django-compressor/blob/develop/compressor/storage.py

A: As noted in https://github.com/django-compressor/django-compressor/issues/914, the brotli storage is not yet available in a django-compressor release, so you need to install the develop branch of django-compressor.


text:
Q: How to manipulate data extracted from a text file using fstream in C++? I need to make a Point of Sale software which is reading product names, barcodes and prices from a given text file. I can extract all the required data from the file, but I don't know how to use that data. To be precise I need to calculate the prices of picked products. My program is currently able to ask a user for a barcode and print out the chosen products
#include <iostream>
#include <string>
#include <fstream>
#include <cstdlib>
using namespace std;

void KeyWord(ifstream &FileSearch)
{
    string line;
    string letters[5];
    ifstream readSearch;

    cout<< "Enter a barcode of a product: \n";
    cin >> letters[0];
    cin >> letters[1];
    cin >> letters[2];
    cin >> letters[3];
    cin >> letters[4];
    readSearch.open("Products.txt");
    if(readSearch.is_open())
    {
        while (getline(readSearch, line))
        {
            while (line.find(letters[0])!=string::npos || line.find(letters[1])!=string::npos || line.find(letters[2])!=string::npos || line.find(letters[3])!=string::npos || line.find(letters[4])!=string::npos)
            {
                cout << line << "\n";
                break;
            }
        }
    }
}

int main()
{
    ifstream file("Products.txt");
    KeyWord(file);
    return 0;
}

A: If each line contains a set of product names, barcodes and prices, get the line into an std::stringstream and move on from there.


text:
Q: How to determine public ip of client in HTTP and HTTPS request? I have read various blogs and done practically but couldn't get conclusive and full proof way to determine the get client public ip in all possible scenarios.
The configuration on server side is: | F5 <--> Apache web server <--> Tomcat |
In code i first fetch and parse the request header X-FORWARDED-FOR to get the left most public ip. If not found i rely on request.getRemoteAddr().
So question is:

*

*This works well in some cases but fails when protocol is HTTPS. What can be done in this case?

*If the X-Forwarded-For doesn't have any value then i have to rely on request.getRemoteAddr() which always give my server ip. This is because of apache web server which sits in between and getRemoteAddr returns the address of the client or last proxy that sent the request. How to overcome this scenario?

*Is there any other headers on which i should read values apart from X-forwarded-for?

*What all are the other possible cases which should be handled?

A: String forwardedHeader  = servletRequest.getHeader("X-Forwarded-For");
clientIP =  servletRequest.getRemoteAddr();

String forwarded = "";
if (forwardedHeader != null && !forwardedHeader.isEmpty())
{
    forwarded = forwardedHeader;

    int commaIdx = forwarded.indexOf(',');
    if (commaIdx > 0)
    {
        clientIP = forwarded.substring(0, commaIdx);
    }

    forwarded = forwarded.replace(',', '|');
}

if (forwarded != null && !forwarded.isEmpty())
{
    clientIP = forwarded;
}


text:
Q: How to flatten out nested array of strings in json column? I have the following table:

id
contents

123
{ blocks: [{ text: "abc" }, { text: "123" }] }

foo
{ blocks: [{ text: "bar" }, { text: "moretext" }, { text: "ok" }] }

I want to write a view of the above that looks like:

id
contents
raw_text

123
{blocks: [{text: "abc"}, {text: "123"}]}
abc, 123

foo
{blocks: [{text: "bar"}, {text: "moretext"}, { text: "ok"}]}
bar, moretext, ok

This was the query I tried running:
select post.id, array_to_string(array_agg(jsonb_array_elements(post.contents -> 'blocks') ->> 'text')) as paragraphs from post group by id

But it results in the error
aggregate function calls cannot contain set-returning function calls.

A: If a JSON array of all the values is also acceptable, you can use a JSON path query:
select id, contents,
       jsonb_path_query_array(contents, '$.blocks[*].text')
from post;

As there is no simply cast from a JSON array to a native Postgres array, and you do need that as a CSV string, you need to unnest and aggregate with a scalar sub-query:
select id, contents,
       (select string_agg(x.item ->> 'text', ', ')
        from jsonb_array_elements(contents -> 'blocks') as x(item)) as raw_text
from post;

The reason for your error is, that you are mixing nesting multiple aggregate and set returning function which simply isn't supported.


text:
Q: Checking result of an L1 -> L2 message/invoke in Starknet I've written a couple contracts for L1 (Ethereum) and L2 (Starknet) and have them communicate here.
I can see that L1 sent the message I'm expecting, see this TX on etherscan. The last message in there however never executed on my L2 contract. I'm trying to figure out whether the L2 Sequencer has invoked the handler function of my contract and if so, whether/how it failed.
Does anyone here know how to find the TX that handles the invoke on L2? Or any other ideas/tools that would help figuring out why the l1_handler never executed/failed?

A: First thing, transactions coming from L1 are regular transactions and therefore their hash can be computed the same way as invoke transactions. To have more information on this you can check the documentation here. Now this is helpful to understand the theory but not that much to actually compute the tx hash.
Here is the L1 event that send a message to StarkNet and this is where I get the needed information to compute the hash
Address 0xde29d060d45901fb19ed6c6e959eb22d8626708e
Name LogMessageToL2 (index_topic_1 address fromAddress, index_topic_2 uint256 toAddress, index_topic_3 uint256 selector, uint256[] payload, uint256 nonce)View Source

Topics
0 0x7d3450d4f5138e54dcb21a322312d50846ead7856426fb38778f8ef33aeccc01
1  0x779b989d7358acd6ce64237f16bbef09f35f6ecc
2  1524569076953457512425355396075576585145183562308719695739798372277154230742
3  1285101517810983806491589552491143496277809242732141897358598292095611420389
Data
payload :
1393428179030720295440092695193628168230707649901849797435563042612822742693
11819812303435348947619
0
nonce :
69106

Here is the script I use applied to your transaction (this may change in the future)
from starkware.cairo.lang.vm.crypto import pedersen_hash
from starkware.cairo.common.hash_state import compute_hash_on_elements
from starkware.crypto.signature.fast_pedersen_hash import pedersen_hash
from typing import List

def calculate_transaction_hash_common(
    tx_hash_prefix,
    version,
    contract_address,
    entry_point_selector,
    calldata,
    max_fee,
    chain_id,
    additional_data,
    hash_function=pedersen_hash,
) -> int:
    calldata_hash = compute_hash_on_elements(data=calldata, hash_func=hash_function)
    data_to_hash = [
        tx_hash_prefix,
        version,
        contract_address,
        entry_point_selector,
        calldata_hash,
        max_fee,
        chain_id,
        *additional_data,
    ]

    return compute_hash_on_elements(
        data=data_to_hash,
        hash_func=hash_function,
    )

def tx_hash_from_message(
    from_address: str, to_address: int, selector: int, nonce: int, payload: List[int]
) -> str:
    int_hash = calculate_transaction_hash_common(
        tx_hash_prefix=510926345461491391292786,    # int.from_bytes(b"l1_handler", "big")
        version=0,
        contract_address=to_address,
        entry_point_selector=selector,
        calldata=[int(from_address, 16), *payload],
        max_fee=0,
        chain_id=1536727068981429685321,  # StarknetChainId.TESTNET.value
        additional_data=[nonce],
    )
    return hex(int_hash)

print(
    tx_hash_from_message(
        from_address="0x779b989d7358acd6ce64237f16bbef09f35f6ecc",
        to_address=1524569076953457512425355396075576585145183562308719695739798372277154230742,
        selector=1285101517810983806491589552491143496277809242732141897358598292095611420389,
        nonce=69106,
        payload=[
            1393428179030720295440092695193628168230707649901849797435563042612822742693,
            11819812303435348947619,
            0,
        ],
    )
)

This outputs 0x4433250847579c56b12822a16205e12410f6ad35d8cfc2d6ab011a250eae77f that we can find here which was properly executed.


text:
Q: Accessing public methods in same class requires an Instance? I'm a newbie to C# so forgive this question but I'm confused: Why do I need an instance of class Program to access method Sandbox which is public and in the same class?
namespace GoogleTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Program p = new Program();
            p.Sandbox();
        }

        public void Sandbox()
        {
            ...
        }
    }
}

A: public void Sandbox()
{
   ...
}

is the important part: This method is not marked static, so it is not callable on the class, but on instances of the class. If you want to be able to call it directly, you need
public static void Sandbox()
{
   ...
}

and can't use this.

A: Because you're trying to access it from within a static method, but Sandbox is an instance method.
If you make Sandbox static, this won't be required:
static void Main(string[] args)
{
    Sandbox();
}

public static void Sandbox()
{
        ...
}

Note that it also doesn't have to be public - public allows it to be used by other classes and within other assemblies, but within Program, that's not required.

A: Static methods exist at the Class level, you can consider them Global functions.  Any non static methods are instance level and just as the name implies you can only execute instance methods on an instance.  So by instantiating the class you have created an instance and now can call any public method.  In your example you could also call any private methods or constructors because you are creating the instance from with the class you are creating.


text:
Q: How To Get Row Entries with Max Column in SQL, Please Help! :p I am a bit stuck on how to get all the rows I want from the max count of one column, grouping by only some specific columns. For example, over here I want to group by user and name so that they are always distinct. But for country and device type I only want the combination of their max event_ct to show up

user
name
country
device
event_ct

5
Albert
US
Mac
5

5
Albert
GB
Phone
7

5
Albert
CN
Mac
3

6
Albert
CN
Mac
1

7
Laurel
US
Phone
7

I want a mysql query to turn it into

user
name
country
device

5
Albert
GB
Phone

6
Albert
CN
Mac

7
Laurel
US
Phone

Please help! Thanks :-)

A: Although I still think this is a duplicate question but for the good measure.
you can use subquery in where clause:
select user,name,country,device from cte
where event_ct in (select max(event_ct) from cte group by user,name)

here is db<>fiddle for better examine.

group by and distinct are fundamental same in some way, because you are telling SQL that you want UNIQUE row. group by a,b will give you distinct combination of a and b since it "GROUP" all the same (a,b) combination together.

re-edit
in some case if you got more then one row with max event_ct
for example user 5 got two row with event_ct = 7
you can add distinct to get rid of duplicate.


text:
Q: Index out of bounds error using Regex Split Posting another question here since last time I did the people who answered were extremely helpful. Bear in mind, I'm relatively new to VB.net.
So I'm working on a program that pulls the first and third columns out of a text file using Regex.Split to eliminate the multiple spaces between the alphanumeric characters in the file.
A high level example of what the text file looks like is here:
VARIABLE1                MEAS1           STORAGE1
VARIABLE2                MEAS2           STORAGE2
VARIABLE3                MEAS3           STORAGE3
VARIABLE4                MEAS4           STORAGE4
VARIABLE5                MEAS5           STORAGE5
VARIABLE6                MEAS6           STORAGE6

#VARIABLE7         MEAS7           STORAGE7
VARIABLE8              MEAS8           STORAGE8
VARIABLE9            MEAS9           STORAGE9
VARIABLE10            MEAS10           STORAGE10
VARIABLE11            MEAS11           STORAGE11
VARIABLE12            MEAS12           STORAGE12
VARIABLE13            MEAS13           STORAGE13
VARIABLE14            MEAS14           STORAGE14

The file uses the "#" to denote comments in the file, so in my code I tell the System.IO to ignore that character.
However, when creating a test function to try this, I continuously get an Index out of bounds error, (only on some files. Some in this format work fine, for some reason)
When looking through the execution output, I am receiving the error after it writes the "STORAGE6" line, so there has to be an error traversing from STORAGE6 to VARIABLE7, and I can't quite figure it out.  Any insight on this would be extremely appreciated!
The test function I have written is below:
    Public Function Testing()
        OpenFileDialog1.ShowDialog()
        Dim file = System.IO.File.ReadAllLines(OpenFileDialog1.FileName)
        For Each line In file
            Dim arrWords() As String = System.Text.RegularExpressions.Regex.Split(line, "\s+")
            Dim upBound = arrWords.GetUpperBound(0)
            If upBound <> 0 Then

                If line.Contains("#") Or line.Length = 0 Then

                Else
                    Console.WriteLine(arrWords(0) + " " + arrWords(2))

                End If

            End If
        Next
    End Function

I get the out of bounds error when calling "arrWords(2)," which I'm sure was pretty obvious, but just trying to make the question as detailed as possible.

A: The simple fix is changing these two lines:
If upBound <> 0 Then
    If line.Contains("#") Or line.Length = 0 Then

like this:
If upBound > 0 Then
    If line.TrimStart().StartsWith("#") OrElse String.IsNullOrWhitespace(line) Then

But I'd really do something more like this:
Public Class DataItem
    Public Property Variable As String
    Public Property Measure As String
    Public Property Storage As String
End Class

Public Function ReadDataFile(fileName As String) As IEnumerable(Of DataItem)
     Return File.ReadLines(fileName).
               Where(Function(line) Not line.TrimStart().StartsWith("#") AndAlso Not String.IsNullorWhitespace(line)).
               Select(Function(line) System.Text.RegularExpressions.Regex.Split(line, "\s+")).
               Where(Function(fields) fields.Length = 3).
               Select(Function(fields)
                    Return New DataItem With {
                     .Variable = fields(0),
                     .Measure = fields(1),
                     .Storage = fields(2)}
               End Function)
End Function

Public Function Testing()
    If OpenFileDialog1.ShowDialog() = DialogResult.OK Then
        Dim records = ReadDataFile(OpenFileDialog1.FileName)
        For Each record in records
            Console.WriteLine($"{record.Variable} {record.Storage}")
        Next
    End If
End Function


text:
Q: .bashrc alias help about terminal error i have alias on .bashrc file like;
alias modemreboot="IP=$(/sbin/ip route | awk '/default/ { print $3 }');echo "reboot" | sshpass -p "12345" ssh admin@$IP"

for to reboot my modem via command line. When i type or copy&paste to terminal it works, but as alias i get this error;
Pseudo-terminal will not be allocated because stdin is not a terminal.
ssh: Could not resolve hostname : Name or service not known

A: Your quoting is messed up - as you can see by running the assignment with set -x:
$ alias modemreboot="IP=$(/sbin/ip route | awk '/default/ { print $3 }');echo "reboot" | sshpass -p "12345" ssh admin@$IP"
++ /sbin/ip route
++ awk '/default/ { print $3 }'
+ alias 'modemreboot=IP=via;echo reboot | sshpass -p 12345 ssh admin@via'

Try instead
alias modemreboot='IP=$(/sbin/ip route | awk "/default/ { print \$3 }");echo "reboot" | sshpass -p "12345" ssh admin@$IP'

(although - unless your /sbin/ip is different from mine - I think you likely want \$4 rather than \$3).
You may want to consider using a shell function instead, like
modemreboot () {
  local IP;
  IP=$(/sbin/ip route | awk '/default/ { print $3 }')
  echo "reboot" | sshpass -p "12345" ssh admin@$IP
}

See

*

*In Bash, when to alias, when to script, and when to write a function?


text:
Q: Weak convergence in probability implies uniform convergence in distribution functions
Exercise 1: Let $\mu_n$, $\mu$ be probability measures on $\left(\mathbb{R}, \mathcal{B}\left(\mathbb{R}\right)\right)$ with distribution functions $F_n$, $F$. Show: If $\left(\mu_n\right)$ converges weakly to $\mu$ and $F$ is continuous, then $\left(F_n\right)$ converges uniformly on $\mathbb{R}$ to $F$.

This is a problem that I am totally stuck at. I know the fact that $F_n$ converges pointwise to $F$ in this question. Also, I looked through Google and found out that I have to show first that $F_{n}(t_{n})$ converges to $F(t)$ if $t_{n}$ converges to $t$. But, no matter how I tried, I keep failing to prove the fact.
Also, I have no idea how to use the fact to get the uniform convergence. So I'm just stymied.
Could anyone please help me with this?
Add : I managed to show that $F_n$ converges uniformly to $F$ on any compact intervals. However, the generalization to the whole real line is still not solved...Could anyone at least help me with the generalization to the real line?

A: Here's another proof for the compact case which I find a bit more intuitive. We are trying to show that $F_n \rightarrow F$ uniformly on an arbitrary closed interval $[a,b]$.
Fix $\epsilon > 0$. Let $d = F(b)-F(a)$, and take $k$ large enough so that $\frac{d}{k} \leq \frac{\epsilon}{5}$. By the continuity of $F$, we can apply the intermediate value theorem to show there exist real numbers $a := x_0 < x_1 < ... < x_k := b$ such that $F(x_i) = F(a) + i\frac{d}{k}$ for each $i \in \{0,1,...,k\}$.
Since $F_n \rightarrow F$ pointwise, for each $i$ in $\{0,1,...,k\}$ there exists $N_i$ such that $|F_n(x_i)-F(x_i)| \leq \frac{\epsilon}{5}$ for all $n \geq N_i$. Taking $N = \max(N_0,N_1,...,N_k)$, we conclude that $|F_n(x_i)-F(x_i)| \leq \frac{\epsilon}{5}$ for all $n \geq N$, $i \in \{0,1,...,k\}$. This gives
$F_n(x_{i+1})-F_n(x_i) \leq |F_n(x_{i+1})-F(x_{i+1})| + |F(x_{i+1})-F(x_i)| + |F(x_i)-F_n(x_i)| \leq \frac{\epsilon}{5} + \frac{d}{k} + \frac{\epsilon}{5} \leq \frac{3\epsilon}{5}$
For any $x \in [a,b)$, we have $x_i \leq x < x_{i+1}$ for some $i \in \{0,1,...,k\}$. Then for all $n \geq N$, we have
$$
\begin{align}
|F_n(x)-F(x)| & \leq |F_n(x)-F_n(x_i)| + |F_n(x_i) - F(x_i)| + |F(x_i)-F(x)| \\\\
& \leq |F_n(x_{i+1})-F_n(x_i)| + |F_n(x_i)-F(x_i)| + |F(x_{i+1})-F(x)| \\\\
& \leq \frac{3\epsilon}{5} + \frac{\epsilon}{5} + \frac{d}{k} \\\\
& \leq \epsilon \\\\
\end{align}
$$
where the second inequality uses monotonicity of $F$ and $F_n$.
Of course, $|F_n(b)-F(b)| \leq \frac{\epsilon}{5} \leq \epsilon$ since $b = x_k$.
Thus, we've shown $|F_n(x)-F(x)| \leq \frac{5\epsilon}{3}$ for all $x \in [a,b]$, concluding the proof.

A: Fix $\epsilon>0$. Since $F$ is a distribution function, there exists $R >0$ such that $F(r) \leq \epsilon$ for all $r \leq -R$ and $F(r) \geq 1-\epsilon$ for all $r \geq R$. As $F_n \to F$ pointwise, we can choose $N \in \mathbb{N}$ such that
$$|F_n(-R) - F(-R)| \leq \epsilon \qquad \text{and} \qquad |F_n(R)-F(R)| \leq \epsilon$$
for all $n \geq N$. Hence, by the monotonicity of $F_n$ and $F$,
$$\begin{align*} |F_n(r)-F(r)| \leq |F_n(r)|+|F(r)| &\leq F_n(-R)+F(-R) \\ &= (F_n(-R)-F(-R)) + 2 F(-R) \\ &\leq 3\epsilon \tag{1} \end{align*}$$
for all $r \leq -R$. Similarly, it follows from
$$1 \geq F_n(r) \geq F_n(R) = (F_n(R)-F(R))+F(R) \geq 1-2\epsilon, \qquad r \geq R,$$
that
$$|F_n(r)-F(r)| \leq |F_n(r)-(1-\epsilon))|+ |F(r)-(1-\epsilon)| \leq 2 \epsilon \tag{2}$$
for all $r \geq R$. Combining $(1)$ and $(2)$ yields
$$\sup_{r \in [-R,R]^c} |F_n(r)-F(r)|  \leq 3 \epsilon$$
for all $n \geq N$. Since you have already shown that $F_n$ converges to $F$ uniformly on compact intervals, there exists $N' \in \mathbb{N}$ such that
$$\sup_{r \in [-R,R]} |F_n(r)-F(r)| \leq \epsilon$$
for all $n \geq N'$. Setting $\tilde{N} := \max\{N,N'\}$, we get
$$\sup_{r \in \mathbb{R}} |F_n(r)-F(r)| \leq 3 \epsilon \qquad \text{for all $n \geq N$}.$$


text:
Q: Add mean of column A for each value of column B Suppose you have the following pandas data frame (df):
       A    B   C
0      2    1   4
1      3    4   5
2      3    1   1
3      1    4   0
4      5    0   1

And you want to add a column containing the mean (or any other aggregate function) of column A for each distinct value of column B. You want to keep all columns. So the result would look like this (df_result):
       A    B   C   meanA_givenB
0      2    1   4        (2+3)/2
1      3    4   5        (3+1)/2
2      3    1   1        (2+3)/2
3      1    4   0        (3+1)/2
4      5    0   1          5  /1

The way I do that is the following:
import pandas as pd

meanA_givenB = df.groupby('B').A.mean()
df_result = pd.merge(df, pd.DataFrame(meanA_givenB),
                     how='left', left_on='A', right_index=True,
                     suffixes=['','_meanA_givenB'])

There must be a cleaner and more efficient way to do it.

A: You may use transform:
>>> df['avg(A)|B'] = df.groupby('B')['A'].transform('mean')
>>> df
   A  B  C  avg(A)|B
0  2  1  4       2.5
1  3  4  5       2.0
2  3  1  1       2.5
3  1  4  0       2.0
4  5  0  1       5.0


text:
Q: Elasticsearch DateTime Range Query Using Elasticsearch 5.1 and I am trying to query a date time mapping that looks like this
"startTime": {
        "properties": {
          "date": {
            "properties": {
              "day": {
                "type": "long"
              },
              "month": {
                "type": "long"
              },
              "year": {
                "type": "long"
              }
            }
          },
          "time": {
            "properties": {
              "hour": {
                "type": "long"
              },
              "minute": {
                "type": "long"
              },
              "nano": {
                "type": "long"
              },
              "second": {
                "type": "long"
              }
            }
          }
        }
      }

Tried doing this query:
{
  "query": {
     "range": {
      "startTime.date": {
        "lte": "2017-05-08",
        "gte": "2017-06-05"
      }
    }
  }
}

also tried
{
  "query": {
    "range": {
      "startTime": {
        "lte": "now+2w/w",
        "gte": "now-2w/w",
        "format": "yyyy-MM-dd'T'HH:mm:ss.SSSZZ"
      }
    }
  }
}

and
{
  "query": {
    "range": {
      "startTime": {
        "lte": "now+2w/w",
        "gte": "now-2w/w"
      }
    }
  }
}

Does anyone know how I would query for a time range 2 weeks in the past and 2 weeks in the future?  All the variations I have tried are not yielding results even though I know there should be some results.


text:
Q: Is it Legal to reinterpret_cast to a void* I was looking at https://en.cppreference.com/w/cpp/language/reinterpret_cast and I noticed that it specifies the legal types we can always cast to:

*

*byte*

*char*

*unsigned char*
But I did not see void* in the list. Is this an oversight? My use case requires a reinterpret_cast because I'm casting from an int** to a void*. And I will eventually cast from the void* back to an int**.

A: Those types are exempt from strict aliasing rules. It does not mean they are the only type you can use with reinterpret_cast. In the case of casting an object pointer to another object pointer type, failing to meet the requirements of strict aliasing rules means you cannot safely dereference the result. But you can still cast the resulting pointer back to the original type safely, and use the result as-if it was the original pointer.
The relevant section from cppreference on reinterpret_cast :

(Any object pointer type T1* can be converted to another object pointer type cv T2*. This is exactly equivalent to static_cast<cv T2*>(static_cast<cv void*>(expression)) (which implies that if T2's alignment requirement is not stricter than T1's, the value of the pointer does not change and conversion of the resulting pointer back to its original type yields the original value). In any case, the resulting pointer may only be dereferenced safely if allowed by the type aliasing rules)

When casting back to the original type, AliasedType and DynamicType are the same, so they are similar, which is the first case listed by the aliasing rules where it is legal to dereference the result of reinterpret_cast :

Whenever an attempt is made to read or modify the stored value of an object of type DynamicType through a glvalue of type AliasedType, the behavior is undefined unless one of the following is true:

*

*AliasedType and DynamicType are similar.

*AliasedType is the (possibly cv-qualified) signed or unsigned variant of DynamicType.

*AliasedType is std::byte, (since C++17)char, or unsigned char: this permits examination of the object representation of any object as an array of bytes.

A: [expr.reinterpret.cast]/7:

An object pointer can be explicitly converted to an object pointer of a different type.

[basic.compound]/3:

The type of a pointer to cv void or a pointer to an object type is called an object pointer type.

You don't need to use reinterpret_cast, though. Every object pointer type whose pointed type is cv-unqualified is implicitly convertible to void*, and the inverse can be done by static_cast.

A: It is always legal to convert from a pointer to a type to a pointer to a different type including void, so if T is a type this is legal C++:
T* x;
void *y = reinterpret_cast<void *>(x);

In real world it is never used because void * is a special case, and you obtain the same value with static_cast:
void *y = static_cast<void *>(x); // equivalent to previous reinterpret_cast

(in fact above conversion is implicit and can be simply written void *y = x; - thank to Michael Kenzel for noticing it)
To be more explicit the standard even says in draft n4659 for C++17 8.2.10 Reinterpret cast [expr.reinterpret.cast], §7

When a prvalue v of
  object pointer type is converted to the object pointer type "pointer to cv T", the result is static_cast<cv T*>(static_cast<cv void*>(v)).

When you refer to byte and char being the only legal types, it is just that it is legal to dereference the converted pointer only for those types. void is not included here because you can never dereference a void *.

To specifically answer your question

.. I'm casting from an int** to a void*. And I will eventually cast from the void* back to an int**.

The standard guarantees that first one is a standard (read implicit) conversion:

A prvalue of type "pointer to cv T", where T is an object type, can be converted to a prvalue of type "pointer
  to cv void". The pointer value (6.9.2) is unchanged by this conversion.

So this is always legal:
int **i = ...;
void *v = i;

For back casting, standard says (in static_cast paragraph):

A prvalue of type "pointer to cv1 void" can be converted to a prvalue of type "pointer to cv2 T",

So this is also legal
int **j = static_cast<int **>(v);

and the standard ensures that j == i.


text:
Q: UISegmentedControl with views animation code review please I am just trying things out in Swift, and just made my first animation using UISegmentedControl, that switch between view, can you help me with a little code review to know that I am on the right track?
import UIKit;

class ViewLikes:UIViewController {

var innerViews:[UIViewController] = [UIViewController]()
var currentIndex:Int = 0;
var centerView:UIViewController = UIViewController()

override func viewDidLoad()  {
    super.viewDidLoad()
    title = "some title";

    var view1:UIViewController = UIViewController()
    var lab1:UILabel = UILabel(frame: CGRectMake(0, 10, 200, 21))
    lab1.center = CGPointMake(160, 284)
    lab1.textAlignment = NSTextAlignment.Center
    lab1.text = "I'am a label1"
    view1.view.addSubview(lab1)

    var view2:UIViewController = UIViewController()
    var lab2:UILabel = UILabel(frame: CGRectMake(0, 10, 200, 21))
    lab2.center = CGPointMake(160, 284)
    lab2.textAlignment = NSTextAlignment.Center
    lab2.text = "I'am a label2"
    view2.view.addSubview(lab2)

    var view3:UIViewController = UIViewController()
    var lab3:UILabel = UILabel(frame: CGRectMake(0, 10, 200, 21))
    lab3.center = CGPointMake(160, 284)
    lab3.textAlignment = NSTextAlignment.Center
    lab3.text = "I'am a label3"
    view3.view.addSubview(lab3)

    innerViews.append(view1)
    innerViews.append(view2)
    innerViews.append(view3)

    var segmentControl:UISegmentedControl = UISegmentedControl(items:["blah", "blah1", "blah2"]);
    segmentControl.selectedSegmentIndex = currentIndex;
    segmentControl.addTarget(self, action:"segmentSwitch:" , forControlEvents:UIControlEvents.ValueChanged  )

    segmentControl.setTranslatesAutoresizingMaskIntoConstraints(false)
    self.centerView.view.setTranslatesAutoresizingMaskIntoConstraints(false)

    self.view.addSubview(segmentControl)
    self.view.addSubview(self.centerView.view)

    var currentView = self.innerViews[0]
    currentView.viewWillAppear(false)
    self.centerView.view.addSubview(currentView.view)
    currentView.viewDidAppear(false)

    //Set layout
    var viewsDict = Dictionary <String, UIView>()
    viewsDict["segment"] = segmentControl;
    viewsDict["center"] = self.centerView.view;

    self.view.addConstraint(NSLayoutConstraint(item: segmentControl,
                                attribute: NSLayoutAttribute.Top,
                                relatedBy: NSLayoutRelation.Equal,
                                toItem: self.topLayoutGuide,
                                attribute: NSLayoutAttribute.Bottom,
                                multiplier: 1, constant: 10))

    self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[segment]-|",
                                options: NSLayoutFormatOptions(0),
                                metrics: nil,
                                views: viewsDict))

    self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[center]-0-|",
        options: NSLayoutFormatOptions(0),
        metrics: nil,
        views: viewsDict))

    self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[segment]-[center]-0-|",
        options: NSLayoutFormatOptions(0),
        metrics: nil,
        views: viewsDict))

}

func segmentSwitch(control:UISegmentedControl) {
    selectView(control.selectedSegmentIndex)
}

func selectView(index:Int) {
    var currentView = self.innerViews[self.currentIndex]

    var nextView = self.innerViews[index]
    nextView.viewWillAppear(false)
    self.centerView.view.addSubview(nextView.view)
    nextView.viewDidAppear(false)

    if(index > currentIndex) {
        nextView.view.frame.origin.x = nextView.view.frame.width;
    } else {
        nextView.view.frame.origin.x -= nextView.view.frame.width;
    }

    UIView.animateWithDuration(0.8,
        animations: {
            var currentFrame = currentView.view.frame;
            var nextFrame = nextView.view.frame;

            if(index > self.currentIndex) {
                currentFrame.origin.x -= currentFrame.size.width;
            } else {
                currentFrame.origin.x = currentFrame.size.width;
            }
            nextFrame.origin.x = 0.0;

            currentView.view.frame = currentFrame
            nextView.view.frame = nextFrame
        }, completion: {finished in
            currentView.viewWillDisappear(false)
            currentView.view.removeFromSuperview()
            currentView.viewDidDisappear(false)
        }
    );

    self.currentIndex = index

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
    for innerView in self.innerViews {
        innerView.didReceiveMemoryWarning();
    }
}
}


text:
Q: ValueError: Error when checking target: expected dense_2 to have shape (2,) but got array with shape (75,) model = Sequential()
model.add(TimeDistributed(Conv2D(64, (3, 3), activation='relu'),input_shape=(10, 255, 255,1)))
model.add(TimeDistributed(Conv2D(64, (3, 3), activation='relu')))
model.add(TimeDistributed(Flatten()))
model.add(LSTM(10, activation='relu', return_sequences=False))
model.add(Dense(1024, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(2, activation='sigmoid'))
model.compile('adam', loss='categorical_crossentropy')

model.fit(train_dataset_new, train_labels,
                                    epochs=25,
                                    batch_size=10,
                                   validation_data=(validation_dataset_new,validation_labels))

Hello,
I'm struggling on the subject at hand.
I will start with my goal:
I would like to train the following model with a sequence of images (video) - 10 to be precise.
My logic:
In order to do so, I have created a video Database and extracted 10 frames from each video into an np.array object. Each frame has the size of (255,255) and on grayscale.
Summing up: The input shape to (255,255,1).
I am certain I'm missing something about the TimeDistrebution layer\ LSTM layer and I couldn't find solution on any sources I have looked for (and I have tried)
I have debugged the code and verified the following:
train_dataset_new = (75,10,255,255,1)  # (75 is the amount of train videos I have )
validation_dataset_new = (19,10,255,255,1)  # (19 is the amount of train videos I have )
My understanding on the problem:
As noted in the headline, my Dense layer is expecting an input of size but I feed into my network my entire sample domain (75) and I cannot find out if I'm fitting wrongly or my model Architecture is wrong (I would like to note that this is a basic Architecture I found online and using it just to explore this subject)
Would be glad for any help \ direction to a reading on the matter.
If any more data is required due tell as Im new to this forum.
Cheers!

A: Take a look at the shape of your target labels. When running your code with (randomly generated) training data of shape (75,10,255,255,1) and target labels of shape (75,2), it seemed to work for me, using TF2.2 and Keras 2.4.3. The error might just being saying the network's output and target label shapes are not matching, though I must say it is not a very clear error message if so.


text:
Q: How to update NestJS Swagger module but use OpenAPI 2.0(Swagger)? We are making an API in Node.js/Typescript with NestJS framework. We use @nestjs/swagger package to make it conform to OpenAPI(formerly known as Swagger). It is inteneded to be used with Azure/autorest to generate client code.
Autorest supports OpenAPI 2.0 and not 3.0 yet. @nestjs/swagger 3.*.* implemented OpenAPI 2.0. When we update @nestjs/swagger to 4.*.* it turns into OpenAPI 3.0. This doesn't fit our needs because we can't use Autorest anymore. On the other hand not updating the package means we might miss out security updates or not even be able to update the entire NestJS framework.
Is there any way to update @nestjs/swagger and stay with OpenAPI 2.0?

A: Unfortunately no. Internally, @nestjs/swagger v4 is specifically generating OpenAPI 3.0 specification specifically. There are two options right now while you wait for autorest 3 to be released officially.

*

*Stay on @nestjs/swagger v3. As for update the entire NestJS
framework, you don't have to worry about this because
@nestjs/swagger is a pretty much stand alone package. Security
issue regarding dependencies, I can see your concern is valid there.

*Try autorest 3.beta out to see if it's stable enough for you to
use.


text:
Q: Copy GIF to UIPasteboard I'm trying to copy a GIF image to the UIPasteboard in swift, at the moment it only copies the static version of the image and seems to convert it to PNG looking at the file extension when I upload it somewhere.
Wondered if anyone had any idea how to achieve this? All other soltions I've found only seem to work when getting NSData from a URL rather than from an image in the bundle

A: For anyone who ever encounters this problem I managed to find a solution
let url: NSURL = NSBundle.mainBundle().URLForResource("\(self.imageNames[indexPath.row])", withExtension: ".gif")!
let data: NSData = NSData(contentsOfURL: url)!
UIPasteboard.generalPasteboard().setData(data, forPasteboardType: "com.compuserve.gif")

As it turns out you do need to use a URL and extract the NSData of the GIF from that URL.
Here I am getting the URL of the GIF that is in my bundle, searching for it using the name and extension of the image. I am then setting the data in the pasteboard and bingo we have an animated GIF when pasting the result from the pasteboard

A: It doesn't look like the image property on the pasteboard supports the GIF type.

The associated array of representation types is UIPasteboardTypeListImage, which includes types kUTTypePNG and kUTTypeJPEG.

You could probably do this using the NSData from the GIF though:
import MobileCoreServices

// ...

var image = UIImage(...)
let data = NSData(bytes: &image, length: sizeof(UIImage))
UIPasteboard.generalPasteboard().setData(data, forPasteboardType: kUTTypeGIF as String)) // com.compuserve.gif


text:
Q: Equivalence between small distance and high energy I see in a lot of particle physics literature statements along the lines of: 'This is valid for high energies (small distances)'. Exactly what do we mean by small distances in this case? From QFT, QM and other physics courses, the connection between small distance and high energy makes intuitive sense, but I am wondering if there is a concrete connection that authors have in mind?

A: In HEP, where (in units of c=1) momenta are much larger than masses, so they are tantamount to energies, the fundamental scale relation of QM, $[x,p]=i\hbar$, comes to bear. The de Broglie relation ${\lambda\over 2\pi}= \hbar/p$ of the particles/waves involved relates distances to momenta/energies inversely.
Consequently, "small distance" is a synonym for "high energy" or momentum. So, analogously to diffractive crystallography, one probes ever smaller distance scales with ever higher enery/momentum scattering probes.
In HEP natural units, (ℏ=1) this is codified by the duality of the units for distance or energy,
such as the  radius of a proton being 4 GeV$^{-1}$ actually meaning
$$
4 \mathrm {GeV}^{-1} (\hbar c) = 8\cdot 10^{-16}{\mathrm m}~.
$$

A: Connections between energy and distance tend to involve the factor
$$
\hbar c= \rm 197\ eV\ nm=197\ MeV\ fm
$$
and some additional factors from doing algebra. The algebraic factors tend to be values like $\frac13$ or $\sqrt 6$, but it is unusual to do a page of first-principles algebra and come up a purely numerical factor of a thousand.
The most common example is a Yukawa-type force mediated by a massive particle, which has potential energy
$$
V=\alpha\hbar c\frac{e^{-r/r_0}}{r},
\qquad\text{where }r_0=\frac{\hbar c}{m c^2}
$$
Electromagnetism, where the photon is massless, is a Yukawa interaction in the limit $r_0\to\infty$, with $\alpha_\text{e.m.}≈10^{-2}$ the fine structure constant. In a meson-mediated model of nucleon-nucleon interactions, the longest-range component comes from the pion, whose mass $mc^2=140\rm\ MeV$ corresponds to a distance $r_0=1.4\ \rm fm$. For nucleons many femtometers apart, the pion-mediated attraction is exponentially suppressed. At shorter distances, you have to include heavier mesons in your calculations. At very high energies, you even have "forces" which mediated by the giga-eV weak bosons.


text:
Q: Connecting two different op-amp circuits I have designed a circuit using an OP amp, 9V battery, and resistors to power up an LED when a thermistors resistance is lowered. (Pictured left on the image).
I am also interested in using another op-amp in the same design that will oscillate a different load. The image attached shows my progress, but I am unable to get the output of the 2nd op-amp to oscillate. My main question is how to connect my first circuit (that turns an LED on when the thermistor detects heat), to the second part that will oscillate the load using another op-amp and capacitor.
The resistor that is 69k in this image is my actual NTC thermistor, so when it is idle (no heat), the first LED is off.

This image shows the 2nd op-amp working. (V-out of the op-amp has an oscillating square wave)

A: The second op-amp is not working because you have no bias resistor on the (+) input, so it 'locks' up.
Add a 1N4148 or 1N4007 diode from the output of the first op-amp through a 10K resistor, to the (+) input of the second op-amp, so when the LED is ON, the second op-amp should start working. The band on the diode should point to the second op-amp.
The diode is to prevent the second op-amp from running constantly, unless that is what you want.
Also, the LED on the second op-amp has no path to ground through a resistor, like your first op-amp does. 500 ohms is ok. You can increase your bias resistors on the first op-amp by a factor of ten, to extend battery life.

A:
I have solved the problem and made the circuit work. I did this by connecting the Vout of the first 4556AD op-amp to the Vs+ on the RC oscillator op-amp that has a frequency of 47 Hz. \begin{equation}
Frequency = \frac{1}{2\pi RC}
\end{equation}
When the 100k NTC thermistor gets heat applied, the Vout goes up to 9V from -9V, we have the LED turning on with somewhere around ~14mA, and the Vout is also connected to Vs+ on the RC op-amp, which begins the capacitors discharging/charging, and therefore the frequency occurs at the speaker.


text:
Q: What's the limit on the no. of partitions I can have? I would like to know how many Primary and Extended Partitions I can create on a x86_64 PC with Linux running on it?

Update  :
If there is a limit to the number of partitions, why is that the limit?

A: Sen, in response to @jlliagre, it should be noted that some operating systems will create a single partition, but essentially create sub-partitions within that space.
It is analogous, but not equal, to doing:
 parted rm 1 /dev/sda
 ...
 parted rm 7 /dev/sda
 parted mkpart primary $start $end /dev/sda
 parted mkpart primary $start1 $end1 /dev/sda1

You could then use kpartx to access these sub-partitions:
 kpartx -a /dev/sda1

The sub-partition(s) would appear as:
 /dev/sda1p1

Of course, this isn't how FreeBSD and similar systems do their slicing, exactly, but it is essentially the same thing.

A: Partitions are totally depended upon Disk type format.
If we use MBR Disk type in Linux then we can create 4 total partitions like:

*

*All four partitions are Primary only.

*Three partitions are primary and remaining 1 is extended.

If we consider above 2 steps then under Extended partition we can create almost 65536 new logical partitions and use them but this logical partitions we can use have some limit and it depends upon OS to OS.
How many partitions we can create under Extended partitions?
Answer: Suppose you created the last partition in MBR as an extended partition and under it, we create a 1GB partition as a logical partition.
Their structure as follows:
[root@localhost ~]# fdisk -l /dev/sdb

Disk /dev/sdb: 21.5 GB, 21474836480 bytes, 41943040 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk label type: dos
Disk identifier: 0x4bc89c19

   Device Boot      Start         End      Blocks   Id  System
/dev/sdb1            2048     2099199     1048576   83  Linux
/dev/sdb2         2099200     2293759       97280   83  Linux
/dev/sdb3         2293760     2488319       97280   83  Linux
/dev/sdb4         2488320    41943039    19727360    5  Extended < br/>

[root@localhost ~]# fdisk  /dev/sdb
Welcome to fdisk (util-linux 2.23.2).

Changes will remain in memory only until you decide to write them.

Be careful before using the write command.

Command (m for help): n
All primary partitions are in use
Adding logical partition 5
First sector (2490368-41943039, default 2490368):
Using default value 2490368
Last sector, +sectors or +size{K,M,G} (2490368-41943039, default 41943039): +1G
Partition 5 of type Linux and of size 1 GiB is set

Command (m for help): p

Disk /dev/sdb: 21.5 GB, 21474836480 bytes, 41943040 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk label type: dos
Disk identifier: 0x4bc89c19

Device Boot      Start         End      Blocks   Id  System
/dev/sdb1            2048     2099199     1048576   83  Linux
/dev/sdb2         2099200     2293759       97280   83  Linux  <
/dev/sdb3         2293760     2488319       97280   83  Linux
/dev/sdb4         2488320    41943039    19727360    5  Extended
/dev/sdb5         2490368     4587519     1048576   83  Linux

Now, After create a 1GB logical partition above we can calculate the total number of logical partition under the extended partition.We know MBR supports 1 Sector space =512 bytes
Difference between /dev/sdb5 and /dev/sdb4 Starting Sector Values has follows 2490368-2488320=2048. 2048 is the difference value which is a Reserved Space in Extended Partition to store the information of logical partitions under it. If we multiply 2048 with 512 bytes then total bytes present in Extended partitions to support Logical partitions i.e. 2048*512=1048576 bytes
In MBR, the total size of 64 bytes is used to store the partition information in the partition table. It means partition table stores each partition information in it which has each partition size of 16 bytes. Each partition can use the 16 bytes of space, so according to it, the total of 4 partitions are provided in MBR including extended. If we see the last partition size which is extended partition then they use 16 bytes of space.
It means if we divide the 1048576 bytes to 16 we get a total number of logical partition under extended partition i.e. 1048576/16=65536(Maximum Logical Partition).
We can use maximum 65536 total logical partitions under it. But the use of this partition depends upon OS to OS. In Linux, MBR uses maximum 60 logical partitions under the extended partition.

So total number of partitions we can create under MBR is 3(primary),1(Extended),60(Logical)=64
But only primary and logical partitions are used to feed the Linux data not extended partitions so it means only 63 partitions are useful to feed the data into the partitions.

How we can say only 60 maximum partitions are created under MBR and not more than that?
Just create the logical partitions as much as you can and when you create your 60th logical partition, the system shows this message
Command (m for help): n
All primary partitions are in use
Adding logical partition 60
First sector (23013477-41943039, default 23031808):
Using default value 23031808
Last sector, +sectors or +size{K,M,G} (23031808-24035327, default 24035327): +100

Partition 60 of type Linux and of size 50.5 KiB is set

Command (m for help): n
The maximum number of partitions has been created

A: The limitation is due to the original BIOS design. At that time, people weren't thinking more than four different OSes would be installed on a single disk. There was also a misunderstanding of the standard by OS implementors, notably Microsoft and Linux which erroneously map file systems with (primary) partitions instead of subdividing their own partition in slices like BSD and Solaris which was the original intended goal.
The maximum number of logical partitions is unlimited by the standard but the number of reachable ones depends on the OS. Windows is limited by the number of letters in the alphabet, Linux used to have 63 slots with the IDE driver (hda1 to hda63) but modern releases standardize on the sd drivers which supports by default 15 slots (sda1 to sda15). By some tuning, this limit can be overcome but might confuse tools (see  http://www.justlinux.com/forum/showthread.php?t=152404 )
In any case, this is becoming history with EFI/GPT. Recent Linuxes support GPT with which you can have 128 partitions by default. To fully use large disks (2TB and more) you'll need GPT anyway.

A: 4 primary partitions or alternatively 3 primary partitions and an extended partition.
The extended partition can be subdivided into multiple logical partitions.

A: In a hard disk we can create 4 primary partitions or alternatively 3 primary partitions and an extended partition.
The primary+extended partition can be divided into 63 logical partitions


text:
Q: how to customize iveiw tabpane's width in vue language? In official statements, the tab component of view in vue is like that:

its code is :
<template>
    <Tabs type="card">
        <TabPane label="标签一">标签一的内容</TabPane>
        <TabPane label="标签二">标签二的内容</TabPane>
        <TabPane label="标签三">标签三的内容</TabPane>
    </Tabs>
</template>

But i want to make the tabpane label wider like this:

how can i customize its width???

A: see other styles on official web:
去看看官方文档:
https://www.iviewui.com/components/tabs#其它样式


text:
Q: Function Definition and Call in Python When you call a function you must define it first, otherwise you will get an error
message. But when you call a functions by another function it's okay to define a fuction after that, for example:
def repeat_name():
    print_name()
    print_name()

def print_name():
    print('Mahmud')

repeat_name()

In this example we call print_name function in repeat_name function before its defination, and it works fine, but why does this happen?
Note: I'm a beginner in Python.

A: Think of it being interpreted as it is run, so the items inside the repeat_name function are not checked until the first time it is called at repeat_name() after the print_name function.
If you put the call to repeat_name() above the print_name function it would also fail.
That is why if you have the code:
def my_func(x):
    print(x)

my_func("hello world")

It doesn't freak out that it doesn't know what x is, becasue x will be defined when you first call that function my_func("hello world")


text:
Q: Substitution method example applied to find higher bound but start assuming it is true for every m < n My question is about the substitution method explanation from the CLRS ( Introduction to algorithms third edition ) book. This is the explanation :
"As an example, let us determine an upper bound on the recurrence
T(n) = 2T([n/2])+n [...]. ( [n/2] being the integer part of n/2 ). We guess that the solution is T(n) = O(nlg(n)). The substitution method requires us to prove that T <= cnlg(n) for an appropriate choice of the constant c > 0. We start by assuming [that this bound holds for all positive m < n, in particular for m = [n/2] ( integer part of n/2 )
yielding T([n/2]) <= c[n/2]lg([n/2]). Substituting into the recurrence yields
T(n) <= 2c*[n/2]lg([n/2]) <= cnlg([n/2])+n = cnlg(n)-cn*lg(2)+n = cnlg(n)-cn+n <= cnlg(n)) where the last step holds as long as c >= 1.
I do not understand the part where they says "We start by assuming [that this bound holds for all positive m < n, in particular for m = [n/2] ( integer part of n/2 )", as we want to find an upper bound, with the big O notation, by definition, everything that matters is that there exist a c > 0 and a m such that T[n] <= cnlg(n) for any n >= m, we do not have to show that it is true BEFORE a certain value but AFTER by definition of big O notation if I am not wrong. Can you help me please ?
Thank you by advance


text:
Q: android: pausing an activity until another finishes When my app starts, it checks to see if it has stored login credentials. if it doesn't, it starts another activity to prompt the user for those credentials. My problem is, that when the prompt activity is started, the first activity continues execution and ends up with null pointers because the prompt activity has not yet returned the needed data
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    tv = new TextView(this);
    setContentView(tv);

    promptForLoginInfo(); //method creates intent and starts activity

    displayCredentials(); //prints data to screen
}

the output reads: "null" because the program executes "displayCredentials()" before the login prompt activity returns.
Anyone have a clue what to do?

A: Your "promptForLoginInfo()" method should be calling startActivityForResult.  Your "displayCredentials()" method should not be called in the onCreate() method, but in the onActivityResult method.

A: In promptForLoginInfo(); you need to start activityForResult.
then you need move  displayCredentials(); from onCreate to onActivityResult

A: Did you tried to check for stored credentials before calling displayCredentials()? If credentials are not found you can start activity by startActivityForResult() method and call displayCredentials() after your prompt activity finishes in onActivityResult().


text:
Q: Undefined variable error while extending the layouts I have created a layout named front where the menu & footer are defined! The front layout contains the menu items from menu controller.
Here's my menu controller -
$menu = Menu::all();
/* some other long code */

Now i'm trying to extend the layouts using @extends('front') on posts page.
It returns the following error:
"Undefined variable: menus" in View: C:\xxxxx\layouts\front.blade.php.

I know it can be fixed by using $menu = Menu::all(); in the posts controller also.
Since the application is huge & i can't keep pasting the menu controller code in every view that is extended.

How do i make the menu controller code global, so that whenever i extend the front layouts, it doesn't give me Undefined variable error ?

A: You can use view composers to make a variable available to multiple views
In your app/Providers/AppServiceProvider.php boot function
/**
 * Bootstrap any application services.
 *
 * @return void
 */
public function boot()
{
    view()->composer(['first.view', 'second.view', 'another.view'], function ($view) {
        return $view->with('menus', App\Menu::all());
    });
}

And to make the variable available everywhere, use the * wildcard instead
/**
 * Bootstrap any application services.
 *
 * @return void
 */
public function boot()
{
    view()->composer('*', function ($view) {
        return $view->with('menus', App\Menu::all());
    });
}

A: Watch the @Watercayman's comment under your question..
But I think the thing that you want is below:
You need to show your variable in the blade where you didn't sent from controller.
In this kind of situations you can use "share" functionality from "Illuminate\Support\Facades\View".
You can just share your variable from main Controller's constructor (this can be as "App\Http\Controllers\Controller", or other as well if it takes care for all pages which uses $menu), like this:
use Illuminate\Support\Facades\View;

public function __construct()
{
    // here you can write some global things for all controllers which extending from this
    $menu = Menu::all();
    View::share('menu', $menu);
}

A: If this variable is only needed by a layout, you can use a view composer for the layout to pass the variable you need.
// a service provider @ boot

View::composer('layouts.front', function ($view) {
    $menus = Menu::all();
    ...
    $view->with('menus', $menus);
});

Laravel 6.0 Docs - Views - View Composers


text:
Q: Should I return html or json in a ajax single page checkout I want to update a current ASP.NET webforms e-commerce site with a nice one-page checkout and I'm looking for some "best practice" on how to update the data. The page will consist of several parts: the cart, user identification, payment options, delivery options etc.
If the user changes the payment option this might result in changes in other parts of the page, like the delivery option becomes unavailable and the total cost changes.
Do I build my webservices so they return the full pre-calculated html when the user changes something on the page? Or do I return some kind of order-object in json format and update all the different parts that need updating with javascript?
The second option seem cleaner to me but is it too slow for a normal page? Or does it exist a third option?

A: 99.9% of the time, JSON will be more compact than equivalent HTML: smaller payload means quicker delivery of the response.  But an even more important reason is:
What if different pages want to call your webservice: one wants to display the results as a list while the other wants to display them as a table, and the third wants to put the results into a jgGrid?  If your webservice returns HTML, 2 of those 3 pages can't use your service.  If your webservice returns JSON, all 3 of those pages can use it easily.
What if, 2 months after deployment, your designer/site-owner wants to change the design from a table to a list?  If your webservice returns JSON, your designer can make the necessary changes quickly and easily, probably affecting only 1 or 2 files in the deployed system.  However, if your webservice returns HTML, you need to compile, test, and redeploy the entire webservice just to support that silly little layout change.
There may be times when returning HTML is a necessary evil (none that I can think of off-hand, but I'm sure there are some).  When that happens, do yourself a favor and make sure the HTML your webservice is building can be changed without a recompile/re-deploy of the entire service.  One heavy-handed but effective way to do this is using ajax to call an ASPX page.
Update: I forgot to mention: even on the slowest javascript engines (InternetExplorer), I've always found this technique (using JS to parse JSON and update the page accordingly) to perform very well.

A: In my view (!) it depends on the overall architecture of your app. In general it is regarded as best practice in traditional web solutions to keep the amount of logic in javascript to a minimum, and only use javascript to update the view with layout changes and such.
This is very rapidly changing as new mobile devices and HTML5 bases solutions make their entry.

*

*If you have a lot of logic in your javascript already it is OK to return JSON.

*If almost all of your logic is on the server you should return HTML.

*If you already have a fully rendered view and only want to update a small piece of it with
new information use JSON

Most of the time I choose whatever is easiest for me to implement in the given use case.

A: I would definitely go with the second one. Return the json which is then filled in the controls from the client-side.
We use this approach in our projects. It's not slow at all, not even on our most complex pages.

A: You might want to check this out:

Of course each action on the catalog and the cart requires it's own Ajax request. Now if this is too simplistic then you can go for a more granular approach on the individual requests for HTML. I've found the point for breaking down the HTML requests is usually when I start breaking down the HTML into individual template objects on the server; cart template, catalog template, and checkout template.


text:
Q: How to play and stop audio whenever we click on button I have a button in which onClick method is attached which will play a vibaration sound.
Button.js
import React from "react";
import "./button.css";

export default function App() {
  let audio = new Audio("/vibrate.mp3");

  const start = () => {
    audio.play();
  };

  return (
    <button className="btn" onClick={start}>
      Click Me
    </button>
  );
}

Vibration sound is playing whenever we click on button. But if I click button again then it is not playing vibration sound because previous sound is not completed yet.
I want to stop the sound (if playing) and play from start if we click on button.
You can check my sandbox .

A: I found a solution to stop the audio...
import React from "react";
import "./button.css";

export default function App() {
  let audio = new Audio("/vibrate.mp3");

  const start = () => {
    if(audio.paused === true){
      audio.play();
    }else{
      audio.pause();
      audio.currentTime = 0;
      audio.play();
    }

  };

  return (
    <button className="btn" onClick={start}>
      Click Me
    </button>
  );
}