text:
Q: css rounded corner of right angled triangle I am creating a small stylised triangular motif 'before' my h1 element, but I am not able to get the corners rounded correctly. The top right is fine but the other two has this clipping issue.
Here is the output along with a blown up image of the shape:

The code used is below:

h1:before {
  content: "";
  display: inline-block;
  width: 0.7em;
  height: 0.7em;
  margin-right: 10px;
  clip-path: polygon(100% 0%, 100% 100%, 0% 0%);
  -webkit-clip-path: polygon(100% 0%, 100% 100%, 0% 0%);
  background-color:  #34495e;
  border-radius: 0.12em;
}

Heading

I would like all corners to be smoothly rounded without any sharp corners. Perhaps there is a better way to do this. Any other tips to improve this are also welcome.

A: That is because you are rounding the whole node. Apply border-radius only to the top-right corner

h1:before {
  content: "";
  display: inline-block;
  width: 0.7em;
  height: 0.7em;
  margin-right: 10px;
  clip-path: polygon(100% 0%, 100% 100%, 0% 0%);
  -webkit-clip-path: polygon(100% 0%, 100% 100%, 0% 0%);
  background-color:  #34495e;
  border-radius: 0 0.12em 0 0;
}

Heading

A: Here is an idea where you can rely on 2 pseudo element and some background coloration to approximate it. You simply need to find the correct value to have the perfect overlap between both pseudo elements.

h1 {
  padding-left:1em;
  position:relative;
}

h1:before {
  content: "";
  position:absolute;
  left: 0;
  top: calc(50% - 0.35em);
  width: 0.7em;
  height: 0.7em;
  background: linear-gradient(to bottom left, #34495e 50%, transparent 50%);
  border-radius: 0.1em;
}
h1:after {
  content: "";
    position: absolute;
    left: 3.8px;
    top: -0.1px;
    width: 0.92em;
    height: 0.8em;
    margin-right: 10px;
    background: linear-gradient(to top,#34495e 3.5px,transparent 5px);
    border-radius: 0.1em;
    transform: rotate(45deg);
    z-index: -1;
}

Heading

A: You can add additional styling to each individual corner in your CSS by adding:
border-radius: 0.4em 0.1em 0.4em 0.1em

You can change these numbers to suit what you need. The first and the third (the ones I've added 0.4em next to) control the corners that you are looking for I believe.

A: Aside from SVG or manually constructing the curves in the clip-path, you could add an :after element to act as the curved hypotenuse. This has a lot of magic numbers in it to get sizing and placement right, so I'm not sure how scalable it is, but it at least gets you there with CSS in this one situation.

h1 {
position: relative;
}

h1:before {
  content: "";
  display: inline-block;
  width: 0.7em;
  height: 0.7em;
  margin-right: 10px;
  clip-path: polygon(100% 0%, 100% 100%, 0% 0%);
  -webkit-clip-path: polygon(100% 0%, 100% 100%, 0% 0%);
  background-color:  #34495e;
  border-radius: 0.12em;
}

h1:after {
  content: "";
  display: inline-block;
  position: absolute;
  left: .24em;
  top: .123em;

  width: 0.2em;
  height: 0.87em;
  background-color:  #34495e;
  border-radius: 0.12em;
  transform: rotate(-45deg);
  transform-origin: center;
}

Heading


text:
Q: SQL BigQuery: fatal error when using PHP string variable in query I am puzzled by this error:

"invalidQuery", "message": "Field 'QLD' not found in table 'medicare.medicareTable'.", "locationType": "other", "location": "query" } ], "code": 400

because the field QLD is most definitely in that table.
I am trying to get a response from BigQuery using the following query in a php file:
$qld = 'QLD';

$request = new Google_Service_Bigquery_QueryRequest();

$request->setQuery("SELECT Gender, SUM(Cost) AS Cost
FROM [medicare.medicareTable]
WHERE State = $qld
GROUP BY Gender");

$response = $bigquery->jobs->query($projectId, $request);

I have played around with the query and found that if I replace $qld with a string, e.g.:
WHERE State = 'QLD'

Then it works.
I am at a loss. What is going wrong here?
Here's the full error, in case it's needed:

Fatal error: Uncaught exception 'Google_Service_Exception' with message '{ "error": { "errors": [ { "domain": "global", "reason": "invalidQuery", "message": "Field 'QLD' not found in table 'medicare.medicareTable'.", "locationType": "other", "location": "query" } ], "code": 400, "message": "Field 'QLD' not found in table 'medicare.medicareTable'." } } ' in /base/data/home/apps/s~s3449107-assign2/1.396261573977805792/php/google-api-php-client/src/Google/Http/REST.php:118 Stack trace: #0 /base/data/home/apps/s~s3449107-assign2/1.396261573977805792/php/google-api-php-client/src/Google/Http/REST.php(94): Google_Http_REST::decodeHttpResponse(Object(GuzzleHttp\Psr7\Response), Object(GuzzleHttp\Psr7\Request), 'Google_Service_...') #1 [internal function]: Google_Http_REST::doExecute(Object(GuzzleHttp\Client), Object(GuzzleHttp\Psr7\Request), 'Google_Service_...') #2 /base/data/home/apps/s~s3449107-assign2/1.396261573977805792/php/google-api-php-client/src/Google/Task/Runner.php(181): call_user_ in /base/data/home/apps/s~s3449107-assign2/1.396261573977805792/php/google-api-php-client/src/Google/Http/REST.php on line 118

A: Not
WHERE State = $qld

But
WHERE State = '$qld'

Text is text ;)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Visual Studio 2013. Creating ActiveX. Add Method wizard not working as expected This is very frustrating. Im trying to create an ActiveX control using Visual Studio 13 Professional edition.
Im selecting New Project->MFC ActiveX Control
I click the Finish button and I get all the files required for an activeX control. This compiles ok. It doesn't do anything but the framework is there.
Its when I use the wizard to add a function that I find a problem. I follow all the instructions as described in MSDN here;
https://msdn.microsoft.com/en-us/library/95357zak.aspx
I find the function is added in the *.cpp file and the header in the associated *.h file as expected. However, contrary to what is described in MSDN, I find;

*

*the *.idl file has NOT been updated

*the DISP_FUNCTION_ID entry has not been added

In addition there is no data type  "VARIANT_BOOL" defined in any of the dropdown boxes for creating the method function parameters. (Neither is there any string types defined)
Ive spent a bit of time on this but am completely baffled. Am I doing something obviously wrong here?


text:
Q: Date_format conversion is adding 1 year to the border dates When I use DATE_FORMAT for Dec 31st date
2018 year is getting changed to 2019. Can someone help say if this is a bug or I am missing something.
import org.apache.spark.sql.functions._

spark.sql("select CAST(1546268400 AS TIMESTAMP)").show(false)
Output: 2018-12-31 15:00:00.0

spark.sql("select DATE_FORMAT(CAST(1546268400 AS TIMESTAMP), 'MM/dd/YYYY HH:mm')").show(false)
Output: 12/31/2019 15:00

A:
So this doesn't exactly answer your question but the use of YYYY vs yyyy seems crucial here. Still investigating actually, but this might help you to figure it out as well.
Update:
https://github.com/davedelong/calendar_fallacies/issues/26
The distinction between YYYY and yyyy is ISO_Week Year vs calendar year.


text:
Q: How to control multiple buttons with a single name to request a response from weather API I have a list of 8 city names that are populated from a previous search via local storage. I need to use the city name to submit an API weather request and don't know how to manage the individual buttons. Right now when I click on the name of the city once it shows up in my previous search list, I am not able to get a response from the API.
Here's my HTML code:

                    <input class="favorite styled" type="button" value="" class="cities" id="city1">
                    <input class="favorite styled" type="button" value="" class="cities" id="city2">
                    <input class="favorite styled" type="button" value="" class="cities" id="city3">
                    <input class="favorite styled" type="button" value="" class="cities" id="city4">
                    <input class="favorite styled" type="button" value="" class="cities" id="city5">
                    <input class="favorite styled" type="button" value="" class="cities" id="city6">
                    <input class="favorite styled" type="button" value="" class="cities" id="city7">
                    <input class="favorite styled" type="button" value="" class="cities" id="city8">

Here's my CSS code:
var savedCities = document.querySelector('cities');
    var newCity = document.getElementById('button');

    $('button').on('click', function() {

        console.log('press')

    event.preventDefault()

    var savedCities = document.querySelector('cities').value;

    //API key & query variables
    var myKey = "ada1f715672a438e9b9acaa7ea0e930b";

    var queryURL1 =`https://api.openweathermap.org/data/2.5/forecast?q=${cityName}&units=imperial&appid=${myKey}`

    $.ajax({
        url: queryURL1,
        method: "GET"
    })
    .then(function(response) {

    console.log(queryURL1);

    console.log(response);

    $(".city").html("
" + response.city.name + "
");
    $("#icon").html("");
    $(".temp").text("Temperature: " + response.list[0].main.temp.toFixed(0) + " °");
    $(".wind").text("Wind Speed: " + response.list[0].wind.speed);
    $(".humidity").text("Humidity: " + response.list[0].main.humidity + " %");
    //$(".uvIndex").text("UV Index: " + response.main.humidity);

    $(".icon1").html("");
    $(".temp1").text("Temp: " + response.list[1].main.temp.toFixed(0) + " °");
    $(".humidity1").text("Humidity: " + response.list[1].main.humidity + " %");

    $(".icon2").html("");
    $(".temp2").text("Temp: " + response.list[2].main.temp.toFixed(0) + " °");
    $(".humidity2").text("Humidity: " + response.list[1].main.humidity + " %");

    $(".icon3").html("");
    $(".temp3").text("Temp: " + response.list[3].main.temp.toFixed(0) + " °");
    $(".humidity3").text("Humidity: " + response.list[1].main.humidity + " %");

    $(".icon4").html("");
    $(".temp4").text("Temp: " + response.list[4].main.temp.toFixed(0) + " °");
    $(".humidity4").text("Humidity: " + response.list[1].main.humidity + " %");

    $(".icon5").html("");
    $(".temp5").text("Temp: " + response.list[5].main.temp.toFixed(0) + " °");
    $(".humidity5").text("Humidity: " + response.list[1].main.humidity + " %");
        })
    });

A: You have 2 class atribute for each button: <input class="favorite styled" type="button" value="" class="cities" id="city1">, so you can't get them with document.querySelectorAll(".cities") nor $(".cities").
Fix them by appending cities to the first class attribute <input class="favorite styled cities" type="button" value="" id="city1">
Another error you have is that you're trying to append the click event on $('button'), but you don't have button tags in your HTML, you have input tags with button type, so you should access them by $('input[type="button"]') or by it's class $(".cities")

$(function() {
    $(".cities").on('click', function() {
        //API key & query variables
        let myKey = "ada1f715672a438e9b9acaa7ea0e930b";
        // Now you can get button value
        let cityName = $(this).val();
        let queryURL1 =`https://api.openweathermap.org/data/2.5/forecast?q=${cityName}&units=imperial&appid=${myKey}`
        // Fetch data below
    });
});

                    <input class="favorite styled cities" type="button" value="New York" id="city1">
                    <input class="favorite styled cities" type="button" value="London" id="city2">
                    <input class="favorite styled cities" type="button" value="Mexico City" id="city3">
                    <input class="favorite styled cities" type="button" value="Buenos Aires" id="city4">
                    <input class="favorite styled cities" type="button" value="Berlin" id="city5">
                    <input class="favorite styled cities" type="button" value="Paris" id="city6">
                    <input class="favorite styled cities" type="button" value="Sao Paulo" id="city7">
                    <input class="favorite styled cities" type="button" value="Roma" id="city8">


text:
Q: Regular expression to match one or more characters every type? There are 3 types of characters: A-Z, a-z and 0-9.
How to write regular expression to match words which have one or more characters in all three types?
For example:
Match: abAcc88, Ua8za8, 88aA
No match: abc, 118, aa7, xxZZ, XYZ111
This boost::regex re("^[A-Za-z0-9]+$"); doesn't work.
Thanks

A: At least IMO, trying to do this all with one regex is a poor idea. Though it's possible to make it work, you end up with an unreadable mess. The intent isn't apparent at all.
IMO, you'd be a lot better off expressing the logic more directly (though using a regex or two in the process won't hurt):
boost::regex lower("[a-z]");
boost::regex upper("[A-Z]");
boost::regex digit("[0-9]");

if (find(string, lower) && find(string,upper) && find(string,digit))
    // it passes
else
    // it fails

It takes little more than a glance for anybody with even the most minimal exposure to REs to figure out what this is doing (and even with no exposure to REs, it probably doesn't take really massive brilliance to figure out that a-z means "the characters from a to z").

A: Assuming you're testing each word separately:
boost::regex re("(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])");

No need for anchors.

Actually, in case boost doesn't support lookarounds:
boost::regex re(".*[a-z].*([A-Z].*[0-9]|[0-9].*[A-Z])|.*[A-Z].*([a-z].*[0-9]|[0-9].*[a-z])|.*[0-9].*([a-z].*[A-Z]|[A-Z].*[a-z])");

This is every combination, as @Bill has pointed out.

A: (\w*[a-z]\w*[A-Z]\w*[0-9]\w*)|(\w*[a-z]\w*[0-9]\w*[A-Z]\w*)|(\w*[A-Z]\w*[a-z]\w*[0-9]\w*)|(\w*[A-Z]\w*[0-9]\w*[a-z]\w*)|(\w*[0-9]\w*[A-Z]\w*[a-z]\w*)|(\w*[0-9]\w*[a-z]\w*[A-Z]\w*)

l = lowerU = upperN = number

1. `(\w*[a-z]\w*[A-Z]\w*[0-9]\w*)` Match words __l__U___N___
2. `(\w*[a-z]\w*[0-9]\w*[A-Z]\w*)` Match words __l__N___U___
3. `(\w*[A-Z]\w*[a-z]\w*[0-9]\w*)` Match words __U__l___N___
4. `(\w*[0-9]\w*[A-Z]\w*[a-z]\w*)` Match words __U__N___l___
5. `(\w*[0-9]\w*[A-Z]\w*[a-z]\w*)` Match words __N__U___l___
6. `(\w*[0-9]\w*[a-z]\w*[A-Z]\w*)` Match words __N__l___U___

A: Well, if we're gonna go the non-regex route, then why not take it all the way ;-)
const char* c = "abAcc88";
char b = 0b000;
for (; *c; c++) b |= 48 <= *c && *c <= 57  ? 0b001 :
                    (65 <= *c && *c <= 90  ? 0b010 :
                    (97 <= *c && *c <= 122 ? 0b100 :
                                             0b000 ));
if (b == 0b111)
{
    std::cout << "pass" << std::endl;
}

(It's not readable, etc.; I'm kidding.)


text:
Q: Problems with RXJava I'm adapting some sample code from what3words for accessing their API via their Java SDK. It uses RXJava.
The sample code is:
Observable.fromCallable(() -> wrapper.convertTo3wa(new Coordinates(51.2423, -0.12423)).execute())
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(result -> {
            if (result.isSuccessful()) {
                Log.i("MainActivity", String.format("3 word address: %s", result.getWords()));
            } else {
                Log.e("MainActivity", result.getError().getMessage());
            }
        });

First of all. this gives a deprecation warning when building and a IDE warning (Result of 'Observable.subscribe()' is ignored).
To resolve this first issue I have added Disposable myDisposable =  in front of the Observable. Is this correct? (See below for where it is added)
Next I need to add a timeout so that I can show a warning etc if the request times out. To do this I have added .timeout(5000, TimeUnit.MILLISECONDS) to the builder.
This works, but the way timeouts seem to work on Observables is that they throw an exception and I cannot figure out how to catch and handle that exception.
What I have right now is:
Disposable myDisposable = Observable.fromCallable(() -> wrapper.convertTo3wa(new Coordinates(51.2423, -0.12423)).execute())
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .timeout(5000, TimeUnit.MILLISECONDS)
        .subscribe(result -> {
            if (result.isSuccessful()) {
                Log.i("MainActivity", String.format("3 word address: %s", result.getWords()));
            } else {
                Log.e("MainActivity", result.getError().getMessage());
            }
        });

This builds and runs fine, and the API/deprecation warning is not shown, BUT when no network is available this correctly times out and throws the unhandled exception.
So, the code seems to be correct, but how on earth do add the exception handling to catch the timeout TimeoutException that is thrown?
I've tried numerous things, including: adding a try-catch clause around the whole Observable - this warns that TimeoutException is not thrown by the code in the `try; and adding an error handler.
Adding the error handler has got me closest, and so the code below is as far as I have got:
Disposable myDisposable = Observable.fromCallable(() -> wrapper.convertTo3wa(new Coordinates(51.2423, -0.12423)).execute())
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .timeout(5000, TimeUnit.MILLISECONDS)
        .subscribe(result -> {
            if (result.isSuccessful()) {
                Log.i("MainActivity", String.format("3 word address: %s", result.getWords()));
            } else {
                Log.e("MainActivity", result.getError().getMessage());
            }
         }, error -> {
             runOnUiThread(new Runnable() {
                 @Override
                 public void run() {
                     myTextView.setText(R.string.network_not_available);
                 }
             });
         });

This catches the Timeout correctly and updates my UI without error, however when the network is restored it seems that the Observable might be trying to return and a null pointer exception is thrown.
(Update, this NPE might actually be being thrown sometimes after a short time whether the network is restored or not... but it is always thrown when the network restores.)
I get FATAL EXCEPTION: RxCachedThreadScheduler-1 and java.lang.NullPointerException: Callable returned a null value. Null values are generally not allowed in 3.x operators and sources.
Do I need to destroy the Observable or something to prevent the NPE?

A: You need to add an onError handler to your subscribe call:
    .subscribe(result -> {
        if (result.isSuccessful()) {
            Log.i("MainActivity", String.format("3 word address: %s", result.getWords()));
        } else {
            Log.e("MainActivity", result.getError().getMessage());
        }
     },
     error -> {
         // handle error here
     });

When a an exception makes it to a subscribe call that does not have an onError handler, it will throw a OnErrorNotImplementedException, like this:
io.reactivex.exceptions.OnErrorNotImplementedException: The exception was not handled due to missing onError handler in the subscribe() method call. Further reading: https://github.com/ReactiveX/RxJava/wiki/Error-Handling | java.util.concurrent.TimeoutException: The source did not signal an event for 1 seconds and has been terminated.

Adding the onError handler will prevent that, and the onError handler will get called instead.

A: There's a few things going on here:

First of all. this gives a deprecation warning when building and a IDE warning (Result of 'Observable.subscribe()' is ignored).

subscribe() returns a Disposable. The idea is that when you're no longer interested in receiving the output of your observable, you call dispose() on the disposable and the work terminates. This can also prevent memory leaks.
As an example, imagine you have an Activity, and you start an Observable to run a long network query which finally posts something to the Activity UI. If the user navigates away before this task completes, or the Activity is otherwise destroyed, then you're no longer interested in its output because there is no longer a UI to post to. So you may call dispose() in onStop().

So, the code seems to be correct, but how on earth do add the exception handling to catch the timeout TimeoutException that is thrown?

Using the error block in subscribe is one option, but there are others. For example, if you wanted to keep using your Result class, you could use something like onErrorReturn(throwable -> Result.error(throwable)). Obviously I'm guessing what that class looks like:
.timeout(5000, TimeUnit.MILLISECONDS)
.onErrorReturn(throwable -> Result.errorWithMessage(R.string.network_not_available))
.subscribe(result -> {
  if (result.isSuccessful()) {
    Log.i("MainActivity", String.format("3 word address: %s", result.getWords()));
  } else {
    myTextView.setText(result.getErrorMessage());
  }
});

java.lang.NullPointerException: Callable returned a null value. Null values are generally not allowed in 3.x operators and sources.

This:
wrapper.convertTo3wa(new Coordinates(51.2423, -0.12423)).execute()

is returning null. You can do something like:
Observable.fromCallable(() -> {
  Result<?> out = wrapper.convertTo3wa(new Coordinates(51.2423, -0.12423)).execute();
  if(out == null)
    out = Result.error(/*Returned null*/);
  }
  return out;
}


text:
Q: They have vs. had three children How do we use "have" or "had" when referring to the number of offspring that a couple produced?
The basic case is when a couple gave birth to, say, three children and everyone is still alive. "They have three children."
What if the parents both died? "They had three children." They are dead so they can no longer have anything. What if only one parent died? I expect that again that we'd use "had" because while they did have the children together, they have nothing together anymore because one of them is dead.
What if all three children died? "They had three children." They no longer have any children. Does this change if not all of their children died? Again, "had" seems more appropriate.
Maybe it depend on exactly what we mean by the terms. Maybe not. Do we refer to the moment when they gave birth to the children or to their act of continuously raising or having raised them. If we speak of birthing, then maybe it should always be "had" because it's always a past event.

A: You have it right, and it would be they had three children if just one or two died too. Also right with birthing and "had" it would go: She had 3 kids. It makes sense in context and wont come off like they are dead.

A: Yes, you are right. But, I'm writing what is generally practised
When parents and children -all are alive --

They have three children

When the parents are dead but children are alive, we say --

They are survived by three children

When children are dead and parents are alive --

They had three children, all dead


text:
Q: C++ Operators overloading >> << () Matrix.h
class Matrix {
private:
    int row;    // rows
    int col;    // columns
public:
    double** matrix;    // pointer to this matrix
    int getRow();
    int getCol();
    void randValues();

    double operator()(int y, int x);
    friend std::ostream& operator<< (std::ostream& stream, Matrix& matrix);
    istream& operator>>(istream& input, Matrix &matrix){
        for(int i=0; i<row; i++){
            for(int k=0; k<col; k++){
                input>>matrix.matrix[i][k];
            }
        }
        return input;
    }
};

For operator >> code::blocks say: include\Matrix.h|50|error: 'std::istream& Matrix::operator>>(std::istream&, Matrix&)' must take exactly one argument|
Matrix.cpp
ostream& operator <<(ostream& stream,  Matrix& matrix){
    for (int i=0; i < matrix.getRow(); i++){
        for (int k=0; k < matrix.getCol(); k++){
            stream << matrix.matrix[i][k] << "  " ;
        }
        stream << '\n';
    }
    return stream;
}
double Matrix::operator() (int y, int x)
{
    if( y < 0 || x < 0 || y > this->row || x > this->col)
    {
        cout << "Wrong index of Matrix()";
    }
    else
    {
        return this->matrix[y][x];
    }
}

For operator <<  code blocks say: Matrix.cpp|432|multiple definition of `operator<<(std::ostream&, Matrix&)'|
For operator () when I use it in main(), code blocks say 'matx' cannot be used as a function|
int main(){
        Matrix *matx = new Matrix(5,5);
        matx->randValues;
        cout << matx(0,0);
}

I would like to ask how to corectly declare  operator overloading, how to implement operator overloading  and then how to use it in main().


text:
Q: Есть ли функция, возвращающая дробную часть после деления двух вещественных чисел Например 6/5 = 1,2.  Мне нужно получить именно 0,2.
Я конечно написал нужную функцию:
def rest(a, b):
    if a < b:
        return a/b
    if a == b:
        return 0.0
    else:   # a>b
        return  a/b - int(a/b)

но может есть такая функция где-то, скажем, в numpy?

A: import math

frac, whole = math.modf(1.2)
print(frac)
print(whole)

Другой способ:
frac = 1.2 % 1
print(frac)


text:
Q: a question based on polynomials $ \frac{x^\alpha+1}{x+1}  = K$ where $K \in \Bbb N$ ,or is it true $\forall \alpha \in \Bbb N$ or their are specific values of $\alpha$ it is true for? and all the assumes values of $x \in\Bbb N$.

A: Let $y=x+1$. Then, by the binomial theorem, $x^\alpha+1=(y-1)^\alpha+1=yb+(-1)^\alpha+1$, which leaves remainder $(-1)^\alpha+1$ when divided by $y=x+1$. The remainder is $0$ when $\alpha$ is odd and $2$ when $\alpha$ is even.
Therefore, $\frac{x^\alpha+1}{x+1}$ is an integer iff $\alpha$ is odd or $x+1$ divides $2$, that is, when $x=0$ or $x=1$.

A: We can use this property of the polynomials: $x-a$ is always a factor of the polynomial $x^{\alpha}-a^{\alpha}$, $\alpha\in \mathbb{N},x\in \mathbb{R}.$
So $x+a=x-(-a)$ is always a factor of the polynomial $x^{\alpha}-(-a)^{\alpha}$, $\alpha\in \mathbb{N}$. For $a=1$ we conclude that $x+1=x-(-1)$ is always a factor of the polynomial $x^{\alpha}-(-1)^{\alpha}$, $\alpha\in \mathbb{N}$.

*

*If $\alpha$ is odd, then $(-1)^\alpha=-1 $ and $x+1$ is a factor of $x^{\alpha}-(-1)^{n}=x^{\alpha}+1$.

*If $\alpha$ is even, then $(-1)^\alpha=1$. So $x+1$ is a factor of $x^{\alpha}-(-1)^{\alpha}=x^{\alpha}-1$, but it is not a factor of $x^{\alpha}+1$.

If $x\in \mathbb{N}$ and $\alpha$ is odd, then $ \dfrac{x^\alpha+1}{x+1}  = K\in \mathbb{N} .$


text:
Q: Store score in a variable after an event Desirable result: After the user choose an answer, I want to modify score variable in:
score += 1 if the answer is right either not changing at all if the answer is wrong.
Current result: For every choice user is making, the score remains the same: 0.
First, I store the paragraph that will be changed in question_paragraph and the button that will be clicked by user in next_button. Also, I stored the value(I put the attribute value on every input using the array notation - 0 first, 1 second etc.) in user_answer.
var question_paragraph = document.getElementById('question');
var next_button = document.getElementById('next');
var i = 0;
var user_answer = getCheckedValue(document.getElementsByName('choice'));
var y = 0;
var score = 0;

The getCheckedValue function will return the value attribute of my input if exists.
function getCheckedValue(radioObj) {
    var radioLength = radioObj.length;
    for(var z = 0; z < radioLength; z++) {
        if(radioObj[z].checked) {
            return radioObj[z].value;
        }
    }
    return "Error!";
}

Here is the problem. The function works fine, except the isolated area. allQuestion is my object where I stored the questions, the possible answers and the right answer, correctAnswer(I don't included it here but works correctly). I put a conditional statement to increase y and code>score with one if the allQuestions[y].correctAnswer is qual with the value of the user_choice.
function changeQuestion() {

    //PROBLEM
    if(allQuestions[y].correctAnswer == user_answer){
    score += 1;
    y++;
    } else{y++;}
    //PROBLEM

    i = (i < allQuestions.length) ? (i + 1) : 0;
    if (i == allQuestions.length) {
        i = 0;
        return question_paragraph.replaceChild(document.createTextNode(allQuestions[0].question), question_paragraph.firstChild);
    }
    var newNode = document.createTextNode(allQuestions[i].question);
    console.log(score);
    return question_paragraph.replaceChild(newNode, question_paragraph.firstChild);
}

Finnaly, I called the addHandler function.
function addHandler(name, type, handler){
    if (name.addEventListener){
        name.addEventListener(type, handler, false);
    } else if (name.attachEvent){
        name.attachEvent("on" + type, handler);
    } else {
        name["on" + type] = handler;
    }
}

addHandler(next_button, 'click', changeQuestion);

A: Well, something just appears to be funny here so far. First of all, I don't see any initialization to the variable y. If y is a global variable that is retaining its value, then maybe there is an issue with your object: allQuestions{}. Could you provide the code for building your object allQuestions{}? Without it, I don't think that I could fully answer this question, but I believe that is where your problem lies.
Oops, this was supposed to be a comment, not an answer, sorry...


text:
Q: When is Facebook deprecating the JavaScript SDK? I've asked this on the Facebook Developer Forums, but no-one is answering, so thought i'd ask it on Stack.
I've got a website which integrates with Facebook Connect using OAuth for authentication. But i have some code which leverages the JavaScript SDK.
I have heard that the JavaScript SDK is being deprecated and/or authentication via the JavaScript SDK is being deprecated.
Can anyone:

*

*Confirm if the above statement is true

*Provide a link giving the date that it is to be deprecated

*Tell me im wrong

EDIT
For anyone who is curious as to why i still use the JavaScript SDK, see my other Stack question for the reasoning.
In short, this cannot be done with OAuth/Graph API:
FB.getLoginStatus(function (response) {
   if (response.status == 'connected') {
      // do single sign on, seamlessly.
   }
}

A: To be very clear, we are not deprecating the JavaScript SDK. It's here to stay. We are in the process of changing it to rely on OAuth 2.0, but it will be just as simple to use. If you use access_token today, then the changes will be minor (largely replace session.access_token with authResponse.accessToken once the updated JS SDK is out). If you rely on session_key and secret and use md5 signature based calls, then you have some migrating to do since those will go away in the OAuth 2.0 only world.

A: Migration to OAuth 2.0 + HTTPS timeline:

*

*July 1: Updates to the PHP and JS SDKs available that use OAuth 2.0 and have new cookie format (without access token).

*September 1: All apps must migrate to OAuth 2.0 and expect an encrypted access token.

*October 1: All Canvas apps must process signed_request (fb_sig will be removed) and obtain an SSL certificate (unless you are in Sandbox mode). This will ensure that users browsing Facebook over HTTPS will have a great experience over a secure connection.

http://developers.facebook.com/blog/post/497
http://developers.facebook.com/docs/authentication/connect_auth/

A: The older SDK is already deprecated but will be available for you to use. But you should really think about migrating to the new SDK.
Currently the latest PHP-SDK is out of sync in terms of authentication implementations with JS; they will be rolling out few changes to both of the SDK's in the near future to unify some of the routines.

A: The current javascript SDK definitely isn't being deprecated.  Perhaps they will deprecate the old Facebook connect javascript, but they haven't announced a date.  The best place for deprecation dates is the Facebook developer roadmap.


text:
Q: show uidatepicker, when I tap on view I have a view with UITapGestureRecognizer
I want to show uidatepicker, when I tap on view
How can I do it ?
thanks in advance

A: I'm not sure exactly what you want, but if you just have something like this?
import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var datePicker: UIDatePicker!

    @IBAction func viewTapped(sender: Any) { // link gesture recogniser here
        datePicker.isHidden = false
    }

    override func viewDidLoad() {
        datePicker.isHidden = true // or set hidden checkbox to true in the picker's attributes inspector
    }
}

A: Just declare your picker datasource inside the touch action.
// in viewDidload method
let gesture = UITapGestureRecognizer(target: self, action:  #selector (self.touchAction (_:)))
self.view.addGestureRecognizer(gesture) // could be your custom view also

//  for Swift 3
func touchAction(_ sender:UITapGestureRecognizer){
    // datasource
    self.pickerData = ["data1","data2" .. ect]

    if pickerData != nil{
        self.picker.delegate = self
        self.picker.dataSource = self
    }
}

Note: your controller class should confirm UIPickerViewDelegate, UIPickerViewDataSource in order to use picker delegates.


text:
Q: Add font awesome for toast ionic 4 Add Font awesome to toast
I can't find a way to add font awesome to toast message on ionic 4 because ionic 4 is shadow Dom for all web controller

A: you can follow the next code to add custom font to toasts.
import { Component } from "@angular/core";
import { ToastController } from "@ionic/angular";

@Component({
  selector: "app-home",
  templateUrl: "home.page.html",
  styleUrls: ["home.page.scss"]
})
export class HomePage {
  constructor(private toastController: ToastController) {}

  async showToast() {
    let toast = await this.toastController.create({
      message: "Your settings have been saved.",
      duration: 2000
    });
    toast.present();
  }

  async showCustomToast() {
    let toast = await this.toastController.create({
      message: "Your settings have been saved.",
      duration: 2000,
      cssClass: "CustomToast"
    });
    toast.present();
  }
}

On documentation of Toast component there are a property to define your custom css styles.

This class need to be on src/global.css
.CustomToast {
   font-family: Verdana, Geneva, Tahoma, sans-serif, Helvetica, sans-serif;
}

Generally when you need to custom a component (alerts, loaders, etc.), you need follow this process.
I hope I've helped :)

A: put the html for your fontawesome in the message parameter.
async showCustomToast() {
    let toast = await this.toastController.create({
      message: "<i class="fas-fa-edit"></i> Your settings have been saved.",
      duration: 2000,
      cssClass: "CustomToast"
    });
    toast.present();
  }


text:
Q: Detect Whether Blob is AWS KMS Encrypted I have a database where I intend to store KMS-encrypted blobs.  Some of the fields are unencrypted (and need to be encrypted) and some of the fields have already been KMS-encrypted.
Looking at the raw data, all of the KMS-encrypted stuff looks kind of similar.  Ideally, the AWS KMS API or AWS SDK should have something like a isEncrypted() method, but it doesn't appear to.
Is there a good way to locally detect whether my field is encrypted or not, short of catching the InvalidCiphertextException from the decrypt API?

A: I think your observation that the encrypted stuff sort of looks the same is valid. It's valid because in the body, the first part is actually the key name that was used to encrypt. that's how KMS knows how to decrypt without you specifying the key (so basically when you encrypt you get something back that's: key description + actually encrypted stuff).
Now, the questions is: do you really want to rely on this observation to ensure if something is encrypted? Do you want to do this at runtime?
As far as the isEncrypted method: how is that different from calling decrypt? It's still a method call.
The real answer is: You should not rely on KMS to encrypt/decrypt stuff you store. You should rely on KMS to encrypt/decrypt the keys you use to encrypt/decrypt your stuff (ie what's called envelope encryption). If you decrypt/encrypt directly via KMS you are going to be limited by the number of calls you can make agains KMS and the max size of what you want to encrypt.
If you switch to envelope encryption it should be trivial to just attempt to decrypt and figure out if content is encrypted or not. That being said, I would recommend to actually be very strict about what is encrypted and enforce it (ie don't guess).
Since we're here: also look at the encryption context for KMS


text:
Q: Using JAX-B in Eclipse 4.23 Plugins I need to update my Eclipse plugin to Java 17 and Eclipse 4.23 (2022-03).
The plugin used JAX-B in Java 8 which included the required classes, but now i need to change it to separate libraries.
In order to do so i added these to the list of "Required Plug-ins"

jakarta.xml.bind
org.eclipse.persistence.moxy

Both plugins are readily available in my installation, so that seemed to be the most sensible approach.
It seems that the javax.xml.bind.ContextFinder included in jakarta.xml.bind is found and tries to load org.eclipse.persistence.jaxb.JAXBContextFactory. But that step fails at JAXBContext.newInstance:

javax.xml.bind.JAXBException: Implementation of JAXB-API has not been
found on module path or classpath.
- with linked exception: [java.lang.ClassNotFoundException:
org.eclipse.persistence.jaxb.JAXBContextFactory]
    at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:232)
    at javax.xml.bind.ContextFinder.find(ContextFinder.java:345)
    at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:691)
    at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:632)

Caused by: java.lang.ClassNotFoundException: org.eclipse.persistence.jaxb.JAXBContextFactory
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:520)
    at org.eclipse.osgi.internal.framework.ContextFinder.loadClass(ContextFinder.java:147)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:520)
    at javax.xml.bind.ServiceLoaderUtil.nullSafeLoadClass(ServiceLoaderUtil.java:92)
    at javax.xml.bind.ServiceLoaderUtil.safeLoadClass(ServiceLoaderUtil.java:125)
    at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:230)
    ... 46 more

What confuses me greatly about this is that the class JAXBContextFactory can be found if i use JAXBContext.class.getClassLoader().getResource("org/eclipse/persistence/jaxb/JAXBContextFactory.class") where the class loader is org.eclipse.osgi.internal.loader.EquinoxClassLoader. But the internal workings of JAXBContext appear to use a different class loader (org.eclipse.osgi.internal.framework.ContextFinder) and that can't find it.
How can i get it to work?


text:
Q: Can i use c/c++ to communicate with a hardware device? i was wondering if its possible to use c/c++ to communicate with a hardware device such as a pci card just like a windows application would?
Or this type of thing too hard for an individual to do alone?
I have tried reading about it, but couldn't find a lot of information on the topic.
If there is no simple answer, maybe some links to examples etc would be great.
Thanks so much
Aiden

A: It depends on how you want to communicate it.  If you want to control it specifically (dependent on this type of hardware), this is not an application thing, but a driver thing, i.e. you will have to write a driver.  This is the most likely way (since you are referring to Windows application).
If you want to talk to it in a generalized way (lets say you have a PCI card with a communication port and you want to interact with that port, no matter what manufacturer made it), you will have to see what interface (API) the operating system offers to interact with that type of device.

A: It is possible,
 hovever you need to look at the devices specification, to see how.
Sometimes you just need to make direct-x/system calls, and windows will handle the rest, or you need to wrap the driver and talk trough it.
But there is no simple answer here im afraid, it all depend on the specific card, and it's driver.
So either post the card specs, or do some research on it.


text:
Q: Parsing json without using the \n character I am currently implementing an Akka Stream Scala application which reads-in a zipped file containing tweets formated as below (using json):
{"created_at": "Mon Nov 04 14:37:29 +0000 2019", ... }
{"created_at": "Mon Nov 04 14:37:29 +0000 2019", ... }

I already succeeded in reading in uncompressing the file but I'm now trying to split the stream into chucks in such a way that each chunck contains one representation of a tweet, which corresponds to one line in the code snippet above.
I have tried using the the following as a flow to achieve this:
Framing.delimiter(ByteString("\n"), 50000)

The problem is however that within the json there is an attribute "full_text", representing the content of the tweet. This text can contain \n characters, resulting in the above code snippet not working as it will also split at those \n text characters. Example below.
{"created_at": "Mon Nov 04 14:37:29 +0000 2019", "full_text": "I love to eat \n CHEESE!!", ... }

Does anyone know a good solution to this issue?

A: It seems that Akka's JSON Framing is made for this purpose:
https://doc.akka.io/docs/alpakka/current/data-transformations/json.html


text:
Q: Download Microstrategy Dossiers in .mstr format with Python I'am searching for downloading Microstrategy Dossiers as in ".mstr" file format with python. I could not find any online source to do it.

*

*I have tried "requests" and "mstrio-py" libraries, but those does not seems to be working.

*There is a function called "export_document_to_mstr" in mstrio.project_objects.document in Document. That requires "body" in json format and "instance_id" which I could not find.

I wonder if is there anyone give me ideas ?
Thanks a lot in advanced !


text:
Q: Get specified record from belongsToMany relation Laravel If I have properties table, and 2 other tables:
 *property_characteristics
  - property_id (i.e. 1)
  - characteristic_id (i.e. 5 - join with default_characteristics)
  - value (i.e. 3 - aka 3 rooms)
 *default_characteristics
  - id (i.e. 5)
  - name (i.e. rooms)

In the Property.php model I have:
public function characteristics()
{
return $this->belongsToMany('Proactiv\DefaultCharacteristic', 'property_characteristics', 'property_id', 'characteristic_id');
}

How can I get the number of rooms (value from property_characteristics) for a property starting from:
$property = Properties::find(1);

I would need something like this in view:
$property->characteristics->rooms // should return 3 which is the value columns on property_characteristics table

A: Since the value is on your pivot table, you need to tell Laravel about this extra field. Add to your belongsToMany line to make:

return $this->belongsToMany('Proactiv\DefaultCharacteristic', 'property_characteristics', 'property_id', 'characteristic_id')
    ->withPivot('value');

Then select characteristics with the name you want, rooms, and get the value:
echo $property->characteristics()->with('name', 'rooms')->first()->pivot->value;

Alternatively, add a getter to your Property model which does this for you (you'll still need to add that withPivot part to the relationship):
public function getRoomsAttribute()
{
    return $this->characteristics()
        ->where('name', 'rooms')
        ->first()
        ->pivot
        ->value;
}

Then you can get the number of rooms in a similar way to how you originally wanted to, with $property->rooms.
Or you could generalize this to get any characteristic:
public function getCharacteristic($name)
{
    return $this->characteristics()
        ->where('name', $name)
        ->first()
        ->pivot
        ->value;
}

And then get the number of rooms with $property->getCharacteristic('rooms').

A: First, you have to tell your relationship to make your additional field available. You do this using the withPivot() method:
public function characteristics() {
    return $this->belongsToMany('Proactiv\DefaultCharacteristic', 'property_characteristics', 'property_id', 'characteristic_id')
        ->withPivot('value');
}

Now you can access your value on the pivot table. You do this like so:
$property = Properties::find(1);

foreach ($property->characteristics as $characteristic) {
    echo $characteristic->pivot->value;
}

You can read more about this in the documentation here, under the Retrieving Intermediate Table Columns heading.


text:
Q: Unable to run multiple AJAX calls without refreshing I have a form that contains a text field and a button. When I start typing, it shows hints from my database and upon clicking the button or hitting the enter key it displays search results. AJAX is used for both hints and search results, and it is working well.
The problem is that it only works the first time after the page loads. If I want another search, it doesn't respond. It just shows the previous search results until the page is refreshed, but the showhint() function works well.
<input type="text" id="txt"  onkeyup="showhint(this.value)"/>
<input type="button" value="search" onclick="searchresult()"/>

The AJAX function:
function searchresult() {
    var key = document.getElementById("txt").value;
    var xmlhttp;

    if(window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
    } else {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange = function() {
        if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            document.getElementById("mid").innerHTML = xmlhttp.responseText;
        }
    };

    xmlhttp.open("GET","keyprocess.php?q=" + key, true);
    xmlhttp.send();
}

What is the problem?

A: I'm guessing the reason it works the first time or on refresh is because the event handler is not persisting between ajax requests.  I would look into jQuery as it will help mitigate issues like this.
For jquery < version 1.7
The .delegate() method does the following

Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements.

Anything after 1.7 you should use the .on() method.
Basically if the elements on the page change from an ajax request the .delegate() or .on() methods will still allow events to be handled.
Update:
//This needs to be within the $(document).ready function
//Attach an event handler to the ID called txt that fires on changes
$("body").on("change", "#txt", function(event){
    //get the value from the input
    var $val = $(this).val();

    //Send the $val to keyprocess.php via ajax call

    //Output Results

});


text:
Q: How to get object that not match in another object lodash I have 2 arrays with objects.
const a = [
 {
  name: 'John'
 },
 {
  name: 'Adam'
 }
]

const b = [
 {
  name: 'Adam'
 }
]

I want to get the object is not the same in the array and also get the object that is same in arrays as well.
const same = [
 {
  name: 'Adam'
 }
]

const not_same = [
 {
  name: 'John'
 }
]

Using lodash library is it possible?

A: You can use intersectionBy and xorBy as follows:

const a = [{
    name: 'John'
  },
  {
    name: 'Adam'
  }
];

const b = [{
  name: 'Adam'
}];

console.log(_.intersectionBy(a, b, 'name')); // values present in both arrays
console.log(_.xorBy(a, b, 'name')); // values present in only one of the arrays
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>

A: You can use _.partition() to get two arrays according to a certain criteria:

const a = [{
    name: 'John'
  },
  {
    name: 'Adam'
  }
];

const b = [{
  name: 'Adam'
}];

const bMap = _.keyBy(b, 'name'); // create a map of names in b
const [same, not_same] = _.partition(a, ({ name }) => name in bMap); // partition according to bMap and destructure into 2 arrays

console.log('same: ', same);

console.log('not_same: ', not_same);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>


text:
Q: PROLOG Finite automata compile error I need help with my Prolog homework.
So I have to represent a finite automata with 4 states. It is a simple laughing automata. But i don't know why I get this error:
Warning: c:/users/joanpc/desktop/p1_ex2.pl:20:
    Singleton variables: [Current]
Warning: c:/users/joanpc/desktop/p1_ex2.pl:32:
    Singleton variables: [ListNodes]
ERROR: c:/users/joanpc/desktop/p1_ex2.pl:32:
    No permission to modify static procedure `(=)/2'

I think that it is some kind of syntax error but I can't recognise it. Here is my code:
recognize(X) :-
  init(ListNodes, Y),
  process(X, Y).

process([X|Rest], Node) :-
  NextNode is (Node+1),
  arc(Node, NextNode, X),
  process(Rest, NextNode).

process(X, Node) :- final(Node).

process([X|Rest], Node) :-
  NextNode is (Node-1),
  arc(Node, NextNode, X),
  process(Rest, NextNode).

init(Current, Y) :-
  initial(Current),
  Y = Current.
init([Current|Rest]) :- init(Rest).

%Facts

initial(1).
final(4).

arc(1,2, j).
arc(2,1, a).
arc(2,3, a).
arc(3,4, !).

ListNodes = [1,2,3,4].

I am new with Prolog so any help will be appreciated.
Thanks :)


text:
Q: Is Stream.Read buffered when doing network I/O? So I was recently doing some work, when somebody told me that if doing a Stream.Read on a network stream that is obtained from calling one of .NET's GetResponseStream on a WebResponse or those are buffered.
He was saying that if you were to put a breakpoint, in the code where you're reading, you wouldn't stop the network traffic. I find that bizzare, but also hoping that it's true. How does that work? Is it even accurate?
using (Stream webResponseStream = this.webResponse.GetResponseStream())
{
   byte[] readBuffer = new byte[bufferSize];
   int bytesRead = webResponseStream.Read(readBuffer, 0, bufferSize);
   while (bytesRead > 0)
   {
        bytesRead = webResponseStream.Read(readBuffer, 0, bufferSize);
        // If I put a breakpoint here, does network activity stop?
   }
}

A: No, the Stream object returned by GetResponseStream is not buffered.
Short answer to your second part (about setting a breakpoint) is that your co-worker is incorrect. Network traffic will stop, but eventually, and to describe "eventually", read on for more details.
Bing for "SO_RCVBUF", "tcp receive window size", "vista auto scaling", for even more general information.
Detailed Part
Let's start with this, here's a textual view of the Windows networking stack:
++ .NET Network API's
++ --- Winsock DLL (user mode)
++ ------ afd.sys (kernel mode)
++ --------- tcpip.sys
++ ------------ ndis
++ --------------- network interface (hal)
This is a rough stack, glossing over some details, but the general idea is that .NET calls into Winsock user-mode dll, which then pushes most of the real work to its cousin AFD (Ancillary Function Driver), onwards to the tcpip sub system, so on ..
At the AFD level, there is a buffer, generally between 8K and 64K, but with Vista (and beyond), it can also scale up. This setting can also be controlled by a registry setting(HKLM\SYSTEM\CurrentControlSet\services\AFD\Parameters).
In addition, the tcpip.sys also has a buffer, that is similar to AFD's buffer. I believe *SO_RCVBUF* setting passed when opening the socket can change this too.
Essentially, when you are receiving data, tcpip.sys on your behalf keeps getting data, and keeps the telling the sender that it got the data (ACK's), and does so until its buffers are full. But at the same time, afd.sys is clearing tcpip.sys buffers by asking it for the data (which it then copies into its own buffer), so tcpip.sys can fill more data from the sender.
And then there's you (the .NET API caller), who is also doing the same, calling the Read() method and copying data into your buffer.
So, if you think about it, a 256Kb message coming over the wire, 64K sitting in the tcpip.sys buffer, 64K sitting in afd.sys buffer, and you set a breakpoint after asking for one 4K (your bufferSize variable) chunk, we're looking at 128K ACK'ed back to the sender as received, and since the tcpip.sys buffer is full (assuming 64K size) now (and you're blocked by your debugging session), tcpip.sys will no have option but to tell the sender to stop sending being bytes over the wire, because it can't process them quick enough.
Practically (i.e. somebody not setting a breakpoint!), I've seen GC to induce such behavior. Seen a case of a 3 second garbage collection that let all the OS buffers fill up.

A: This is accurate.  TCP is implemented by the Windows TCP/IP driver stack.  Setting a breakpoint in your program does not stop the driver from downloading data from the server.  Not until the driver decides that too much kernel pool space is being used to buffer the data.  The exact rules for which are undocumented.
This is an optimization, a standard one in operating systems.  The strategy makes TCP transfers very efficient, it isn't paced by how responsive your program is, only by the bandwidth of the connection and how responsive the driver stack is to network card interrupts.  Which it is very good at, it is a driver's job.

A: A NetworkStream is not buffered by default. When you put a breakpoint inside the procedure that is reading this stream, the client that is sending data to the underlying socket will block and wait until the remote socket is ready to receive once again. The client won't be able to write to the socket, so, yes, the network traffic stops.
Here's a blog post which illustrates how you could make it buffered by using the BufferedStream class.


text:
Q: Holding Page during SharePoint Upgrade? We'll be upgrading a client's MOSS public internet site soon from a Cumulative Update to SP2 and are conscious that there will be downtime (to perform the upgrade and possibly troubleshooting!). We would like to add a holding page so that visitors still get access to key contact details and a message that the site is under maintenance.
Does anyone have any tips for doing this type of thing with SharePoint? I know of the app_offline.htm file that when dropped into the web root, will automatically prevent access to the rest of the site but wasn't sure if this was standard practice in the SharePoint world?
Any tips?
Cheers, James.

A: If the app_offline.htm works for you, then by all means, use it.
I think that it will the best option for you, and to the best of my knowledge SharePoint doesn't have any other means of putting itself offline.

A: As this is a public intranet site you are updating, presumably there is already a test environment for it that is close or the same in configuration. It is important to follow exactly the same steps for updating the test environment as you would for production. These should be documented as well and followed to the letter to reduce the likelihood of mistakes. This way you are much less likely to run into problems.
I would try app_offline.htm as you suggest (like Magnus I don't believe there is another way to take SharePoint offline). If your test environment updates with this in place you should be fine.


text:
Q: cancan/devise - redirect to requested path When a user visits a page that they are not authorized to view they get redirected to the login page.   After they log in they are redirected to the site root.   Is there a quick and easy way to redirect them back to the page they initially asked for?

A: You could add a hidden field referring_page to your sign_in-form to add the former referrer to that field and route back to there if its existing, like this:
def after_sign_in_path_for(resource)
  params[:referring_page] || super
end

It's a manual solution but i prefer it to using complex logic on controller side.

A: I dont understand what you exactly want to achieve by saying "if a user visits a page that they are not authorized to view they get redirected to the login page. After they log in they are redirected to the site root"
I assume there will be two sets of users one is admin- user and another is non-admin user the way i handle this will be something like this,
Inside  application controller
class ApplicationController < ActionController::Base
  protect_from_forgery

  check_authorization :unless => :devise_controller?
  before_filter :authenticate_user!

  rescue_from CanCan::AccessDenied do |exception|
    redirect_to root_url, :alert => exception.message
  end

  protected

  def stored_location_for(resource_or_scope)
    nil
  end

  def after_sign_in_path_for(resource_or_scope)
    if current_user.admin?
      #add your desired path
    else
      #redirect to your desired path
    end
  end
end


text:
Q: asp.net core PascalCase for JsonResult for just one method
Using MVC Core.  Json results are being sent to client modifying the properties!  It is converting everything to camelCase.  I would like to change just one method to return the data without being modified. (Since I have no control over the entire project in visual studio I cannot change the global mvc settings)  Currently this is messing up my method and converting everything to camelCase:
[HttpPost]
public async Task<JsonResult> CustomerSearch(string search)
{
...
// This is changing the json to camelCase
return Json(lstCustomers);
}

I am trying to leave it as default by using this return:
var pascalCaseFormatter = new JsonSerializerSettings();
pascalCaseFormatter.ContractResolver = new DefaultContractResolver();
return Json(lstCustomers, pascalCaseFormatter);

However this returns an error 500 from server.  Any help would be appreciated.

A: This will not change casing (Pascal-casing when using normal c# naming conventions)
return Json(lstCustomers, new JsonSerializerOptions());

And this will return camel-casing
var serializeOptions = new JsonSerializerOptions
{
    PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};
return Json(lstCustomers, serializeOptions);

Finally, what OP is trying will throw an exception:
return Json(lstCustomers, new JsonSerializerSettings());

System.InvalidOperationException: Property 'JsonResult.SerializerSettings' must be an instance of type 'System.Text.Json.JsonSerializerOptions'.

Tested using an asp.net Core 5 app.


text:
Q: how to import java.security.* in my gwt application i want to develop a plugin using gwt. It has to use java.security.* for the key generation on client side.
i have made all requirement
But it is showing following error.

Loading modules
coreservlets.GwtApp1
Loading inherited module 'coreservlets.GwtApp1'
    Loading inherited module 'java.security.KeyPair'
       [ERROR] Unable to find 'java/security/KeyPair.gwt.xml' on your classpath; >could be a typo, or maybe you forgot to include a classpath entry for source?
    [ERROR] Line 15: Unexpected exception while processing element 'inherits'

i have inherited all the related class  like "java.security.KeyPair" in my gwtapp1.gwt.xml file
also i included jar in  classpath itself.but still the error has not gone.
what should i do.plz suggest
here is my java code
package coreservlets.client;

import java.io.UnsupportedEncodingException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;

public class Keygen {

private PrivateKey privKey;
private PublicKey pubKey;
private static Keygen keygen = null;

private Keygen() {

}

public static Keygen getInstance() {

    if (keygen == null) {
        keygen = new Keygen();
    }

    return keygen;
}

public void KeyGenerator(String ALGORITHAM) {
    KeyPairGenerator keyGen = null;
    SecureRandom random = null;
    try {
        keyGen = KeyPairGenerator.getInstance(ALGORITHAM);
    } catch (NoSuchAlgorithmException ex) {
        ex.printStackTrace();
    }
    try {
        random = SecureRandom.getInstance("SHA1PRNG", "SUN");
        //random = SecureRandom.getInstance("SHA1PRNG");
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();

    } catch (NoSuchProviderException ex) {
        ex.printStackTrace();
    }

    //keyGen.initialize(1024, random);
    keyGen.initialize(1024);
    KeyPair key = keyGen.generateKeyPair();
    privKey = key.getPrivate();
    pubKey = key.getPublic();

}

public String getPubKeyasString() {
    //return Base64.encodeBase64String(pubKey.getEncoded());
    try {
        return new String(pubKey.getEncoded(),"ISO-8859-1");
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}
public String getPriKeyasString() {
    //return Base64.encodeBase64String(privKey.getEncoded());
    try {
        return new String(privKey.getEncoded(),"ISO-8859-1");
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}

}

A: For key generation you can use the gwt-crypto library, but be prepared to certain performance issues and unsupported features.
[Edit]
Some time ago, I did success wrapping a pure js rsa solution using jsni. The js I took was the jsbn.js library

A: In a .gwt.xml file <inherits ...> refers to another .gwt.xml file. I suspect that you have used it like a java import ... instead?
What you should do, if you want to use java.security.KeyPair clientside in GWT is to ascertain that the source is available to the GWT compiler. This is done using a <source path="..."  /> entry in the .gwt.xml file.
You may want to visit the GWT JRE Emulation Reference page, where sadly you will see that none of the javax.* packages are supported, so good luck with your project... Perhaps you should keep the code using KeyPair on the server side only?
Hope that helps.


text:
Q: Run controller only first time tab was clicked - AngularJS I'm developing a website for our company, and one of the pages contains several tabs :

I want the loading operation to be done for each tab only once and not every time I click it, because these tabs have some API calls, and reloading takes time.
What is the best way to do it? I'm using Ui-router and ui-sref to move between each tab :

                      TAB1

                      TAB2

                      TAB3

                    <graph-panel  panel-title="TabThree {{vm.isTabThreeSelected}}" chart-config="vm.charts.TabOneChartSite"></graph-panel>

A: On Each Controller, You can cache your loaded data in a service, and when you load your controller you will start by checking this service if it does not have the data, then you will request it from your APIs , in this case you only request your data once you access the tab for the first time :
eg. your service
app.service('dataService', function() {

    this.firstTabData =  null;

    this.getFirstTabData = function () {
        return this.firstTabData;
    };

    this.setFirstTabData = function (data) {
        this.firstTabData = data;
    };
});

your controller
app.controller('tabOne', function($scope, dataService) {
    $scope.data = {};

    $scope.load = function () {
        if(dataService.getFirstTabData()) {
            $scope.data = dataService.getFirstTabData();
        }
        else {
            $scope.data = getDataFromAPI();
        }

    };

    var getDataFromAPI = function () {
         //get your data

         dataService.setFirstTabData(dataFromAPI);
    };

});


text:
Q: Registering a COM dll on another machine I have written a class library of which a UserControl is ComVisible.
When I register this using Visual Studio (check the "Register for Com interop" box and build), it is registered and works well. Now I would like to register on another machine. How do I do this?
I have tried using this (and every possible combination of this):
regasm.exe comdll.dll /tlb /nologo /codebase

Does anyone know which command Visual Studio 2010 uses to register COM dlls?
I have tried looking at the output window when building but this doesn't display anything.
When I use regasm.exe as described above, I get a message that the types are registered but no other messages. Shouldn't I get more information here?
Your help is much appreciated. If this is a duplicate please tell me. I have searched on stackoverflow but so far nothing has helped.

A: Currently no... (The Less You Know, the Better)
It put just this simple Line out. But it works. I use regasm.exe to implement my COM-ActiveX Controls.
If you want more Information you have to use OleView.exe, it's shows you a great Overview about the OLE and Interfaces at COM.


text:
Q: WARNING: erroneous pipeline: no element "voaacenc" i try to execute
gst-launch-1.0 -em rtpbin name=rtpbin latency=5 udpsrc port=5102 caps="application/x-rtp,media=(string)audio,clock-rate=(int)48000,encoding-name=(string)OPUS" ! rtpbin.recv_rtp_sink_0 rtpbin. ! queue ! rtpopusdepay ! opusdec ! audioconvert ! audioresample ! voaacenc ! mux. udpsrc port=5104 caps="application/x-rtp,media=(string)video,clock-rate=(int)90000,encoding-name=(string)H264" ! rtpbin.recv_rtp_sink_1 rtpbin. ! queue ! rtph264depay ! h264parse ! mux. flvmux name=mux streamable=true ! rtmpsink sync=false location="rtmp://127.0.0.1:1935/show/stream live=1"

Unfortunately it raise an error: WARNING: erroneous pipeline: no element "voaacenc"

A: Did you try running gst-inspect voaacenc?
Try installing  gst-plugins-bad, should solve it.


text:
Q: Flex 4 resize groups within a group I am trying to automatically resize the children within an s:Group. The children are another s:Group and a H:Group. Each have a percentage width of 10% and 90% each. The problem is that when one of the groups is resized (using a transition and rotation combination in the Skin), the other group does not automatically resize to fill the space?
Shouldn't Flex do this automatically? or do I have to code this?
<s:Group
    id="listsGroup"
    width="100%"
    height="255"
    >

    <s:Label text="LIST WITH HEADER TEST" styleName="h1" />

    <s:Group
        id="listsGroupSavedSearches"
        width="10%"
        height="255"
        >
        <components1:ListWithHeader
            id="categories11"
            dataProvider="{listModel}"
            headerLabel="Saved Searches"
            allowMultipleSelection="true"
            top="10" bottom="0"
            left="0" width="10%"
            />
    </s:Group>

    <s:HGroup left="160" width="90%" height="150" top="50" gap="6">
         <components1:ListWithHeader
            id="categories1"
            dataProvider="{listModel}"
            headerLabel="Category1 "
            allowMultipleSelection="true"
            width="100%"
            height="150"
            />
        <components1:ListWithHeader
            id="categories2"
            dataProvider="{listModel}"
            headerLabel="Category2"
            allowMultipleSelection="true"
            width="100%"
            height="150"
            />
        <components1:ListWithHeader
            id="categories3"
            dataProvider="{listModel}"
            headerLabel="Category3"
            allowMultipleSelection="true"
            width="100%"
            height="150"
            />
    </s:HGroup>
</s:Group>

A: The best way to approach something like this is to tie into the Flex Component lifecycle methods, specifically updateDisplayList().  UpdateDisplayList() is used to position and size your children.  It has two parameters, the height and width of your component.  You can then write an algorithm to size and position your children based on the component's height and width.
MXML does this all under the hood, kind of in a black magic sort of way; but you'll gain more control if you write the layout code yourself.


text:
Q: Inter-Sub ErrorLine I'm looking for a fancy solution on the identification of the line on error in a called Sub.
Here is an example which doesn't tell me the line on error in the called Sub but only the line in the main Sub.
Private Sub TestThis()
    On Error GoTo ErrorHandler
a1:
    Call SubError
    Exit Sub
ErrorHandler:
    Debug.Print "Error: " & Erl & ", " & Err & ", " & Error(Err)
End Sub

Private Sub SubError()
b1:
    Err.Raise Number:=2000, Description:="MyError"
End Sub

The solution I came up with is having a global variable called error_line and simply changing it appropriately through the code.
Do you know any fancier solution for this?

A: In VBA, the best practice IMHO is to put an error handler into absolutely every procedure you write.  And in every error handler, you could then call another central routine which is handling the error (like writing to a log or something).
Oh well, and the really best practice is to minimize the use of VBA at all ;) - I mean for real: Treat VBA like a scripting language for small projects; but for really big projects, better use C# or VB.NET, and create an add-in or executeable of its own.


text:
Q: Want to display an alert when the app enters foreground from background I am trying to build an iOS app, where when the app enters background and the user brings it to foreground, I want to display a message like "Welcome Back", Is there a way of doing that?
I have read about the UILocalNotification but that is not what I want.

A: Yes, of course. For such kind of methods you should always look in AppDelegate.m file.
It has the default method:
- (void)applicationWillEnterForeground:(UIApplication *)application
{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Welcome back!" message:@"Welcome back!" delegate:nil cancelButtonTitle:nil otherButtonTitles:nil];
    [alert show];
}

Some of that kind...

A: Implement the UIApplicationDelegate applicationWillEnterForeground: method. This is called when the app returns to the foreground.


text:
Q: Classical Stack Overflowing? I am new to this forum and I am still an amateur in programming languages so please be kind with any of my silly mistakes :p
I am programming a recursive function which builds a kd-tree for a search process. I am using the c language on Visual Studio '08. After some seconds of processing, the program execution halts due to an error namely:

Unhandled exception at 0x77063de7 in run_FAST_corner_detection.exe:
  0xC00000FD: Stack overflow

Now when the code breaks, there is a green arrow just near the instruction:
kd_node = malloc(sizeof(struct kd_node));
//this function allocates a pointer to a reserved memory of size struct kd_node.

Is this the classical problem of running out of memory?
How can I monitor the stack memory? (I know that this question has been asked repeatedly but honestly I have yet found no good method to do this).

A: Well, the stack overflow might be due to you calling malloc while deep in the recursion. The call to malloc pushes the return address and perhaps even parameters on the stack and this might be the thing which causes the stack to overflow. Don't do recursions in your code - try to make the code iterative (with loops instead). This is especially true for when the recursion is not bounded.

A: To monitor stack usage, simply take the address of any local variable (one defined within a function), and compare it against the address of a local variable in your main function (or thread entry function):
int stack_bottom;

int stack-usage () {
  int top = 0;

  /* Note, stack grows downward through memory, so high - low is .. */
  return stack_bottom - (int)⊤
}

....

int main () {
  int bottom = 0;

  stack_bottom = (int)⊥

  ....
}

To reduce stack usage, either limit recursion, or avoid using large local variables (such as structs, arrays) and don't use alloca. You can replace large local variable with pointers to dynamically allocated heap memory (but don't forget to free it!)


text:
Q: In the unary numeral system, how are the numbers between 1 and -1 labelled? In the unary numeral system, does 1 - 1 = -1 ? Because if this is true, then how would the numbers between 1 and -1 be represented? Where on a number line would .1 and -.1 be?
I am not necessarily looking for an answer to each of these other questions; I am curious about the problems that arise if a unary number system allows for negative numbers. Specifically, what is there between 1 and -1? I ask this question because I don't know the answers and I haven't yet found an answer on the Internet.

A: Here is an answer for the question : " I am curious about the problems that arise if a unary number system allows for negative numbers."
In the unary counting method that I will call "tally stick" counting method (that our ancestors must have practised), one can consider negative numbers in the following way.
You take a point on the stick, and make grooves either on the right (positive quantities) or on the left (negative quantities). Then if you have 7 grooves on the right and 8 on the left, you can consider it as $-1$.
Said in a mathematical way, $-1$ designates the equivalence class of ordered pairs of the form $(n+1,n)$, i.e., $n+1$ tallies on the left, $n$ on the right...
Immediate generalization to any negative number $-a$ represented by the set of ordered pairs $\{(n+a,n) \ | \ n \in \mathbb{N} \}$


text:
Q: what is alternative in bigtable to hbase bulkload We are planning to migrate from hbase to bigtable. We used bulkload to load large amount of data. The bulkload is efficient and it is able to ensure Idempotency. How to achieve the efficiency and update idempotency via bigtable? Do you have any recommendation?

A: You can upload your HBase data to Cloud Storage and then import it to Cloud BigTable using Dataflow. For this you can use the already existing templates depending on the file type you export the data to.


text:
Q: matlab - filter out row by condition on certain column I have a data structured like this
3159,417.236206055,300.815246582,264.060791016,341.630493164,7.86748231008e-06,2
3159,134.812591553,184.91859436,531.439208984,269.763793945,4.9377590905e-07,2
3159,760.162597656,166.481231689,476.437255859,468.503387451,2.78121348174e-07,2
3159,551.595581055,74.2536621094,479.859985352,303.471374512,1.48180667736e-07,2
3159,1065.83898926,314.981079102,204.258789062,326.364746094,8.80023665051e-08,2
3159,248.040405273,21.629524231,829.945678711,138.450164795,1.37097971864e-08,2
3159,80.3406066895,28.684425354,386.45324707,143.023040771,4.562183617e-09,2
3159,947.76953125,31.7755508423,305.259033203,202.499755859,3.76411957159e-09,2
3159,358.889862061,47.3729171753,382.564605713,221.994903564,1.59999635069e-09,2
3159,1078.03979492,99.2788238525,186.233398438,341.675964355,5.5474613618e-10,2
1,387.461395264,272.173980713,43.5688476562,63.8592529297,0.108503072988,3
1,152.127593994,277.128143311,64.2265625,44.8813476562,0.0766168581322,3
1,226.51335144,153.107879639,31.1640167236,43.1790161133,0.0501157774124,3
1,247.809906006,180.634460449,24.0384521484,21.3278198242,0.0226649455726,3
1,518.350952148,446.070495605,71.6326904297,71.5654296875,0.0222841088544,3
1,506.014434814,452.800079346,38.2752990723,80.2373962402,0.00226600914175,3
1,421.329223633,201.027603149,32.4918823242,24.7145996094,0.000995551727101,3
1,253.987335205,195.959823608,21.352722168,17.3350830078,0.000434513503933,3
1,375.351654053,180.608520508,29.7174682617,29.6880187988,7.9327679714e-05,3
1,194.039138794,145.845596313,40.6948547363,49.4976196289,5.12218832682e-05,3
1,416.31741333,157.50378418,26.3580932617,25.781036377,3.00556763477e-05,3
1,251.972137451,163.274612427,19.8468017578,25.6938781738,2.31373164183e-05,3
1,403.309234619,160.924667358,24.6165771484,22.4505004883,1.56914580884e-05,3
1,385.329711914,156.467712402,17.0793457031,17.9400939941,4.03955411343e-06,3

Now I need to loop over column7 which is 2,3,... and count the filter out others(ex: just keep row contain 2 in columns for a iteration)
Now my solution is to loop over the whole file. However my file is so big that take so many time. Is there any smarter way to do so?

A: Let data be your matrix read/ lodaded from txst file. To pick rows which have 2 in column 7, you can do the following:
col7 = data(:,7) ;
idx = col7==2 ;
iwant = data(idx,:) ;


text:
Q: Querying Two Custom Post Types with OR Not Working I'm trying to query two custom post types - I want all research_article to return, but only events that are in the future. My events are working as expected, but I'm not getting any research_article posts appearing. What's going wrong here?
$today = date( 'Y-m-d' );
        $args = array(
            'post_type'   => array('research_article', 'events'),
            'meta_key'    => 'wpcf-date_time',
            'post_status' => 'publish',
            'orderby'     => 'meta_value',
            'order'       => 'DESC',
            'meta_query' => array(
                array(                    // THIS ONE WORKS
                'key' => 'wpcf-date_time',
                'value' => $today,
                'compare' => '>=',
                'type' => 'DATE',
                ),
                array(
                  'key'      => 'pub_date', // THIS DOESNT WORK
                  'compare'  => 'EXISTS'
                ),
                'relation' => 'OR',
            )
             );

A: So the issue seemed to be with my second meta_query array - instead of checking if pub_date EXISTS, I decided to check if wpcf-date-time DOESNT EXIST:
$today = date( 'Y-m-d' );
        $args = array(
            'post_type'   => array('research_article', 'events'),
           'posts_per_page' => 10,
            'post_status' => 'publish',
            'orderby'     => 'meta_value date',
            'order'       => 'DESC',
            'meta_query' => array(
                array(
                'key' => 'wpcf-date_time',
                'value' => $today,
                'compare' => '>=',
                'type' => 'DATE',
                ),
                array(
                  'key'      => 'wpcf-date_time',
                  'compare'  => 'NOT EXISTS'
                ),
                'relation' => 'OR',
            )
        );


text:
Q: Is a group complement of a subspace of a vector space necessarily a subspace? Let $W$ be a vector space. Let $U$ be a subspace and $V$ be a subgroup of $W$, and assume that $W$ is the direct sum (as groups!) of $U$ and $V$. Does it follow that $V$ is a subspace, such that in fact $W=U\oplus V$ as vector spaces? (In case a counterexample is found, i'd like to see if the answer is the same for finite and infinite dimensional vector spaces?)
Put another way, if $U$ and $V$ are complementary subgroups and $U$ is closed under scalar multiplication, does it follow that $V$ is also closed under scalar multiplication?
I can't see a particular reason why this should be the case, but at the same time I can't seem to find a counterexample, so here we are.... As a related example, considering $\Bbb C$ as a complex vector space, we have $\Bbb C = \Bbb R \oplus i\Bbb R$ as groups, but neither of these subgroups are subspaces, so it's not applicable.

A: To do things the proper way, let me flesh out the solution in the comments as an answer.
The idea suggested is to consider a field extension $K/F$ and a vector space $W$ over $K$ (which thereby also can be viewed as a vector space over $F$). Then choose $U$ as a $K$-linear subspace and $V$ as an $F$-linear complement. In general (probably always?), there are many choices for $V$ that are not $K$-linear, which means we get a solution to the problem.
Concrete example: Take $W=\Bbb C^2$, $U=\{(z,0)\mid z\in\Bbb C\}$, $V=\{(\alpha, \alpha+i\beta)\mid \alpha,\beta\in\Bbb R\}$.


text:
Q: Separate hashes from array? I am using google charts api with RoR 4.  I have this json data to populate my chart rows
rows: [
  {c: [{v: "Week 1"}, [{v: 0}, {v: 3}, {v: 1}]]},
  {c: [{v: 0}]},
  {c: [{v: 0}]},
  {c: [{v: 0}]}
]

notice after the week 1 object another array of hashes(eg. [{v: 0}, {v: 3}]).
Is there anyway to remove the containing array to format the json properly
{v: 0}, {v: 3}, {v: 1}
I have tried using numerous methods(inject,map,etc.) and have not been able to remove the containing array.
 values = first_count.inject({}){|h,k| h[k] = 'v'; h}

I am formatting the data ruby and passing it to my chart via ajax.

A: Is this what you meant?
rows = {
  rows: [
        {c: [{v: "Week 1"}, [{v: 0}, {v: 3}, {v: 1}]]},
        {c: [{v: 0}]},
        {c: [{v: 0}]},
        {c: [{v: 0}]}
    ]
}

rows[:rows][0][:c].flatten!

which leaves rows with the value:
{
  rows: [
        {c: [{v: "Week 1"}, {v: 0}, {v: 3}, {v: 1}]},
        {c: [{v: 0}]},
        {c: [{v: 0}]},
        {c: [{v: 0}]}
    ]
}


text:
Q: Using Regula-Falsi to determine the solution to a non-linear system Apologies, for this isn't a field or subject I know much about.
Regula Falsi (I believe some may know this as "double false position" or something like this) can be used trivially, of course, to determine the root of some arbitrary non-linear equation (forgoing some special cases, other details...). How might Regula Falsi be applied to the solution of a non-linear system, provided we can assume such a solution exists?
It seems like such a simple thing, and I know that it can and has been done, yet I cannot find any literature on this, nor can I quite ascertain how one might go about doing this nor why it works.


text:
Q: Rational points on a weighted projective surface The equation
$$\displaystyle y^2 = f(x_1, x_2, x_3)$$
with $f$ a non-singular quartic form in three variables defines a del Pezzo surface of degree 2. I am interested in the similar construction
$$\displaystyle y^2 = f_1(x_1, x_2, x_3) f_2(x_1, x_2, x_3)$$
where $f_1, f_2$ are quadratic forms defined over $\mathbb{Q}$. Is there anything known about the study of rational points for such surfaces in the weighted projective space $\mathbb{P}(1,1,1,2)$?


text:
Q: What is the maximum markers quantity in the Leaflet library on a standard browser? I'm using Leaflet on standard conditions, let's say Firefox on a usual PC.
What is the maximum markers quantity it can display at the same time?
I don't need an exact number, just to know capabilities, is near the 1000 dots, near 10.000 or can it display 100k without problems?

A: I guess the border is something like 1000 as it's getting hard for browsers to deal with huge amount of smal object instances. For example, if you load hundrets of point objects from a KML it's getting pretty slow at every JS webmap framework.
A better way to deal with that problem is to use server side components to filter the objects. For example stream simplified layers for low zoomlevels and just stream the nessary objects within your current map view via a bbox filter strategy.


text:
Q: Dynamically created element width overflows I am giving dynamically created element a width but it overflows.
Also if i give overflow:hidden;, it does not show all the text i wrote or copied there.
Tried max-width in my code.
JSFIDDLE
Basically; how can i get text with a specific px  without overlapping ?
Here how it looks like;

HTML
<input type="text" id="text" />
<input type="submit" id="add" value="add" />

SOME JS (used h1 element when i append)
$("#add").click(function() {
var val=$("#text").val();
$("#text").val('');
var item ="
"+val+'
x
'+"
";

$("#list").append(item);
});

CSS
#list {
  border:1px solid #333;
  width:300px;
}
#list h1 {
  position:relative;
  border:1px solid #333;
  max-width:300px;
  min-width:300px;
}
#list p {
  color:red;
  position:absolute;
  right:0;
  top:-35px;
}

A: If there will be no space between the word you are entering then obviously it will come in one line and overflow for this situation you can use a css property word-break:break-all

word-break property breaks the word according to the space available in parent div weather there is space in word or not

#list h1 {
  position:relative;
  border:1px solid #333;
  max-width:300px;
  min-width:300px;
  word-break:break-all;
}

Check this example : https://jsfiddle.net/gc8wto1j/12/

A: You can try this one
#list h1 {
    border: 1px solid #333;
    max-width: 300px;
    min-width: 300px;
    overflow: hidden;
    position: relative;
    text-overflow: ellipsis;
    word-break: keep-all;
}


text:
Q: Node Canvas context filters don't do anything in NodeJS When trying to use canvas to blur an image of text in NodeJS, it simply does nothing.
This is an example of a Discord bot that's supposed to return a blurred image of the text "Hello World" in SansSerif, but what it actually returns is this
    //create canvas and context
    let cnvs = canvas.createCanvas(740, 260)
    let ctx = cnvs.getContext('2d')

    //set the context filter to blur
    ctx.filter = 'blur(10px)';
    //set the context font to sans serif size 48
    ctx.font = '48px serif';
    //add the text on the image
    ctx.fillText('Hello world', 50, 100);

    //send the image as a message attachment
    message.channel.send({files: [{ attachment: cnvs.toBuffer() }]}).catch(allerrors)

None of the other context filters work either, all return the exact same image.
I don't get any errors or warnings, it acts as if everything worked as intended.
Does anyone know what could cause this?
Is there another workaround for turning an image grayscale, changing the hue or blurring it?


text:
Q: Gradle mongo dependency I am using mongo dependency using gradle
But getting exception:
Could not resolve: org.mongodb:mongodb-driver:3.6.3
Could not resolve: org.springframework.data:spring-data-mongodb:2.0.6.RELEASE
Could not resolve: org.mongodb:mongo-java-driver:3.6.3

My Gradle file look like below :
repositories {
    mavenCentral()
}

configurations.all {
   exclude group: "commons-logging", module: "commons-logging"
}

dependencies {

    compile 'org.mongodb:mongodb-driver:3.6.3'
    compile 'org.springframework.data:spring-data-mongodb:2.0.6.RELEASE'
    compile group: 'org.mongodb', name: 'mongo-java-driver', version: '3.6.3'

    testCompile("org.testng:testng:${testNGVersion}")
    testCompile("junit:junit:${jUnitVersion}")
    testCompile("org.mockito:mockito-core:${mockitoVersion}")
}

Can someone please help me why I am getting above exception.

A: Simply go to https://start.spring.io/, choose Generate a 'Gradle Project' with 'Java' and whatever Boot version you want, type mongo in the "Search for dependencies" and download the project.

A: Add below dependency code in build.gradle file and re-build project.
   dependencies {
          implementation 'org.springframework.boot:spring-boot-starter-data-mongodb'
    }


text:
Q: problem with the injection of an EJB that resides in a jar I have some problems regarding the EJB injection and I haven't been able to find a solution anywhere.
My situation is the following: I have an EAR file that includes a WAR and several JARs, all listed in the application.xml file. All is working fine for this part.
The problems come out when I try to add what we can call a "plugin system".
I have a JAR with inside some .xhtml pages, backing beans and EJBs. This JAR, if needed, is inserted inside the EAR in a specific directory (let's call it "plugins") and is detected from the application at startup.
When the JAR is detected it's path is added to the WAR class loader so all the pages and the backing bean are detected without problems. What is not working is the injection of the EJBs (I tried to use the notation @EJB, @Inject, the lookup...). I can't inject any of the EJBs that is inside the JAR plugin.
My guess is that the application server treats the JAR as a simple library module and doesn't look for any EJB inside it, so they are inside the JAR but not usable from the application.
My question is: there's a way of having this working? I tried to add the JAR in the EAR's MANIFEST.MF but nothing changed...

the application server i'm using is glassfish 3.0. About the application.xml: there's no reference in it about the JARs that are part of what i called "plugin system". This because i detect them when i deploy (or i restart) the application in the application server, so they may or may not be inside the system and i don't really know that before the system is started.
Each plugin JAR is a "collection" of pages and functionalities that can be added or removed from the system dynamically (more less like a real plugin system).
My EAR structure is the following:
MyApp.EAR

*

*META-INF

*lib

*plugins

*

*plugin1.JAR

*app.WAR

*logic1.JAR

*logic2.JAR

for example: in the application.xml i have the references for app.WAR, logic1.JAR and logic2.JAR (they are always inside the system), at startup the application looks inside the folder "plugins" for any plugin (specific JARs) to be added to the system.
I hope i've been more clear about what i'm trying to do...

A: It seems that the EJB are not even registered in the JNDI tree of the server. Which application server are you using? You can have a look to this JNDI tree to see if the EJBs are there, but the way to do this depends on the specific server.
How are you declaring the JAR that contains the EJBs in the EAR application.xml?
It should be someting lide this:
<application>
  ....
  <module>
    <ejb>nameOfTheJarFile.jar</ejb>
  </module>
</application>

The Jar should be in a the "/lib" directory of the EAR.
I hope this helps.


text:
Q: flash media server (FMS) reattach camera to new stream I'm using flash media server and trying to record the stream but having a problem as I've outlined below. Thanks for taking the time to read this post.
How do I detach my camera from one stream and attach it to a new stream? What I'm trying to do is record the camera stream for 10 seconds and then play it live on a different stream..I try to netstream.close and then netstream.attachCamera(cam0) but it won't let me attach it to the second new stream. What's wrong?

A: You dont have to close the stream. You can use the attachCamera method with a null argument.
netstream.attachCamera(null);


text:
Q: Python: Do we really need wrappers for decorators? (Revisited) A similar question has been asked, but the OP compares the wrapper to a function without return, thus the answers focus on that "fault".
I understood decorators and why we use them instead of sub-classes after reading this article. There, they write the following example in which they introduce the need of the wrapper:
def uppercase_decorator(function):
    def wrapper():
        funct = function()
        make_uppercase = funct.upper()
        return make_uppercase

    return wrapper

Yet, I can write "the same thing" (I'm expecting you to say it is not), this way:
def uppercase_decorator(function): #previously 'function' was called 'message' but 'function' is clearer for comparison.
    make_uppercase = function().upper
    return make_uppercase

Both versions could be applied to this fn, resulting in the same output ('HI ALL!') when calling salute():
@uppercase_decorator
def salute():
    return 'Hi all!'

If main fn returns a random string (thanks to @wim for suggestion) one can notice that every time it runs it, the one without wrapper always returns the same thing when running the sayGarbage() line:
def decorateIt(fn):
    toUpper = fn().upper
    return toUpper

def decorateW(fn):
    def wrapper():
        funct = fn()
        toUpper = funct.upper()
        return toUpper
    return wrapper

import random, string

@decorateIt
def sayGarbage():
    return "".join(random.choice(string.ascii_lowercase) for i in range(6))

sayGarbage()

Why is that so?

A: Let's look what happens here:
def uppercase_decorator(message):
    make_uppercase = func().upper
    return make_uppercase

@uppercase_decorator
def salute():
    return 'Hi all!'

*

*Firstly, uppercase_decorator gets defined.

*Secondly, salute gets defined.

*Thirdly, uppercase_decorator gets called, passing in the function object salute in the place of the first positional argument (message).

At this point, the code will crash, because func() gets called and that was not defined anywhere.  If it worked in your Python REPL session, then you must have had the name func lying around in global scope from earlier, and so the code only appeared to work by coincidence.

Do we really need wrappers for decorators?

No. It is possible to write decorators in a nicer "closureless" style like you suggest.  To write a decorator without the nested function, you can use the popular library decorator.py.  It works like this:
from decorator import decorator

@decorator
def uppercase_decorator(func, *args, **kwargs):
    result = func(*args, **kwargs)
    return result.upper()


text:
Q: How can I place Gedit's tab close buttons on the left? I would like to make Gedit fit more to the Ubuntu default themes Ambiance and Radiance. Therefore I would like to place the tab close buttons on the left instead of the right of each tab.
I asked a similar question about Firefox, but the best answer was adding an extension. So what can I do for Gedit ?
Besides, I bet I will shortly ask equivalent questions for Nautilus, etc.

A: During the Ayatana discussion in this bug report, tab placement inconsistency in the design was mentioned 115 times, in over 20 separate posts, throughout the near-800 comments, but the final decision was still to move window buttons to the left.
If you desire consistency, you're far better moving the window buttons back to the right using one of the many methods described in that bug report.  For example, use gconftool-2 --set /apps/metacity/general/button_layout --type string ":minimize,maximize,close" or add the PPA outlined in comment 792.
However, you've already fixed Firefox with a plug-in, and hopefully someone can help you hack Gedit.  That leaves the list of "to-do", for me personally, at :
Nautilus, Pidgin/Empathy, Thunderbird, Chromium and Eclipse
Bottom line, re-designing all these apps will take time.  I doubt the work will be complete for Natty, but perhaps we'll start to see some consistency by Natty+1.
I realise that this "answer" isn't going to help you.  I raise it simply to make you aware of the scope of the task you've undertaken here.

A: Ubuntu Tweak can handle the position of the titlebar buttons. Nevertheless, the close icon for the tabs in gedit seems not to be affected directly by the changes made by the window titlebar buttons layout.
However, Here I place a screenshot for you to find a tip on how to change the orientation of these buttons in all the applications (including firefox, nautilus, etc.)
Good luck in your quest!
Here is the screenshot:


text:
Q: Get "client info is null" with MSAL 1.1.0-preview I have some code that was working on MSAL 1.1.0-alpha307, but on 1.1.0-preview it throws exception "client info is null", which is returned in the HTTP response. The app is registered in the AAD V2 endpoint and it gets MS Graph data. From the stack trace below, it looks like its able to get the token for Graph but not able to cache it.
Can anyone suggest a diagnosis/fix/workaround?
This is the code:
var bootstrapContext = ClaimsPrincipal.Current.Identities.First().BootstrapContext as BootstrapContext;
UserAssertion userAssertion = new UserAssertion(bootstrapContext.Token);
ClientCredential clientCred = new ClientCredential(ConfigurationManager.AppSettings["ida:Password"]);
ConfidentialClientApplication cca =
                    new ConfidentialClientApplication(ConfigurationManager.AppSettings["ida:ClientID"],
                                                      "https://localhost:44355", clientCred, null, null);
string[] graphScopes = { "Files.Read.All" };
AuthenticationResult result = await cca.AcquireTokenOnBehalfOfAsync(graphScopes, userAssertion, "https://login.microsoftonline.com/common/oauth2/v2.0");

This is the stack trace:
{"Message":"An error has occurred.","ExceptionMessage":"client info is null","ExceptionType":"Microsoft.Identity.Client.MsalClientException","StackTrace":"   at Microsoft.Identity.Client.Internal.ClientInfo.CreateFromJson(String clientInfo)\r\n   at Microsoft.Identity.Client.Internal.Requests.RequestBase.SaveTokenResponseToCache()\r\n   at Microsoft.Identity.Client.Internal.Requests.RequestBase.PostTokenRequest()\r\n   at Microsoft.Identity.Client.Internal.Requests.RequestBase.<RunAsync>d__33.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at Microsoft.Identity.Client.ConfidentialClientApplication.<AcquireTokenOnBehalfCommonAsync>d__16.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at Microsoft.Identity.Client.ConfidentialClientApplication.<AcquireTokenOnBehalfOfAsync>d__3.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n   at Office_Add_in_ASPNET_SSO_WebAPI.Controllers.ValuesController.<Get>d__0.MoveNext() in D:\\repos\\Office-Add-in-ASP.NET-SSO\\Complete\\Office-Add-in-ASPNET-SSO-WebAPI\\Controllers\\ValuesController.cs:line 46\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Threading.Tasks.TaskHelpersExtensions.<CastToObject>d__3`1.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Filters.AuthorizationFilterAttribute.<ExecuteAuthorizationFilterAsyncCore>d__2.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()"}

A: This turned out to be a bug in Azure Active Directory V2.0 endpoint. It is fixed.