text:
Q: Await fetch not working as expected in Javascript Why output from code below is  Promise {<pending>} instead of Response.
What I doing wrong? Also await fetch("https://...") not working.
function asynchronousFunction() {
  return fetch("https://thatcopy.pw/catapi/rest/")
}

const mainFunction = async () => {
  const result = await asynchronousFunction()
  return result;
}
console.log(mainFunction())

A: You shouldn't think of Promises and async functions (which return Promises) as something you can use to return a value at top-level. It's usually a bad idea that comes from the imperative and synchronous programming mindset.
Use chaining instead, either move the console.log inside mainFunction, or write this:
asynchronousFunction()
  .then(console.log)


text:
Q: No validator could be found for constraint 'javax.validation.constraints.NotEmpty' error in JBOSS i have a SpringBoot version '2.3.9.RELEASE' application.
Jboss version: jboss-eap-7.1
successfully deployed the application to jboss. when i try to login through my web application, an error occured.
No validator could be found for constraint 'javax.validation.constraints.NotEmpty' validating type 'java.lang.String'. Check configuration for 'emailAddress'

validation class is as below
@Getter @Setter public class Login  {
@NotEmpty(message = "Please enter email address.", groups = ValidationOrder.Step1.class)
private String emailAddress;

@NotEmpty(message = "Please enter password.", groups = ValidationOrder.Step1.class)
private String password; }

I have added "jboss-deployment-structure" to 'WEB-INF' directory.
<jboss-deployment-structure>
   <deployment>
      <exclusions>
         <module name="javax.validation.api" />
      </exclusions>
   </deployment>
</jboss-deployment-structure>

pom.xml
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <exclusions>
        <exclusion>
            <artifactId>tomcat-embed-websocket</artifactId>
            <groupId>org.apache.tomcat.embed</groupId>
        </exclusion>
        <exclusion>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-tomcat</artifactId>
    <scope>compile</scope>
    <optional>true</optional>
    <exclusions>
        <exclusion>
            <artifactId>tomcat-embed-websocket</artifactId>
            <groupId>org.apache.tomcat.embed</groupId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>7.0.1.Final</version>
    <type>jar</type>
</dependency>
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.16.16</version>
</dependency>
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.5</version>
    <type>jar</type>
</dependency>
<dependency>
    <groupId>javax.validation</groupId>
    <artifactId>validation-api</artifactId>
    <version>2.0.1.Final</version>
</dependency>

Error still remains. An idea?
Its working fine in Netbeans 8.2 + Apache Tomcat

A: You should use spring-boot-starter-validation instead of adding the libraries.
So remove:
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>7.0.1.Final</version>
    <type>jar</type>
</dependency>
<dependency>
    <groupId>javax.validation</groupId>
    <artifactId>validation-api</artifactId>
    <version>2.0.1.Final</version>
</dependency>

Add:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

Also remove the version of lombok. This is already defined by the spring boot parent

redpajama_set_name: RedPajamaStackExchange


text:
Q: $1 = 0$ by using $f(x) = e^{x}$? Let $f(x) = e^{x}$. Then $f(-x) = e^{-x} = \frac{1}{e^{x}} = \frac{1}{f(x)}$ and $$f(x+y) = e^{x+y} = e^{x} \cdot e^{y} = f(x) \cdot f(y)$$
Then by using the rules for differentiating real functions: $$f'(x) = e^{x} \Rightarrow f'(0) = e^{0} = 1$$
But $$f'(0) = f'(x-x) = (f(x-x))' = (f(x)\cdot f(-x))' = 1' = 0$$
So $$1 = 0$$ What went wrong?

A: The error is where you say $f'(x-x) = (f(x)\cdot f(-x))'$; that's simply not so.
A simpler version of the same error:  Say $f(x)=x^2$. Then $f'(2)=4$, but $(f(2))'=4'=0$.

A: The problem is changing where the derivative is taken. On the left, you evaluate the derivative at $0$. On the right, you're evaluating the function (which gives $1$), then taking the derivative, which gives $0$.

A: There is nothing special about f(x)=e^x.
The problem with $$f'(0) = f'(x-x) = (f(x-x))' = (f(x)\cdot f(-x))' = 1' = 0$$
is that $f'(0)$ is not the same as $(f(0))'.$
Note that if your function is $f(x)=\sin(x)$, then $f'(0) =\cos(0)=1$ but $(f(0))' = 0'=0$
Regardless of the function f(x), $f(0)$ is a real number not a function.
Thus when you take derivative of $f(0)$, you always get $0$ regardless of what f(x) is.


text:
Q: How to build a javascript object with key/value format I have a series input tag like
<input id="t1" value="1">
<input id="t2" value="2">
<input id="t3" value="3">

then I want build a javascript object as id/value format,like :
input:
{
   ["t1",1]
   ["t2",2]
   ["t3",3]
}

how can I achieve that?with which function or method?with Array?

A: The object you describe is invalid. Assuming you mean:
{
   "t1":1,
   "t2":2,
   "t3":3
}

Just loop over the elements, and examine the id and value properties to get the data.
var inputs = document.getElementsByTagName('input');
var ob = {};
for (var i = 0; i < inputs.length; i++) {
  var input = inputs[i];
  ob[input.id] = input.value;
}

A: Your output object makes no sense, it's an object with no keys.  Assuming what you really want is:
{
    "t1": 1,
    "t2": 2,
    "t3": 3
}

You could do something like this and inputVals will contain the above object:
var inputs = document.getElementsByTagName('input'),
    inputVals = {};

for (var i = 0, il = inputs.length; i < il; i++) {
    inputVals[inputs[i].id] = inputs[i].value;
}

A: jQuery serializeArray goes a long way to get what you want.
http://api.jquery.com/serializeArray/
It doesn't return exactly the array format that you present in the question, but it should give you something to work with.


text:
Q: How do I redirect a page in php I'm having difficulties in the making the logout code for php to work.
When I click on the logout button, it will go back to the home page, but when I click on the back button in the browser. I can still access the previous page, wherein the user must be logged on to access it.
So I'm thinking of redirecting to the login page when the user clicks on the back button on the browser.
This is my code, in the home page(where in no user is logged in yet. This page is being called by a logout link on the user page.
   <?
session_start();
session_destroy();
?>

<form name="form1" method="post" action="checklogin.php">

Member Login

Username
:
<input name="myusername" type="text" id="myusername">

Password
:
<input name="mypassword" type="text" id="mypassword">

<input type="submit" name="Submit" value="Login">

</form>

A: <?php header('Location:'. $myurl);exit;?>

Should do the trick to redirect assuming nothing has been sent to the browser.
But your problem is more about checking if the user have the right credential for this page. After the session_start(), you should check if a user is present in the session.
For example when the user logging, put something in the session to identify your user:
<?php $_SESSION['user_id'] = $userid; ?>

When you want to access any page which requires a user to be logged:
<?php if (empty($_SESSION['user_id)) { header('Location: /');exit;} ?>

so if the user_id is not present in the session, you user is not logged, thus redirect him to the homepage.
You should also not destroy the session after creating it. Destroying the session should only been done when the user sign out. but session start should be done all the time (just easier that way)

A: In your sign out page just unset $_SESSION['user_id'] before you can redirect it to the home page.
unset($_SESSIOM['user_id']);

Then in all other pages which requires user to login first just check if the user_id for the session is set if its not set just redirect them back to the home page, just like stunti told in above comment

A: The spaces before the script start will break the "Location" method proposed by stunti.
   <?
^^^

Be careful and remove them.


text:
Q: Ways to visualize the real numbers? I was just wondering if there are any diagrams for visualizing subsets of the real numbers, or totally 'radically' different ways of looking at them as a real line? The model of the line relies on order - which is great for intervals, but you can hardly draw the cantor set on there.
This got me thinking - a set with zero measure but same cardinilty as any interval; the image does not represent that 'length' (i.e. intervals) and 'size' (i.e. cardinilty) are well represented on the picture.
Before this seems like a stupid question, I would like to add it isn't impossible to try to visualize infinite sets; for instance, I think of the power set of $ \mathbb N $ as the graph of all functions with domain being the natural numbers and image 0 or 1. Okay, this doesn't say much about it's cardinilty from the diagram but it's trivial to prove the sequences of 0 and 1's are uncountable (similarly you could argue as the Cantor set is homemorphic to the set of sequences you can visualize it similarly, but I'm not so keen on that).
Thanks for the replies sorry if this goes nowhere, but the responses are usually illuminating on all SE threads.

A: Stephen Brooks has a website that has a way to visualize Transfinite Number Line


text:
Q: Maximum size of abandonable codes Consider a keypad which accepts fixed-length numeric sequences from $b$ symbols and maps them uniquely to a set of actions. What is the largest set of actions which can be mapped for a given length of key $n$, subject to them being abandonable. Abandoning a code means that after entering a number of characters $k<n$, the enterer may completely forget that they were entering a code and start another. The partially entered code has no effect, the one which is completed acting as if not prefixed.
This is clearly related to the issue of synchronisaiton and is, I suppose, a very tight bound on a self-synchronising prefix code. No special "abandon" sequence is permitted, as the enterer has no knowledge of any earlier entry. They must also be prefix codes, ie completion be implicit in the sequence. Within these constraints, what is the maximum number of valid codes?
From what I can see, for $b=2$, there is a trivial code with $n=1$ mapping to two actions which cannot be extended to larger $n$.
For larger numbers of symbols, the obvious approach, which is easily analysed, is to reserve one symbol as valid only for the initial character of a code. For example, with $b=10$, $n=3$, we can insist the first character is $1$ and so have $(b-1)^2 = 81$ codes. For example the sequence $1213121156$ would map to $156$ and $141912317178$ would map to actions $123, 178$. By simple extension, $m<b$ such codes can be reserved for the initial character, giving $m(b-m)^2$ codes, but this is clearly optimal when $m=1$.
I'm sure there is a clever procedure which can exceed $(b-1)^{(n-1)}$?


text:
Q: Проблема с Gradle при установке Android Studio в оффлайн режиме Установил portable версию Android Studio на свой рабочий ПК, на котором нет выхода в интернет. При открытии проекта сразу же выскакивает проблема с Gradle - Gradle project sync failed.
Полностью ошибка выглядит так:
A problem occurred configuring root project 'My Application'.
> Could not resolve all artifacts for configuration ':classpath'.
   > Could not resolve com.android.tools.build:gradle:4.2.1.
     Required by:
         project :
      > No cached version of com.android.tools.build:gradle:4.2.1 available for offline mode.
      > No cached version of com.android.tools.build:gradle:4.2.1 available for offline mode.
   > Could not resolve org.jetbrains.kotlin:kotlin-gradle-plugin:1.5.0.
     Required by:
         project :
      > No cached version of org.jetbrains.kotlin:kotlin-gradle-plugin:1.5.0 available for offline mode.
      > No cached version of org.jetbrains.kotlin:kotlin-gradle-plugin:1.5.0 available for offline mode.

Possible solution:
 - Disable offline mode and rerun the build

Насколько я понял из лога ошибки No cached version of..., дело в том, что в файле build.gradle находятся ссылки, к которым, естественно, без интернета доступа нет. Подскажите, пожалуйста, как решить эту проблему? Возможно, надо вставить в build.gradle не адрес в интернете, а найти нужные файлы, скачать и разместить в build.gradle путь к ним?
Всё происходит в оффлайн режиме Gradle.
Сам build.gradle:
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    ext.kotlin_version = "1.5.0"
    repositories {
        google()
        maven {
            url 'https://maven.google/com'
        }
    }
    dependencies {
        classpath "com.android.tools.build:gradle:4.2.1"
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        maven {
            url 'https://maven.google/com'
        } // Warning: this repository is going to shut down soon
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}


text:
Q: Facebook Open Graph Object Link to Facebook App I'm building a Facebook canvas app which makes use of Open Graph. So for example the app pulls in content from http://www.mysite.com/ Say the action posted to the timeline as "Duncan completed MyObject on My App"
Clicking My App opens the app page on Facebook. However clicking the MyObject link opens the actual page where all my meta data is added outside of Facebook www.mysite.com
I really just want both links to open the app in Facebook. Am I missing a trick here or is my only solution to perform a redirect or something?
I understand I need to get Facebook to parse mysite.com in order to grab meta data. However, setting the og:url to the url of my app doesn't make a difference.

A: I was having the same issue. I ended up making a separate .jsp file which writes all the og: tags in the page, and in the body it only contains:
<script>
    location.href = "<%=redirectUrl%>";
</script>

The redirectUrl variable is a String I calculate from the original requested URL, it is like "http://apps.facebook.com/xxxyyy?myParam=zzz". Of course it can be anything, and in PHP or whatever language you use.
When you post an action to Open Graph, use the page with the redirect as the object URL. Facebook will parse the og tags nicely, and when an actual browser reads the page, it will redirect the user to your Facebook app.

A: I had the same problem, not sure if I was missing something really obvious.
I had a PHP file that followed the example file from Facebook. But when clicking the object on the timeline story, I noticed the following GET parameter: fb_source=timeline_og
So to solve the redirecting issue, I put the following at the top of the file, just inside the PHP tags:
<?php
    if ($_GET['fb_source'] == 'timeline_og') {
        // clicked on link in timeline, so redirect to required URL
        header('Location: REDIRECT_URL_HERE');
    }

(Obviously, replace REDIRECT_URL_HERE with whatever URL you wish to redirect to.)
Hopefully someone will find this useful!


text:
Q: Subscript/superscript characters in rasterVis::levelplot strip labels Can we include subscript/superscript characters in rasterVis::levelplot strip labels?
Consider the following RasterStack, s:
library(rasterVis)
s <- stack(replicate(2, raster(matrix(runif(9), 3))))

The default plot method for Raster* objects allows expressions to be passed to the main argument:
plot(s, main=expression(Something, Something[2]))

With rasterVis::levelplot, strip names are passed via the names.attr argument, but it seems these are coerced to character before eventually being passed to lattice::levelplot with strip.custom(factor.levels = names.attr).
The result is:
levelplot(s, names.attr=expression(Something, Something[2]))

Short of modifying the source, is there a way to use expressions (or otherwise achieve subscript/superscript characters) in strip labels of rasterVis::levelplot?

A: You might think that rasterVis::levelplot was using the code of lattice::levelplot and to an extent that turns out to be the case, but a bunch of data transformation occurs first. The S4-method cannot be seen by using the signature with x="RasterBrick", but rather needs x="Raster".
showMethods("levelplot", classes="RasterStack", includeDefs=TRUE)

getMethod("levelplot", signature=c(x="Raster", data="missing"))

That shows that the code constructing the strips is defined as:
    ....
            strip = strip.custom(factor.levels = names.attr),
    ....

I would have guessed that factor.levels would have been the correct parameter to pass an expression to. There is a coercion step that is causing the failure. So you need to hack the code to allow an expression to make it through. If I comment out the coercion with as.character:
        else {
         # names.attr <- as.character(names.attr)
         if (length(names.attr) != nlayers(object))
             stop("Length of names.attr should match number of layers.")

Using:
setMethod( "levelplot:   {
  function code
  },  signature= c(x="Raster", data="missing"))

And copy two unexported function from rasterVis to the the global environment I get success:
drawMargin <- rasterVis:::drawMargin
constructMargin <- rasterVis:::constructMargin

And pass the uncoerced expressions to 'factor.levels' via names.attr:
png(); print(levelplot(s, names.attr=expression(Something, Something[2])) );dev.off()


text:
Q: What is the error at else statement? What is the problem in the code? When I try to run the code, I have problem in else part. Hope someone can help me to solve this part.

<?php

$first_name="William";
$last_name="Smitch";
$age="22";
$staus="";

if ($age>0 && $age<18);
    {
        $status="Under Age";
    }
    else
    {
        $status="Adult";
    }

function profile ($fnam,$lnam,$age)
{
    echo "My friend is ".$fnam." ".$lnam.", He is ".$age."year old";
}
echo "My name is ".$first_name." ".$last_name."
";
echo "I am ".$age." year old and i m an ".$status."
";
echo "Thank You
";
profile ("Frankie","Jones",20);
?>

The error I am encountering: Parse error: syntax error, unexpected 'else' (T_ELSE) in C:\xampp\htdocs\june2012_d.php on line 16

A: Your problem is the ; after your if-statement.
if ($age>0 && $age<18);
{
    $status="Under Age";
}
else
{
    $status="Adult";
}

It closes the if and thus it won't expect an else. Remove it and it will work.
Hint: $status and $staus are not the same variable ;-)


text:
Q: How to handle leap years when using groupby.shift in Pandas data frame I have a data frame with the following structure:

What I am trying to do is for each [location, date] to have not only the current amount but also the amount from one year ago (NOT 365 days). What I am struggling with here is the leap year handling (For example, 2020). If I had to find the value for 29th of Feb, 2020, it would be 1st of March, 2021.
My main approach goes around groupby.shift
data[f"1_year_ago_amnt"] = (
        data.sort_values("date")
        .groupby("location")["amount"]
        .shift(??365 or 366??)
    )

I've been trying to add some metadata to the data frame related to the fact if current year is a leap one or not

and then have two additional columns (365 days back and 366 days back). But I am not sure this is the right approach. It really depends if current day is before 29th of Feb or after that. I believe there's a more elegant straight-forward way.

A: Short Answer
One trick (both in Pandas and other tabular frameworks supporting groupby) is to group by not only the location column but also the portions of the date that you want to keep in tact. In this case you want to keep the month and day fixed while moving one year backward. This can be accomplished for your DataFrame with something like the following:
(data.sort_values('date')
     .groupby([
         data.location,
         data.date.dt.month,
         data.date.dt.day
     ])
     .amount
     .shift(1))

Diving Deeper
For more complex problems involving variable-length date and time offsets (years, "four business days from now", etc.), Pandas has built-in timeseries offsets that can usually be used alongside groupby, apply, etc. to accomplish your goals.
For example, you can use a DateOffset to make adding years (regardless of whether or not they're leap years) easy.
import pandas as pd

timestamp = pd.Timestamp('2019-03-01 01:02:03')

# Right
print(
    'Date + DateOffset(years=1):',
    timestamp + pd.tseries.offsets.DateOffset(years=1)
)

# Wrong
print(
    'Date + DateOffset:',
    timestamp + pd.tseries.offsets.DateOffset(days=365)
)

The first of the print statements will output 2020-03-01 09:10:11, which is correct, since 2020 is a leap year.
On the other hand, the second matches what you've tried with groupby(…).shift, printing 2020-02-29 09:10:11.


text:
Q: Torque free rigid body Is kinetic energy constant for a rigid body with one fixed point and no torque, if so how to prove it? I'm considering free rotation.

A: There is no change in kinetic energy (translational and rotational) of a rigid body if there is no net force and no net torque on the body.

i am considering torque free precession

I'm not familiar with torque free precession, but according to Wikipedia while angular momentum is a constant the angular velocity vector changes orientation with time. That, however, does not mean that the magnitude of the angular velocity, or rotational speed, changes. If there are no external net forces or net torques acting on the object, then there can be no net work done on the object. Per the work energy theorem the net work done on an object equals its change in kinetic energy.
Since no net work is done on the object undergoing torque free precession, the kinetic energy must remain constant.
Hope this helps.

A: Kinetic energy for rotation is $$K = \frac{1}{2}I\omega^2$$
Since there is no torque, $\omega$ is constant (by Newton's first law for rotations). And if there is no change in the mass distribution, I is constant. This means the kinetic energy, K, is constant.
If the object is also moving through space (not just spinning), you would have another kinetic energy term $\frac{1}{2}mv^2$. If there is a net force then v would not be constant. This would make $\frac{1}{2}mv^2$ not constant, meaning the total kinetic energy $$K_{total} = \frac{1}{2}mv^2 + \frac{1}{2}I\omega^2$$ is not constant.
If there is no net force and no net torque, then $K_{total}$ is constant.

A: First we need to ask ourselves how could the kinetic energy of an object change (considering only mechanical systems)? The answer is that if a force or a torque acts on it, then the kinetic energy will change.
Now if an object is rotating in free space about its centre of mass, it's kinetic energy can change if there is a change in the velocity of the centre of mass. That is, the point about which it is rotating is accelerating due to some external force that is acting at the centre of mass. In this case it's rotational velocity is fixed but not translational.
However if we are fixing one of the ends by means of some constraint, then there is no way to apply force on the rotating object such that the torque is zero. Thus in that case the total kinetic energy will be constant for a pivoted object rotating at fixed velocity.

A: Take the kinetic energy of the body, and measure it at the pivot where there is zero velocity
$$ K=\tfrac{1}{2}\boldsymbol{\omega}\cdot\mathbf{I}_{A}\boldsymbol{\omega} $$
where $\mathbf{I}_A$ is the mass moment of inertia tensor at the pivot.
Now consider the component of MMOI along the rotation axis as
$$ I_A = \boldsymbol{z}\cdot\mathbf{I}_{A}\boldsymbol{z} $$
where $\boldsymbol{z}$ is the direction of rotation. The speed of rotation is $\dot{\theta}$ and thus:
$$\boldsymbol{\omega}=\boldsymbol{z}\,\dot{\theta}$$
As such the kinetic energy is
$$ K = \tfrac{1}{2} I_A \dot{\theta}^2 $$
Now if there is no torques and no forces that do work on the body (only the pivot reaction forces & moments) then the acceleration is zero $\ddot{\theta}=0$ and the speed is constant $\dot{\theta} = \text{(const)}$.
Finally, the component of the MMOI along the rotation axis is also constant since the rotation axis is fixed on the body.
So in the end, the kinetic energy is constant also.


text:
Q: Testing file upload with Flask test client I'm testing two views and both of those views using the FileStorage object to save uploaded files from a post request.
During the tests I don't want to actually save the uploaded storage so I patch the FileStorage.save method using unittest's patch decorator.
Test #1:
@patch.object(FileStorage, 'save')
def test_create_data_file(self, fs_save_mock):
    """Test creation/upload of a data data file."""
    file_storage = FileStorage(
        name='Test Storage', filename='teststorage.ext')
    data = {'file': file_storage}

    rv = self.client.post('/api/data/upload', data=data)
    json_data = rv.get_json()
    datafile = DataFile.query.get(json_data['id'])

    fs_save_mock.assert_called_once_with(
        generate_upload_filepath(file_storage.filename))

Test #2:
@patch.object(FileStorage, 'save')
def test_create_data_file(self, fs_save_mock):
    """Test creation/upload of a data data file."""
    file_storage = FileStorage(
        name='Test Storage', filename='teststorage.ext')
    data = {'file': file_storage}

    rv = self.client.post('/api/data/upload', data=data)
    json_data = rv.get_json()
    datafile = DataFile.query.get(json_data['id'])

    fs_save_mock.assert_called_once_with(
        generate_upload_filepath(file_storage.filename))

One of the views I'm testing looks like this:
@blueprint.route('/upload', methods=['POST'])
@use_kwargs({'file_storage': fields.Field(location='files', load_from='file')})
def upload_datafile(file_storage):
    """Upload a datafile."""
    if file_storage is missing:
        abort(400, 'No file found in the request.')

    filepath = generate_upload_filepath(file_storage.filename)
    file_storage.save(filepath)

    data_file = DataFile.create(filename=file_storage.filename, path=filepath)
    return jsonify(DataFileSchema().dump(data_file).data), 201

It works fine if I run only one of the tests, but when I add the second test the run fails with the following error:
___________________ TestDataFileList.test_create_data_file ____________________

self = <test.test_api.TestDataFileList testMethod=test_create_data_file>
fs_save_mock = <MagicMock name='save' id='268959928'>

    @patch.object(FileStorage, 'save')
    def test_create_data_file(self, fs_save_mock):
        """Test creation/upload of a data data file."""
        file_storage = FileStorage(
            name='Test Storage', filename='teststorage.ext')
        data = {'file': file_storage}

>       rv = self.client.post('/api/data/upload', data=data)

test\test_api.py:469:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
..\venv\lib\site-packages\werkzeug\test.py:840: in post
    return self.open(*args, **kw)
..\venv\lib\site-packages\flask\testing.py:192: in open
    environ = builder.get_environ()
..\venv\lib\site-packages\werkzeug\test.py:588: in get_environ
    stream_encode_multipart(values, charset=self.charset)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

values = [<FileStorage: 'teststorage.ext' (None)>], use_tempfile = True
threshold = 512000
boundary = '---------------WerkzeugFormPart_1534924385.40363360.05943907979559804'
charset = 'utf-8'

    def stream_encode_multipart(values, use_tempfile=True, threshold=1024 * 500,
                                boundary=None, charset='utf-8'):
        """Encode a dict of values (either strings or file descriptors or
        :class:`FileStorage` objects.) into a multipart encoded string stored
        in a file descriptor.
        """
        if boundary is None:
            boundary = '---------------WerkzeugFormPart_%s%s' % (time(), random())
        _closure = [BytesIO(), 0, False]

        if use_tempfile:
            def write_binary(string):
                stream, total_length, on_disk = _closure
                if on_disk:
                    stream.write(string)
                else:
                    length = len(string)
                    if length + _closure[1] <= threshold:
                        stream.write(string)
                    else:
                        new_stream = TemporaryFile('wb+')
                        new_stream.write(stream.getvalue())
                        new_stream.write(string)
                        _closure[0] = new_stream
                        _closure[2] = True
                    _closure[1] = total_length + length
        else:
            write_binary = _closure[0].write

        def write(string):
            write_binary(string.encode(charset))

        if not isinstance(values, MultiDict):
            values = MultiDict(values)

        for key, values in iterlists(values):
            for value in values:
                write('--%s\r\nContent-Disposition: form-data; name="%s"' %
                      (boundary, key))
                reader = getattr(value, 'read', None)
                if reader is not None:
                    filename = getattr(value, 'filename',
                                       getattr(value, 'name', None))
                    content_type = getattr(value, 'content_type', None)
                    if content_type is None:
                        content_type = filename and \
                            mimetypes.guess_type(filename)[0] or \
                            'application/octet-stream'
                    if filename is not None:
                        write('; filename="%s"\r\n' % filename)
                    else:
                        write('\r\n')
                    write('Content-Type: %s\r\n\r\n' % content_type)
                    while 1:
>                       chunk = reader(16384)
E                       ValueError: I/O operation on closed file.

..\venv\lib\site-packages\werkzeug\test.py:96: ValueError
===================== 1 failed, 31 passed in 3.89 seconds =====================

Not sure how to resolve this issue, can anyone of you help me out with this?


text:
Q: $\sin(x)<\cos(x)$ and $\tan(x)<1$ confusion Correct me if I'm wrong but the above inequalities are same right?
But when I solve the first one the solution is
[0 , pi/4) U (5pi/4 , 2pi]
But when i solve other one I get
[0, pi/4) U (pi/2 , 5pi/4) U (3pi/2 , 2pi]
Why?

A: When you divide by a negative number, you flip the inequality symbol, so when $\cos{x} <0$ (note strict inequality), and you divide through by it, you get $\frac{\sin{x}}{\cos{x}} =\tan{x} >1$
The best way to solve the inequality is to sketch the graphs and use points of intersection to work it out.

A: If $x=\frac{4\pi}{3}$, then $\sin(x)=-\frac{\sqrt{3}}{2}<-\frac{1}{2}=\cos(x)$, but $\tan(x)=\sqrt{3}>1$, so no, the two inequalities are not the same.
Furthermore, if $x=\frac{\pi}{2}$, then the first inequality is defined (and false), but the second one is not, and if $x=\frac{3\pi}{2}$, then the first inequality is true, and the second is undefined.

The inequalities are only the same if $\cos (x) > 0$.


text:
Q: dsimport fails to set GeneratedUID for Computers I'm populating machines into our Apple OpenDirectory (running on a 10.5 Server).
My script will output a file like this:
0x0A 0x5C 0x3A 0x2C dsRecTypeStandard:Computers 6 dsAttrTypeStandard:RecordName dsAttrTypeStandard:Comment dsAttrTypeStandard:ENetAddress dsAttrTypeStandard:GeneratedUID dsAttrTypeStandard:Keywords dsAttrTypeStandard:RealName
XXX-1to1-47-Fai:Asset 01015:00\:19\:e3\:3c\:07\:28:1A964A90-ADB1-44D5-BA44-EE3B5C8255CA:1A964A90-ADB1-44D5-BA44-EE3B5C8255CA:XXX-1to1-47-Fai
XXX-1to1-20-Bre:Asset 01012:00\:19\:e3\:3e\:a1\:fb:D3083AFF-8B62-4D74-B483-68BF40F41069:D3083AFF-8B62-4D74-B483-68BF40F41069:XXX-1to1-20-Bre

and then import it, like this:
dsimport -g machines.txt "/LDAPv3/127.0.0.1" "O" -u diradmin -p diradmin_password -y remote_host -yrnm diradmin -yrpwd diradmin_password

For reasons that I do not understand, it fails to import the GeneratedUID field that I set.  Instead, it creates one itself.
When I look at the results like this
dscl -u diradmin -p remote_host -readall /LDAPv3/127.0.0.1/Computers

I get
dsAttrTypeNative:apple-generateduid: 3247AAC8-CB4C-47B0-A97C-167722480C0E
dsAttrTypeNative:apple-keyword: D3083AFF-8B62-4D74-B483-68BF40F41069
dsAttrTypeNative:apple-ownerguid: 9DD42971-FD0D-4232-931C-FB42507B3185
dsAttrTypeNative:apple-realname: XXX-1to1-20-Bre
dsAttrTypeNative:cn: XXX-1to1-20-Bre
dsAttrTypeNative:description:
 Asset 01012
dsAttrTypeNative:gidNumber: 157380
dsAttrTypeNative:macAddress: 00:19:e3:3e:a1:fb
dsAttrTypeNative:objectClass: apple-computer top
AppleMetaNodeLocation: /LDAPv3/127.0.0.1
Comment:
 Asset 01012
ENetAddress: 00:19:e3:3e:a1:fb
GeneratedUID: 3247AAC8-CB4C-47B0-A97C-167722480C0E
Keywords: D3083AFF-8B62-4D74-B483-68BF40F41069
PasswordPlus: ********
PrimaryGroupID: 157380
RealName: XXX-1to1-20-Bre
RecordName: XXX-1to1-20-Bre
RecordType: dsRecTypeStandard:Computers

for the first record, and, the relevant part of the second record is, noting that I made it export the UUID I generated for both the GeneratedUID field and the Keywords field:
GeneratedUID: 13C81E32-F4C6-433F-AB62-54A801E25180
Keywords: 1A964A90-ADB1-44D5-BA44-EE3B5C8255CA

I can manually change the setting using dscl, but, any other time I've set the GeneratedUID (such as for Users and Groups), I have not had a problem.  Any idea why this might be?
[Yes, I know you normally don't care about what the GeneratedUID is.  Knowing it makes it easier for my script to create groups.]

A: I found that if I imported it as specified above, in overwrite mode:
dsimport -g machines.txt "/LDAPv3/127.0.0.1" "O" -u diradmin -p diradmin_password -y remote_host -yrnm diradmin -yrpwd diradmin_password

and then followed that by importing the same file in merge mode:
dsimport -g machines.txt "/LDAPv3/127.0.0.1" "M" -u diradmin -p diradmin_password -y remote_host -yrnm diradmin -yrpwd diradmin_password

that I get the desired results.  It makes me think there is a bug in dsimport.


text:
Q: Не изменяются настройки визуализации Есть процедура, вызывающее окно настроек визуализации
procedure TfmTableData.menusettingsClick(Sender: TObject);
var i : integer;
    fmset : TfmSettings;
begin
  fmSet:=TfmSettings.Create(fmTableData);
  fmSet.edTitleForm.Text:='';
  //fmSettings:=TfmSettings.Create(fmShowData);
for i := 0 to TTableSpec(DBSchema.Tables.FindComponent({fmListOfTables.DisplayTable}databasetable)).Fields.ComponentCount-1 do
begin
  if (TTableSpec(DBSchema.Tables.FindComponent({fmListOfTables.DisplayTable}databasetable)).Fields.Components[i] is TFieldSpec) then
    begin
      fmSet.CheckListBox1.Items.Add(TFieldSpec(TTableSpec(DBSchema.Tables.FindComponent({fmListOfTables.DisplayTable}databasetable)).Fields.Components[i]).FieldName);
      fmSet.CheckListBox1.Checked[i]:=DBGrid1.Columns[i].Visible;
    end;
end;
  fmSet.NameFormOwner:=databasetable;
  fmSet.Cont:=fmTableData;
  fmSet.Show();
end;

Есть также процедура, изменяющая визуализацию окна, для которого было вызвано окно настроек визуализации, которая срабатывает по щелчку на пункте CheckListBox, в результате которого соответствующий столбец таблицы перестает быть видимым
procedure TfmSettings.CheckListBox1ClickCheck(Sender: TObject);
var querystr : string;
    i, j : integer;
    TitleArray : array[0..1000] of string;
    WidthArray : array[0..1000] of integer;
begin
    querystr:='select ';
    for I := 0 to fmTableData.DBGrid1.Columns.Count-1 do
      begin
        TitleArray[i]:=fmTableData{ShowData}.DBGrid1.Columns[i].Title.Caption;
        WidthArray[i]:=fmTableData{ShowData}.DBGrid1.Columns[i].Width;
      end;
    for I := 0 to CheckListBox1.Items.Count-1 do
      begin
         querystr:=querystr+ConvertNameField(CheckListBox1.Items[i])+', ';
      end;
    Delete(querystr, Length(querystr)-1, 1);
    querystr:=querystr+'from '+NameFormOwner;
      {for i := 0 to MainWindow.ComponentCount-1 do
      begin
      if MainWindow.Components[i] is TfmTableData then
          if (MainWindow.Components[i] as TfmTableData) then}

      TfmTableData(Panel1.Owner.Owner).IBQuery1.SQL.Clear;
      TfmTableData(Panel1.Owner.Owner).IBQuery1.SQL.Add(querystr);
      TfmTableData(Panel1.Owner.Owner).IBQuery1.Open;
    for i := 0 to CheckListBox1.Items.Count-1 do
    begin
      if not CheckListBox1.Checked[i] then

      TfmTableData(Panel1.Owner.Owner).DBGrid1.Columns[{CheckListBox1.ItemIndex}i].Visible :=CheckListBox1.Checked[i];
      //not(fmShowData.DBGrid1.Columns[CheckListBox1.ItemIndex].Visible);
    end;
    for j:=0 to fmTableData{ShowData}.DBGrid1.Columns.Count-1 do
      begin
        for i:=0 to CheckListBox1.Items.Count-1 do
          begin
            if TfmTableData(Panel1.Owner.Owner){fmTableData}{ShowData}.DBGrid1.Columns[j].Title.Caption=TitleArray[i] then
              TfmTableData(Panel1.Owner.Owner){fmTableData}{ShowData}.DBGrid1.Columns[j].Width:=WidthArray[i];
          end;
      end;
      //end;
end;

Но в результате визуализация не меняется.столбцы не перестают быть видимыми после отмены выделения соответствующих пунктов в CheckListBox.
Формируется sql запрос с использованием пунктов CheckListBox, который выполняется в окне владельце окна настроек визуализации. Затем в зависимости от состояния соответствующих пунктов CheckListBox соответствующие столбцы перестают быть видимыми. Почему? Помогите устранить ошибку.


text:
Q: React reusable components which method is better to use I want to make some reusable components like modal, autocomplete, popover, etc. But I don t know which approach is better when is about the state

*

*keep the state in redux - the disadvantage that I see in redux is that I must to create a reducer foreach place where I'm using the modal(example)

*keep the state in parent component - the disadvantage is that when for example I press the button to open the modal will re render parent + children.

*keep the state in the component - the disadvantage is that I must to pass everytime the button like props.

Which approach is better? I'm beginner I don't know if this is a dumb question to ask. Thanks!


text:
Q: Generating PDF using fop and XSL when having URLS in XSLT Generating PDF using fop and XSL when having URLS in XSLT
I am generating PDF using FOP 2.0 and XSLT. Here i am getting XSL from web url. my one XSL URL is including and importing other urls of XSLs. If its a single XSL I could able to generate PDF. If i have multiple URLS in one XSLT on Web . The FOP is not able to Connect automatically to other URLS[ Example of using XSLTS]

xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" \
xmlns:fo="http://www.w3.org/1999/XSL/Format" version="1.0">
<xsl:include href="abc.xsl"/>

<xsl:include href="xyz.xsl"/>

<xsl:include href="wgh.xsl"/>

This is the way Its including XSLs in one XSLs. In this Case my FOP is not redirecting to those xsls and couldn't able to generate PDF
ERROR:
SystemId Unknown; Line #3; Column #34; Had IO Exception with stylesheet file: header.xsl
SystemId Unknown; Line #4; Column #34; Had IO Exception with stylesheet file: footer.xsl
SystemId Unknown; Line #5; Column #36; Had IO Exception with stylesheet file: mainbody.xsl
SystemId Unknown; Line #6; Column #41; Had IO Exception with stylesheet file: secondarybody.xsl
SystemId Unknown; Line #10; Column #38; org.xml.sax.SAXException: ElemTemplateElement error: layout
javax.xml.transform.TransformerException: ElemTemplateElement error: layout
13:58:27.326 [http-nio-auto-1-exec-2] DEBUG org.apache.fop.fo.FOTreeBuilder - Building formatting object tree
SystemId Unknown; Line #10; Column #38; Could not find template named: layout
Code for PDF Generator:
public class PdfGenerator {
private static final Logger LOG=LoggerFactory.getLogger(PdfGenerator.class);

public List<OutputStream>  generatePdfs(List<Content> xmlList, int reqestListSize,String xslPath)

{
        try {
    List<OutputStream> pdfOutputStreams= new ArrayList();

    for(int p = 0; p <reqestListSize; p++) {

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        String jaxbType = "com.abc.model"; // model package
        JAXBContext context = JAXBContext.newInstance(jaxbType);
        Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty("jaxb.formatted.output",Boolean.TRUE);
        marshaller.marshal(xmlList.get(p),bos);
        ByteArrayInputStream inStream = new ByteArrayInputStream(bos.toByteArray());
        StreamSource xmlSource = new StreamSource(inStream);
        // create an instance of fop factory
        FopFactory fopFactory = FopFactory.newInstance(new File(".").toURI());
        // a user agent is needed for transformation
        FOUserAgent foUserAgent = fopFactory.newFOUserAgent();

        ByteArrayOutputStream tempOutputStream = new ByteArrayOutputStream();
        Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, tempOutputStream);
        pdfOutputStreams.add(p, tempOutputStream);
        // Setup XSLT
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        URL url = new URL(xslPath);
        InputStream xslFile = url.openStream();  (   **http://home.www.test.com/abc_web/xsl/test.xsl**  ( Using an url to get XSLT. faild loading due to XSL :include) )
        StreamSource xsltStreamSource = new StreamSource(xslFile);
        Transformer transformer = transformerFactory.newTransformer(xsltStreamSource);
        Result res = new SAXResult(fop.getDefaultHandler());
        // Start XSLT transformation and FOP processing
        // That's where the XML is first transformed to XSL-FO and then
        // PDF is created
        transformer.transform(xmlSource, res);
    }
    return pdfOutputStreams;

    }catch(Exception ex) {
        LOG.error("Error", ex);
        return new ArrayList();
    }

A: Simply replace
URL url = new URL(xslPath);
InputStream xslFile = url.openStream();
StreamSource xsltStreamSource = new StreamSource(xslFile);

with
StreamSource xsltStreamSource = new StreamSource(xslPath);

and the XSLT processor should be able to resolve any relative imports or includes.
Or you would need to explicitly set the SystemId on your xsltStreamSource. But the single line I have suggested should do the job just fine.


text:
Q: Criteria for convergence of a sequence in a metric space Let $X$ be a metric space, $z$ be in $X$ and let $(x_n)$ be a sequence in $X$
Using the fact that, Every open subset of $X$ that contains $z$ includes a tail of $(x_n)$,
I have to prove that
$\{z\}=⋂\{\textrm{cl}\{x_n∣n∈S\}∣S⊆\mathbb{N}$ and $S$ is infinite $\}$.
I started off with the proof by letting, $S$ to be an infinite subset of $\mathbb{N}$.
Then $X\backslash\textrm{cl}\{x_n∣n∈S\}$ is an open subset of $X$.
I know that this should not contain a tail of $(x_n)$, because if it would then $z$ would not belong to $\textrm{cl}\{x_n∣n∈S\}$.
What i don't understand is that, how should i show this ? I know this has got something to do with $S$ being infinite, but i just can't relate the two things.

A: You've started off just fine. For convenience let $U=X\setminus\operatorname{cl}\{x_n:n\in S\}$. For future reference note that if $n\in S$, then $x_n\notin U$.
Now suppose that $z\in U$; your hypothesis tells you that $U$ contains a tail of the sequence, so there is an $m\in\Bbb N$ such that $x_n\in U$ for all $n\ge m$. Suppose that $n\in S$; then $x_n\notin U$, so $n<m$. But that means that $S$ is finite, which is a contradiction. Thus, $z\notin U$, and therefore $z\in\operatorname{cl}\{x_n:n\in S\}$.


text:
Q: Blinking TreeView after programatically selected node I have a problem with flickering TreeView. I want first node to be selected after creation of TreeView.
tv.SelectedNode = tv.Nodes[0];

This set this, but also first click on any node in program makes TreeView blink, and after that everything is fine and after next clicks nothing is flickering.
I use BeginUpdate and EndUpdate on MouseDown and MouseUp, and in fact it works, but only after that first click. Without programmatically selecting first node as selected it works well. I have no idea, what makes TreeView blink.
Thanks in advance! Cheers.

A: You can avoid flickering using the TreeView descendant with double-buffered painting enabled:
class DoubleBufferedTreeView : TreeView {
    public MyTreeView() {
        SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, true);
    }
}


text:
Q: Ingress Liveness and Readiness of pods I use 6 separate microservice inside the one kubernetes cluster and  I have Configured Liveness and Readiness Probes also. I used an ingress load balancer to call microservice endpoints.
example:
<ingress_host>/api/auth-server/<api-endpoint>

Our main assumption is When all pods are available then that cluster is working fine.
are there any way to get health endpoint via ingress to check the health of the kubernetes cluster.
I need to config Akamai Load Balancer. For that, I need to expose the health endpoint. That health endpoint need to ensure that all the pods are works or not

A: I dont think that there is any concept such as a healthy cluster , and i am not sure why you would need it. I would suggest an alternative way to check this, write a simple script which will check or keep on checking after regular time intervals if all your pods/microservices are ready , you can use something similar in lines of below which is for checking the nodes but you should be able to do the same for pods.
JSONPATH='{range .items[*]}{@.metadata.name}:{range @.status.conditions[*]}{@.type}={@.status};{end}{end}' \
 && kubectl get nodes -o jsonpath="$JSONPATH" | grep "Ready=True"```


text:
Q: How to search and edit only 'date type' cells in an excel worksheet i have this code
Sub fill()
  Dim rg As Range
  Set rg = Range("a1")
  Set rg = Range(rg, Cells(ActiveSheet.UsedRange.Row + ActiveSheet.UsedRange.Rows.Count - 1, rg.Column))
  On Error Resume Next
  Set rg = rg.SpecialCells(xlCellTypeBlanks)
  On Error GoTo 0
  If Not rg Is Nothing Then
    rg.Value = "1/1/2020"
  End If
End Sub

but it doesn't work as I wanted to.
I need to search in a whole excel worksheet range(a1:bj1223) and check all 'date type' cells. when it finds a cell that is 'date type' and it is empty, i need to add the value "1/1/2020" in this cell.
thank you

A: Is this what you are trying? This will first look for blank cells and then check if each cell in that range is of a specific format "dd/mm/yyyy" Change that as applicable.
Sub Sample()
    Dim rng As Range, aCell As Range
    Dim blnkCells As Range

    Set rng = ThisWorkbook.Sheets("Sheet1").Range("A1:BJ1223")

    On Error Resume Next
    Set blnkCells = rng.SpecialCells(xlCellTypeBlanks)
    On Error GoTo 0

    If Not blnkCells Is Nothing Then
        For Each aCell In blnkCells
            If aCell.NumberFormat = "dd/mm/yyyy" Then aCell.Value = "1/1/2020"
        Next aCell
    End If
End Sub


text:
Q: How many ways are there to create a controller and what are they? I have been developing with Magento 1.9 for the last two weeks. I have found several problems to develop each project (probably because my first project with magento had a high level...).
I come from developing mainly with Yii Framework and sometimes I do not find the way to develop some things which were very easy using Yii.
Using Yii, I could create a controller, add a function actionPage and I could access the controller/page url. However, using Magento, I only have seen that everything is done through a module.
Then I would like to know some real life example about "when I should create a controller with a module". On the other side, I would like to know if there is another way to develop a controller. This is only a theorical question.
Thanks.


text:
Q: Need some assistance trying to parse this JSON response from our backend server Currently working on an android app and I need help on how I can go about extracting the subfields within the responses field of this json object:

Currently I am doing the following to extract some of the other fields:
 JSONObject json = new JSONObject(response2);
 int id = json.getInt("id");
 String desc = json.getString("description");
 JSONObject json2 = json.getJSONObject("owner");
 String username = json2.getString("userName");

A: You need to create logic to parse the data.  Every item from the JSON string is in the JSONObject you created with
JSONObject json = new JSONObject(response2);

You're on the right track with what you're doing.  Just use the corresponding methods available in JSONObject and JSONArray classes to move through the object.
Start with the main object
{                              // <-- this is your main object (AKA JSONObject json = new JSONObject(response2))
    "id": 1,                   // to pull this id use json.getInt("id");
    "title": "some text here",  // to pull this title use json.getString("title");
    ...
    "owner": {                 // Here's the logic part, owner is itself, a JSON object. so now you must extract it and parse through it.
                               // to pull the "owner" JSON object, use JSONObject ownerObject = json.getJSONObject("owner");
        "userId": 1,           // Now use the ownerObject to pull it's values. ownerObject.getInt("userId");
        "userName": "TestingUser",  // to pull this userName use ownerObject.getString("userName");
        ...
    }
...
}

If it's an array, for example:
"someJSONArray": [{ "id": 1, "userName": "TestingUser1" }, { "id": 2, "userName": "TestingUser2" }]

then you would call:
JSONArray someJSONArray = getJSONArray("someJSONArray");
// Get each object from the array.
JSONObject object1 = someJSONArray.getJSONObject(0);
JSONObject object2 = someJSONArray.getJSONObject(1);

or if the array contains a string, for example:
"someKey": [ 23, 435, 123, 6345, 123 ]

then you would call:
JSONArray someKeyArray = getJSONArray("someKey");
for (int i = 0; i < someKeyArray.length(); i++) {
    // Extract the value.
    int itemValue = someKeyArray.getInt(i);
}

The data is there, you just have to parse it.


text:
Q: How to use Chebyshev's inequality and CLT to determine bounds. Was doing practice problems in preparation for an examination. Ran into a problem in a book that requests us to determine the sample size needed to fit the probability of rolling a specific die face (lets say 1) between [0.111111, 0.222222] with 95% confidence interval using CLT and Chebyshev Inequality.
For Chebyshev, what I have so far is
$$Pr\left(|\overline{X} − \mu| < \frac{kx}{\sqrt{n}}\right) \geq 1−\frac{1}{k^2}.$$ I have determined that $k$ must be 4.47 in order to fit into a 95% interval. In which case the inequality would be $<4.47\sigma$. However, I am not sure how to proceed.
For CLT, I am unsure as to how to proceed.

A: Well, you have found $k=\sqrt{20}\approx 4.472135955$.
For one trial the probability of getting 1 on a die is $1/6$. You have $n$ independent random variables $X_1,\ldots,X_n$ where $X_i=1$ is you see the specific die face (1) in $i$-th roll of a die, and $X_i=0$ if the other faces appeared in $i$-th roll. The sum $X_1+\ldots+X_n$ represents total number of times when 1 is shown in $n$ rolls.
Then $$Pr(X_i=1)=\frac16, \quad Pr(X_i=0)=\frac56, \quad E[X_i]=\frac16, \quad Var[X_i]=\frac{1}{6} \cdot \frac{5}{6}$$
Therefore, standard deviation for $X_i$ is $\sqrt{\frac{1}{6} \cdot \frac{5}{6}}=\frac{\sqrt{5}}{6}$ and SD for $\overline X$ is $\sqrt{n}$ times smaller:
$$
\sigma=\frac{\sqrt{5}}{6\sqrt{n}}
$$
And $$\mu=E[\overline X]=E[X_1]=\frac16.$$
We can rewrite Chebyshev inequality as (keep in mind that $k=\sqrt{20}$)
$$
Pr\left(|\overline{X} − \tfrac16| < \tfrac{k\sqrt{5}}{6\sqrt{n}}\right) = Pr\left(|\overline{X} − \tfrac16| < {k\sigma}\right) \geq 1−\frac{1}{k^2}.
$$
Let us compare the desired interval $0.111111\leq \overline X \leq 0.222222$ with interval from Chebyshev inequality $|\overline{X} − \tfrac16| < {k\sigma}$. The value $\mu=1/6=0.166666$ is exactly the middle point of interval $[0.111111, 0.222222]$. Both intervals coincide when ${k\sigma}=0.222222-0.166666=0.055555$:
Finally we can find $n$ from the equation
$$
0.055555=k\sigma=\sqrt{20}\frac{\sqrt{5}}{6\sqrt{n}} \Rightarrow \sqrt{n}=30 \Rightarrow n=900.
$$
Using CLT: with $\sigma=\sqrt{\tfrac{Var[X_1]}{n}}$
$$
Pr\left(|\overline{X} − \mu| < k\sigma\right) \approx \Phi(k)-\Phi(-k)=2\Phi(k)-1
$$
We need $2\Phi(k)-1 = 0.95$, $\Phi(k)=0.975$ and $k=1.96$.
Then solve the equation $0.055555=k\sigma$ again with $k=1.96$
$$0.055555=k\sigma=\tfrac{1.96\sqrt{5}}{6\sqrt{n}}\quad \Rightarrow \quad \sqrt{n}=13.148 \quad \Rightarrow \quad n=172.9
$$
Round to the larger integer value give $n=173$.


text:
Q: How to use pip's version of ipython? I had a system ipython notebook installed on my Ubuntu 14.04 via apt-get. To upgrade the notebook to the newest version, I ran
sudo pip install ipython[notebook] -U

This installed version 3.0.0 of ipython. But when I run ipython, the old version still starts. What is the correct way of using the pip's version?


text:
Q: need guidance in css animation behaviour for multiple transform I did css animation with multiple transform on one element. It behaves differently what i am expecting. So i need guidance in correcting my code to achieve the result. I will add my code below.

.container1 {
  width: 100px;
  height: 100px;
  border: 1px solid black;
}

.stem1 {
  width: 6px;
  height: 50px;
  margin: 0 auto;
  background: #154360;
  animation: stem1-motion 5s linear forwards;
  animation-iteration-count: infinite;
}

.container2 {
  width: 100px;
  height: 150px;
  border: 1px solid black;
}

.stem2 {
  width: 6px;
  height: 50px;
  margin: 0 auto;
  background: #154360;
  animation: stem2-motion 5s linear forwards;
  animation-iteration-count: infinite;
}

.container3 {
  width: 100px;
  height: 150px;
  border: 1px solid black;
}

.stem3 {
  width: 6px;
  height: 50px;
  margin: 0 auto;
  background: #154360;
  animation: stem3-motion 5s linear forwards;
  animation-iteration-count: infinite;
}

@keyframes stem1-motion {
  0% {
    transform: rotate(0.0deg);
    transform-origin: top center;
  }
  8% {
    transform: rotate(-9.98deg);
    transform-origin: top center;
  }
  16% {
    transform: rotate(-17.69deg);
    transform-origin: top center;
  }
  25% {
    transform: rotate(-21.10deg);
    transform-origin: top center;
  }
  33% {
    transform: rotate(-18.38deg);
    transform-origin: top center;
  }
  41% {
    transform: rotate(-11.12deg);
    transform-origin: top center;
  }
  50% {
    transform: rotate(-2.52deg);
    transform-origin: top center;
  }
  58% {
    transform: rotate(9.98deg);
    transform-origin: top center;
  }
  66% {
    transform: rotate(17.69deg);
    transform-origin: top center;
  }
  75% {
    transform: rotate(21.10deg);
    transform-origin: top center;
  }
  83% {
    transform: rotate(18.38deg);
    transform-origin: top center;
  }
  91% {
    transform: rotate(11.12deg);
    transform-origin: top center;
  }
  100% {
    transform: rotate(5.05deg);
    transform-origin: top center;
  }
}

@keyframes stem2-motion {
  0% {
    transform: translateY(0.0px);
    transform-origin: top center;
  }
  8% {
    transform: translateY(5.566199398026136px);
    transform-origin: top center;
  }
  16% {
    transform: translateY(20.887794225945157px);
    transform-origin: top center;
  }
  25% {
    transform: translateY(45.0px);
    transform-origin: top center;
  }
  33% {
    transform: translateY(66.67891533457717px);
    transform-origin: top center;
  }
  41% {
    transform: translateY(82.99475664759068px);
    transform-origin: top center;
  }
  50% {
    transform: translateY(90.0px);
    transform-origin: top center;
  }
  58% {
    transform: translateY(84.43380060197387px);
    transform-origin: top center;
  }
  66% {
    transform: translateY(69.11220577405487px);
    transform-origin: top center;
  }
  75% {
    transform: translateY(45.00000000000001px);
    transform-origin: top center;
  }
  83% {
    transform: translateY(23.32108466542279px);
    transform-origin: top center;
  }
  91% {
    transform: translateY(7.005243352409316px);
    transform-origin: top center;
  }
  100% {
    transform: translateY(0.0px);
    transform-origin: top center;
  }
}

@keyframes stem3-motion {
  0% {
    transform: rotate(0.0deg) translateY(0.0px);
    transform-origin: top center;
  }
  8% {
    transform: rotate(-9.987383695374957deg) translateY(5.566199398026136px);
    transform-origin: top center;
  }
  16% {
    transform: rotate(-17.69548887689718deg) translateY(20.887794225945157px);
    transform-origin: top center;
  }
  25% {
    transform: rotate(-21.10019602409302deg) translateY(45.0px);
    transform-origin: top center;
  }
  33% {
    transform: rotate(-18.38921403145706deg) translateY(66.67891533457717px);
    transform-origin: top center;
  }
  41% {
    transform: rotate(-11.1219360330404deg) translateY(82.99475664759068px);
    transform-origin: top center;
  }
  50% {
    transform: rotate(-2.5260153474725556e-15deg) translateY(90.0px);
    transform-origin: top center;
  }
  58% {
    transform: rotate(9.987383695374957deg) translateY(84.43380060197387px);
    transform-origin: top center;
  }
  66% {
    transform: rotate(17.695488876897173deg) translateY(69.11220577405487px);
    transform-origin: top center;
  }
  75% {
    transform: rotate(21.10019602409302deg) translateY(45.00000000000001px);
    transform-origin: top center;
  }
  83% {
    transform: rotate(18.38921403145705deg) translateY(23.32108466542279px);
    transform-origin: top center;
  }
  91% {
    transform: rotate(11.121936033040393deg) translateY(7.005243352409316px);
    transform-origin: top center;
  }
  100% {
    transform: rotate(5.052030694945111e-15deg) translateY(0.0px);
    transform-origin: top center;
  }
}

I combined both linear and rotate movements in transform. I am expecting top end movement should be linear that is it should flow only in y direction. Your suggestions will help me proceed further.

A: If I am understanding your goal correctly, I think this is what you want. You just have to switch around the translation and the rotation so the translation happens first. The reason is because if you rotate and then translate, you are translating in the direction of the rotation.

.container1 {
  width: 100px;
  height: 100px;
  border: 1px solid black;
}

.stem1 {
  width: 6px;
  height: 50px;
  margin: 0 auto;
  background: #154360;
  animation: stem1-motion 5s linear forwards;
  animation-iteration-count: infinite;
}

.container2 {
  width: 100px;
  height: 150px;
  border: 1px solid black;
}

.stem2 {
  width: 6px;
  height: 50px;
  margin: 0 auto;
  background: #154360;
  animation: stem2-motion 5s linear forwards;
  animation-iteration-count: infinite;
}

.container3 {
  width: 100px;
  height: 150px;
  border: 1px solid black;
}

.stem3 {
  width: 6px;
  height: 50px;
  margin: 0 auto;
  background: #154360;
  animation: stem3-motion 5s linear forwards;
  animation-iteration-count: infinite;
}

@keyframes stem1-motion {
  0% {
    transform: rotate(0.0deg);
    transform-origin: top center;
  }
  8% {
    transform: rotate(-9.98deg);
    transform-origin: top center;
  }
  16% {
    transform: rotate(-17.69deg);
    transform-origin: top center;
  }
  25% {
    transform: rotate(-21.10deg);
    transform-origin: top center;
  }
  33% {
    transform: rotate(-18.38deg);
    transform-origin: top center;
  }
  41% {
    transform: rotate(-11.12deg);
    transform-origin: top center;
  }
  50% {
    transform: rotate(-2.52deg);
    transform-origin: top center;
  }
  58% {
    transform: rotate(9.98deg);
    transform-origin: top center;
  }
  66% {
    transform: rotate(17.69deg);
    transform-origin: top center;
  }
  75% {
    transform: rotate(21.10deg);
    transform-origin: top center;
  }
  83% {
    transform: rotate(18.38deg);
    transform-origin: top center;
  }
  91% {
    transform: rotate(11.12deg);
    transform-origin: top center;
  }
  100% {
    transform: rotate(5.05deg);
    transform-origin: top center;
  }
}

@keyframes stem2-motion {
  0% {
    transform: translateY(0.0px);
    transform-origin: top center;
  }
  8% {
    transform: translateY(5.566199398026136px);
    transform-origin: top center;
  }
  16% {
    transform: translateY(20.887794225945157px);
    transform-origin: top center;
  }
  25% {
    transform: translateY(45.0px);
    transform-origin: top center;
  }
  33% {
    transform: translateY(66.67891533457717px);
    transform-origin: top center;
  }
  41% {
    transform: translateY(82.99475664759068px);
    transform-origin: top center;
  }
  50% {
    transform: translateY(90.0px);
    transform-origin: top center;
  }
  58% {
    transform: translateY(84.43380060197387px);
    transform-origin: top center;
  }
  66% {
    transform: translateY(69.11220577405487px);
    transform-origin: top center;
  }
  75% {
    transform: translateY(45.00000000000001px);
    transform-origin: top center;
  }
  83% {
    transform: translateY(23.32108466542279px);
    transform-origin: top center;
  }
  91% {
    transform: translateY(7.005243352409316px);
    transform-origin: top center;
  }
  100% {
    transform: translateY(0.0px);
    transform-origin: top center;
  }
}

@keyframes stem3-motion {
  0% {
    transform: translateY(0.0px) rotate(0.0deg);
    transform-origin: top center;
  }
  8% {
    transform: translateY(5.566199398026136px) rotate(-9.987383695374957deg);
    transform-origin: top center;
  }
  16% {
    transform: translateY(20.887794225945157px) rotate(-17.69548887689718deg);
    transform-origin: top center;
  }
  25% {
    transform: translateY(45.0px) rotate(-21.10019602409302deg);
    transform-origin: top center;
  }
  33% {
    transform: translateY(66.67891533457717px) rotate(-18.38921403145706deg);
    transform-origin: top center;
  }
  41% {
    transform: translateY(82.99475664759068px) rotate(-11.1219360330404deg);
    transform-origin: top center;
  }
  50% {
    transform: translateY(90.0px) rotate(-2.5260153474725556e-15deg);
    transform-origin: top center;
  }
  58% {
    transform: translateY(84.43380060197387px) rotate(9.987383695374957deg);
    transform-origin: top center;
  }
  66% {
    transform: translateY(69.11220577405487px) rotate(17.695488876897173deg);
    transform-origin: top center;
  }
  75% {
    transform: translateY(45.00000000000001px) rotate(21.10019602409302deg);
    transform-origin: top center;
  }
  83% {
    transform: translateY(23.32108466542279px) rotate(18.38921403145705deg);
    transform-origin: top center;
  }
  91% {
    transform: translateY(7.005243352409316px) rotate(11.121936033040393deg);
    transform-origin: top center;
  }
  100% {
    transform: translateY(0.0px) rotate(5.052030694945111e-15deg);
    transform-origin: top center;
  }
}


text:
Q: Nginx Reverse Proxy, SSL Offloading, Caching, IIS, Wordpress - Redirect 301 loop I'm trying to setup a Nginx Reverse Proxy with SSL Offloading and Caching in front an IIS 10 and WordPress with pretty links, but I'm getting an infinite redirect 301 loop.
My Nginx configuration is almost the same as find in this tutorial, as can be see bellow.
upstream www_iis {
    server 10.10.0.10:8001;
    server 10.10.0.11:8001;
}

server {

    listen 443 ssl;

    server_name exemple.com;

    ssl_certificate /etc/letsencrypt/live/exemple.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/exemple.com/privkey.pem;
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
    include /etc/letsencrypt/options-ssl-nginx.conf;

    set $do_not_cache 0;
    set $skip_reason "";
    set $bypass 0;

    if ($remote_addr ~ "^(127.0.0.1)$") {
        set $bypass $http_secret_header;
    }

    if ($http_cookie ~* "comment_author_|wordpress_(?!test_cookie)|wp-postpass_" ) {
        set $do_not_cache 1;
        set $skip_reason Cookie;
    }

    if ($request_uri ~* "/wp-admin/|/xmlrpc.php|wp-.*.php|/feed/|sitemap(_index)?.xml") {
        set $skip_cache 1;
        set $skip_reason URI;
    }

    location / {
        proxy_redirect off;
        proxy_cache edge-cache;
        proxy_cache_revalidate on;
        proxy_ignore_headers  Expires Cache-Control;
        proxy_cache_bypass $bypass $do_not_cache;
        proxy_no_cache $do_not_cache;
        proxy_set_header Proxy "";
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $host;
        proxy_set_header Connection "";

        proxy_pass http://www_iis;
    }
}

On the IIS side, I only have the pretty links rewrite in web.config.
<rewrite>
  <rules>
            <rule name="WordPress" enabled="true" patternSyntax="Wildcard">
                <match url="*" />
                <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
                    <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
                    <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
                </conditions>
                <action type="Rewrite" url="index.php" />
            </rule></rules>
</rewrite>

In WordPress both, WordPress Address (URL) and Site Address (URL), was defined with the external url (https://exemple.com), and no additional changes on WordPress files.
I'm not getting why this behavior is happening, but I'm assuming there is something about the pretty links rewrite, because on IIS Server when I type the local ip address on url I'm redirected to domain.
Please, can someone clarify to me how to solve this?
Thanks in advance!


text:
Q: Erro ao consumir json utilizando ajax Tenho o seguinte retorno em json:
{
    "ConsultarRegistroPorCodigoResult": {
        "Codigo": 2,
        "CodigoSetor": 1,
        "Login": "ednilson1",
        "Nome": "Ednilson",
        "RegistroAtivo": true,
        "Senha": "123456",
        "Tipo": "D"
    }
}

Do webservice feito em WCF estou usando o seguinte codigo:

<title></title>

<form id="form1">

        <input type="text" id="codUser"/>
        <button onclick="ConsUsuario(); return false;">Consulta Usuario</button>

</form>

Retorna o erro 'Unexpected token u in JSON at position 0', pelo que vi o json esta inválido, como "converto" para um json valido?
O erro ocorre na linha var myData = JSON.parse(result.d), segue a mensagem de erro completa:

(index):1 Uncaught SyntaxError: Unexpected token u in JSON at
  position 0
      at JSON.parse ()
      at Object.success ((index):31)
      at l (jquery.min.js:2)
      at Object.fireWith [as resolveWith] (jquery.min.js:2)
      at T (jquery.min.js:2)
      at XMLHttpRequest.r (jquery.min.js:2)

o retorno da variável result:

Object {ConsultarRegistroPorCodigoResult: Object}

A: O seu retorno JSON parece estar correto, o que não parece é a maneira que você tratando-o.
$.ajax({
  type: "GET",
  url: "ServiceRestPub/ServiceUsuario.svc/ConsultarRegistroPorCodigo/" + value,
  contentType: "application/json",
  dataType: "json",
  success: function(result) {
    debugger;
    var tabela = $("#datagrid");
    var rows = "";
    tabela.find("tbody td").remove();

    var myData = JSON.parse(result.d); // <~~~~~~~~~~~~~~~~~~~~ (1)
    for (var i = 0; i < myData.length; i++) { // <~~~~~~~~~~~~~ (2)
      var obj = myData[i];
      alert(obj.descricao); // <~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ (3)

      rows += "
";
      rows += " " + obj.id_usuario + "	"; // <~~~~~~~~~ (3)
      rows += " " + obj.nm_usuario + "	"; // <~~~~~~~~~ (3)
      rows += " " + obj.ds_login + "	"; // <~~~~~~~~~~~ (3)
      rows += "  <input type='checkbox' /> 	";
      rows += "
";
    }

    // tabela.find("tbody").html(rows);
    tabela.html('
' + rows + '
');

    //console.info(result.d);
  }
});

Explicações

*

*Não há necessidade de utilizar JSON.parse para obter o resultado. Você já especificou para o jQuery que o seu retorno será um JSON em dataType: "json" e, desta forma, o jQuery já entrega para você em result um objeto JavaScript construído a partir do JSON. Neste caso você estaria tentando fazer o parse de um objeto, não uma string, gerando o erro. Este .d também não faz sentido algum estar ali;

*No seu caso, result será um objeto JavaScript com apenas um atributo. ConsultarRegistroPorCodigoResult, que também será um objeto. Neste ponto do código você parece querer iterar sobre result como se ele fosse uma lista de objetos. Não produziria nenhum erro sintático, mas o resultado não seria o esperado, pois ao invés de estar iterando sobre uma lista de objetos, você estaria iterando sobre o objeto em si;

*Nesses pontos você tenta acessar atributos do objeto que não estão definidos no seu JSON. Perceba que o objeto definido em result.ConsultarRegistroPorCodigoResult possui apenas os atributos Codigo, CodigoSetor, Login, Nome, RegistroAtivo, Senha, 123456 e Tipo. Você tenta utilizar descricao, id_usuario, nm_usuario e ds_login. Nenhum deles existe no seu retorno.


text:
Q: Uniform convergence on three intervals Determine the uniformly convergence of   $f_n(x) = \frac{1}{(x-n)^2+1}$ on $(1, \infty), (0,1), (0, \frac{1}{2})$. Here is my solution: On $(1, \infty)$ it's not uniformly convergence by choosing $x=n$. I'm not sure about the other 2 cases.

A: If $n \ge 2$ and $x \in [0,1]$ then $f_n(x) \le {1 \over (n-1)^2 +1 }$.


text:
Q: dumpcap stops logging after 1184 files? Recently I come across a linux application design. The indent of the application is to log the ethernet frames via dumpcap <> api in linux. But they implemented as below:

*

*Create a new process using fork()

*Call dumpcap <> in execl() as shown below
a.    execl("/bin/sh", "/bin/sh", "-c", dumpcap<>, NULL);
b.    sudo dumpcap -i "eth0" -B 1 -b filesize:5 -w "/mnt/Test_1561890567.pcapng" -t -q

*They send a SIGTERM to kill the process
The problem facing now is when ever we run the command from the process after 1184 or 1185 no:files then dumpcap stops logging. The process and thread is alive the command we can see in top command.


text:
Q: PyQt5 - How can I add image in 'pushbutton' widget? | (not icon) Is there a function or option that adds an image in PushButton widget? In this situation, The added image means an image as a background applied to the entire widget, not an image as an 'icon'. I tried to find this option and I use the 'setStyleSheet' function, but it doesn't work. What is a problem, and how can I add an image in pushbutton?
btn6.setStyleSheet(
    "color: black;"
    "border-style: solid;"
    "border-width: 2px;"
    "border-color: #FFB400;"
    "border-radius: 3px;"
    "background-color: #FFD732;"
    "**background-image: url('D:\PyQt5_Tutorial\Test.png')")**

A: You can just override QPushButton.paintEvent() for this. And dont forget to add interactivity to reflect different states of button: sunken, disabled, mouse hover, input focus.
from PyQt5 import QtWidgets, QtGui

class Button(QtWidgets.QPushButton):

    def __init__(self, parent = None) -> None:
        super().__init__(parent)
        self._image = None

    def setImage(self, image):
        self._image = image
        self.update()

class Button(QtWidgets.QPushButton):

    def __init__(self, parent = None) -> None:
        super().__init__(parent)
        self._image = None

    def setImage(self, image):
        self._image = image
        self.update()

    def paintEvent(self, event):
        if self._image is None:
            return
        opt = QtWidgets.QStyleOptionButton()
        self.initStyleOption(opt)

        rect = self.rect()

        painter = QtGui.QPainter(self)

        self.style().drawControl(QtWidgets.QStyle.CE_PushButtonBevel, opt, painter, self)

        if opt.state & QtWidgets.QStyle.State_Sunken:
            rect.adjust(2,2,2,2)

        painter.drawImage(rect, self._image)

        if opt.state & QtWidgets.QStyle.State_MouseOver:
            color = self.palette().color(QtGui.QPalette.Highlight)
            color.setAlpha(50)
            painter.fillRect(self.rect(), color)

if __name__ == "__main__":
    app = QtWidgets.QApplication([])

    button = Button()
    button.setImage(QtGui.QImage("D:\\PyQt5_Tutorial\\Test.png"))
    button.show()

    app.exec()


text:
Q: Difference between benchmark and time macro in Julia I've recently discovered a huge difference between two macros: @benchmark and @time in terms of memory allocation information and time. For example:
@benchmark quadgk(x -> x, 0., 1.)
BenchmarkTools.Trial:
memory estimate:  560 bytes
allocs estimate:  17
--------------
minimum time:     575.890 ns (0.00% GC)
median time:      595.049 ns (0.00% GC)
mean time:        787.248 ns (22.15% GC)
maximum time:     41.578 μs (97.60% GC)
--------------
samples:          10000
evals/sample:     182

@time quadgk(x -> x, 0., 1.)
0.234635 seconds (175.02 k allocations: 9.000 MiB)
(0.5, 0.0)

Why there is a big difference between these two examples?

A: The reason is precompilation overhead. To see this define:
julia> h() = quadgk(x -> x, 0., 1.)
h (generic function with 1 method)

julia> @time h()
  1.151921 seconds (915.60 k allocations: 48.166 MiB, 1.64% gc time)
(0.5, 0.0)

julia> @time h()
  0.000013 seconds (21 allocations: 720 bytes)
(0.5, 0.0)

as opposed to
julia> @time quadgk(x -> x, 0., 1.)
  0.312454 seconds (217.94 k allocations: 11.158 MiB, 2.37% gc time)
(0.5, 0.0)

julia> @time quadgk(x -> x, 0., 1.)
  0.279686 seconds (180.17 k allocations: 9.234 MiB)
(0.5, 0.0)

What happens here is that in the first call, wrapping quadgk in a function, anonymous function x->x is defined only once, since it is wrapped in a function, and thus quadgk is compiled only once. In the second call x->x is defined anew with every call and thus compilation has to be performed each time.
And now the crucial point is that BenchmarkTools.jl wraps your code in a function which you can check by inspecting how generate_benchmark_definition function works in this package, so it is equivalent to the first approach presented above.
Another way to run the code without redefining the optimized function would be:
julia> g(x) = x
g (generic function with 1 method)

julia> @time quadgk(g, 0., 1.)
  1.184723 seconds (951.18 k allocations: 49.977 MiB, 1.58% gc time)
(0.5, 0.0)

julia> @time quadgk(g, 0., 1.)
  0.000020 seconds (23 allocations: 752 bytes)
(0.5, 0.0)

(though this is not what BenchmarkTools.jl does - I add it to show that when you use function g you do not pay precompilation tax twice)


text:
Q: How to limit current of transformer to protect rectifier? Lets suppose that I got a transformer with a 3.3A output. The transformer is then used in a circuit that includes a rectifier that can tolerate a max draw of 3A. What would be the best solution for limiting the current without risking damaging the rectifier. Could a limiting resistor be used or would a thermistor be better? Any other solutions would be appreciated.
NOTE: We prefer not to drop the voltage in the circuit

A: I would be far more worried about overloading your 3.3 A transformer than over loading a 3 A rectifier. Just use a slow-blow fuse.

A: A fuse is the obvious answer, but if you are expecting to routinely draw more than the limit, you can use a PTC thermistor that rises in resistance as the temperature rises (as a result of the current). You'd need to choose one that has a similar or shorter thermal time constant than the rectifier such that it responds before damage is done to the diodes. Most diodes will tolerate a significant overload for short periods, but depending on the construction of the bridge, the thermal mass can keep the rate of rise of the junctions low.


text:
Q: do/did/would do/could do? Lets say you bought a new device and found out that it cant do one of the things you were hoping for. Which of the following can be said and which one is best.
 1. "I thought it does that."
 2. "I thought it did that."
 3. "I thought it would do that."
 4. "I thought it could do that."

A: If the purchaser held the mistaken belief it had specific functionality, but discovered it did not, the fourth option would be my recommendation.
If the purchaser of the device was hoping (implying uncertainty) it had specific functionality, but discovered it did not, I'd replace "thought" with "hoped" in the fourth option.


text:
Q: How to dynamic delete table row with jquery How to dynamic delete row ?
sorry i fail to embed jsfiddle to post
my fiddle code here

A: use jquery on click
$(document).on('click', '.btn', function() {
    $(this).parent().parent('tr').remove();
});

$('.add').on('click', function() {
    $('tbody').append('
' +
        '<input type="text" class="no">	' +
        '<input type="text" class="item">	' +
        '<input type="text" class="description">	' +
        '' +
        '<button class="btn">' +
        '' +
        'Delete' +
        '</button>' +
        '	' +
        '
');
});
$(document).on('click', '.btn', function() {
    $(this).parent().parent('tr').remove();
});
input {
    width: 100%;
}

.add {
    float: right;
    margin-right: 10px;
    margin-top: 50px
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<button class="btn add">
     add
</button>

            No
            Item
            description
            Action

            1
            Lipsum
            Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ea earum hic accusamus, reprehenderit recusandae, quisquam consequatur quasi eum cum, nam atque aperiam at? Veniam cupiditate, commodi numquam voluptates dicta nisi.

                <button class="btn">
                     Delete
                </button>


text:
Q: VHDL unconstrained std_logic_vector - detection of increasing/decreasing index With an unconstrained std_logic_vector port on a component, it will follow the signal declaration from the higher level entity where the component was instantiated (if the signal is (n downto 0), the port will obviously match this).
However, if assigning a constant vector ("10100001" or x"A1" for example) to the port on the instantiation, the port will automatically default to "0 to 7" instead of "7 downto 0". Is there any way to "detect" that a unconstrained std_logic_vector is in the increasing/decreasing index format, so I can appropriately flip the bits if necessary?

A: The VHDL attribute 'ascending does what I want. So "My_Signal'ascending" will return a boolean true if the vector is in "0 to n" format, false if "n downto 0" format.

A: First be careful with unconstrained arrays on components as some synthesis tools may not support this feature, however, for testbenches it is just fine.
Next, rather than being concerned about ascending or descending ranges, instead you should normalize the ranges.  You can do this with an alias:
entity fred is
port (
  Unconstrained_Port : std_logic_vector ;
  . . .
) ;
end entity fred ;
architecture one of fred is
  alias Constrained_Port : std_logic_vector(Unconstrained_Port'length -1 downto 0) is Unconstrained_Port ;


text:
Q: Apples, oranges, and pointers to the most derived c++ class Suppose I have a bunch of fruit:
class Fruit { ... };
class Apple : public Fruit { ... };
class Orange: public Fruit { ... };

And some polymorphic functions that operate on said fruit:
void Eat(Fruit* f, Pesticide* p)   { ... }
void Eat(Apple* f, Pesticide* p)   { ingest(f,p); }
void Eat(Orange* f, Pesticide* p)   { peel(f,p); ingest(f,p); }

OK, wait. Stop right there. Note at this point that any sane person would make Eat() a virtual member function of the Fruit classes. But that's not an option, because I am not a sane person. Also, I don't want that Pesticide* in the header file for my fruit class.
Sadly, what I want to be able to do next is exactly what member functions and dynamic binding allow:
typedef list<Fruit*> Fruits;
Fruits fs;
...
for(Fruits::iterator i=fs.begin(), e=fs.end(); i!=e; ++i)
    Eat(*i);

And obviously, the problem here is that the pointer we pass to Eat() will be a Fruit*, not an Apple* or an Orange*, therefore nothing will get eaten and we will all be very hungry.
So what I really want to be able to do instead of this:
Eat(*i);

is this:
Eat(MAGIC_CAST_TO_MOST_DERIVED_CLASS(*i));

But to my limited knowledge, such magic does not exist, except possibly in the form of a big nasty if-statement full of calls to dynamic_cast.
So is there some run-time magic of which I am not aware? Or should I implement and maintain a big nasty if-statement full of dynamic_casts? Or should I suck it up, quit thinking about how I would implement this in Ruby, and allow a little Pesticide to make its way into my fruit header?
Update: Instead of the contrived bit with the bare Eat functions and Pesticide, suppose instead that I just don't want to put Eat in the fruit because it makes no sense. A fruit that knows how to eat itself? Pshaw. Instead I need an Eater class with an Eat function, with different code for eating each kind of fruit, and some default code in case it's a fruit that the eater doesn't recognize:
class Eater
{
public:
  void Eat(Apple* f) { wash(); nom(); }
  void Eat(Orange* f) { peel(); nom(); }
  void Eat(Fruit* f) { nibble(); }
};
...
Eater me;
for(Fruits::iterator i=fs.begin(), e=fs.end(); i!=e; ++i)
  me.Eat(*i);  //me tarzan! me eat!

But again, this doesn't work, and the straightforward solution in C++ seems to be a bunch of calls to dynamic_cast.
However, as one of the answers suggests, there may be another clever solution. What if Fruits exposed the qualities that mattered to eaters, with functions like MustPeel() and MustWash()? Then you could get by with a single Eat() function ...
Update: Daniel Newby points out that using Visitor also solves the problem as presented ... but this requires a bit of a semantic headstand (Fruit::use or Fruit::beEaten?).
While I'd like to accept several answers, I think psmears's answer is actually the best one for future readers. Thanks, everyone.

A: You need to redesign. Namely, do everything you seem to be avoiding (for what reason, who knows.)
Polymorphic behavior requires polymorphic functions. This means a virtual function. (Or your ladder of dynamic_cast's, which completely defeats the purpose...)
// fruit.h
class Pesticide; // you don't need a complete type

struct Fruit
{
    virtual void Eat(Pesticide*) = 0;
};

// apple.h
class Apple : public Fruit
{
    void Eat(Pesticide* p) { ... }
};

// orange.h
class Orange : public Fruit
{
    void Eat(Pesticide* p) { ... }
};

If you still want a free function*:
void Eat(Fruit* f, Pesticide* p)   { f->Eat(p); }

*Note that your post is already indicative of bad design; namely the first Eat function:
void Eat(Fruit* f, Pesticide* p)   { }

When does doing nothing to a fruit equate to eating the fruit? A pure virtual function is a much better interface choice.

A: When a question like this comes up, it's good to look at exactly why you want to make particular decisions - for instance, why do you not want the Fruit classes to know about Pesticide?
I'm sure there is a good reason for this - but expressing that reason will help clarify in your mind exactly what your aims are - and this often sheds a new light on a possible angle for structuring the program.
For instance, you might end up adding new virtual methods "IsEdible" and "PrepareForEating". Then you can implement these for each fruit, and implement one generic Eat method that works for all fruits - and ingests the pesky pesticide too - all without the Fruit classes knowing anything about it.
Of course, depending on your precise aims, that may be totally inappropriate - which is why you'll have to clarify the example in your own head :-)

A: Just use the I Am Standing Right Here! Pattern.  It's like the Visitor Pattern but without a container.
// fruit.h
class Fruit;
class Apple;
class Orange;

class Fruit_user {
    public:
        Fruit_user();
        virtual ~Fruit_user();
        virtual use(Apple *f) = 0;
        virtual use(Orange *f) = 0;
};

class Fruit {
    public:
        // Somebody with strong template fu could probably do
        // it all here.
        virtual void use(Fruit_user *fu) = 0;
};

class Apple : public Fruit {
    public:
        virtual void use(Fruit_user *fu) {
            fu->use(this);
        }
};

class Orange: public Fruit {
    public:
        virtual void use(Fruit_user *fu) {
            fu->use(this);
        }
};

// dow-chemical.h
class Pesticide_fruit_user : public Fruit_user {
    public:
        Pesticide_fruit_user(Pesticide *p) {
            p_ = p;
        }

        virtual void use(Apple *f) { ingest(f, p_); }
        virtual void use(Orange *f) { peel(f, p_); ingest(f, p_); }

    private:
        Pesticide *p_;
};

A: There's nothing wrong with having arbitrary class pointers in headers. They form the basis of many idioms, like PIMPL and opaque pointers. Also, if you aren't a sane person, how are you supposed to understand my answer?
Seriously, derived functions and polymorphism exist to solve this problem. If you refuse to use the language provided tools, why bother using it at all? Any solution you can come up with can be translated into a virtual function call in any case, just you would have coded it manually instead of having the compiler do it.

A: What you're asking for isn't possible.  The function overloading resolution needs to know at compile time which class the parameter is so it can call the correct Eat function. The only exception is for virtual member functions, which you've already ruled out.


text:
Q: Mule 4 - Parse DateTime as DD/MM/YYYY 24HH:MM:SS format? I am stuck with a requirement where I need to parse incoming payload String 6-12-2019 2:13:30 to DateTime format DD/MM/YYYY 24HH:MM:SS
I tried few approaches but nothing seems to work here.
"6-12-2019 2:13:30" as DateTime {format : "d-M-yyyy h:m:ss"}
this results in error stating...
"Cannot coerce String (6-12-2019 2:13:30) to DateTime, caused by: Text '6-12-2019 2:13:30' could not be parsed: Unable to obtain ZonedDateTime from TemporaAccessor: {SecondOfMinute=30, MicroOfSecond=0, MilliOfSecond=0, HourOfAmPm=2, MinuteOfHour=13, NanoOfSecond=0},ISO resolved to 2019-12-06 of type java.time.format.Parsed
Can someone please help me with this?
Thanks.

A: Your input doesn't match the type DateTime. It is missing a timezone, and the 'h' format character implicates it is an AM/PM date, but it is missing it. A LocalDateTime doesn't need a timezone. You can either change the input and format or change the type.
Please find below some valid examples:
%dw 2.0
output application/json
---
{
    localDateTime: "6-12-2019 2:13:30 pm" as LocalDateTime {format : "d-MM-yyyy h:mm:ss a"},
    localDateTime24h: "6-12-2019 14:13:30" as LocalDateTime {format : "d-MM-yyyy H:mm:ss"},
    dateTime: "6-12-2019 2:13:30 +0500" as DateTime {format : "d-MM-yyyy H:mm:ss Z"}
}

Output:
{
  "localDateTime": "6-12-2019 2:13:30 PM",
  "localDateTime24h": "6-12-2019 14:13:30",
  "dateTime": "6-12-2019 2:13:30 +0500"
}

A: You can try to cast the incoming date to your specific format. And then reformat as need. In below sample, we converted the date to MM/dd/yyyy format and the reformatted it to the required format i.e. y-MM-dd.
(date1 as Date {format: "MM/dd/yyyy"}) as String {format: "y-MM-dd"}


text:
Q: Measure cpu intensive time with async code we want to outsource some part of our application to an external company. These components make async requests to external websites and handle the content with html parsers or regular expressions.
async Task Do()
{
   var webContent = await Get("http://...");
   var match = Regex.Match(webContent);

   if (IsXXX(match))
   {
       webContent = await Get("http://other...");
   }
}

Each component is different, some make only one request, others do a lot more. We want to ensure that the CPU intensive part (Regex, Parsing) does not take a longer than 100ms and want to test it automatically as first step in the quality ensurance pipeline. Is there a way to measure the performance without the waiting time for the web requests?
I see only two solutions at the moment, but would like to know if there is better approach:

*

*Provide an wrapper for the web requests and measure the waiting time. Then use simple stopwatch to measure the time and subtract the waiting time. Difficult for soap calls when using generated client classes.

*Implement a custom synchronization context and measure the time here.

Are there some builtin solutions?

A: Mock the IO-bound web requests to immediately return an HTML string that will take similar CPU to process. E.g. use return Task.FromResult(XXX) to get a task that is already completed. Then measure the method as a whole.
Note that you can use Microsoft Fakes to replace any internal call with your own method.


text:
Q: Comparing sets that contain nan in python I'm trying to compare two sets in python that contain nan but struggling to do so because {float('nan')} != {float('nan')}.  For example:
s1 = {float('nan'), 1}
s2 = {float('nan'), 1, 2}

assert set.issubset(s1, s2)

And I get an assertion error.  How can I handle this?

A: One approach: identity is tested before equality (see here in the docs, for example), so it'd work if you use the same nan:
>>> nan = float("nan")
>>> s1 = {nan, 1}
>>> s2 = {nan, 1, 2}
>>> set.issubset(s1, s2)
True

even though
>>> s1 = {float("nan"), 1}
>>> s2 = {float("nan"), 1, 2}
>>> set.issubset(s1, s2)
False

Working with nans is awkward enough that I'd try to avoid putting them in sets and switch to a different canonical form.  But you could always just make sure it's the same one:
>>> def one_nan(x, nan=float("nan")):
...     return nan if math.isnan(x) else x
...
>>> set.issubset(set(map(one_nan, s1)), set(map(one_nan, s2)))
True

or a thousand variants on the same.  (I sometimes use x != x as a shortcut for nan-detection but it's probably a good idea to be explicit here.)

A: Create temporary sets with all nan values removed, and compare those instead. Afterwards, handle the nan comparison separately. For example, you could check if both of the original sets contain nan.
Even if you could perform the comparison for your sets without the assertion exception, float('nan') == float('nan') will return False so there is little value gained from this set comparison (it will invalidate the rest of the comparison). You can check this behavior by printing set.issubset.
s1 = frozenset({float('nan'), 1})
s2 = frozenset({float('nan'), 1, 2})
print frozenset.issubset(s1,s2)

which prints False.
Although set is deprecated, you may generate the temporary sets as follows:
s3 = set([value for value in s1 if not math.isnan(value)])

(repeat for each temporary set as needed)

A: You could also write a simple function for this. Note that float('nan') == float('nan') is False for nan; to check if any element is nan, we just have to compare it with itself.
def is_subset(s1, s2):
    no_nan_set = lambda s: {x for x in s if x == x}
    s1_nan, s2_nan = no_nan_set(s1), no_nan_set(s2)
    if s1_nan != s1 and s2_nan != s2:
        return s1_nan.issubset(s2_nan)
    elif s1_nan == s1 and s2_nan == s2:
        return s1.issubset(s2)
    else:
        return False

You can simplify the if-elif-else block
def is_subset(s1, s2):
    no_nan_set = lambda s: {x for x in s if x == x}
    s1_nan, s2_nan = no_nan_set(s1), no_nan_set(s2)
    return (s1_nan != s1 and s2_nan != s2 and s1_nan.issubset(s2_nan)) \
        or (s1_nan == s1 and s2_nan == s2 and s1.issubset(s2))

Note that if either of your set has two or more nans (because float('nan') != float('nan')), this will work correctly, and similarly it will work all right if the ids of the nans are different. And lastly, this will work even if you don't have the nans in one or both of your set.


text:
Q: how to plot normal distribution with the same mean but different variance in r I tried to plot 6 normal distribution figure to display the effect of mean and variance on such a plot,my code is as follow:
    par(mfrow=c(3,2),bty = "n")     # 3 rows by 2 columns, turn off border
    mu <- c(6, 8, 6, 8, 6, 8)       #designate the 6 mean values
    sigma <- c(3, 3, 2, 2, 1, 1)        #designate the 6 sd values
    label <- c("(a)","(b)","(c)","(d)","(e)","(f)") #designate the 6 labels of the 6 figures
    for(i in 1:length(mu))
    {
     mu.r <- mu[i]
     sigma.r <- sigma[i]
     lab.r <- label[i]
     x <- seq((mu.r - 4*sigma.r), (mu.r + 4*sigma.r), len = 200)
    #designate the starting and ending value of mean
     plot(x, dnorm(x, mean = mu.r, sd = sigma.r),axes = F,
         type="l",lwd = 2, xlab = lab.r, ylab = "",
              main=paste0('mu=',mu.r,', sigma=',sigma.r),
           )
    axis(1, at = (mu.r - 4*sigma.r) : (mu.r + 4*sigma.r))
    abline(v = mu.r, col = "red", lwd = 2.5, lty = "longdash")

    }
    the figures generated is as follow:
   [enter image description here][1]

  [1]: https://i.stack.imgur.com/Z4czh.png

A: You didin't said what exactly was the problem. I assume is that all your graphs look the same. That happens because you set your x axis depending on the variance, you need to leave all the graphs on the same scale in order to compare them. I simply set a arbitrary interval of 7 around the mean:
for(i in 1:length(mu))
{
  mu.r <- mu[i]
  sigma.r <- sigma[i]
  lab.r <- label[i]
  x <- (mu.r - 7):(mu.r + 7)
  #designate the starting and ending value of mean
  plot(x, dnorm(x, mean = mu.r, sd = sigma.r),axes = F,
       type="l",lwd = 2, xlab = lab.r, ylab = "",
       main=paste0('mu=',mu.r,', sigma=',sigma.r),
  )
  axis(1, at = x)
  abline(v = mu.r, col = "red", lwd = 2.5, lty = "longdash")

}

Output:


text:
Q: Generic functional interface I'm facing with some lambda problem.
I'm trying to use lambda expression and functional interface to create method accepting functional interface and some arguments and execute that function.
Here is my code:
@FunctionalInterface
interface TwoArgumentFunction {
    public <T, K, V> T doJob(K arg1, V arg2);
} //I know I've ommited return value in that case

class SomeClass {
<T, K, V> T runLongAction(TwoArgumentFunction action, K arg1, V arg2){
    SwingWorker<T, Void> worker = new SwingWorker<T, Void>(){

        @Override
        protected T doInBackground() throws Exception {
            {... some code ... }
            return action.doJob(arg1, arg2);
        }
        @Override
        protected void done(){
            {... some code ... }
        }

    };
    worker.execute();
    try {
        return worker.get();
    } catch (InterruptedException | ExecutionException e) {
        {... some code ... }
    }
}

void mainInvoke(ArgType1 arg1, ArgType2 arg2){
    runLongAction((arg1, arg2) -> doSomething(arg1, arg2), arg1, arg2);
}

}
I've got error:

The method runLongAction(( arg1,  arg2) -> {}, ArgType1, ArgType2) is undefined for the type SomeClass

I even tried cast lambda to TwoArgumentFunction but then I've got:

Illegal lambda expression: Method doJob of type TwoArgumentFunction is generic

Anonymouse class instead of lambda expression works fine and that's the simplest workaround I found.

A: Try that :
  @FunctionalInterface
  interface TwoArgumentFunction<T, K, V> {
     T doJob(K arg1, V arg2);
  } //I know I've ommited return value in that case

  public <T, K, V> T runLongAction(final TwoArgumentFunction<? extends T, ? super K, ? super V> action, final K arg1, final V arg2) {
    return action.doJob(arg1, arg2);
  }

  private void test() {
    final String a = "A";
    final Long b = 1L;
    this.runLongAction((ta, tb) -> {return 1;}, a, b);
  }

You were putting the generics on the method, while I putted it on the interface. And I also added ? super and ? extends (but this work without it).
In case you don't know it and if you need it, you can also put the type in the lambda :
this.runLongAction((String ta, Long tb) -> {return 1;}, a, b);

A: There is no need for you to create an interface that already exists in Java 8. You should use the 'BiFunction' interface,  which has a method 'R apply(T t, U u))'.

A: I didn't see the doSomething() method
but this works for me
void mainInvoke(ArgType1 arg1, ArgType2 arg2){
    runLongAction(this::doSomething, arg1, arg2);
}

private <T, K, V> T doSomething(K arg1, V arg2) {
  // TODO Auto-generated method stub
  return null;
}


text:
Q: Is it possible to get access to Chrome's DevTools Console output in the "main web page" I am using the Chrome's DevTools console to debug a webpage.  Is there a way to pipe what is being outputted in the console, back up to the main webpage?

A: You could try and replace console.log if its just those messages which you are trying to capture with something like
console.log = function(what){
    //Do what you want with what has been logged
    alert(what);
};


text:
Q: How to delete unused mount points? How do I delete these 2 unwanted mount points.

A: Use sudo rmdir /path/to/mount/point

A: Mount points are empty directories. In GNU/Linux, all filesystems are mounted in one tree, and Ubuntu is a GNU/Linux. You tried to remove that directory using rmdir command. It's OK. But it said permission denied. It is expected to happen. You are not the owner of neither those directories nor the parent directory, /mnt . You must have superuser permissions to remove those. So use sudo which give root permissions like this:
sudo rmdir /unused/mount/point/

It will prompt for the password. Type your password and hit enter. Your password won't be seen, even not dots. That's normal.