text:
Q: Lagrange Multiplier to find maximum and minimum Question:
Find the maximum and minimum of the function $f(x,y,x)=3x^2 + 2xz + 5y^2 +3z^2$ on the sphere $x^2 + y^2 + z^2 = 25$
Attempt:
This seems that it should be solvable using the Lagrange multiplier method so my attempt is focused on that.
$f(x,y,x)=3x^2 + 2xz + 5y^2 +3z^2$
$g(x,y,z)=x^2+y^2+z^2-25$
$\nabla f = \lambda \nabla g$
$\nabla f = (6x+2z,10y,2x+6z)$
$\nabla g = (2x, 2y, 2z) $
therefore we can make a system of equations:
$6x+2z=\lambda (2x)$ [1]
$10y=\lambda (2y)$ [2]
$2x+6z= \lambda (2z)$ [3]
$x^2 + y^2 + z^2 = 25$ [4]
From equation [2] it is clear to see that $\lambda = 5$
Subbing $\lambda$ into eqn [1] and [3] yeilds
$6x + 2z = 10x$ [1]
$2x + 6z = 10z$ [3]
It is also clear to see that $x=z$
This however creates a contradiction because if $x$ and $z$ are equal $\lambda$ cannot be equal to $5$ it must be equal to $4$ as shown below
From eqn [1] subbing x=z yeilds
$6x + 2x = \lambda (2x)$
$\lambda = 4$
I am unsure what I am doing wrong that is resulting in this system of equations to be unsolvable I know for a fact this question has a solution and I don't see why using Lagrange multipliers wouldn't work.
Any help would be appreciated Thank you.

A: Hint: Solve your equation for the sphere for $$y^2$$ and your function will containes only two variables.
$$y^2=25-x^2-z^2$$ so you will get
$$f(x,\pm\sqrt{25-x^2-z^2},z)=3x^2+2xz+5(25-x^2-z^2)+3z^2$$

A: Your mistakes:

*

*From equation [2] you get $ \lambda=5$ or $y=0$ !

*With $\lambda=5$ we get $x=z$ and then $x=z=0$, hence $y= \pm 5$.

*You have also to investigate the case $y=0$ (see 1.).

A: The function $ \ f(x,y,x) \ = \ 3x^2 \ +  \ 2xz \ + \ 5y^2 \  + \ 3z^2 \ $  would have full symmetry about the origin, if it weren't for the "mixed-variable" term $ \ 2xz \ $ .  Its effect is to "break" the symmetry so that the value of the function at points where $ \ x \ = \ z \ $  differs from the value where $ \ x = -z \ \ . $  We may then expect to find extremal points with coordinates $ \ ( \ \pm x \ , \ \pm y \ , \ \pm x \ ) \ $ and $ \ ( \ \pm x \ , \ \pm y \ , \ \mp x \ ) \ \ . $
Your system of Lagrange equations
$$ 6x+2z \ = \ \lambda ·  2x  \ \ , \ \ 10y \ = \ \lambda · 2y  \ \ , \ \  2x+6z \ = \ \lambda·2z \ \  $$
may be handled in a couple of different ways.
One of these is related to Fred's answer, in which we bring all terms to one side in each equation thus
$$ (3 - \lambda) \ x \ + \ z \ = \ 0 \ \ , \ \ (5 - \lambda) \ y \ = 0  \ \ , \ \  x \ + \ (3 - \lambda) \ z \ = \ 0 \ \ . $$
This shows the division of the solution into two cases.  The simpler of these is where $ \ \lambda = 5 \ \ , $ which as you found forces $ \ (3 - 5) \ x \ + \ z \ = \ 0 \ ,  \  2x \ + \ (3 - 5) \ z \ = \ 0 \ \ \Rightarrow \ \ z = 2x \ , \ x = 2z  \ \ , $ so that we have $ \ x = 0 \  , \  z = 0 \ \ \Rightarrow \ \ y^2 = 25 \ \ \Rightarrow \ \ y  \ = \ \pm  5 \ \ . $  The function at these points has the value $ \ f(0 \ , \ \pm 5 \ , \ 0) \ = \   5·5^2 \ = \ 125 \ \ . $
For $ \ y = 0 \ \ (\lambda \neq 5) \ , $  the first and third equations form a system
$$ \begin{array}{cc}   (3 - \lambda) \ x & + \ z  & \ = \ 0 \\  x   &   + \  (3 - \lambda)  \ z  & \ = \ 0 \end{array} \ \ . $$
We will only have non-zero values for $ \ x \ $ and $ \ z \ $ when $ \ (3 - \lambda)^2 \ - \ 1 \ = \ 0  \ \ \Rightarrow \ \ \lambda \ = \ 2 \ , \ 4 \ \ . $  We then have $ \ \lambda = 2 \ \Rightarrow \ x + z \ = \ 0 \ \  $ or $ \ \ \lambda = 4 \ \Rightarrow \ x - z \ = \ 0 \ \ . $  Inserting this into the spherical constraint equation yields
$ \mathbf{\lambda \ = \ 4 \ :} \quad x \ = \ z \ \ \Rightarrow \ \ x^2 \ + \ 0 \ + \  z^2 \ = \ 25 \ \ \Rightarrow \ \ 2x^2 \ = \ 25 \ \ \Rightarrow \ \ x \ = \ z \ = \ \pm  \frac{5}{\sqrt2}  \ \ ;  $
$ f(\pm \ x \ , \ 0 \ , \ \pm \ x) \ = \ 3x^2 \ +  \ 2·(\pm \ x)^2 \  + \ 3x^2    \ \ = \ \ 8·x^2 $
$ \Rightarrow \ \ f \left(\pm \ \frac{5}{\sqrt2} \ , \ 0 \ , \ \pm \ \frac{5}{\sqrt2} \right) \ = \ 8·\left(\frac{25}{ 2} \right)  \ = \ 100    $
$ \mathbf{\lambda \ = \ 2 \ :} \quad x \ = \ -z \ = \ \pm  \frac{5}{\sqrt2}  \ \ ;    \ \ f(\pm \ x \ , \ 0 \ , \ \mp \ x) \ = \ 3x^2 \ +  \ 2·(\pm \ x)·(\mp \ x) \  + \ 3x^2    \ \ = \ \ 4·x^2 $
$ \Rightarrow \ \ f \left(\pm \ \frac{5}{\sqrt2} \ , \ 0 \ , \ \mp \ \frac{5}{\sqrt2} \right) \ = \ 4·\left(\frac{25}{ 2} \right)  \ = \ 50  \ \ .  $
[We also see from this that $ \ \lambda = 3 \ $  immediately leads to all three coordinates being equal to zero.  The origin is a critical point of the function, but we are only concerned with its behavior on the spherical surface.]
We conclude that the extremal values of our function on the sphere are given by
$$   f(0 \ , \ \pm 5 \ , \ 0) \  = \ 125 \quad \mathbf{\text{ [ absolute maximum  ] } } $$
and
$$   f \left(\pm \ \frac{5}{\sqrt2} \ , \ 0 \ , \ \mp \ \frac{5}{\sqrt2} \right)   \ = \ 50 \quad \mathbf{\text{[  absolute minimum  ] } } \ \ . $$
Another approach that can be taken is to solve the original Lagrange equations for $ \ \lambda \ $ and not generally concern ourselves with its values:
$$ \lambda \ \ = \ \ \frac{6x \ + \ 2z}{2x} \ \ = \ \ \frac{2x \ + \ 6z}{2z} \ \ = \ \ \frac{10 \ y}{2 \ y} \ \ . $$
This can be interpreted in the following way.  Solving the equation of the first pair of ratios leads to $ \ 3 \ + \ \frac{z}{x} \ = \ 3 \ + \ \frac{x}{z} \ \ \Rightarrow \ \ x^2 = z^2 \ \ ,  $ unless $ \ x = 0 \ , \ z = 0 \ \ . $  The last ratio gives us $ \ \lambda = 5 \ \ , $ unless $ \ y = 0 \ \ . $  Combining these with $ \ (3 - \lambda) \ x \ + \ z \ = \ 0 \ \ , \ \ (5 - \lambda) \ y \ = 0  \ \ , \ \  x \ + \ (3 - \lambda) \ z \ = \ 0 \ \   $ allows us to sort the cases as
$ \mathbf{\lambda \ = \ 5 \ :} \quad x \ = \  z \ = \ 0  \ \ \Rightarrow \ \ y \ = \ \pm \ 5 \quad \text{or} \quad  \mathbf{\lambda \ \neq \ 5 \ :} \quad y =  0 \ \ \text{and} \ \ x  =    z \neq 0  \ \   \text{or} \ \ x  =   -z  \neq 0 \ \ , $
with the rest of the calculations following as before.
$ \ \ $
It is reasonable to ask whether the value of the function  $ \  f(0 \ , \ \pm 5 \ , \ 0) \  = \ 125 \ $  "fits together" with the extrema on the circle $ \ x^2 + z^2 \ = \ 25 \ \ , $ which is the intersection of the plane $ \ y = 0 \ $ with the constraint sphere.  If we parametrize this circle by $ \ x \ = \ 5 \cos \theta \ , \   z \ = \ 5 \sin \theta \ \ , $ our function becomes
$$   f(x,0,z) \ = \ 3·(5 \cos \theta)^2 \ +  \ 2·(5 \cos \theta)·(5 \sin \theta) \ + \ 5·0^2 \  + \ 3·(5 \sin \theta)^2   $$
$$   = \ 75·(  \cos^2 \theta \ + \ \sin^2 \theta)  \ +  \ 50 · \sin \theta \ \cos \theta \ \  = \ 75   \ +  \ 25 · \sin (2 \theta) \ \ . $$
We can see from this that the relative maxima occur at $ \ \theta \ = \ \frac{\pi}{4} \ , \ \frac{5\pi}{4} \ \ ( x = z ) \ \ $ and the relative minima   at $ \ \theta \ = \ \frac{3\pi}{4} \ , \ \frac{7\pi}{4} \ \ ( x = -z ) \ \ . $
Applying the symmetry of the function and of the sphere, we can use "vertical planes" $ \ y \ = \ \pm Y_0 \ $ and examine the intersection circles $ \ x^2 + z^2 \ = \ 25 - Y_0^2 \ \ $ with radii $ \ R \ = \ \sqrt{25 - Y_0^2} \ \ . $  Their parametrization is $ \ x \ = \ R \cos \theta \ , \ R \ = \ 5 \sin \theta \ \   $ and the function on said circles is
$$   f(x \ , \ \pm Y_0 \ , \ z) \ \ =  \ \ 3·R^2·(  \cos^2 \theta \ + \ \sin^2 \theta)  \ +  \ 5·Y_0^2 \ + \ 2·R^2 · \sin \theta \ \cos \theta $$
$$ = \ \  3·(25 - Y_0^2)  \ + \ 5·Y_0^2 \ +  \ (25 - Y_0^2) · \sin (2 \theta) \ \ = \ \  (75 + 2Y_0^2)  \ +  \ (25 - Y_0^2) · \sin (2 \theta) \ \ . $$
We observe that when these planes become tangent to the sphere at $ \ Y_0 = \pm \ 5 \ \ , $ the function "collapses" to $ \    75 \ + \ 2 · 5^2   \ +  \ 0 · \sin (2 \theta)  \ = \ 125 \ \ . $
Indeed, using the symmetry argument discussed at the start, we could have solved for the extremal points in this manner.


text:
Q: how to compare two xmi files of two activity diagrams and to display the differences among them? I am doing this in C# Visual studio 2008. I did the Xmi  files from AgroUmL by export feature.
kindly please help me....
how to compare two xmi files of  two activity diagrams and to display the differences among them?
with out  use of any other tools, but write the code to compare the two xmi files][1]

A: If you want to just compare the XML files, Use WinDiff which comes with Visual Studio or any other file comparison tool

redpajama_set_name: RedPajamaStackExchange


text:
Q: Uispy Return's Value as "?" i am using UISpy to detect the outlook TO Address Field but uispy return the Values as "?"

If it's normal text then Uispy detects correctly it's showing the To Address. the problem is when we enter any email address in To address field its converting into hyperlink how can we get the to Address using Ui spy.

A: Inspect.exe from Windows 10 SDK seems to be able to find the email address:

(using Outlook 2016 on Windows 10)


text:
Q: Make tableView cell with struct and data by indexpath I already known how to make a basic tableView, below is my basic code
class ShoppingTableViewController: UITableViewController{
var description = ["D1", "299900", "D2", "P201712310000003000", "D3", "ASS+DfDFxSuu", "D10", "901", "D11", "00,46246226301561000110001001", "D12", "20201231123030"]
var dictDescription = ["D10": "901", "D11": "00,46246226301561000110001001", "D3": "ASS+DfDFxSuu", "D12": "20201231123030", "D2": "P201712310000003000", "D1": "299900"]

override func viewDidLoad() {
        super.viewDidLoad()
// Xib
        tableView.register(UINib(nibName:PropertyKeys.pictureCell , bundle: nil), forCellReuseIdentifier: PropertyKeys.pictureCell)
        tableView.register(UINib(nibName:PropertyKeys.infoCell , bundle: nil), forCellReuseIdentifier: PropertyKeys.infoCell)
}

 override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 4
    }
 override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
 switch indexPath.row {
case 0:
            let cell = tableView.dequeueReusableCell(withIdentifier: PropertyKeys.pictureCell, for: indexPath) as! PictureWithTableViewCell
            cell.iconImageView.image = UIImage(named: "amount")
            cell.lbDescription.text = "Type"
            cell.lbName.text = "Shopping"
            return cell
case 1:
             let cell = tableView.dequeueReusableCell(withIdentifier: PropertyKeys.infoCell, for: indexPath) as! InfoTableViewCell
                cell.lbDescription.text = "Taiwan dollar"
                cell.lbName.text = m_dictDescription["D1"]
                return cell
case 2:
            let cell = tableView.dequeueReusableCell(withIdentifier: PropertyKeys.pictureCell, for: indexPath) as! PictureWithTableViewCell
            cell.iconImageView.image = UIImage(named: "info")
            cell.lbDescription.text = "BankName"
            cell.lbName.text = m_dictDescription["D11"]
            return cell
case 3:
            if m_dictDescription["D2"] != nil {
                let cell = tableView.dequeueReusableCell(withIdentifier: PropertyKeys.infoCell, for: indexPath) as! InfoTableViewCell
                cell.lbDescription.text = "orderNumber"
                cell.lbName.text = m_dictDescription["D2"]
                return cell
            }else {
                let cell = tableView.dequeueReusableCell(withIdentifier: PropertyKeys.infoCell, for: indexPath) as! InfoTableViewCell
                cell.isHidden = true
                return cell
            }

but this is an unsafe way because i write func number of rows and cell for row as hardcode.
so I want to change tableView composing way from decide cell format first then fill data in (like my basic code) to let data decide my number of rows and cell for row. (use indexPath)
but I got some problems:
I try to write:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let test = self.m_arrDescription[indexPath.row]
cell.lbName.text = test

It works but every cell looks the same while I want to present different cells.
I search some information on internet, perhaps I can use struct and combine m_arrDescription to make tableview cell.
// use struct to decide cell label or image , for example: cell.lbDescription.text ...
struct CellFormat {
        var title : String
        var image : UIImage
        var name : String
    }

So far this is what i've written, can anyone please kindly help me to go on?
Be clearly, how do I use [indexPath.row] in this code ?

A: please create first one enum
enum CellType: String, CaseIterable {
     case title, image, name
}

and then use this code in tableview delegate methods.
switch CellType(rawValue: indexPath.row) {
    case .title:
        break
    case .image:
        break
    case .name:
        break
    case .none:
        break
    }

If any problem let me know


text:
Q: HttpClient.SendAsync takes a lot longer to receive response from the api than expected I have a simple program that uses System.Net.Http.HttpClient which works like this:
// Get existing or create new httpclient if there isn't one instace of it already
mClient = GetHttpClient();
var startTime = DateTime.Now;

var res = await mClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);

var executeMethodTime = DateTime.Now.Subtract(startTime).TotalMilliseconds;
mLog.Info("restPostExecuteMethodTime : {0}", executeMethodTime);

It makes a simple request to the API and waits for the response. The content of the request is very small just some simple objects nothing too big.
The API side looks like this:
public async Task<IHttpActionResult> DoWork([FromBody]TemplateInput templateInput)
{
        IHttpActionResult res;
        var startTime = DateTime.Now;

        // do logic
        var auditTime = DateTime.Now.Subtract(startTime).TotalMilliseconds;
        mLog.Info($"auditTime {auditTime}");
        return res;
}

Here is the logging generated by that code :
2020-07-15 09:12:19.7472|auditTime 204.9607|
2020-07-15 09:12:24.8172|executeMethodTime : 5321.9861|

What surprised me is that the API took over 5 seconds to return the result when in fact all the logic in the API took only about 200 milliseconds to finish executing. But it took whole entire 5 seconds to return the result back to the requester.
I checked the network and there were no problems.
It made no sense to me. Is there anything in HttpClient that could potentially affect the response speed? To the point that it would cost request 5 seconds?
I first thought it was caused by proxy setting inside httpClient so I tried to set proxy to false when creating httpClient it turned out to make no difference to speed.
If anyone has any idea - please let me know.


text:
Q: Hide specific button on android navigation bar I have another question for you:
Is there a way to hide a specific virtual button from android navigation bar?
My particular case is hide recent apps button. I've searched in some posts about this, but they mention how to hide or disable navigation bar. I just need to hide one virtual button from navigation bar.
I hope that you can give me an answer, thanks!
Update:
Somebody told me that Airwatch app from VM-Ware does this customization

A: It is currently impossible to make an App-specific customization, but it is possible to make a device-specific modification on Navigation Bar, starting from Android 8.0 (Oreo) by unlocking System UI Tuner.

However, do consider the limitation as both Navigation Bar and System UI Tuner ability is pre-defined by OEMs. Which means we cannot customize more than the given customization choices, and different device might introduce different customization capabilities.

A: You can not change the navigation bar from your application; you do not have access to these settings. Instead, what you can do is using adb to hide the navigation bar and use only the navigation inside your app. You can follow this tutorial of XDA-dev and their application called "Navigation Gesture", you will find the adb command.


text:
Q: How do I get Thread.Priority to work on Linux (.NET Core 3.1) I'm having trouble getting Thread.Prority to do anything in a Linux build. It looks like the code to convert Thread.Priority to posix is there in the code (thanks huoyaoyuan) but I can't get this to work for me.
To demonstrate this, I've used a modified version of the code in the Thread.Priority doc which runs more threads so it works sensibly with multiple cores.
This is the output I get running on Windows (win-x64):

thread_5    with AboveNormal priority has a count =   563,441,005
thread_15   with      Normal priority has a count =   251,310,557
thread_3    with      Normal priority has a count =   239,580,270
thread_0    with      Normal priority has a count =   236,077,285
thread_2    with AboveNormal priority has a count =   537,902,014
thread_4    with BelowNormal priority has a count =     5,903,969
thread_7    with BelowNormal priority has a count =     5,958,548
thread_8    with AboveNormal priority has a count =   555,518,195
thread_11   with AboveNormal priority has a count =   549,665,909
thread_12   with      Normal priority has a count =   258,493,564
thread_14   with AboveNormal priority has a count =   550,025,919
thread_9    with      Normal priority has a count =   135,923,866
thread_6    with      Normal priority has a count =   138,882,526
thread_13   with BelowNormal priority has a count =     4,273,232
thread_1    with BelowNormal priority has a count =     4,608,543
thread_10   with BelowNormal priority has a count =     5,908,285

This is what I get on Ubuntu (linux-x64):

thread_4    with BelowNormal priority has a count =   465,192,119
thread_11   with AboveNormal priority has a count =   558,351,324
thread_9    with      Normal priority has a count =   459,901,696
thread_10   with BelowNormal priority has a count =   484,271,783
thread_7    with BelowNormal priority has a count =   519,165,910
thread_14   with AboveNormal priority has a count =   487,836,279
thread_12   with      Normal priority has a count =   465,635,561
thread_3    with      Normal priority has a count =   450,569,622
thread_5    with AboveNormal priority has a count =   503,227,636
thread_6    with      Normal priority has a count =   499,300,694
thread_8    with AboveNormal priority has a count =   515,728,537
thread_1    with BelowNormal priority has a count =   547,473,038
thread_15   with      Normal priority has a count =   462,427,461
thread_13   with BelowNormal priority has a count =   526,524,771
thread_2    with AboveNormal priority has a count =   493,184,092
thread_0    with      Normal priority has a count =   465,902,186

So it looks like all the threads are running at the same priority on Linux.
I've used setcap to give the app the required permissions:
sudo setcap 'cap_sys_nice=eip' ./ThreadPriorityTest
but that doesn't make any difference.
What am I missing?
Here's my modified sample code :
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using Timers = System.Timers;

namespace ThreadPriorityTest
{
    class Test
    {
        static void Main()
        {
            PriorityTest priorityTest = new PriorityTest();

            int threadCount = 16;

            List<Thread> threads = new List<Thread>();
            for(int i=0; i<threadCount; i++)
            {
                Thread thread = new Thread(priorityTest.ThreadMethod);
                thread.Name = $"thread_{i}";
                switch(i%3)
                {
                    case 0:
                        thread.Priority = ThreadPriority.Normal;
                        break;
                    case 1:
                        thread.Priority = ThreadPriority.BelowNormal;
                        break;
                    case 2:
                        thread.Priority = ThreadPriority.AboveNormal;
                        break;
                }
                threads.Add(thread);
            }

            Thread.CurrentThread.Priority = ThreadPriority.Highest;
            Console.WriteLine($"Starting {threadCount} threads...");
            foreach(Thread thread in threads)
            {
                thread.Start();
            }
            Console.WriteLine($"Done starting {threadCount} threads.");
            priorityTest.StartEvent.Set();

            // Allow counting for 10 seconds.
            Thread.Sleep(10000);
            priorityTest.LoopSwitch = false;
        }
    }

    class PriorityTest
    {
        static volatile bool loopSwitch;
        static ManualResetEvent startEvent = new ManualResetEvent(false);
        [ThreadStatic] static long threadCount = 0;

        public PriorityTest()
        {
            loopSwitch = true;
        }

        public bool LoopSwitch
        {
            set { loopSwitch = value; }
        }

        public ManualResetEvent StartEvent
        {
            get { return startEvent; }
        }

        public void ThreadMethod()
        {
            startEvent.WaitOne();
            while (loopSwitch)
            {
                threadCount++;
            }
            Console.WriteLine("{0,-11} with {1,11} priority " +
                "has a count = {2,13}", Thread.CurrentThread.Name,
                Thread.CurrentThread.Priority.ToString(),
                threadCount.ToString("N0"));
        }
    }
}

A: I was reluctant to post this as an issue on GitHub dotnet/runtime, as I was pretty sure the issue was with my ignorance of scheduling on Linux - and so it proved. However, I bit-the-bullet and got an answer. I needed to use chrt to run my process using the SCHED_RR scheduling policy. Thanks janvorli@github.


text:
Q: Correct notation for the probability of a discrete random variable Assume a random variable $X$ for a coin toss experiment. The sample space (i.e. possible outcomes) is in this case $\Omega = \{ \text{heads}, \text{tails}\}$.
The randon variable $X$ is a function that maps events (a particular outcome) $\omega$, which in this case is not measurable, to a measurable space, like so:
$X(\omega )={\begin{cases}1,&{\text{if}}\ \ \omega ={\text{heads}},\\0,&{\text{if}}\ \ \omega ={\text{tails}}.\end{cases}}
$
If I want to talk about the probability of $X$ taking certain value, I know I can write as follows (please correct me if I'm wrong, this is relatively new to me). For example, lets talk about the probability of tossing a head $\{\omega :X(\omega )=1\}$:

*

*$P(X(\text{heads}))$, edit after comments: this one is also wrong

*$P(X=1)$

*$P(\text{heads})$, although this no longer talks about the random variable.

But, is it correct to write any of the following?:

*

*$P(X=\text{heads})$

*$P(x=\text{heads})$, where small $x$ is a particular realization of $X$.

Edit 2017.05.25
I am looking for a more convenient notation that enables the reader to immediately see we are talking about "heads", as "1" by itself does not carry this meaning.

A: $\mathsf P(X=1)$ is acceptable notation for $\mathsf P(\{\omega\in\Omega: X(\omega)=1\})$, the probability for the event that $1$ is the value of the $X$ function for the outcome.   Because we are very lazy and would rather not write the whole thing out every time, we except the shorthand representation of the event.
Technically we could write it as $\mathsf P(X^{-1}\{1\})$ , though more often we'll write this as $\mathsf P_X(1)$ or $p_{\lower{0.5ex}X}(1)$ ; a probability mass function.
This is, of course, equal to $\mathsf P(\{\text{heads}\})$, or $\mathsf P(\text{heads})$.
$$X^{-1}\{1\} ~{:=~ \{\omega\in\Omega: X(\omega)=1\} \\[2ex]=~ \{\text{heads}\}}$$

It is not at all correct to write $\mathsf P(X=\text{heads})$ or $\mathsf P(X(\text{heads}))$.   $X=\text{heads}$ is an invalid type comparison.   $X(\text{heads})$ equals $1$, which is not an outcome of the probability space.


text:
Q: Не работает скрипт jquery.Что я делаю не так? Здравствуйте, пытаюсь сделать обработку формы с помощью jquery.Проект делается на laravel 5.3.Скрипт должен проверять форму на количество символов и если их меньше 3-х - оповещать об этом пользователя и останавливать запрос,ничего не добавляя в базу данных.Плюс при отправки данных страница не должна перезагружаться.
Код такой:
newcategory.blade.php
@extends('layouts.app')

@section('content')
<!doctype html>

    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>

<form method="POST" enctype="multipart/form-data">
    {{ csrf_field() }}
    <input type="text" name="title" id="title" placeholder="Добавить категорию">
    <input type="submit" class="btn-primary" value="Добавить" id="send">

</form>

@endsection

CategoriesController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Categories;
use Illuminate\Support\Facades\Input;
use Validator;

class CategoriesController extends Controller
{
    public function store(){

        $input = Input::all();
        $rules = array(
            'title' => 'required',
        );

        $validator = Validator::make($input,$rules);
        if($validator->fails()) {
            return $validator->errors();
        }
        if($validator->passes()) {
            $newcategory = new Categories;
            $newcategory->title=Input::get('title');
            $newcategory->save();
            return view('post.newcategory');
        }
    }

    public function index(){
        return view('post.newcategory');
    }
}

routes/web.php
Route::get('newcategory', 'CategoriesController@index');
Route::post('newcategory','CategoriesController@store');

При использовании данного кода данные формы беспрепятственно отправляются и сохраняются в базе данных,даже если введенных символов в форме менее 3-х. Подскажите пожалуйста,что я делаю не так?Заранее спасибо.

A: Для того чтобы можно было отправить форму нужен csrf-token. Он у вас есть в форме но вы его не отправляете. Присвойте форме id="send-form" событие напишите на ('#send-form').submit(), а данные в ajax отправляйте через data: ('#send-form').serialize(), чтобы отправлять все поля из формы сразу.

A: По поводу ошибки, у Вас лишняя точка в начале после знака $. Этот знак означает функцию jQuery, в которую мы передаем аргументы, в данном случае document. Кроме того, чтобы остановить отправку формы до проверки, нужно остановить действие браузера по умолчанию, воспользовавшись event.preventDefault().
Ваш код должен начинаться так
    $(document).ready(function () {
                $("#send").click(function (ev) {
                  ev.preventDefault();
                  var title = $("#title").val();
                  var fail="";
                  ...

и лучше бы повесить вашу функцию на событие submit самой формы, которое может происходить и просто при нажатии Enter, если пользователь находится в форме. Добавьте Id для формы и обрабатывайте событие отправки на ней
         $(document).ready(function () {
                $("#sendForm").submit(function (ev) {
                  ev.preventDefault();
                  var title = $("#title").val();
                  var fail="";
                  ...


text:
Q: Reuse components with internal state an vuex module store I want to reuse a Counter component with his own internal store.
The problem is when I change the state, it´s changed in all the Counter instances. I´m returning state as state = () => ({}) but, It´s shared in all instances...
How can setup this to use his own state?
Demo: https://codesandbox.io/s/infallible-black-k9e8f


text:
Q: How to pass value to another component in lightning? I try to use event with type="APPLICATION" in my superbadge step, but can't to get the result even from the simple second component.
I need to get my boat's Id when I press "Search" button. In both alerts I get it. But not in the second component. What is wrong here?
FormSubmit.evt:
<aura:event type="APPLICATION">
    <aura:attribute name="eventAttribute" type="String"/>
</aura:event>

BoatSearchForm.cmp:
<aura:component controller="BoatSearchFormApex" implements="force:appHostable,flexipage:availableForAllPageTypes" access="global" >
<aura:handler name="init" value="{!this}" action="{!c.doInit}" />
<aura:registerEvent name="formSubmit" type="c.FormSubmit"/>

<aura:attribute name="types" type='String[]' default='All'/>
<aura:attribute name="showNewButton" type="Boolean" default="true"/>

<lightning:layout horizontalAlign="center" verticalAlign="end" class="layoutClass">
    <lightning:select aura:id="types" name="types" variant="label-hidden" label="">
        <option value="allTypesValue">All Types</option>
        <aura:iteration items="{!v.types}" var="type">
            <option value="{!type.Id}">{!type.Name}</option>
        </aura:iteration>
    </lightning:select>

    <lightning:button variant="brand" label="Search" onclick="{!c.onFormSubmit}"/>
    <aura:if isTrue="{!v.showNewButton}">
        <lightning:button variant="neutral" label="New" onclick="{!c.newBoat}"/>
    </aura:if>
</lightning:layout>

Function in controller:
({
onFormSubmit : function(component, event, helper){
    var typeId = component.find("types").get("v.value");
    alert(typeId);
    var formSubmit = $A.get("e.c:FormSubmit");
    formSubmit.setParams({"eventAttribute" : typeId})
    var test = formSubmit.getParam("eventAttribute");
    alert(test);
    formSubmit.fire();
},
})

cmp2 for test:
<aura:component >
<aura:attribute name="Get" type="String"/>
<aura:handler event="c:FormSubmit" action="act"/>
The result is {!v.Get}
</aura:component>

cmp2Controller.js:
({
act : function(component, event, helper) {
    var show = event.getParam("eventAttribute");
    component.set("v.Get", show);
}
})

A: Your aura:handler tag has action="act", when it should be action="{!c.act}". Don't forget that it has to point to a controller action.
Also, on your declaration, you're using a period instead of a semicolon. Change this
<aura:registerEvent name="formSubmit" type="c.FormSubmit"/>
to this
<aura:registerEvent name="formSubmit" type="c:FormSubmit"/>


text:
Q: Is react-toolbox ready for webpack 4? I am having a dickens of a time getting the default styles of certain components (namely buttons with icons and dialogs) to display when compiled with Webpack 4 (using the MiniCssExtractPlugin in place of the ExtractTextPlugin.
Has anyone else found this to be the case when upgrading to Webpack 4?
annotated screenshot


text:
Q: Noether's theorems and General covariance Given the action
$$ A = \int_{M} d^{4}x \ \mathcal{L}(\phi, \nabla \phi) $$
where $\mathcal{L}$ is a lagrangian density, or if you prefer $\mathcal{L} = \sqrt{-g} \mathcal{\tilde{L}}$ and $\mathcal{\tilde{L}}$ a function of spacetime.
From Noether second theorem we know that diffeomorphism invariance produces the following identity:
$$ \nabla_{\mu} T^{\mu \nu } = \nabla_{\mu} \bigg( \frac{2}{\sqrt{|g|}}\frac{\delta \mathcal L}{\delta g_{\mu\nu}} \bigg) = 0$$
Where we have an infinite dimensional Lie Algebra $ \big( \ \Gamma (M) \ , \ [ , ] \ \big)$ where $\Gamma ( M ) $ are the smooth sections of the Tangent bundle $TM$.
So, smooth vector field generates the lie group of diffeomorphism, hence diffeomorphism invariance is arena for the Second Noether Theorem.
In principle I know that if we have a family $\xi_{(i)}^{\mu}$ of killing vector fields($\mathscr{L}_{\xi_{(i)}^{\mu}} g_{ab} = 0$), we can construct from $T^{\mu \nu}$ a conserved current and a corresponging conserved quantity integrating the current over a Cauchy Hypersurface.
This I know. But my question is: If in principle we start from a diffeomorphism invariant action, what stops me from defining arbitrary $\xi_{(i)}^{\mu}$ such that with the usual Lie Bracket $[ , ]$ form a finite dimensional Lie subalgebra of $ \big( \ \Gamma (M) \ , \ [ , ] \ \big)$. The action would still be invariant w.r.t. the action of the Lie Group generated by this Lie Subalgebra, hence I can apply Noether First Theorem obtaining free a conserved current and an integral conserved charge. All this without the assumption that $\mathscr{L}_{\xi_{(i)}^{\mu}} g_{ab} = 0$.
I mean Invariance from an infinite dimensional Lie Algebra implies invariance from a finite dimensional Lie Subalgebra (es. $SO(3)$). So why we need a priori killing vector field in this picture? Where Killing vector field enters the picture if my construction doesn't need them and is arbitrary on the choise of the Lie Subalgebra generators?

A: *

*OP is considering the matter action $S_m\equiv A$ and its corresponding symmetric SEM tensor $T^{\mu\nu}$ of matter.

*Notice that the gravitational Einstein-Hilbert (EH) action $S_{EH}$ is not included. For a good reason: The SEM pseudo-tensor $t^{\mu\nu}$ to the gravitational field is marred with problems.

*If one reads the fineprint of Noether's first theorem, one will notice that
its conservation laws are only satisfied modulo terms proportional to $\delta S_m / \delta g_{\mu\nu}$ and $\delta S_m /\delta\phi$. The latter vanishes on-shell since it is the EOM for $\phi$, but the former does not since the gravitational sector is incomplete. Hence its conservation laws are violated.

*See also this related Phys.SE post.


text:
Q: Lodash compare/merge object to array I need to compare/merge 2 objects with diferent structure using Lodash.
   data= [
      {
        "name": "EMPRESA",
        "value": ""
      },
      {
        "name": "DESIGEMPRESA",
        "value": "CMIP"
      },
      {
        "name": "UTILIZADOR",
        "value": ""
      },
      {
        "name": "CD_INDICADOR",
        "value": ""
      },
      {
        "name": "DT_INI_INDICADOR",
        "value": ""
      },
      {
        "name": "DT_INI",
        "value": "2017-12-13"
      },
      .....
    ]

and
dbcolsData={
  "EMPRESA": "",
  "UTILIZADOR": "paulo.figueiredo",
  "CD_INDICADOR": "",
  "DT_INI_INDICADOR": "",
  "DT_INI": "",
  "DT_FIM": ""
}

The question is how i can fill the values of data with the values of dbcolsData ?
Lets say put the values of dbColsData in data
Thanks in advance

A: Try something like this:
_.forEach(data, function(object){
   object.value = dbcolsData[object.name];
})

A: Use Array#map (or lodash's _.map()) to iterate the data, and get the results from dbcolsData:

var data = [{"name":"EMPRESA","value":""},{"name":"DESIGEMPRESA","value":"CMIP"},{"name":"UTILIZADOR","value":""},{"name":"CD_INDICADOR","value":""},{"name":"DT_INI_INDICADOR","value":""},{"name":"DT_INI","value":"2017-12-13"}];

var dbcolsData = {"EMPRESA":"","UTILIZADOR":"paulo.figueiredo","CD_INDICADOR":"","DT_INI_INDICADOR":"","DT_INI":"","DT_FIM":""};

var result = data.map(function(o) {
  return Object.assign({ data: dbcolsData[o.name] }, o);
});

console.log(result);

A: Reduce data to the dbcolsData structure :
var myData = data.reduce((o, nvO) => Object.defineProperty(o, nvO.name, {value: nvO.value}), {})

->
Now you can use lodash comparison functions like _.isEqual :
_.isEqual(myData, dbcolsData)


text:
Q: Failing to fill multiple rows in Pandas Dataframe with .iloc() method I'm having a hard time adding multiple rows of data to a dataset I have. For some reason, when I try to add values, it only sets the first row, and the rest of the rows are set to NaN.
It outputs the following as the head:
         Time    Open Tone
0  1449341520  377.48    0
1  1449341580  377.50  NaN
2  1449341640  377.50  NaN
3  1449341760  377.50  NaN
4  1449341820  377.50  NaN

Expected:
         Time    Open Tone
0  1449341520  377.48    0
1  1449341580  377.50    0
2  1449341640  377.50    0
3  1449341760  377.50    0
4  1449341820  377.50    0

btc_data.iloc[:position, -1] = to_btc_data["tone_id"] is supposed to set those rows up to what position is, but instead it only sets the first row.
Full code:
from pygooglenews import GoogleNews
import datetime
import time
from datetime import timezone
from datetime import datetime
import json
import numpy as np
import pandas as pd

gn = GoogleNews()

def create_week_data(ts=1449341520):
  df = pd.DataFrame()

  search = gn.search('Bitcoin', from_=datetime.fromtimestamp(ts).strftime('%Y-%m-%d'), to_=datetime.fromtimestamp(ts+604800).strftime('%Y-%m-%d'))

  titles=[]
  dates=[]
  timestamps=[]

  for item in search["entries"]:
    titles.append(item["title"])
    dates.append(item["published"])

  df["published"] = dates
  df["title"] = titles

  for item in dates:
    month = 1

    if (item[8:11] == "Jan"):
      month = 1
    elif (item[8:11] == "Feb"):
      month = 2
    elif (item[8:11] == "Mar"):
      month = 3
    elif (item[8:11] == "Apr"):
      month = 4
    elif (item[8:11] == "May"):
      month = 5
    elif (item[8:11] == "Jun"):
      month = 6
    elif (item[8:11] == "Jul"):
      month = 7
    elif (item[8:11] == "Aug"):
      month = 8
    elif (item[8:11] == "Sep"):
      month = 9
    elif (item[8:11] == "Oct"):
      month = 10
    elif (item[8:11] == "Nov"):
      month = 11
    elif (item[8:11] == "Dec"):
      month = 12

    dt = item[5:7]+"/"+str(month)+"/"+item[12:16]

    timestamps.append(int(time.mktime(datetime.strptime(dt, "%d/%m/%Y").timetuple())))

  df["timestamp"] = timestamps

  return df

from ibm_watson import ToneAnalyzerV3
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
import json

watson_api_key = "KEY"
watson_url = "URL"

authenticator = IAMAuthenticator(watson_api_key)
tone_analyzer = ToneAnalyzerV3(version='2021-11-27', authenticator=authenticator)
tone_analyzer.set_service_url(watson_url)

def to_tone(df = df):
  toneData = pd.DataFrame()
  tones = []
  timestamps = []

  for index, row in df.iterrows():
    timestamp = row["timestamp"]
    title = row["title"]

    dump = json.dumps(tone_analyzer.tone(title).get_result())[10:]
    tone_id = 0;

    if (dump.find("Joy") >= 0):
      tone_id = 1
    elif (dump.find("Anger") >= 0):
      tone_id = 2
    elif (dump.find("Fear") >= 0):
      tone_id = 3
    elif (dump.find("Sadness") >= 0):
      tone_id = 4
    elif (dump.find("Analytical") >= 0):
      next
    elif (dump.find("Confident") >= 0):
      next
    elif (dump.find("Tentative") >= 0):
      next
    else:
      tone_id = 0

    tones.append(tone_id)
    timestamps.append(timestamp)

    if (len(tones) >= 1):
      break

  toneData["timestamp"] = timestamps
  toneData["tone_id"] = tones

  return toneData

print(to_tone())

import numpy as np
import pandas as pd

np.set_printoptions(precision=15, suppress=True)
btc_data = pd.read_csv(
    "/content/drive/MyDrive/Science Fair/output.csv",
    names=["Time", "Open"])

btc_data["Tone"] = None

ts = 1449341520
position = 0

while (True):
  to_btc_data = pd.DataFrame()

  to_btc_data = to_tone(df=create_week_data(ts=ts))

  for index, row in btc_data.iterrows():
    timestamp = row["Time"]

    if (timestamp >= ts):
      ts = timestamp
      position = index
      break

  btc_data.iloc[:position, -1] = to_btc_data["tone_id"]

  ts+=604800

  print(btc_data.head())

  if (ts > 1617148800):
    btc_data.iloc[ts+604800:] = to_btc_data[0]
    break

btc_data.head()

Whatever value is in the to_btc_data DF is supposed to be set there. What am I doing wrong here?
Also sorry about the terribly structured code. I am playing on organizing it during production, and I usually don't code in Python so I won't be writing any beautiful code.


text:
Q: Multiple docx file read collectively I'm trying to make a framework under which a folder will contain multiple word document which python will read collectively & would provide me an output with all the SSN in that file.
I'm done with the solution also, i.e. I'm able to build the function which provides the results, but I want to get the corresponding file name also from which the SSN is extracted.
#importing libraries
import pandas as pd
import docx2txt

#extracting data from all the files at once
import glob
data = ''
for file in glob.glob('C:/Users/d118/Desktop/Word Files/*.docx'):
    data += docx2txt.process(file)

#defining the function
def isSSNNumber(text):
    if len(text) != 11:
        return False
    for i in range(0,3):
        if not text[i].isdecimal():
               return False
    if text[3] != '-':
           return False
    for i in range(4,6):
         if not text[i].isdecimal():
            return False
    if text[6] != '-':
           return False
    for i in range(7,11):
         if not text[i].isdecimal():
            return False
    return True

#using the function
result = []
for i in range(len(data)):
    chunk = data[i:i+11]
    if isSSNNumber(chunk):
        result.append(chunk)

#required dataframe

df = pd.DataFrame(result)
df

Now that I have my SSN extracted I also want to have corresponding file name from which they exactly belong to.
Please click below to see the output.
Output

A: Try using this:
def isSSNNumber(text, file):
    if len(text) != 11:
        return False
    for i in range(0,3):
        if not text[i].isdecimal():
               return False
    if text[3] != '-':
           return False
    for i in range(4,6):
         if not text[i].isdecimal():
            return False
    if text[6] != '-':
           return False
    for i in range(7,11):
         if not text[i].isdecimal():
            return False
    print(file)
    return True

main:
for file in glob.glob('C:/Users/d118/Desktop/Word Files/*.docx'):
    data = docx2txt.process(file)
    result = []
    for i in range(len(data)):
        chunk = data[i:i + 11]
        if isSSNNumber(chunk, file):
            result.append(chunk)


text:
Q: Change content between vertical line in Rust In Neovim, I usually do a "change inside" action - key: ci + <char> - to change the content inside some brackets or quotations. But it does not work for the vertical line in a rust closure.
    // ---------------- v cursor here ---------
    let spawn_worker = |nonce: u32| {
        let tx = nonce_tx.clone();
        thread::spawn(move || {
            // Do the CPU work
            let _ = make_block(nonce).hash();

            // Send the result
            let _ = tx.send(());
        })
    };

For example, I put the cursor here and press ci + | but it does not work.
Does anyone know the most intuitive way to do it without selecting the content for closures in Rust?


text:
Q: how to check gltf model lightning after loading in aframe? I have a gltf model with lightning information, in https://gltf-viewer.donmccurdy.com/ it looks like:

after I import it like :
         <a-asset-item id="meeting_room" src="https://cdn.glitch.me/a8291825-29e8-463c-aa81-b88bf9bbe58c/changjing_v03.gltf?v=1657000875278"></a-asset-item>
...
    <a-gltf-model position="0 0 0" scale="1 1 1" src="#meeting_room"></a-gltf-model>

it looks like:

Question: where and how to enable the gltf light source? I don't see light entity in the inspector  besides the aframe default light. if I turn off the aframe light entity off, it turns out all black.
a demo glitch is here: glitch
20220705:
I try
<a-scene renderer="
               colorManagement: true;">

but cant get gltf lights as well.
update 20220706

as Piotr Adam Milewski and Mugen87 mention, in lightning setting in gltf viewer, there is environment light and "add lights", which add a ambient and a direction light to the scene. the environment light is from gltf export, which needs to open a environment light in THREEJS. how about the "add lights" ambient and direction light? is from gltf file or the gltfviewer? if it's from gltf file, how to check it's position color or intensity things?


text:
Q: How to load bag data in Apache Pig Here is my sample bag data and my file name is bag.txt:
{(8,9),(0,1)},{(8,9),(1,1)}
{(2,3),(4,5)},{(2,3),(4,5)}
{(6,7),(3,7)},{(2,2),(3,7)}

Now i want to load this data in my Apache Pig shell when I am loading this data using
A = LOAD '/home/mvsubhash/Desktop/bag.txt' AS (B1:bag{T1:tuple(t1:int,t2:int)},B2:bag{T2:tuple(f1:int,f2:int)});

But my final result is like this
({(8,9),(0,1)},)
({(2,3),(4,5)},)
({(6,7),(3,7)},)

In the above result second bag is not processing.

A: By default the delimiter used for reading the file in Pig is tab(\t).Since your records is a comma seprated bags.Try using PigStorage(,)
A = LOAD '/home/mvsubhash/Desktop/bag.txt' USING PigStorage(',') AS (B1:bag{},B2:bag{});

A: This data is not in format which Pig can process, as the record separator inside bag is similar to record separator between fields in a row i.e ',' so this can only be done using UDF.
But if we represent the field separator in record as Semicolon  ";"
Then we can load the data using:
grunt> Data = load 'bag_data' using PigStorage(';') as (Bag1:bag{tuple1:(A1:int,A2:int)},Bag2:bag{tuple2:(B1:int,B2:int)});
grunt> Dump Data;


text:
Q: Python: read output while executing cmd commands I am executing cmd commands using python subprocess module. Execution of this cmd commands (eg., running some batch file, .exe file) are opening new command prompt window. How to read output of newly open cmd window using python?
I am using following code to execute commands provided by user:
process = subprocess.Popen(command, cwd = working_directory, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

I am using process.communicate() method to read the output. However it is allowing me to read output of the existing command prompt window only. If user is providing command which triggers new command prompt window, then how to read output of that window?

A: Below code opens a new command prompt, execute a command there and display the output of that command window
from subprocess import Popen,CREATE_NEW_CONSOLE,PIPE

# /K option tells cmd to run the command and keep the command window from closing. You may use /C instead to close the command window after the

command='cmd /C help'
proc=Popen(command,creationflags=CREATE_NEW_CONSOLE,stdout=PIPE)
output=proc.communicate()[0]
print ('').join(output)


text:
Q: Zend Framework 2. Invokables                 return array(
                'router' => array(
                    'routes' => array(
                        'wall' => array(
                            'type' => 'Zend\Mvc\Router\Http\Segment',
                            'options' => array(
                                'route' => '/api/wall[/:id]',
                                'constraints' => array(
                                    'id' => '\w+'
                                ),
                                'defaults' => array(
                                    'controller' => 'Wall\Controller\Index'
                                ),
                            ),
                        ),
                    ),
                ),
                'controllers' => array(
                    'invokables' => array(
                        'Wall\Controller\Index' => 'Wall\Controller\IndexController',
                    ),
                ),
            );

I am looking at the configuration for a module Wall which is part of a JSON restfull API program with Zend Framework 2. In /myprogram/Wall/src/Controller directory there is a file IndexController.php and inside it the namespace is declared 'namespace Wall\Controller'. My question is about 'invokables'. The right hand side of '=>' makes sense to me it is referencing the controllers class name and namespace if I understand correctly. What is on the left hand side of '=>' I am still looking for an explanation of what is 'Wall\Controller\Index'.
Thank you for posting...

A: invokables defines classes you can call. You would usually define classes that can be invoked like this:
'invokables' => array(
    'Some\Namespace\Class',
    'Some\Namespace\OtherClass',
),

You can also define aliases, by passing an array, like in the example you gave:
'invokables' => array(
    'Wall\Controller\Index' => 'Wall\Controller\IndexController',
),

It defines Wall\Controller\Index invokable as an alias for Wall\Controller\IndexController.

A: It's really just a key. Arrays within the configuration are stored with the schema key => value. And the string Module\Controller\Foo is just it's name. You could write module-controller-foo, too, and use it like this within your route configuration.


text:
Q: Can different power socket in one house charge at different speeds We all have power socket at our homes. Now I observed something:
When I connect my phone for charging at socket it charges up at a faster rate than other socket obviously with the same cable and adaptor
How is this is possible since all the connections have a common connection to main circuit in the house?
This is the typical circuit . I think the purpose of switch is only to supply power and that will be available at equation rate but is it somehow possible that the circuit had some problem which gave me this observation?
charges fast and less used
 charges slow and frequently used

A: Highly unlikely that the charging points are centralized. Much more likely that each USB charging point is its own device, each with its own connection to the mains. If some are charging differently than others, it is the fault of the local USB charger.
The reason? Long lines have high voltage drop which is bad when your voltage is already low to begin with. Losing 1V when your voltage is 120V is barely noticeable. Losing 1V when your voltage is 5V is very bad.

A: The voltage on ac sockets on a house can very quite a bit. From the circuit breaker panel comes many different branch circuits. If there is a branch circuit supply a huge amount of cuurent to a portable heater, the voltage at the circuit breaker panel may be 120VAC but the voltage at the socket which connects heater is at 110VAC because 10 volts are dropped by the wiring.  But another socket in the house may be 120V because there is nothing hooked up to it, no current flow, no voltage drop.
But most phone chargers provide the same amount of power to a phone down to 90 volts at the socket, so this is not a problem. If you have an older adapter that is heavy because it has a big transformer in it (it also gets hot) to charge your phone....there could be a difference in time to charge

A: 5V USB chargers are not all built the same and vary in their intended output, from 500mA on older models or models specific to low power devices to 4 or more amp on multiport chargers.  Not all chargers can sustain 5V at maximum charging current.  They also regulate the 5V output voltage based on an internal reference, so reasonable line voltage changes won't affect the USB charger output.
In addition to that, USB chargers with additional charge voltage exist.  On my Samsung S6, it's called adaptive fast charge, but I believe the other voltages were built as options into the USB standard.  USB C can support up to 90W based on existing chargers.
Many or most phones will say "Charging" or "Fast charging depending on what you plug them into.

A: Just measure voltage in your wall outlet (with some load plug in!), it should be the equal. If not the problem  is in house installation.


text: Q: Measuring compositions using peak heights or FWHM? Let's say I have a simple X-ray spectrum, consisting of peaks corresponding to emission lines. How do I determine the percentage-wise composition of the source? Is it by taking the heights of the peaks, summing them, and then dividing one peak height by the total to get that peak's composition? Or is there something more complicated involved by taking the FWHM? What can the FWHM be used for?


text:
Q: Python 3.7: Library not loaded I downloaded and installed Python 3.7 macOS 64-bit installer from
https://www.python.org/downloads/release/python-370/
I have the IDLE, so I know I installed python.
However, when I try to check the version I have on terminal, it appears:
$ python -v
dyld: Library not loaded: @rpath/Python
  Referenced from: /Users/EmiPaz/Library/Enthought/Canopy_64bit/User/bin/python
  Reason: image not found
Abort trap: 6


text:
Q: How to calculate a confidence interval for a series of Bernoulli Trials? I have to test if a event have a p probability of happening. I can run this event as much times I like (given it can be run by a computer). So I was searching a way to test if the probability of this event is in an acceptable range for my case.
How can I compute, given $n$ Bernoulli Trials with probability $p$ ($P(\text{Success}) = p$ and $P(\text{Failure}) = 1-p$), the probability of ($\text{no. of successes}/n$) be within a range of $[p-a, p+a]$? [1]
Example: given 100 events, whats the probability of the proportion of successes to be greater than 45% but lesser than 55% of the total number of events?
(Apologize my lack of formalization, I have little background in statistics, only studied it in my graduation, but you can point me to the concepts and theories that I need to study to solve this problem).
Edit:
Seeing now the answers I see that I poorly asked my question.
This [1] was just a way that I thought I could achieve what I want, which is:
I have an event that I expect it to have a probability $p$ of yielding success and $1-p$ probability of yielding failure. By observing this event $n$ times, I can infer the $p'$ observed probability of that event succeeding ($\text{no of success}/n$). So I want to compare $p$ against $p'$ and check if my initial guess (which is $p$) is correct, in other words, I want to be able to claim that my event has a 99% chance of having a $p \pm \alpha$ probability of succeeding.
I thought on doing a Hypothesis Test but I couldn't quite fit my problem into it.

A: Contrary to the other answer, you don't need approximations in here. If $x$ is the number of success and $n$ is the number of trials, then you are looking for
$$
\Pr\{p-a \le \tfrac{x}{n} \le p+a\} = \Pr\{np-na \le x \le np+na\}
$$
The sum of $n$ independent Bernoulli trials, each with probability of success $p$, follows binomial distribution. Knowing this, you can calculate things like
$$
\Pr\{x \le np+na\} = F_X(np+na)
$$
where $F_X$ is the binomial cumulative distribution function, and use it to calculate the probability of interest.

A: Let us start from the scratch here.
Let $X_i \, i = 1,2,...,n$ be independent random variables which take value $0$ if failure occurs on the $i^{th}$ trial and $1$ if success.
Further, let the probability of success in each trial be $p$. Then each $X_i$ are identical too.
Further we know that, from the theory of statistics, $\sum\limits_{i=1}^{n}X_i \sim Bin(n, p)$
Further, let $\hat{p} = \dfrac{\sum\limits_{i=1}^{n}x_i}{n}$ be the observed sample proportion.
We need to check or infact build a $99\%$ confidence interval for $p$ based on the observed $\hat{p}$.
Now, for a very brief description of confidence intervals, it is a random interval $(a(\textbf{X}), b(\textbf{X}))$ (where $\textbf{X}$ is the random vector) with some pre-specified level of confidence say $(1-\alpha)$ such that when the sampling procedure is repeated for a large number of times, these random intervals shall contain the true parameter $100(1-\alpha)\%$ times. You can read more about confidence intervals online.
Given this description, we may now proceed to solve our problem. So we need an interval of type $(a(\textbf{X}), b(\textbf{X}))$ such that when we repeat our experiment with $n$ trials, a large number of times, these intervals will contain the true value of $p$ on an average $99\%$ of times.
There are various methods available to construct the confidence intervals, however I would proceed with the most common one, that is Pivotal Quantity Method. Again, you can read more about this online. For the purpose of this answer, a pivotal quantity is that quantity whose distribution does not depend on any parameter.
Now, since your $n(=100)$ is large and assuming that the value of $p$ does not lie in the extremes, we have by the CLT that $Z(say) = \dfrac{\hat{p} - E(\hat{p})}{\sqrt{Var(\hat{p})}} \sim N(0,1)$. Clearly $Z$ is a pivotal quantity. Further, $E(\hat{p}) = p$ and $Var(\hat{p}) = \frac{p(1-p)}{n}$. But since, $p$ is unknown, we use an estimate of $Var(\hat{p})$ instead, which is equal to $\frac{\hat{p}(1-\hat{p})}{n}$.
Now, all we need is to construct the confidence interval.
We know that since $Z \sim N(0,1)$,
$P(-Z_{0.005} < Z < Z_{0.005}) = 0.99$
Where $Z_{\alpha}$ is such that $P(Z \geq Z_{\alpha}) = \alpha$ and $Z$ is the standard normal variate.
So,
$P(-Z_{0.005} < \dfrac{\sqrt{n}(\hat{p} - p)}{\sqrt{\hat{p}(1-\hat{p})}} < Z_{0.005}) = 0.99$
Finally, rearrange the inequalities inside the probability to obtain a statement in terms of the parameter $p$ and by plugging in the values of observed $\hat{p}$, you get the required confidence intervals.
Note: Another answer mentioned about using cumulative distribution function of Binomial distribution to construct such intervals. I would like to add that that is also a method. You can use any.

A: Let's $\hat{p} = \tfrac{1}{n}\sum_i x_i$ where $x_i$ is the realisation $0$ or $1$ and $n$ the number of trials.
Using the approximation of binomial to normal distribution, you have :
$$\mathbb{P}[45\%<p<55\%] = \mathbb{P}\left[\tfrac{45\%-\hat{p}}{\sqrt{\tfrac{\hat{p}(1-\hat{p})}{n}}}<\tfrac{p-\hat{p}}{\sqrt{\tfrac{\hat{p}(1-\hat{p})}{n}}}<\tfrac{55\%-\hat{p}}{\sqrt{\tfrac{\hat{p}(1-\hat{p})}{n}}}\right] = \Phi\left[\tfrac{55\%-\hat{p}}{\sqrt{\tfrac{\hat{p}(1-\hat{p})}{n}}}\right] - \Phi\left[\tfrac{45\%-\hat{p}}{\sqrt{\tfrac{\hat{p}(1-\hat{p})}{n}}}\right]$$
where $\Phi$ is the normal distribution function.


text:
Q: Error: Deployment failed: ERROR_DESTINATION_NOT_REACHABLE when deploying to App Service from Azure DevOps Services I am trying to deploy my site to an App Service from Azure DevOps Services. However, when I try to deploy the site, the Deploy Azure App Service task fails with the error message:

Error: Error Code: ERROR_DESTINATION_NOT_REACHABLE
  More Information: Could not connect to the remote computer ("{my-website}.scm.azurewebsites.net"). On the remote computer, make sure that Web Deploy is installed and that the required process ("Web Management Service") is started.  Learn more at: http://go.microsoft.com/fwlink/?LinkId=221672#ERROR_DESTINATION_NOT_REACHABLE.

Steps to replicate:

*

*Create a site in .NET Core and uploaded it to an Azure Repo in Azure DevOps Services

*Create an App Service in the Azure Portal with a staging deployment slot

*Create a pipeline in the Pipelines section Azure DevOps which will build the solution and publish the build artifacts to the default staging directory

*Create a pipeline in the Releases section of Azure DevOps which will take the build artifact and run the Deploy Azure App service task to deploy it to my app service. (I filled in the mandatory fields, but not the optional ones.)

The logs for the release pipeline show that it is failing on the msdeploy.exe (ComputerName='https://{my-website}.scm.azurewebsites.net:443/msdeploy.axd?site=dotnetcore-webpack-test') step with the above error, due to a 404.
https://{my-website}.scm.azurewebsites.net:443 will take me to the kudu dashboard, but the route /msdeploy.exe, returns a page saying "No route registered for '/msdeploy.axd'"
According to the link in the error message, this error is caused by "Web Management Service or Remote Agent is not installed or unreachable on the remote computer."
However, I am trying to deploy to an App Service, not a VM, and all the tutorials I've been trying to follow, it simply seems to work out of the box without them needing to configure web management services/firewall settings  etc.
Am I missing a step or doing something wrong? I'd appreciate any advice on how to troubleshoot this further.

A: You need to check if your app service is hosted on Windows OS. You can select the Operation System when you create your app service from Azure Portal.

If the operation system is Linux and you deploy as a Web App on Windows in App Service Deploy task, you will get aboveERROR_DESTINATION_NOT_REACHABLE error. You can try recreating you web app services from azure portal and try to deploy again.
You can check the detailed steps in this tutorial(in yaml format).
I followed above steps of yours. It worked fine for me. When I create a web app services on Linux system. I got the same error with yours. Below is my App Service Deploy task.

Hope above helps!


text:
Q: Logic related to sessions I have an requirement to show users a pop up when there is one minute left to session expires time. Suppose session expiration time is 5 minutes and I need to show a pop up that "Your session will expire in next one minute" please click here if you want to continue otherwise click cancel. So, if user clicks ok, time should again refreshed automatically and if cancelled then no need to do any thing .
For this I have done something like this in my Shared folder in Layout
var myVar = setInterval(function () { myTimer() }, 240000);
function myTimer() {
    var r = confirm("Session will expire in a minute. will you like to continue working?");
    if (r == true) {
        var _Id = $("#Id").val();

        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "../Home/ResetUser",
            data: "{'User_ID':'" + _Id + "'}",
            dataType: "json",
            success: function (data) {
                if (data.Data == 'Done') {
                }
            },
            error: function (xhr) {
            }
        });
    }
    else {
        window.clearInterval(myVar);
    }

But I have one problem and that is I do not have the same layout derived in all the pages. Some modules have different layout and some pages do not need any layout.So, I need to keep that script running differently for different layouts or the pages which do not use the layouts.
Will it work fine if I keep the script differently for different layouts?
Also Suppose I have logged in and I set a session variable. Now time is set to 5 minutes
and user come to home page which is not using the layout  where I kept the above script.
I have the script added differently in this page and script function time starts..
but then user went to another page then session time will refreshed?
and I have to load my above script function on that page?
Am I doing the right things.

A: Hi You can write your script in _viewstart.cshtml file.
This will be executed for each request irrespective of the Layout page you are using
but then user went to another page then session time will refreshed? and I have to load my above script function on that page?
Yes when you user refresh the page or request the server again the session time will be reset.
This is the one way to achieve your requirement.


text:
Q: `import re` вызывает ошибку: "AttributeError: module 'enum' has no attribute 'IntFlag'" При компиляции Python, компилятор ссылается на файл re.py который тот в свою очередь ссылается на enum.py
При обработке re.py в консоль выходит ошибка

Traceback (most recent call last):
   File "string", line 1, in "module"
File "C:\Users\Gr4Y\AppData\Local\Programs\Python\Python3632\lib\tkinter__init__.py", line 39, in
  "module"
import re
File "C:\Users\Gr4Y\AppData\Local\Programs\Python\Python36-32\lib\re.py", line >143, in "module"
class RegexFlag(enum.IntFlag):
AttributeError: module 'enum' has no attribute 'IntFlag'

Данная ошибка была вызвана когда я используя программу для сборки .py в .exe  .
Программа Auto Py To Exe Master
https://github.com/brentvollebregt/auto-py-to-exe

A: Требуется удалить enum34.
Введите в терминале (или консоли):
pip uninstall enum34


text:
Q: Async request in Redux Here is my store:
import {createStore, applyMiddleware} from 'redux';
import reducerFoo from './reducers/reducer';
import thunkMiddleware from 'redux-thunk';

export default function configureStore() {
  return createStore(
    reducerFoo,
    applyMiddleware(thunkMiddleware)
  );
}

actions:
import * as types from './actionTypes';
import axios from 'axios';

export const selectTag = function(tag) {

  fetchQuestions(tag);

  return {
    type: types.SELECT_TAG,
    selectedTag: tag
  }
};

export const receiveQuestions = (json) => ({
  type: types.RECEIVE_QUESTIONS,
  questions: json
});

export const fetchQuestions = tag => {

  console.log(tag);

  let url = 'https://api.stackexchange.com/2.2/questions?order=desc&site=stackoverflow ....';
  console.log(url);

  return function(dispatch) {
    return axios.get(url).then((response) =>
      dispatch(receiveQuestions(response))
    );
  };
};

reducer:
import * as types from '../actions/actionTypes';
import { fetchQuestions } from '../actions/actions';

const initialState = {
  questions: [],
  showTagPanel: true,
  selectedTag: '...',
  tags: ['one', 'two', 'three']
};

export default function reducerFoo(state = initialState, action) {

  switch(action.type) {

    case types.SHOW_TAG_PANEL:

      return Object.assign({}, state, {
        showTagPanel: true
      });

    case types.SELECT_TAG:

      return Object.assign({}, state, {
        showTagPanel: false,
        selectedTag: action.selectedTag
      });

    case types.RECEIVE_QUESTIONS:

      console.log('get it');
      return state;

    default:
      return state;
  }
}

I can see url and the tag in the console:
export const fetchQuestions = tag => {

  console.log(tag);

  let url = 'https://api.stackexchange.com/2.2/questions?order=desc&site=stackoverflow ....';
  console.log(url);

But the RECEIVE_QUESTIONS action is not working:
case types.RECEIVE_QUESTIONS:
      console.log('get it');
      break;

Why and how can I fix it ?
Update: but it works if I call it from index.js:
const store = configureStore();
store.dispatch(fetchQuestions('...'));

Update 2: I think in selectTag() I need to use
dispatch(fetchQuestions(tag));

instead of
fetchQuestions(tag);

but I don't know how to get dispatch() here.

A: Inside your fetchQuestions function, you have:
return function(dispatch) {
  return axios.get(url).then((response) =>
    dispatch(receiveQuestions(response))
  );
};

However, the place you're calling the function, within selectTag function: fetchQuestions(tag); is returning
function(dispatch) {
  return axios.get(url).then((response) =>
    dispatch(receiveQuestions(response))
  );
};

But it's never being called anywhere else. So one thing you can do is instead of returning that function within fetchQuestions, just call the axios.get part within which will eventually dispatch the receiveQuestions action once the get request returns.
export const fetchQuestions = tag => {

  console.log(tag);

  let url = 'https://api.stackexchange.com/2.2/questions?order=desc&site=stackoverflow ....';
  console.log(url);

  return axios.get(url).then((response) =>
    dispatch(receiveQuestions(response))
  );
};


text:
Q: Skew the drawing horizontally and vertically in html5 canvas using mouse In my code I am loading images to canvas element. Then I need to drag, resize, rotate and skew it. I managed to implement both dragging and resizing. How can I implement skew using mouse on this code? I read a helpful article on this subject (http://www.subshell.com/en/subshell/blog/image-manipulation-html5-canvas102.html). I found fabricjs plugin, but it work only one image and without drag. For example: http://fabricjs.com/matrix-transformation/ .
If you will use the transform function:
ctx.transform(1, 0.5, -0.5, 1.2, 30, 60);

This will transform all image objects assigned to the canvas element. I would like only the selected image.
My code:
https://jsfiddle.net/sjLnqk5d/2/

A: Here's an updated fiddle that allows you to skew any image individually by pressing Shift when clicking one of the corner handles. You may need to tweak it a little bit to have the movements appear a bit more intuitive.
The trick is indeed in using ctx.save() and ctx.restore() around the ctx.transform() call, which makes sure that the transformation (and any other property changes) only applies between the save and restore.
Here are the key changes:
Shape.prototype.draw:
...
var skewX = this.skewX;
var skewY = this.skewY;
imgNew.onload = function(){
    ctx.save();
    ctx.transform(1, skewX/100, skewY/100, 1, 0, 0);
    ctx.drawImage(imgNew, locx, locy, width, height);
    ctx.restore();
}


text:
Q: Is there any way to make an apk run on emulator? I have an apk that does not install on emulators or tablets, I was wondering if it has any method?
Already opened the file with android studio, apk clone enter image description here
I get this message:

The app does not support this device, install and use on your mobile

A: Try getting an app such as BlueStacks, it should be able to run APKs.


text:
Q: IIS redirecting subdomain and an optional path How can I redirect a subdomain to a path BUT the path may also contain the subdomain. It's not any subdomain so I don't need wildcards but a specific one so for example using 'test' as the subdomain:
test.example.com/test/this-is-a-test

or
test.example.com/this-is-a-test

which I'd like either one to redirect to:
example.com/test/this-is-a-test

This is what I have so far but I cannot get it to work:
<rule name="redirect test.example.com" patternSyntax="ECMAScript" stopProcessing="true">
    <match url=".*" />
    <conditions logicalGrouping="MatchAny">
        <add input="{HTTP_HOST}" pattern="^test.example.com(/test)?" />
    </conditions>
    <action type="Redirect" redirectType="Permanent" url="https://www.example.com/test/{R:0}" appendQueryString="true" />
</rule>

A: This should've been rather simple but due to my unfamiliarity with the IIS rewrite module it became complicated. I misunderstood one important thing which is match url=... is not actually the full URL but rather the path after domain.com/
So after that revelation it was easy to implement like so:
<match url="^(test)?/?(.*)" />
<conditions logicalGrouping="MatchAny">
    <add input="{HTTP_HOST}" pattern="^test.example.com" />
</conditions>
<action type="Redirect" redirectType="Permanent" url="https://www.example.com/test/{R:2}" appendQueryString="true" />


text:
Q: Selenium Parallel execution Hey guys i am running parallel operations in headless mode or without headless mode i get the same error, which are the following :
INFO: Using parallel execution mode 'CONCURRENT' set via the 'junit.jupiter.execution.parallel.mode.default' configuration parameter.

stale element reference: element is not attached to the page document

stale element reference error is a WebDriver error that occurs because the referenced web element is no longer attached to the DOM. ... When an element is no longer attached to the DOM, i.e. it has been removed from the document or the document has changed, it is said to be stale
How can i fix this problem?
My test configs
test {
    systemProperty("junit.jupiter.execution.parallel.enabled", true)
    systemProperty("junit.jupiter.execution.parallel.mode.default", "CONCURRENT")
    useJUnitPlatform()
}

and my webdriver initialisation
 protected WebDriver driver;
    protected String TARGET_URL;

    @BeforeEach
    public void setUp() {
        WebDriverManager.chromedriver().setup();
        driver = new ChromeDriver(new ChromeOptions());
        driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
        driver.manage().window().maximize();
        loginToEnvironment();
    }

    @AfterEach
    public void tearDown() {
        driver.manage().deleteAllCookies();
        driver.close();
    }


text:
Q: How do I download a specific revision of llvm? I am trying to patch clang with the latest version of templight (2014 Jan 22). However, this version unfortunately fails to patch clang 3.4 or 3.5, and presumably only works with the revision it was designed for (trunk 199501).
How can I obtain this particular revision of clang?

A: You can obtain it via subversion:
$ svn checkout https://llvm.org/svn/llvm-project/cfe/trunk@199501

it is dated Jan 17, 2014.


text:
Q: PostgreSQL custom exceptions? In Firebird we can declare custom exceptions like so:

CREATE EXCEPTION EXP_CUSTOM_0 'Exception: Custom exception';

these are stored at the database level. In stored procedures, we can raise the exception like so:

EXCEPTION EXP_CUSTOM_0 ;

Is there an equivalent in PostgreSQL ?

A: No, not like this. But you can raise and maintain your own exceptions, no problem:
CREATE TABLE exceptions(
    id serial primary key,
    MESSAGE text,
    DETAIL text,
    HINT text,
    ERRCODE text
);

INSERT INTO exceptions (message, detail, hint, errcode) VALUES ('wrong', 'really wrong!', 'fix this problem', 'P0000');

CREATE OR REPLACE FUNCTION foo() RETURNS int LANGUAGE plpgsql AS
$$
DECLARE
    row record;
BEGIN
    PERFORM * FROM fox; -- does not exist, undefined_table, fail

    EXCEPTION
        WHEN undefined_table THEN
            SELECT * INTO row FROM exceptions WHERE id = 1; -- get your exception
            RAISE EXCEPTION USING MESSAGE = row.message, DETAIL = row.detail, HINT = row.hint, ERRCODE = row.errcode;

    RETURN 1;
END;
$$

SELECT foo();

Offcourse you can also have them hardcoded in your procedures, that's up to you.


text:
Q: ZF3 upgrade does not show exceptions anymore in views using ZF2 I was able to show $this->display_exceptions in my views but after upgrading to ZF3 this does not work anymore.
Is this changed as well in ZF3 or am I missing something ?


text:
Q: Crawlspider to parse and add links from XML pages on the way I have created a crawlspider for my needs it works perfectly. However there are certain xml sitemaps on some categories(not in all) on the site I am crawling. So I would like to have the feature to parse .xml sitemap on these categories and get links then leave it to the crawlspider to go deeper to those links.
I am aware that there is a SitemapSpider and XMLFeedSpider however I need the functionality of crawlspider with XMLFeedSpider or vice-versa.
Any help would be appreciated.

A: To make CrawlSpider work with URLs in sitemaps, you can cook up a custom link extractor for XML responses, but it looks like
CrawlSpider does not process XML responses. So you also need to override _requests_to_follow to accept them.
Here's an example spider I tried with a sitemap.gz URL to start with (containing a sitemapindex)
from scrapy.spiders.crawl import CrawlSpider, Rule
from scrapy.link import Link
from scrapy.http import Request

class XmlLinkExtractor():

    def __init__(self, xpath, namespaces):
        self.xpath = xpath
        self.namespaces = namespaces

    def extract_links(self, response):
        selector = response.selector
        if self.namespaces:
            for i, ns in self.namespaces.items():
                selector.register_namespace(i, ns)
        for link in selector.xpath(self.xpath).extract():
            yield Link(link)

class ExampleSitemapCrawlSpider(CrawlSpider):
    name = "myspider"
    start_urls = (
        # link to a sitemap index file
        'http://www.example.com/sitemap.gz',

        # link to a sitemap file
        #'http://www.example.com/sitemaps/sitemap-general.xml',
        )
    rules = (

        # this handles sitemap indexes, following links to other sitemaps
        Rule(XmlLinkExtractor('/sm:sitemapindex/sm:sitemap/sm:loc/text()',
                {"sm": "http://www.sitemaps.org/schemas/sitemap/0.9"}),),

        # this is for "leaf" pages in sitemaps
        Rule(XmlLinkExtractor('/sm:urlset/sm:url/sm:loc/text()',
                {"sm": "http://www.sitemaps.org/schemas/sitemap/0.9"}),
            # here, defining the callback without follow=True
            # makes the crawler stop at these pages level,
            # not following deeper links
            # unset the callback if you want those pages
            # to go through other rules once downloaded
            callback='parse_loc'),
        # ... other rules
    )

    def _requests_to_follow(self, response):
        # we need to override `_requests_to_follow`
        # and comment these 2 lines, because they filter XML responses
        #if not isinstance(response, HtmlResponse):
        #    return
        seen = set()
        for n, rule in enumerate(self._rules):
            links = [lnk for lnk in rule.link_extractor.extract_links(response)
                     if lnk not in seen]
            if links and rule.process_links:
                links = rule.process_links(links)
            for link in links:
                seen.add(link)
                r = Request(url=link.url, callback=self._response_downloaded)
                r.meta.update(rule=n, link_text=link.text)
                yield rule.process_request(r)

    def parse_loc(self, response):
        self.logger.debug("parsing %r" % response)

Depending on how you want to parse pages from /urlset/url/loc, you may want to redirect different URLs to different callbacks (adding different Rules, and customizing XmlLinkExtractor to allow filtering (or use XPath to filter)

A: You can just add a rule to your current CrawlSpider and parse the XML yourself. You just need to add a rule at the top of rules and edit sitemap_xml_xpath in the callback:
import scrapy
import scrapy.linkextractors
import scrapy.spiders.crawl

class SmartlipoSpider(scrapy.spiders.crawl.CrawlSpider):
    name = "myspider"
    start_urls = ('http://example.com/',)
    rules = (
        scrapy.spiders.crawl.Rule(
            scrapy.linkextractors.LinkExtractor(
                allow=r'sitemap\.xml$',
            ),
            callback='parse_sitemap_xml', follow=True,
        ),
        # the other rules...
    )

    def parse_sitemap_xml(self, response):
        sitemap_xml_xpath = '/urlset/url'

        for url in response.xpath(sitemap_xml_xpath):
            yield scrapy.Request(url)

    # your other callbacks...


text:
Q: How to flatten nested dataclass while serializing to pandas dataframe? I have dataclass containing other dataclass as its field:
@dataclass
class Bar:
    abc: int
    bed: int
    asd: int

@dataclass
class Foo:
    xy: int
    yz: Bar

then I try to serialize it to csv by pandas like this:
dataset = [Foo(xy=1, yz=Bar(abc=1, bed=2, asd=3))]
pd_dataset = pandas.DataFrame(vars(row) for row in dataset)
pd_dataset.to_csv('dataset_example.csv', index=False)

but the result I get is kinda different than I want to achieve. To be precise I now get:
xy,yz
1,"Bar(abc=1, bed=2, asd=3)"

and I want:
xy,yz_abc,yz_bed,yz_asd
1,1,2,3

Can you help me getting it right? I tried to write my own serialization function and do something like:
pandas.DataFrame(asdict(row, dict_factory=row_to_dict) for row in dataset)
but I can't get how to correctly write it.

A: There is no need for using an external library, Pandas provides you with everything you need in the form of pd.json_normalize:
>>> import pandas as pd
... from dataclasses import asdict, dataclass
...
... @dataclass
... class Bar:
...     abc: int
...     bed: int
...     asd: int
...
... @dataclass
... class Foo:
...     xy: int
...     yz: Bar
...
... dataset = [
...     Foo(xy=1, yz=Bar(abc=1, bed=2, asd=3)),
...     Foo(xy=10, yz=Bar(abc=10, bed=20, asd=30)),
... ]

>>> dataset
[Foo(xy=1, yz=Bar(abc=1, bed=2, asd=3)),
 Foo(xy=10, yz=Bar(abc=10, bed=20, asd=30))]

>>> df = pd.json_normalize(asdict(obj) for obj in dataset)
>>> df
   xy  yz.abc  yz.bed  yz.asd
0   1       1       2       3
1  10      10      20      30

>>> print(df.to_csv(index=False))
xy,yz.abc,yz.bed,yz.asd
1,1,2,3
10,10,20,30

I personally prefer the above default "." separator, but if you feel strongly about underscores, Pandas also got you covered:
>>> pd.json_normalize((asdict(obj) for obj in dataset), sep="_")
   xy  yz_abc  yz_bed  yz_asd
0   1       1       2       3
1  10      10      20      30

A: Carefully create desired key from vars(Bar) can do what you want.
dataset = [Foo(xy=1, yz=Bar(abc=1, bed=2, asd=3))]

res = []

for obj in dataset:
    d = {}
    for k, v in vars(obj).items():
        if isinstance(v, Bar):
            for k_, v_ in vars(vars(obj)[k]).items():
                d[f'{k}_{k_}'] = v_
        else:
            d[k] = v
    res.append(d)

print(res)
'''
[{'xy': 1, 'yz_abc': 1, 'yz_bed': 2, 'yz_asd': 3}]
'''

pd_dataset = pd.DataFrame.from_records(res)

print(pd_dataset)
'''
   xy  yz_abc  yz_bed  yz_asd
0   1       1       2       3
'''

A: Ok I figured it myself while after posting a question. To solve this problem I needed to download a library called flatten-dict. Then use it like this:
pd_dataset = pandas.DataFrame(flatten(asdict(row), reducer='underscore') for row in dataset)

If there's room for improvement to this approach let me know, but I find it really clean and simple.


text:
Q: How to add Mouse Bites or V-Groove to PCB In Altium? I know mouse bites are more used to snap off one of many of the same boards in a panelized array, but I'm hoping to put mouse bites to snap off part of the same board if that's possible.
Is there just a standard for how far apart you put centers of drill holes?  Is there a standard diameter for the holes?
V-groove could work as well.

A: I had one project with an L shaped board. The PC assembly house wanted me to keep the inner corner of the board in place so that it was better supported by the rails through the pick and place machine. So I used mouse bites to connect the two sections together but to later have that inner corner removed when the boards went to functional testing.
Here is a picture showing the board (red outline) and the breakaway inner corner (green outline).

Here is the detail of the mouse bite design from the board fabrication drawing.

Notice that the breakaways are used in conjunction with routing that is performed using a cutter bit that is 100 mils in diameter.


text:
Q: Dual Monitors on Integrated VGA and Video Card VGA I'm not sure if this site is the best place for this question, if there is another stack exchange site where this would be more appropriate, please suggest it, or move it there.
I have a VGA port on my desktop computer that is integrated, and I also installed a video card that has a VGA, HDMI and DVI port. I connected my main monitor to the video card, and all is well. However, I have a second monitor that I connected to the VGA port of my integrated video card (the one that's on the motherboard). When I go to the Display properties of my PC, I can't see the 2nd monitor.
Is it possible to use a setup like this? Or do I need to get a VGA to DVI converter and use the video card? If it IS possible could it support 3 monitors (one vga, one vga -integrated and one dvi?)?

A:
Is it possible to use a setup like this?

Depends on the BIOS. It might disable the on-board when a discrete card is plugged in, but this also may be configurable in the BIOS menu.

If it IS possible could it support 3 monitors (one vga, one vga -integrated and one dvi?)?

See the previous statement, plus the video card would have to support 2 displays itself to begin with.


text:
Q: Публикация мобильного приложения Expo Всем привет!
Занимаюсь поддержкой мобильного приложения на React Native + Expo. До этого опыта публикации не имел.
В доке от предыдущего разработчика указано, что публикация в сторы производится через релизные каналы с помощью команды expo publish --release-channel (testing/production).
Это все прекрасно работает и для тестового канала и для прода(на устройствах обновляется при попадании в приложение).
Но я обратил внимание, что при публикациях предыдущим разработчиком, в кабинете Expo отображается информация о публикации(дата, канал и тд). И в сторах указывается, что произошло обновление. Версию в app.json изменял, ничего не менялось.
Какие варианты публикаций еще есть для отображения в кабинете Expo, а также отображение обновления в сторах(с текстом внесенных изменений в новой версии)? Спасибо!


text:
Q: Incorrect boolean return -- CodeIgniter PHP Ion Auth I want to thank you all in advance for taking a look at this! I am quite perplexed as to why this is not working:
My Controller:
$ownertest = $this->ion_auth->is_owner();
$grouptest = $this->ion_auth->in_group(2);

var_dump($ownertest); // echos TRUE
var_dump($grouptest); // echos TRUE

I am attempting to return "TRUE" for both $ownertest and $grouptest.
The former function result always comes back TRUE as expected, this is good.
However, the latter function result ($grouptest) only returns TRUE when I pass the number 2 directly into it.
THE PROBLEM:
I don't know why $grouptest result is returning false when I pass$groupid into it! When I echo $groupid the result is 2. Here is an example:
$groupid = $this->ion_auth->get_users_groups()->row()->id;
echo $groupid; // echos "2" in my browser

$ownertest = $this->ion_auth->is_owner();
$grouptest = $this->ion_auth->in_group($groupid)

;
    var_dump($ownertest); // dumps TRUE
    var_dump($grouptest); // dumps FALSE

I would have assumed that $groupid being 2 would result in a TRUE return within this function. I cannot figure this out. Does anyone have any suggestions?
I can post Ion Auth's  in_group function code if needed!

A: Do following
Cast your variable type to integer
$grouptest = $this->ion_auth->in_group((int)$groupid);


text:
Q: How to Create a Linq Query with Multiple Conditional Where Clauses I have a linq query with multiple conditional where clauses. The query returns all data in the table when there is no filter in the where clause. How to make the linq query returns 0 record in the first time when there is no filter in the where clause? See my code below:
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web.Http;
using API.Models;
using System.Linq.Expressions;
namespace API.Controllers
{

//api code starts here
public class MYTABLEController : ApiController
{
    private DataModel db = new DataModel();

    //GET /MYTABLE
    public List<MYTABLE> Get(string filter1 = null,string filter2=null)
    {

        IQueryable<MYTABLE> qry = db.MYTABLE.AsQueryable();
        var searchPredicate = PredicateBuilder.False<MYTABLE>();

        if (!string.IsNullOrWhiteSpace(filter1))
        {

            searchPredicate = searchPredicate.And(a => a.COLUMN1==(filter1);

        }
        if (!string.IsNullOrWhiteSpace(filter2))
        {

            searchPredicate = searchPredicate.And(a => a.COLUMN2==(filter2);

        }

        return qry.Where(searchPredicate).ToList();

    }

//PredicateBuilder https://petemontgomery.wordpress.com/2011/02/10/a-universal-predicatebuilder/
      public static class PredicateBuilder
{
    /// <summary>
    /// Creates a predicate that evaluates to true.
    /// </summary>
    public static Expression<Func<T, bool>> True<T>() { return param => true; }

    /// <summary>
    /// Creates a predicate that evaluates to false.
    /// </summary>
    public static Expression<Func<T, bool>> False<T>() { return param => false; }

    /// <summary>
    /// Creates a predicate expression from the specified lambda expression.
    /// </summary>
    public static Expression<Func<T, bool>> Create<T>(Expression<Func<T, bool>> predicate) { return predicate; }

    /// <summary>
    /// Combines the first predicate with the second using the logical "and".
    /// </summary>
    public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second)
    {
        return first.Compose(second, Expression.AndAlso);
    }

    /// <summary>
    /// Combines the first predicate with the second using the logical "or".
    /// </summary>
    public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second)
    {
        return first.Compose(second, Expression.OrElse);
    }

    /// <summary>
    /// Negates the predicate.
    /// </summary>
    public static Expression<Func<T, bool>> Not<T>(this Expression<Func<T, bool>> expression)
    {
        var negated = Expression.Not(expression.Body);
        return Expression.Lambda<Func<T, bool>>(negated, expression.Parameters);
    }

    /// <summary>
    /// Combines the first expression with the second using the specified merge function.
    /// </summary>
    static Expression<T> Compose<T>(this Expression<T> first, Expression<T> second, Func<Expression, Expression, Expression> merge)
    {
        // zip parameters (map from parameters of second to parameters of first)
        var map = first.Parameters
            .Select((f, i) => new { f, s = second.Parameters[i] })
            .ToDictionary(p => p.s, p => p.f);

        // replace parameters in the second lambda expression with the parameters in the first
        var secondBody = ParameterRebinder.ReplaceParameters(map, second.Body);

        // create a merged lambda expression with parameters from the first expression
        return Expression.Lambda<T>(merge(first.Body, secondBody), first.Parameters);
    }

    class ParameterRebinder : ExpressionVisitor
    {
        readonly Dictionary<ParameterExpression, ParameterExpression> map;

        ParameterRebinder(Dictionary<ParameterExpression, ParameterExpression> map)
        {
            this.map = map ?? new Dictionary<ParameterExpression, ParameterExpression>();
        }

        public static Expression ReplaceParameters(Dictionary<ParameterExpression, ParameterExpression> map, Expression exp)
        {
            return new ParameterRebinder(map).Visit(exp);
        }

        protected override Expression VisitParameter(ParameterExpression p)
        {
            ParameterExpression replacement;

            if (map.TryGetValue(p, out replacement))
            {
                p = replacement;
            }

            return base.VisitParameter(p);
        }
    }
}

A: First, I'd use a predicate builder for this. For example this one.
That would turn your code into:
IQyeryable<MyTable> qry = db.myTable;
var predicate = PredicateBuilder.True<MyTable>();

if (!string.IsNullOrWhiteSpace(filter1))
{
    predicate = predicate.And(a => a.column1.Contains(filter1));
}
if (!string.IsNullOrWhiteSpace(filter2))
{
    predicate = predicate.And(a => a.column2.Contains(filter2));
}
...

qry = qry.Where(predicate);

Now it's easy to check if any predicates were added. If not, predicate is nothing but a => true, which means that its body is just a ConstantExpression (value: true). You can add this check just above the last line:
if (predicate.Body is ConstantExpression)
{
    predicate = PredicateBuilder.False<MyTable>();
}

(Of course provided that you don't replace predicate by another predicate, another constant expression, but I guess that wouldn't make much sense).

A: Update this method like this:
public List<MYTABLE> Get(string filter1 = null,string filter2=null)
{
    if(string.IsNullOrWhiteSpace(filter1) && string.IsNullOrWhiteSpace(filter2))
        return new List<MYTABLE>();

    IQueryable<MYTABLE> qry = db.MYTABLE.AsQueryable();
    var searchPredicate = PredicateBuilder.False<MYTABLE>();

    if (!string.IsNullOrWhiteSpace(filter1))
    {
        searchPredicate = searchPredicate.And(a => a.COLUMN1==(filter1);
    }
    if (!string.IsNullOrWhiteSpace(filter2))
    {
        searchPredicate = searchPredicate.And(a => a.COLUMN2==(filter2);
    }
    return qry.Where(searchPredicate).ToList();
}

A: You can create an extension method:
public static IQueryable<T> WhereIf<T>(
   this IQueryable<T> source, bool condition,
   Expression<Func<T, bool>> predicate)
{
    return condition ? source.Where(predicate) : source;
}

And use it in a following fashion:
using static System.String;

...

public List<MYTABLE> Get(string filter1 = null,string filter2=null)
{
    return db.MYTABLE
       .WhereIf(!IsNullOrEmpty(filter1), y => y.COLUMN1 == filter1)
       .WhereIf(!IsNullOrEmpty(filter2), y => y.COLUMN2 == filter2)
       .ToList();
}


text:
Q: How to make Chinese pinyin keyboard work in vim? When I am using a Chinese keyboard as input source, I cannot navigate around vim using regular keys.
I would like to leave the Chinese keyboard selected, but still be able to use vim as normal when I am not in insert mode.
When in Insert mode, any typing should type Chinese, but when not in a typing mode keys should have their normal vim functionality.

A: The arrow keys still work, but other than that, you'd have to switch keyboards to navigate or turn on insert/replace/delete functions, then switch back.  Perhaps use Cmd-dot to toggle back and forth.
If you have a numeric keypad, you could program some of those keys with different navigation outputs.  Or function keys.
I use mostly TextEdit.  I'll get some downvotes for having the audacity to suggest it's not completely useless.  Other editors are available that do a lot more.  But there's some value in choosing a simpler product that does everything you need over one that can do a lot of things you don't need.  Can't recommend TextEdit for Monterey, though—Apple is still working on a serious bug.


text:
Q: How can get values from dictionaries of array in python? I have array which contain some firebase datas. Inside of that array I have dictionaries.
Here my array:
[{'name': 'mehmet Tilsed'}, {'name': 'mahmut Tilsed'}, {'name': 'mre Tilsed'}, {'name': 'Joe Tilsed'}, {'name': 'Joe Tilsed'}, {'name': 'Joe Tilsed'}]

I want to get values of each item. How can I make it?
Here my code:
firebase = Firebase(config)

db = firebase.database()

all_users = db.child("users").child("Joe").child("users").get()

for user in all_users.each():
   userArray.append(user.val())

item1.update(userArray[2])   // In here I take only given items value. I want to get all values.

for k in item1.values():
   print(k)

for j in userArray:
    print(j)

A: If I understand your question correctly you want to print all the names from the array right? I don't know what item1 or userArray is because you left that out but this works fine:
array = [{'name': 'mehmet Tilsed'}, {'name': 'mahmut Tilsed'}, {'name': 'mre Tilsed'}, {'name': 'Joe Tilsed'}, {'name': 'Joe Tilsed'}, {'name': 'Joe Tilsed'}]
for name in array:
        print(name['name'])

output:
mehmet Tilsed
mahmut Tilsed
mre Tilsed
Joe Tilsed
Joe Tilsed
Joe Tilsed

A: If you want those in a list, you can try:
from operator import itemgetter

>>> arr = [{'name': 'mehmet Tilsed'}, {'name': 'mahmut Tilsed'}, {'name': 'mre Tilsed'}, {'name': 'Joe Tilsed'}, {'name': 'Joe Tilsed'}, {'name': 'Joe Tilsed'}]

>>> lst = list(map(itemgetter('name'),arr))
>>> lst
['mehmet Tilsed',
 'mahmut Tilsed',
 'mre Tilsed',
 'Joe Tilsed',
 'Joe Tilsed',
 'Joe Tilsed']

Or,
>>> lst = [dct['name'] for dct in arr]
>>> lst
['mehmet Tilsed',
 'mahmut Tilsed',
 'mre Tilsed',
 'Joe Tilsed',
 'Joe Tilsed',
 'Joe Tilsed']


text:
Q: Counting and printing a serial number +1 if less than last serial number JavaScript So I have two serial numbers and 199 serials in between them:
899720101000105500 (first)
899720101000105699 (last)
I need to print the first serial and then all 199 up to the last serial. The only thing I've found is just +1 to the first serial every time the loop runs and printing it.
I've copied/pasted different parts and this is what I have:
var lowEnd = 899720101000105500;
var highEnd = 899720101000105699;
var arr = [];
while(lowEnd <= highEnd){
   arr.push(lowEnd++);
}

Is there a max number length you can store in a variable?

A: Here's the solution for this specific problem for anyone that may come across this. Make the static parts of the number (the digits that don't change) a string and just use the digits that do change (for me it was the last 4) to count and then add the string to the count and log it.
var serialNumber = 5500;

while(serialNumber <= 5699)
{
    serialNumber = serialNumber + 1;
    var fullNumber = "89972010100010" + serialNumber;
    console.log(fullNumber);
}

A:  for (let i = BigInt(899720101000105500); i <= 899720101000105699; BigInt(i++)) {
         console.log(i + '')
 }


text:
Q: GPLv3 licensing and Software-as-a-Service web apps I am trying to figure out once and for all how the GPLv3 interacts with web applications, specifically SaaS applications.  I haven't been able to find a concrete answer about this.
Let's say I have a SaaS web app that users can purchase a monthly subscription to and access.  The source code is not distributed or made available to the customers in any way, shape or form and their only interaction is via the website and any APIs that I've provided via web services.
If I am using a third-party library licensed under the GPLv3, let's say a UI toolkit like Telerik's "KendoUI" (the open source version of which is licensed under GPLv3), then am I required to provide the source code for my web app (and therefore, in effect, make it worthless to sell as the source code would be readily available)?
I am aware that the Affero GPL does require this and was specifically created to close the "loophole" wherein you could use open-source libraries in a web app and never have to release your own source code (which IMO kind of defeats the purpose of a web app, but neither here nor there), but it doesn't appear that the standard GPLv3 license has this clause (in fact it appears to have been taken out specifically because of the backlash it would cause).
Is this understanding correct?  In other words, unless I want to open source my proprietary application, I should steer clear of anything using the Affero GPL, but the GPLv3 and others are fine as the "loophole" still exists within those?