Can't Update AngularJS Input value

Question: I am trying to add my own spin on a AngularJS tutorial I did about a Saturn Quiz by changing it from multiple choice to a fill-in-the-blank quiz.
I am able to get the first answer to recognize if it is right or wrong but the next question always returns incorrect even when the answer is right. By using console.log I find that the input value though changed is not recognized by AngularJS. It always retains the first value I put into the quiz.
Plunkr Demo
HTML

Test Your Knowledge:Saturn

 -1) ? 'inactive' : 'active' }}">

Welcome

Click to begin to test your knowledge of Saturn.

Begin

 {{ myQuestion.instructions }}

Check Answer

Correct.

Oops! That is not correct.

 {{ myQuestion.feedback }}

Continue

App.js
    (function(){
    var codeApp = angular.module('codeApp', ['ngSanitize']);

    codeApp.controller('QuizController', ['$scope', '$http', "$sce", function($scope, $http, $sce){
        $scope.score = 0;
        $scope.activeQuestion = -1;
        $scope.activeQuestionAnswered = 0;
        $scope.percentage = 0;

        $http.get('quiz_data.json').then(function(quizData){
            $scope.myQuestions = quizData.data;
            $scope.totalQuestions = $scope.myQuestions.length;
        });
        $scope.checkAnswer = function(qIndex,aIndex){
            var questionState = $scope.myQuestions[qIndex].questionState;

                if(questionState != 'answered') {
                    var userAnswer = document.getElementsByClassName("fillin")[0].value;
                    var correctAnswer = $scope.myQuestions[qIndex].questionAnswer;

                    $scope.myQuestions[qIndex].questionAnswer = correctAnswer;

                            if(userAnswer === correctAnswer){
                                $scope.myQuestions[qIndex].correctness = 'correct';
                                $scope.score += 1;
                                console.log('Correct!' + $scope.score);
                            }
                            else{
                                $scope.myQuestions[qIndex].correctness = 'incorrect';
                                console.log('Wrong!');
                                console.log(correctAnswer);
                                console.log(userAnswer);
                                console.log( document.getElementsByClassName("fillin")[0].value );
                            }
                        $scope.myQuestions[qIndex].questionState = 'answered';

                }else{
                    console.log('Something is wrong');
                }

        }

        $scope.selectContinue = function(){
            return $scope.activeQuestion += 1;

        }

        $scope.createShareLinks = function(percentage){

            var url = 'http://codifydesign.com';
            var emailLink = '<input type="text" placeholder="hi" />Email a friend';
            var twitterLink = 'Tweet your score';
            var newMarkup = emailLink + twitterLink;
            return $sce.trustAsHtml(newMarkup);
        }
    }]).filter('trustAsHtml', [
    '$sce',
    function($sce) {
        return function(value) {
            return $sce.trustAsHtml(value);
        }
    }
    ]);
})();

data.json
[
    {
        "questionId": 0,
        "question" : "Saturn is <input id='guess-input' class='fillin' ng-blur='clearValues()' type='text' name='\"six\"'> many planets from the sun?",
        "questionAnswer" : "six"
    },
    {
        "questionId": 1,
        "question" : "Around Saturn are <input id='guess-input' class='fillin' ng-blur='clearValues()' type='text' name='\"rings\"'>",
        "questionAnswer" : "rings"
    }
]

Comment: With the AngularJS framework, the use of `getElementsByClassName` is a [code smell](https://en.wikipedia.org/wiki/Code_smell), a symptom of a deeper problem. The AngularJS framework interacts with the `` element using the `ng-model` directive. For more information, see [AngularJS `` Directive API Reference](https://docs.angularjs.org/api/ng/input/input%5Btext%5D).
Comment: @georgeawg Thank you for bringing this to my attention! I will leave the question open a little longer if you would like to answer since you seem knowledgeable about AngularJS. I have used ng-model in another tutorial and I will look into it more to understand how it works and how I can apply it here.
Answer: You have hardcoded it to always look for the first instance of an element with a class of fillin. Change both instances of this...
document.getElementsByClassName("fillin")[0].value

...to this...
document.getElementsByClassName("fillin")[aIndex].value

...and it should begin working for you.
Comment: This is really helpful. Following the tutorial a couple of times I kind of understood the concept of the qIndex and aIndex but I am not sure where they are really pulling from (or how). This solution works, and it makes sense to me on a JS level!

Can't Update AngularJS Input value


Is n O(n)? Is n Ω(n)?

Question: I have a homework assignment (though this isn't part of it!) which I want to be sure on. This may be a stupid question.
The functions in question are $f(n) = 2^n$ and $g(n) = 3^n$. I'm pretty sure about the following:
$f$ is $O(g)$ as $2^n \leq 3^n \ \forall \ n \in \mathbb{N}$, using $c = 1$.
$f$ is also $\Omega(g)$. Proof:
$f$ being $\Omega(g)$ means that for some $c > 0$ we have that $c \cdot 2^n \geq 3^n$ for sufficiently large $n$.
Taking $log_3$ of both sides gives us $\log_3(c \cdot 2^n) \geq n$.
We can use change-of-base to get: $\frac{\log_2(c \cdot 2^n)}{\log_2(3)} \geq n$.
Log rules give us $\frac{\log_2(c)}{\log_2(3)} + \frac{n}{\log_2(3)} \geq n$.
This shows that $f$ is $\Omega(g)$ if $n$ is $\Omega(n)$, with some $c$ equal to $\frac{1}{log_2(3)}$.
If there are any problems, please let me know.
Thanks!
Comment: You don't switch the inequality sign when taking logs....
Comment: @mathworker21 you're right - changed
Comment: Your last inequality implies this is only true for $n\le\frac{\log_2c}{\log_23-1}=k$, so whatever value of $c$ you chose, it will not be true for $n>k$
Comment: @ShubhamJohri could you explain that further, please?
Comment: @mathworker21 Thanks. Realized that that wasn't the main problem (and deleted the comment). But now that is the problem.
Comment: You want to prove that for some $c>0,c2^n\ge3^n$ for all $n\ge n_0$. On solving the inequality, you get that this is only true for $n\le k$, so your hypothesis is not true for any $n>k$. So $2^n\notin\Omega(3^n)$
Comment: @FibroMyAlgebra $\log f\in \Omega(\log g)$ does not imply $f\in\Omega(g)$, as mathworker21 implied in his comment.
Comment: @mathworker21 where am I implying this?
Comment: @DirkGently I don't think he is assuming this. He is just taking logarithms of the concrete inequality $c 2^n \ge 3^n$. Nowhere does he have $c (n \log 2) \ge n \log 3$.
Comment: @DirkGently I think $\log$ is only being taken to solve the inequality
Answer: You have correctly (as far as I can see from a quick read) rewritten the condition to
$$\frac{\log_2(c)}{\log_2(3)} + \frac{n}{\log_2(3)} \geq n$$
But then you need to argue that you can make this true for all sufficiently large $n$ just by choosing $c$ right -- and that is not the case.
The factor $\frac{1}{\log_2 3}$ is less than $1$, so the difference between the two terms involving $n$ gets ever larger the larger $n$ is. Therefore, no matter what you take $c$ to be, this difference will eventually be more than the constant $\frac{\log_2c}{\log_23}$, and therefore your rewritten inequality does not hold for all large enough $n$ -- also no matter what you take "large enough" to mean.
Comment: There we go. Thanks! I really appreciate the help. I'm pretty new to the wonderful world of asymptotics.
Answer: Simpler approach: $$\frac{c 2^n}{3^n} \to 0$$ no matter what $c$ is, so $2^n$ is not $\Omega(3^n)$.

Using your approach:
Because $\log_2(3) > 1$ we will always have $\frac{\log_2(c)}{\log_2(3)} + \frac{n}{\log_2(3)} \le n$ for all sufficiently large $n$, no matter what $c$ is.
Comment: he's probably asking what the flaw in his logic is
Comment: Yes. Could you explain further?
Comment: @angryavian Sorry, did I mess up my ineq signs or did you mess up yours? I think you mean $\geq$ there as $f = Ω(g)$ means: $\exists c > 0$, $n_0 \geq 0$ such that $g(n) \leq cf(n)$ for all $n \geq n_0$.
Comment: @FibroMyAlgebra From your work, you showed that you want to find a $c$ such that $\frac{\log_2(c)}{\log_2(3)} + \frac{n}{\log_2(3)} \ge n$ for all large $n$. In my answer I note that this is impossible, since the left-hand side is a line (as a function of $n$ with a smaller slope than the slope of the right-hand side.
Comment: Ah, I see. @henningmakholm also answered this. Thanks!

Is n O(n)? Is n Ω(n)?


Não Consigo Criar BitmapImage "interface that was marshalled for a different thread"

Question: Erro:

System.Exception: 'The application called an interface that was marshalled for a different thread. (Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD))'

Eu estou tentando obter um BitmapImage a partir de um StorageItemThumbnail, mas eu não consigo nem cria-lo, sempre que eu tento cria-lo BitmapImage bitmapImage = new BitmapImage();  recebo o erro acima independente se eu usar Dispatcher.Invoke ou não. Ele é a única linha que da o problema.
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        GetThumbnailFile();
    }

    private async void GetThumbnailFile()
    {
        BitmapImage image  = await ThumbnailPhoto(@"C:\...\");

    }

    private async Task<BitmapImage> ThumbnailPhoto(string FilePath)
    {
        StorageFile sf = await StorageFile.GetFileFromPathAsync(FilePath);
        StorageItemThumbnail fileThumbnail = await sf.GetThumbnailAsync(ThumbnailMode.SingleItem, 250);
        BitmapImage bitmapImage = new BitmapImage();
        bitmapImage.SetSource(fileThumbnail);

        return bitmapImage;
    }
}

Windows 10 API para usar StorageFile: Calling Windows 10 APIs From a Desktop Application
Não funcionam: resolução1, resolução2, Dispatcher.Invoke.
BitmapImage usado: using Windows.UI.Xaml.Media.Imaging;.
Answer: É necessário utilizar BeginInit(), bitmap.EndInit() e bitmap.Freeze().
Exemplo:
bitmap.BeginInit();
bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.StreamSource = memoryStream;
bitmap.EndInit();
bitmap.Freeze();


Gráfico com legendas sobrepostas em R [sem usar ggplot2

Question: Olá, meu gráfico está ficando com alguns valores sobrepostos, já tentei aumentar o gráfico não resolveu.
<code> library(RColorBrewer) #cores
cor = brewer.pal(12, "BuPu")
gen =c(1, 130, 2, 31, 1 )
labs_g =c( "Desconhecido" , "Genótipo 1", "Genótipo 2", "Genótipo 3",  "Genótipo 4")
val_g =c("0,5% (1)", "77,3 %(130)", "2,9%(2)", "18,5%(31)", "0,5% (1)" )
pie(gen, col= cor, main =  'Genótipo', labels = c(val_g), radius = .7 )
legend("bottomright",legend=labs_g, bty="n",fill= cor)
</code>
Comment: 1) Falta o vetor `cor`. 2) Não consigo reproduzir o erro com os valores da pergunta. 3) Usando os valores do gráfico o erro é reprodutível, por favor edite a pergunta com esses valores.
Comment: Não creio que seja possível. Na source de `pie`, ficheiro `pie.R` está a seguinte linha `text(1.1*P$x, 1.1*P$y, labels[i], xpd = TRUE, adj = ifelse(P$x < 0, 1, 0), ...)`. Veja o parâmetro `adj`. É ele que controla a justificação do texto na label e não pode ser mudado pelo usuário.
Comment: Olá, adcionei o vetor cor e copiei os valores novamente
Answer: <code>library(RColorBrewer) #cores
cor = brewer.pal(12, "BuPu")
gen = c(1, 130, 2, 31, 1 )
labs_g = c( "Desconhecido" , "Genótipo 1", "Genótipo 2", "Genótipo 3", "Genótipo 4")
val_g = c("0,5% (1)", "77,3 %(130)", "2,9%(2)", "18,5%(31)", "0,5% (1)")

par(xpd = TRUE)
pie(gen, col= cor, main =  'Genótipo', labels = c(val_g), radius = 0.7, clockwise = TRUE)
legend(1.3, .1, "bottomright", legend=labs_g, bty = "n", fill = cor, cex = 0.7)
</code>


Dart coding styles

Question: Maybe this is not a Dart specific question.
I have :
class A {
  int a;

  A(this.a);
}

class B extends A {
  String b;

  B(a, this.b) : super(a);
}

So you see, class A has an attribute int a and B just extends A and has an extra attribute String b and a wrapper class C :
class C {
  A c;

  C(this.c);

  void doSomething() {
    if (c is B) {
      print(c.b);
    } else {
      print(c.a);
    }
  }

}

The Dart Editor complaints that the c doesn't have a getter b. How do you deal with this? I want to get rid the warning, but I don't want to add attribute b to class A
Answer: (c as B) works, but will do a dynamic type check (which will probably be eliminated by the VM).
If you just want to remove the warning, without changing the semantics of the program you can assign to a temporary variable of the correct type:
void doSomething() {
  if (c is B) {
    B b = c;
    print(b.b);
  } else {
    print(c.a);
  }
}

Answer: The analyzer shouldn't add a warning here. I think it's related to this issue : Analyzer fails to respect certain "is" checks.
In the meanwhile, you can use (c as B).b to cast c in B.
Answer: You can cast expression.
print((c as B).b);

Dart coding styles


Why are these quavers beamed this way?

Question:
I don't know why the quavers in the bass are beamed across barlines the way they are. Does it signify phrasing or is there another reason for it?
Comment: I've never encounter something like this. It's surely to show the phrases I couldn't see another reason. but I could even be a typo ...
Comment: I'd guess it's just to make it easier to read.
Comment: They are eighth notes, not quavers.
Comment: @Vighnesh Eighth notes and quavers are the same thing.
Answer: Yes, it's a way to signify another level of phrase grouping. Just as your beaming within a bar can indicate groupings of beamed notes beneath the level indicated by the slur, this shows that the composer or editor wanted to indicate this grouping that extends across bar lines.
The beaming itself is already a kind of editorial decision because each quaver has a rest in between, so they could have been notated with flags. But flags plus two levels of slurs for phrasing may have been seen as less readable than using beams, since the symbology for each level of phrasing would be the same instead of different, and by using beams we also satisfy conveying the rhythmic value at the same time.
Comment: Beaming is more commonly used these days to indicate metrical structure than phrasing, though it is also used to indicate text underlay in vocal music, a practice which seems to have fallen out of favor in recent decades, to my dismay.
Answer: Looking at the phrase mark itself, it would appear that it is because of phrasing. Although it's not that clear where the phrase mark in bar 3 goes, being at the end of a line. I guess it goes on to be a phrase over 4 bars - bar 3 to the start of bar 6.
Comment: True, but most publishers settle for the phrasing mark (overhead curve) as being sufficient.  Beaming across a bar line is kind of weird.

Why are these quavers beamed this way?


How to call a variable from a class without calling the class - c#?

Question: I want to use a const variable from this class:
 class foo
 {
    public const bool x = true;
 }

is there any way to use x without doing foo.x?
i want to use it like this:
if( x )

and not like this:
if( foo.x )

Comment: Not unless you are within the `foo` class. What's the problem with `foo.x`?
Comment: @cnom there is no such thing as global variables in C#.  Everything has to be declared within a class or struct context.
Comment: If someone can use x without creating a foo, then x is decoupled from foo. So, why put it inside foo?
Comment: `foo.x` won't work either, unless you mark `x` as public.
Comment: Glorin is right. you cant in anyway call it as x.Since its defined within a class
Comment: Maybe you just want to declare x as a global variable of your application. It should not be a member of foo, or else it needs to define its class to get its value
Comment: VB.NET allows this with static classes (called "Modules").  Take *that* VB haters...
Comment: @DavidL, correct, I meant "blobal" as if "in a higher level of scope", e.g. in a parrent class
Comment: forgot to add the public, the meaning of the question dosnt change though, public wont make you access it without accessing the class first...
Answer: The only way to achieve that is to mark foo as static and use using static where you want to have access to foo.x as x.
namespace Foo
{
    static class Bar
    {
         public const bool x = true;
    }
}

and later:
using static Foo.Bar;
Console.WriteLine(x);

using static is a C# feature, so make sure you're using C# 6 before you use it.
Comment: So clever, so much potential for abuse and unclear code :).  But good alternative.
Comment: Still you are using the class reference, but you are hiding it through a `using`. Smart though...
Comment: @PatrickHofman Yep. But it's the same with regular `using` - you're actually using fully qualified name with namespace, but hiding it behind a `using`.
Comment: Yeah, true. Just wanted to point out this in fact makes no different.
Comment: @DavidL I think it's primary meant to be used to bring into scope extension methods defined in a given static class (instead of all of them from a given namespace). But you can actually bring anything :)
Comment: @MarcinJuraszek I agree, that is probably the original intention and it makes a lot of sense for that case so that you aren't exposing everything.  Clever and tricky the other things it allows however :P.
Comment: @TheNormalPotato If you think an answer solved your problem you should mark it as accepted. That's how StackOverflow works. See http://stackoverflow.com/help/accepted-answer for details.
Answer: No, a member always stays a member of a class, so you either have to call a static (or constant) variable through the class name, or call the member on the instance.
So this would work:
public class Foo { public static int SomeInt {get;set;} = 12; }

int i = Foo.SomeInt;

Or:
public class Foo { public int SomeInt {get;set;} = 12; }

Foo f = new Foo();
int i = foo.SomeInt;

And as shown by Marcin, you can somewhat hide that truth by using using static. Still, it is called through the class.
Answer: For starters it will need to be publicly accessible
public class foo
{
    public const bool x = true;
}

And then you can store the value in a variable
var x = foo.x;
if(x) { .. }


Open default mail app to create a mail with body and attachment file in .net framework

Question: I use a .net framework application and I want on button click to open a new mail in default mail application. I use Interop.Outlook library but it works only if has outlook installed. I want to open with any default mail application. Also, I use mailTo in Proccess.Start but with this method ,file attachment doesn't work. How I can create a mail with default mail app.
Comment: I highly doubt your request will be possible, particularly for security reasons
Answer: The best what you could do with any mail application used on the system is to use the mailto protocol. In other cases you need to detect the default mail application installed and try to automate it (if possible).
See Get and sign in to an instance of Outlook which shows how to obtain an Application object that represents an active instance of Microsoft Outlook, if there is one running on the local computer, or to create a new instance of Outlook, sign in to the default profile, and return that instance of Outlook.
Comment: I try mailto but with this method I cant attach any file to mail from code. Also I want to open default mail app if user hasnt got  installed outlook in the machine
Comment: Yeah, the `mailto` protocol doesn't support adding attachments. So, you can find what is the default app on the system by looking in the windows registry.
Comment: If I find the default program from registry how can I open it from code and create a new mail with attachment?
Comment: In case of Outlook you can use the COM automation technology. Take a look at the link I posted for more information on that.


function that generates a String in Haskell

Question: I want to program a function that generates a String. The String contains only 1,0,s and S.
The numbers are binary numbers. Each number is separated through a s. And a number gives the length of the rest of the String. The capital S is the end of the String.
Examples:
func :: Integral a => a -> String

func 1

"1S"

func 3

"110s11s1S"

func 4

"1010s110s11s1S"

My problem is, that I don't know, how I can get the length of the tail ("s1S" -> tail, 11 -> head) and than get the new tail.
My new code:
>toBinary :: Integral a => a -> String
>toBinary 0 = []
>toBinary x
>       | mod x 2 == 0 =  '0' : toBinary (div x 2)
>       | mod x 2 == 1 =  '1' : toBinary (div x 2)

>zubinaer :: Integral a => a -> String
>zubinaer x = reverse (toBinary x)
>
>distan :: Integral a => a -> String
>distan n = if n > 0 then hilfsfunktion (n-1) "1S" else  []
>
>       where
>           hilfsfunktion :: Integral a => a -> String -> String
>           hilfsfunktion 0 s = s
>           hilfsfunktion n s = hilfsfunktion (n-1) (zubinaer(length s + 1) ++ "s" ++ s )

Here my older code: http://hpaste.org/54863
Comment: yes, it is. So I thought that I could get some hints. Thank you for the help. :)
Comment: @Alexei That code is.pretty okay for a beginner. Try to use map! It really saves you work.
Answer: I think you are tackling your problem from the wrong angle. In Haskell, one often thinks of lists. Actually, a String is just a list of Chars. Try to build your function from these bricks:

Write a function toBinary :: Integral a => a -> [Bool] that outputs a binary representation of its parameters. A 1 is True and a 0 is False
You can use map to turn the [Bool] into a String by replacing each boolean by a character 0 or 1.
You can use the syntax [1..n] to generate a list of integers from 1 to n. Use map to generate a list of binary representation strings.
Use intercalate from Data.List to create your string.
Comment: @Alexei You can [edit](http://stackoverflow.com/posts/8378281/edit) your original question and include your code. (Prepend four space to each line for syntax highlighting). You can also use a pastebin such as http://hpaste.org
Answer: Since the tail is defined recursively (ex.: the "tail" of (f 4) is (f 3)) you can get the length of the tail by first getting the tail:
let the_tail = f (n-1) in

then calling the length function on it
length the_tail


Study the monotonicity of this function

Question: The function is $$y=x^2-5x+6$$
I have made
$$[f(x_2)-f(x_1)]/(x_2-x_1)$$
It results in
$$x_1+x_2-5.$$
What should I do next?
Comment: Roll it in paper and light it. What is it you want and why?
Comment: I don't know what level you are at and what tools are available. Maybe you are supposed to use the fact that $y=(x-2)(x-3)$ is an upward facing parabola, with axis of symmetry the vertical line $x=\frac{2+3}{2}$.  Or maybe you are expected to complete the square.  You do not mention calculus, but that too works quickly.
Answer: Now suppose that $x_2+h =x_1$ with $ h \to 0$. For a positive monotonicity it has to be
$$\lim_{h \to 0 } x_1+x_1+h -5\geq 0$$
Solving for $x_1$
$x_1 \geq \frac{5}{2}$
Therefore for $x \geq \frac{5}{2}$ the function is positive monotonic. And for $x < \frac{5}{2}$ the function is strictly negative monotonic.
Comment: Please don't use lim, we haven't learnt them yet
Comment: Ok. Do you have any idea what to use instead ? What do your notes say ?

Study the monotonicity of this function


How do I apply a Taylor expansion of this?

Question: Given
$$\frac{1}{r}\left(1+\frac{2\epsilon \cos\theta}{r}\right)^{-1/2}$$
I was told by using Taylor expansion I could get
$$1-\frac{2\epsilon \cos\theta}{r}$$ with term of order $\epsilon^2$.
Can someone explain to me how?
Answer: That's wrong.
$$ \dfrac{1}{r} \left( 1 + \dfrac{2\epsilon \cos(\theta)}{r}\right)^{-1/2} =  \dfrac{1}{r} - \dfrac{\cos(\theta)}{r^2} \epsilon + O(\epsilon^2)$$
That comes from the binomial series:
$$ (1 + x)^p = 1 + p x + O(x^2)$$


Retrieving data based on several conditions in ajax

Question: I'm using AJAX to get database data, compare it to a variable to display it. I'm only comparing in "Where" based on one condition, which is whether the field ID is equal to a variable "+id_var +". The thing is that now i'm trying to add more conditions in Where for different fields, but i'm not being successful, any help on how to do so?
 var key=null;
 $.ajax({
                   type: "POST",
                   url: "GetRecord?DB=EMP&Table=EMP_HISTORY",
                   dataType : 'xml',
                   data : {
                    "Where" : "ID="+id_var +""
                   },
                 success:function(xml) {
                     $(xml).find('record').each(function () {
                        key = $(this).find("KEY").text();
                     });
                     if(key) {
                        var url = "GetDisplay?DB=EMP&Table=EMP_HISTORY&Where=KEY="+key +"";
                        window.open(url,"_self");
                     }
                 },
                 error: function (error) {
                     alert('error');
                 }
               });

Comment: please show all the conditions you would like to add
Comment: @nosthertus i'm just looking for syntax, but let's the say the above condition with " OR "+id_var +" IS NULL "
Answer: i can see you have an error in your HTTP Query, you can't define where a value which is defining key another value inside.. for this you would have to change Where to be an array which would contain KEY and other variables you want it to have..
Assuming you are using jQuery.. you can use $.param(), check in here for more details..
var query = {
    DB: "EMP",
    Table: "EMP_HISTORY",
    Where: {
        KEY: "1234",
        OR: {
            id_var: 'IS NULL'

        }
    }
};

$.param(query);

// returns "DB=EMP&Table=EMP_HISTORY&Where%5BKEY%5D=1234&Where%5BOR%5D%5Bid_var%5D=IS+NULL"


Partial order homework

Question: I need to check my homework. I'm not good at discrete mathematics and I need to have this homework correct.
Let $S=\{1,2,\ldots,100\}^2$. The partial order $\le_S$ is defined as follows: for $\langle a,b\rangle,\langle x,y\rangle\in S$, $\langle a,b\rangle\le_S\langle x,y\rangle\iff a\le x\land b\le y$.
And I have to find the longest chain and the longest antichain. The minimal element is ordered pair (1,1) and the maximal element is (100,100). I suppose the longest antichain are ordered pairs (1,100), (2,99), ..., (100,1). Am I right? Can I write this result using following formula?
$$\alpha(\{1, 2, ..., 100\}^2,\le S)=\bigcup_{i=1}^{100}(i,101-i)$$
The longest chain goes from minimal element (1,1) to maximal element (100,100). I think there is a lot of longest chains. As an example I chose this one - (1,1), (1,2), …, (1,99), (1,100), (2,100), …, (99,100), (100,100). I think it has length of 199 ordered pairs. Am I right? Can I write this result using following formula?
$$\omega(\{1, 2, ..., 100\}^2,\le S)=\bigcup_{i=1}^{100}(1,i) \cup \bigcup_{i=2}^{100}(i,100)$$
Thank you very much for your help.
Comment: FYI, the mathematical assertion $$(S,\le ) = \{1, 2, ..., 100\}^2 \iff a\le x \land b \le y$$ might be one of the most ill-composed one can imagine. Please reread (and rewrite) your question.
Comment: I hope it's better now.
Comment: @Speedding: It's really not; see my answer for a way to write what I think you're trying to express. By the way, are you required to *prove* that your antichain and chain are longest possible, or just to identify them?
Comment: I am required to prove that, but ofc I have no idea how should I do that.
Answer: You have correctly identified the longest antichain in $S$, but your notation for it is incorrect. It is not the union of the ordered pairs $\langle i,101-i\rangle; it is the set of those ordered pairs,
$$\big\{\langle i,101-i\rangle:i\in\{1,2,\ldots,100\}\big\}\;.$$
You have also correctly identified one of the longest chains, all of which do indeed have $199$ elements, but you've made the same mistake in your notation; it should be
$$\big\{\langle 1,i\rangle:i\in\{1,2,\ldots,100\}\big\}\cup\big\{\langle i,100\rangle:i\in\{2,3,\ldots,100\}\big\}\;.$$
As Did notes in the comments, your description of the partial order is very badly written. I suspect that it is supposed to be something like this:

Let $S=\{1,2,\ldots,100\}^2$. The partial order $\le_S$ is defined as follows: for $\langle a,b\rangle,\langle x,y\rangle\in S$, $\langle a,b\rangle\le_S\langle x,y\rangle\iff a\le x\land b\le y$.
Comment: Thanks for your help, things are clearer for me now. I will pay more attention while writing assertion next time.
Comment: @Speedding: You're welcome.

Partial order homework


NextJS: TypeError: Cannot read property 'json' of undefined

Question: I've this code into pages folder on my NextJS environment. It gets data calling an external API Rest, and it's working because the console.log(response); line show me by console the Json API response. The problem I've is that I get this error in browser:
TypeError: Cannot read property 'json' of undefined
Corresponding with this line code:
const data = await res.json();
This is the complete file with the code:
import React from "react";
import fetch from "node-fetch";

const getFetch = async (invoicesUrl, params) => {
  fetch(invoicesUrl, params)
    .then((response) => {
      return response.json();
    })
    .then((response) => {
      console.log(response);
    })
    .catch((err) => {
      console.log(err);
    });
};

export const getServerSideProps = async () => {
  const invoicesUrl = "https://192.168.1.38/accounts/123456";
  const params = {
    method: "get",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
    },
  };
  const res = await getFetch(invoicesUrl, params);
  const data = await res.json();
  console.log("Data Json: ", data);

  return { props: { data } };
};

This is the Json API response that I see by console:
{
  account: [
    {
      id: '7051321',
      type: 'probe',
      status: 'open',
      newAccount: [Object],
      lastDate: '2020-07-04',
      taxExcluded: [Object],
      totalRecover: [Object],
      documentLinks: []
    },
  ]
}

Any idea how can I solve it?
Thanks in advance.
UPDATE
Here the code working good:
import React from "react";
import fetch from "node-fetch";

const getFetch = async (invoicesUrl, params) => {
   return fetch(invoicesUrl, params);
};

export const getServerSideProps = async () => {
  const invoicesUrl = "https://192.168.1.38/accounts/123456";
  const params = {
    method: "get",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
    },
  };
  try {
    const res = await getFetch(invoicesUrl, params);
    const data = await res.json();
    console.log("Data JSON: ", data);
    return { props: { data } };
  } catch (error) {
    console.log("Data ERROR: ", error);
  }
};

Answer: There are a couple of things you have to change.
const getFetch = async (invoicesUrl, params) => {
  fetch(invoicesUrl, params)
    .then((response) => {
      return response.json();
    })
    .then((response) => {
      console.log(response);
      return response; // 1. Add this line. You need to return the response.
    })
    .catch((err) => {
      console.log(err);
    });
};

export const getServerSideProps = async () => {
  const invoicesUrl = "https://192.168.1.38/accounts/123456";
  const params = {
    method: "get",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
    },
  };
  const data = await getFetch(invoicesUrl, params);
  // const data = await res.json(); 2. Remove this you have already converted to JSON by calling .json in getFetch
  console.log("Data Json: ", data); // Make sure this prints the data.

  return { props: { data } };
};

Comment: I've made that changes you suggest, and now I get this error: "SerializableError: Error serializing `.data` returned from `getServerSideProps` in "/invoicing/invoices".
Reason: `undefined` cannot be serialized as JSON. Please use `null` or omit this value all together". There are two "return" into your getFetch function, is that correct?
Comment: The reason is that the response returned from your API is not serializable. If you update your question with the full object I will be able to point where the problem is. If not, you can find it out yourself using the answer here: https://stackoverflow.com/questions/30579940/reliable-way-to-check-if-objects-is-serializable-in-javascript
Comment: Ok, probably the reason to not be serializable is those elements with content "[Object]" in the console but with content if I call the API with another way (curl, Postman).
Comment: Yes, it is something inside [Object] that is not serializable. For NextJS, it needs to be serializable. You can use this: https://stackoverflow.com/questions/41587443/trying-to-print-the-nested-json to print the entire structure and see where the problem is.  I'll be happy to help more.  Btw I think I have fixed the original issue for the question. If so please accept..:)
Comment: Thanks for the help. I'll take a look to that link. Sorry, but I can't accept your answer as correct (i don't want confuse another users) because it can't work for me after try many times. I've updated my original question and after UPDATE title I putted the code that works for me. However, may be another user with this issue can vote your answer as the right! Thanks again.
Comment: No problem.. :)
Answer: You have return statement in wrong place.
When the function is expecting a return. You need to return when the statements are executed not inside the promise then function because it is an async callback function which is not sync with the statement inside getFetchfunction. I hope i have made things clear. Below is the code which will any how return something
import React from "react";
import fetch from "node-fetch";

const getFetch = async (invoicesUrl, params) => {
  return fetch(invoicesUrl, params);
};

export const getServerSideProps = async () => {
  const invoicesUrl = "https://192.168.1.38/accounts/123456";
  const params = {
    method: "get",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
    },
  };
  try{
     const res = await getFetch(invoicesUrl, params);
     console.log("Data Json: ", res);
  }catch(error){
     console.log("Data Json: ", error);
  }
  return { props: { res } };
};

Comment: Ok, thanks! it helped me. Now my code is working. I will update my original question with the code working. However, here I thing you should change "return { props: { data } }" by "return { props: { res } }". Thanks again.


How to make adjustment for correlation coefficient?

Question: Suppose that there are two two-dimensional maps. For simplification, let's say one map is the temperatures in the 48 continental U. S. states, and the other map is the corresponding humidities. The data of temperature and humidity are collected at one specific moment at some equally-spaced (e.g., 1000) locations. If I directly calculate the correlation between the two maps, the coefficient would be inflated because the maps are spatially correlated? Suppose that I know the full width at half maximum (FWHM) that characterizes the spatial correlation, is there a way that I can adjust the correlation coefficient or its degrees of freedom?
Comment: It would be nice to have a clearer idea of what you mean by "inflated." This suggests a comparison, so one is moved to ask, inflated *compared to what*?  If you mean the correlation coefficient of the distribution of *all* temperatures and humidities at that moment, we should pause for a moment to consider what relationship the *sample* correlation would have to it and why--if at all--it could be expected to be "inflated," and how--if at all--that would be related to "spatial correlation." I believe that if you clarify these points, you might be able to answer this question yourself.
Comment: @whuber: You're right that the correlation coefficient is unbiased, but it's the significance of the correlation that I'm interested. And yes I thought about the adjustment about the DF, but just couldn't figure out how to make a proper adjustment for the DF based on the spatial correlation such as FWHM. Sorry I didn't bring up the real data context, but the essential issue in terms of spatial correlation remains the same. I hope that the temperature/humidity analogy captures the problem I'm facing.
Comment: @whuber: Thanks a lot for the comment! The suspicion of inflation is not based on any empirical information (I don't have any), but comes from my intuition. In other words, my concern is that the data for temperature/humidity are not sampled independently, and that's why I thought the spatial correlation might provide a way to correct for any inflation, if existing.
Comment: In what sense are they not sampled "independently"? Consider the non-spatial situation where two related variables are observed: each measurement produces an ordered pair of numbers.  How does your situation differ from that? Here's another way to think about it: imagine that $10^{1000}$ pairs of (temp, humidity) values could be recorded, effectively making an exhaustive census of the two fields. Taking a simple random sample of these pairs obviously has no problems with spatial correlation. Your sample does not differ a whole lot from that situation.
Comment: Have you looked at Spacial Dynamic Factor Analysis? http://faculty.chicagobooth.edu/hedibert.lopes/scientific/pdf/talk-tokyo.pdf It appears to have been designed to solve exactly this problem.
Comment: @Mimshot: Thanks for the suggestion! Spacial Dynamic Factor Analysis seems to be an interesting idea. However, that approach would not work for me. The correlation between temperature and humidity is my case is calculated among all the geological locations at one time point. And there is no time dimension involved.
Comment: @whuber: Suppose $x_i$ and $y_i$ are the temperature and at location $i$.  The correlation calculation is essentially a simple regression model: $y_i$ = $\alpha$ + $\beta$ * $x_i$ + $\epsilon_i$. If I understand it correctly, the $t$-statistic for $\beta$ (or the correlation between the two variables) would be inflated if the residuals $\epsilon$ are serially correlated (e.g., AR(1)). In my case, the complication is that my data are on a two-dimensional space, not a 1D time series. Is my concern still illusional?
Comment: Yes, it is an illusion, because although your temperatures $x$ and humidities $y$ likely are spatially correlated, the *residuals* possibly are not. Your regression setup is not ideal for analyzing this situation, since the $x_i$ are themselves random variables. Think instead of the dataset $((x_i,y_i), i=1,\ldots,n)$ as consisting of a sample of some bivariate distribution.  Furthermore, although correlated residuals will affect aspects of regression, when you have sufficiently extensive data (compared to the range of correlation) the regression estimates are still accurate.
Comment: @whuber: I used the temperature/humidity example simply as an analogy. There is some concern about the spatial correlation in the residuals in the field with the data I'm dealing with. I understand that the estimates for the regression coefficients are unbiased, but the correlation structure in the residuals would inflate the statistics including correlation coefficients, right? So my question is, if the residuals are indeed correlated, is there any way to correct for it on a 2D space?
Comment: The point of the last half of my previous comment is that your correlation coefficient estimates are unbiased, regardless. There is only the question of adjusting the DF if you want to compute the variance of those estimates. The adjustments require you to quantify the spatial correlation, so a mere analogy won't do you any good: you need to tell us about the data you actually are dealing with rather than some hypothetical situation.
Answer: What does correlation between the maps mean?  On the other hand, if you mean the correlation between the temperature and the humidity, we then have to ask what the population is that you are interested in and what the context of the question is.  For example, the correlation between humidity and temperature in one location over time may differ from that in another location.  The correlation between humidity and temperature over the entire geography of the US (assuming you can take a random sample from the US) during the summer may differ from that during the winter.
To even take a stab at answer those questions requires knowing why you are asking them.


What are the benefits of determining form before composing?

Question: I've heard time and time again of composers who say "It is better [for beginners] to know your form, and have a general idea of important chord progressions before you begin thinking seriously about melodies, basslines, etc."
How does one actually go about this process of roughly sketching out the structure of your piece beforehand?  How do you decide how long phrases, sections, etc. should be... or should you allow them to expand dynamically according to your melodies as you write them without prematurely confining them to said predefined space?  This way the melodies would feel much more natural, and the length of the piece (or number of measures) would adjust accordingly.
I apologize if this question seems trivial, but I am in the process of writing my first serious piece, and I think it would be extremely beneficial to have a goal in mind at pivotal moments.  Conversely, if this is an overly ambitious, "good-in-theory" idea, then please don't hold back in telling me so.
Thank you.
Answer: I have often used graph paper to create a left-to-right timeline where each cube of the graph paper represents a unit of time (say 5 seconds, or 15 seconds).  I then "draw" the form, sometimes getting carried away with colored pencils and such.  I then try to compose the music in-line with the formal diagram.  This doesn't always work and sometimes leads to a train wreck.  But sometimes the stars align and it leads to good music.  Often the piece that ensues ends up bearing little resemblance to the original formal diagram.
Here is an example of a formal diagram and the resulting piece.  Although, the final piece bears little resemblance to the original diagram, I believe the diagram was an important part of the creative process.
Lastly, composing is different for everybody, so if sketching forms doesn't work for you, don't do it!
Escape Sequence Recording on Spotify
Answer: Disclaimer: I'm just a hobby composer and I'm not very original either, so anything I say can be called BS. However, your question resonates with me and I do have some answers.
I'd say form is definitely important to me. My writing usually revolves around a melodic theme and its development. Classical forms like sonata, fugue and invention are pretty good vehicles for this purpose.
That said, the form should be a skeleton that helps you to freely flesh out the idea rather than a straight-jacket that constrains what you can do. The classical forms are exemplary and offer a number of devices that help me to work through a musical idea, but if an idea pops up that isn't prescribed by the form then you shouldn't be reluctant to add that. After all you're making music, not an ikea cupboard.
The underlying ideas of musical forms, like starting with an exposition section, contrasting the initial theme with a counter theme, gradually transforming themes in a developmental section, and finishing of with a conclusion or recapitulation are more important than the exact method you use to do that.
Developmental sections are definitely a good place to let phrases expand and flow freely (as your heart tells you), however, such development is usually more effective if it is preceded by an exposition that clearly and compactly states the idea in a form that is easily remembered and recognized.
With that in mind I don't really know what to make of the advice to "plan important chord progressions ahead". Perhaps that suggestion makes more sense if your theme is harmonic rather than melodic.
Finally, I think none of the strict form thinking is required if you have a clear vision of your piece ahead. But without a strict form, it seems many compositions rapidly start suffering from an over-abundance of themes, losing all coherence, or worse, a constant repetition. Form helps me balance these two competing elements.
Answer: Disclaimer: not an expert in composition, and definitely no more than a semester college instruction in composition in classical music.
At the end of the day, what is best to do is what works best for you.  Unless you're doing improv, nobody's listening to your process, they're listening to your finished piece.  Results are what matter.  That said, some observations:
1) Me, I'm all about starting with melody, and I am here to testify that it's a terrible idea.  It's amazing what musical dead-ends I manage to write myself into this way.  If there's any other way you can get your musical imagination to proceed, definitely do that.
2) Re "naturalness": nothing in music is natural by nature.  All is artifice.  Plan on working hard to make things sound effortless, and endlessly tweaking to make something sound spontaneous.  Do not expect the free-flowing product of your imagination to be better than what you can craft it into with some thought.  While it can happen that way, there's no reason to assume it.
3) In music, as in life, I'm a big fan of the idea that the reason one makes plans is not to have a plan, but to have gone through the beneficial exercise of planning.  Once one has done that, one can, and often one must, throw away the plan once one starts implementing and finds things just won't go to plan.
Comment: @RolandBouman My job as a mod is not to decide what is and isn't on-topic, it's to act as an exception handler for what the _community_ decides is and isn't on-topic. That's why we have meta. I encourage you to bring that up again -- the [last time](http://meta.music.stackexchange.com/q/221/133) we covered it was a few years ago.
Comment: Your point 1) is baffling. You're all about starting with melody, but you get stuck when you do so, so that's why others definitely shouldn't attempt to do that? Earlier today you gave what I think is a pretty useful answer about developing rhythmical sophistication. http://music.stackexchange.com/questions/17026/how-to-develop-rhythmic-sophistication-in-writing-music/17030#17030 Why doesn't work that method for melody for you?
Comment: +1 for everything but point 1. About 2/3 of the time, I personally start out with just a melody and basic chord progression and finish with a complete song. So to each  his own.
Comment: @Roland Bouman.  I think you misunderstand.  I can generate endless melody -- pretty good stuff, too, at least in my opinion - but I seem to have a knack for coming up with things that don't play nice with (1) harmony, or (2) the other stuff I was planning on having going on around it.  If my aspirations are low, this is not a problem: the melody gets to do whatever it wants, and I'll harmonize it (or not) one way or another. If I want to build something more sophisticated, not so much. ETA: Indeed, that **is** the method I use for composition!  That's where I got the idea for the rhythm post.
Comment: Hmm.  It occurs to me it might be entertaining to post some problematic chunks of score, and ask how other people might resolve them.  Is that on topic?
Comment: @Codeswitcher I don't care too much whether the moderators think it's on-topic. I'd be interested to see the things you feel got you stuck.
Comment: @NReilingh thanks for chiming in. I can't speak for "community" but personally I think Codeswitcher's proposal is great and I would happily follow and maybe answer to topics like that.
Comment: I suspect questions about how to get a melody to work would be best if you could explain how getting your specific examples to work would help you write better music in the future. This way, your questions would have a general principle that would be helpful to future readers.
Answer: I guess this applies to songs as well as instrumental/compositions.
I tend to write pop/rock songs rather than 'pieces of music' so they tend to have a fairly traditional/popular structure. However sometimes it's only once I've written the song and played it through a couple of times that it becomes obvious something needs changing in the structure - a half length verse, or remove some weird part that doesn't add anything. So I have an idea of the form, but not necessarily a difinitive notion until I hear the whole thing.
Why change from the orignal plan ? Often it's something to do with the lyrics- either make more room for some extra wordage, or sometimes repeating a musical section sounds overly repetitive when it may not seem that way when sketching the song out first.
I guess it depends on what you're trying to achieve:  with popular tunes, it's normally a nicely crafted piece which kind of wraps itself up in just over 3-4 minutes. But with other kinds of music like classical, film backing music, etc, you're aiming (presumably) at just getting your mood across and aren't quite so concerned about time taken or making it 'safe on the ears' like pop can be.
Here's an anatomy of a typical pop song ... explains a bit about why it is like it is, in my view:

Intro = Here we go.. it's a bit like this .. or is it.. but when you
hear this part you will, in future, know whether to run to the dance
floor or switch the radio off.
Verse 1 = Laying the scene
Verse 2 =
Like verse 1, to show it didn't happen by accident
Chorus 1 = Ok
that's enough of that, let's have something else a bit more catchy
Verse 3 = Return to safety of scene layed out in 1st verse Chorus 2=
Here's that bit you liked last time, again
Middle 8 (bridge) = Another bit which doens't quite fit to give you a rest from the verse and chorus, and give a different context so that it sounds like we're starting a different song wiht the next verse- but rest assured, there will be one.
Solo (if there is one) = Time to show our skills, and have the song burst into life. Woa yeh.
Verse 4 = like verse 1 but slightly different, maybe more
assertive or quiter to add some tension
Chorus 3 = Here's that bit you liked .. again ..
Chorus 4 = Re-statement of the original point
of the song
End (or fade) = full stop, implying the point was made
and now it's time to quit. Expected Duration : 3 mins 15 seconds.
Answer: Musical Form, while vital to the process of writing complex music of maturity and significance, has always been my second priority. My number one priority has always been... whether I like what I'm writing or not. If what I happen to have laying out before me isn't in any strict form than whatever. It shouldn't matter as long as it's beautiful. Tbh, I have never planned out any of my compositions beforehand, unless you consider me saying "I'm gonna write a scherzo in D# minor" to be planning out a piece before hand. So I suppose my answer would be that I wouldn't plan out my pieces before hand with sketches or spreadsheets. I just sit down and write.


How to use Adobe AIR with Flex 4.6 SDK?

Question: I've been trying to use Adobe AIR 3.1 that comes with Flex 4.6 for my project.  I have been receiving the error application descriptor not found.
My descriptor file looks like this inside D:/Test/.
<?xml version="1.0" encoding="utf-8"?>

<application xmlns="http://ns.adobe.com/air/application/3.1">
    <id>Test</id>
    <versionNumber>1.0</versionnumber>
    <filename>Main</filename>
    <initialWindow>
        <content>Main.swf</content>
        <visible>true</visible>
        <width>800</width>
        <height>600</height>
    </initialWindow>
</application>

I build my swf with the following command while Main.mxml is in the /src subdirectory.
D:/Flex/bin/mxmlc.exe -debug=true -swf-version=14 D:/Test/src/Main.mxml
Then the SWF is moved to the /bin subdirectory.
I try using AIR with the following command in the directory D:/Test/.
D:/Flex/bin/adl.exe AIR.xml /bin/
My directory tree looks something like this:
D:/
- Flex/
-- bin/
--- adl.exe
- Test/
-- AIR.xml
-- bin/
--- Main.swf
-- src/
--- Main.mxml

Answer: I didn't CamelCase the closing tag: </versionnumber>.  It is actually </versionNumber>.
Also, to run AIR, this is the proper command: D:/Flex/bin/adl.exe AIR.xml
And finally the content tags now hold this: <content>bin/Main.swf</content>

How to use Adobe AIR with Flex 4.6 SDK?


Mybatis: How can I get the first element from the passed parameter?

Question: Given that my parameterType is an ArrayList, is it possible to get the first element from that list and use it  in the where clause ?
<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="db">

    <select id="selectFlag" resultType="java.lang.Boolean" parameterType="java.util.ArrayList">
        select TOP 1 'true' from customers where id = ???
    </select>
</mapper>

Answer: If your query uses one id, why are you sending a list and then picking the first one for the query?
Change your parameterType to an int (or whatever type the id has), don't send a list. This is a simple approach that also conveys the information that you are only retrieving data based on a single id. Your condition then changes to something like:
where id = #{id}

If you must absolutely send an ArrayList (for whatever reason) then MyBatis supports OGNL expressions so something like this should work:
where id = #{list[0]}

Unfortunately MyBatis lacks on the documentation side, so you can find out about things like this only by looking at the source code.


Floquet Theory $\phi(t)=P(t)e^{tR}$, can be $R$ Hermitian?

Question: Let ${\displaystyle {\dot {x}}=A(t)x}$ be a linear first order differential equation, where ${\displaystyle x(t)}$ is a column vector of length ${\displaystyle n}$ and ${\displaystyle A(t)}$ an ${\displaystyle n\times n}$ periodic matrix with period ${\displaystyle T}$ (that is ${\displaystyle A(t+T)=A(t)}$ for all real values of ${\displaystyle t}$. Let ${\displaystyle \phi(t)}$ be a fundamental matrix solution of this differential equation.
The Floquet Theory tells us that there is a constant matrix $R$ (possibly complex) and a T-periodic matrix valued function ${\displaystyle t\mapsto P(t)}$ such that
$$\phi(t)=P(t)e^{tR}.$$
This gives rise to a time-dependent change of coordinates ${\displaystyle y=P^{-1}(t)x}$, under which our original system becomes a linear system with constant coefficients ${\displaystyle {\dot {y}}=Ry}$.
My question: Does $R$ follow the algebraic properties of $A(t)$. For example if $A(t)$ is Hermitian, can we chose $R$ to be also Hermitian? The same question when $A(t)$ is skew-Hermitian, unitary,...
Answer: Let $A : \mathbb{R} \to M_n(\mathbb{C})$ be continuous and periodic with period $T>0$, so that the principal fundamental solution of the vector-valued ODE $\dot{x} = Ax$ is the unique continuously differentiable function $\Phi : \mathbb{R} \to \operatorname{GL}(n,\mathbb{C})$, such that
$$
 \dot{\Phi} = A\Phi, \quad \Phi(0) = I_n.
$$
Something remarkable happens when $A$ is valued in a matrix Lie algebra $\mathfrak{g} \leq M_n(\mathbb{C})$, i.e., an $\mathbb{R}$-linear subspace of $M_n(\mathbb{C})$, such that
$$
 \forall X,Y \in \mathfrak{g}, \quad XY-YX \in \mathfrak{g}.
$$
In this case, by standard theory of ODE on manifolds, the principal fundamental solution $\Phi$ is necessarily valued in the connected matrix Lie group
$$
 G := \{\exp(X) : X \in \mathfrak{g}\} \leq \operatorname{GL}(n,\mathbb{C})
$$
corresponding to the matrix Lie algebra $\mathfrak{g}$.
Hence, there exists $R \in \mathfrak{g}$, such that $\Phi(T) = \exp(TR)$.
Since $\mathfrak{g} = \{X \in M_n(\mathbb{C}) : \forall t \in \mathbb{R}, \, \exp(tX) \in G\}$, we can safely define $T$-periodic $P : \mathbb{R} \to G$ by
$$
 \forall t \in \mathbb{R}, \quad P(t) := \Phi(t) \exp(-tR).
$$
In turn, given $g_0 \in G$, the unique global solution $g : \mathbb{R} \to G$ of
$$
 \dot{g}  = Ag, \quad g(0) = g_0,
$$
i.e., the fundamental solution with initial value $g_0$, is given by
$$
 \forall t \in \mathbb{R}, \quad g(t) := (P(t)g_0)\exp(t g_0^{-1}Xg_0),
$$
where $g_0^{-1}Xg_0 \in \mathfrak{g}$ by $\mathrm{Ad}$-invariance of $\mathfrak{g}$ and where $(t \mapsto P(t)g_0) : \mathbb{R} \to G$ since $G$ is a subgroup of $\operatorname{GL}(n,\mathbb{C})$ and since $P$ is $G$-valued.
Let me close by mentioning some concrete special cases:

if $\mathfrak{g} = \mathfrak{u}(n) := \{X \in M_n(\mathbb{C}) : X^\ast + X=0\}$, then $G = \operatorname{U}(n) := \{g \in M_n(\mathbb{C}) : g^\ast g = I_n\}$;
if $\mathfrak{g} = \mathfrak{su}(n) := \{X \in \mathfrak{su}(n) : \operatorname{tr}(X) = 0\}$, then $G = \operatorname{SU}(n) := \{g \in \operatorname{U}(n) : \det g = 1\}$;
if $\mathfrak{g} = \mathfrak{so}(n) := \{X \in M_n(\mathbb{R}) : X^T + X = 0\}$, then $G = \operatorname{SO}(n) := \{g \in M_n(\mathbb{R}) : g^T g = I_n, \, \det g = 1\}$.

Note, however, that the $n \times n$ Hermitian matrices do not define a matrix Lie algebra, so that this general method is inapplicable to that case.


How to link migrated image file to the user profile picture field?

Question: I used the following migration file to migrate user pictures from a Drupal 7 site installation to Drupal 8:

migrate_plus.migration.drupal7_image.yml

id: drupal7_image
label: Images
migration_group: dhm_migrate_taxonomy
migration_tags:
  - Drupal 7
source:
  plugin: d7_file
  constants:
    source_base_path: '/var/www/html/migrate_training_7/web/'
process:
  fid: fid
  filename: filename
  source_full_path:
    -
      plugin: concat
      delimiter: /
      source:
        - constants/source_base_path
        - filepath
    -
      plugin: urlencode
  uri:
    plugin: file_copy
    source:
      - '@source_full_path'
      - uri
  filemime: filemime
  status: status
  created: timestamp
  changed: timestamp
  uid: uid
destination:
  plugin: entity:file
migration_dependencies: {}

And I am using this next snippet to link the migrated image files to the user picture field (This is used in my user migration file):

migrate_plus.migration.custom_user.yml

  user_picture: # Image field name in Drupal 8 site
    plugin: iterator
    source: user_picture # Image field name in Drupal 7 site
    process:
      target_id: fid
      alt: alt
      title: title
      width: width
      height: height

migration_dependencies:
  required:
    - drupal7_image

I can see that the files are being migrated and downloaded to my Drupal 8 installation but when I check the users I don't see any user pictures (fields are blank).
I really don't know what I am missing, I searched for examples on the Internet but I didn't find much.
Any help would be much appreciated. Thanks in advance. ;)
Comment: Let try plugin **migration_lookup** to apply new fid for user picture value.
Answer: Thanks a lot @MrD I tested using the migration_lookup plugin and it works like a charm:
  user_picture:
    -
      plugin: default_value
      source: picture
      default_value: null
    -
      plugin: migration_lookup
      migration: drupal7_image

Comment: Do we need to migrate files before the users or should the migration_lookup pull the pic in as the user migrates?
Comment: I think you need to migrate the files first. I am not sure tbh.


What is the easiest way to check if the two CRgn intersects?

Question: I use VS2010 and have:
CRgn rRgn1, rRgn2;

I'd expected a function like:
BOOL CRgn::Intersect(CRgn rRgn);

or
BOOL Intersect(CRgn rRgn1, CRgn rRgn2);

Already had search the official documentation and the SO with no results.
Answer: You can use CRgn::CombineRgn with a parameter of RGN_AND. It will return NULLREGION if the intersection is empty.


Update default value of form element with AJAX

Question: I have an email field on node add form , I want to check if this email exist fill the city field in the same node form , then my code is :
function custom_code_form_car_node_form_alter(&$form, &$form_state, $form_id){
  $form["field_user_email"]['und'][0]['email']['#ajax'] = array(
      'callback' => 'user_ajax_check',
      'wrapper' => 'field-user-city-add-more-wrapper',
      'effect' => 'fade',
  );
}

function user_ajax_check($form,$form_state){
    // load the user then
    $form["field_user_city"]['und'][0]['value']["#default_value"] ="foo";
    return $form["field_user_city"];
}

Comment: Not sure what you're trying to do here. Can you provide a more thorough explanation?
Answer: The value must be set in the hook_form_alter, not in the callback of ajax :
function custom_code_form_car_node_form_alter(&$form, &$form_state, $form_id){
  $form["field_user_email"]['und'][0]['email']['#ajax'] = array(
      'callback' => 'user_ajax_check',
      'wrapper' => 'field-user-city-add-more-wrapper',
      'effect' => 'fade',
  );

  if(!empty($form_state['values']['field_user_email']){
       $form["field_user_city"]['und'][0]['value']["#default_value"] = "foo";
  }
}

function user_ajax_check($form,$form_state){
    // load the user then
    return $form["field_user_city"];
}


Installing require-dev dependencies from core/composer.json

Question: I understand the composer-merge-plugin allows the Drupal root composer.json file to load core/composer.json on runtime. I also understand require-dev will only pull dependencies for the root composer.json file (see this link).
How can I force one/all core/composer.json dependencies (including the required-dev ones) to be pulled if I want without hacking the root composer.json file e.g. with a composer require vendor/package?
Answer: By default, Composer will install also the development requirements, if you don't use the --no-dev option.
I ran  composer create-project drupal/drupal test 8.3.*@dev, and in the output of the command I could see the following:

Installing drupal/drupal (8.3.x-dev
  8a84ec5556f354861f1ddc5d7a80081b91ca42df)
    - Installing drupal/drupal (8.3.x-dev 8a84ec5)
  Cloning 8a84ec5556 from cache
  Created project in test
  Loading composer repositories with package information
  Installing dependencies (including require-dev) from lock file
  Package operations: 76 installs, 0 updates, 0 removals
[Omissis]

Installing drupal/coder (8.2.11) Downloading: 100%
Installing phpunit/phpunit (4.8.28) Downloading: 100%

If you downloaded the archived release for example from https://www.drupal.org/project/drupal/releases/8.2.7, which doesn't include the development requirements, you need to run composer update from the directory containing core and composer.json.
I tested composer update --dev after removing the vendor directory from the test directory created from the previous command, and I got this output:

You are using the deprecated option "dev". Dev packages are installed by default now.
  Loading composer repositories with package information
  Updating dependencies (including require-dev)
  Package operations: 76 installs, 0 updates, 0 removals
Comment: My issue with this is I'm currently pulling from a `git clone` and installing via `drush site-install` as there's no way that I know of we can install the tip of 8.4.x (aka chase HEAD) with `create-project`. But regardless, your answer does provide an interesting workaround to the original issue. Thanks.
Comment: You can use `composer create-project drupal/drupal test 8.4.*@dev` for Drupal 8.4.x.
Comment: I was more talking about something like `composer create-project drupal/drupal test 8.4.*@dev#` - Filed https://stackoverflow.com/questions/42872173/pull-latest-commit-with-composer-create-project accordingly.


Finding the value of $\tan\theta \tan(\theta+60^\circ)+\tan\theta \tan(\theta-60^\circ)+\tan(\theta + 60^\circ) \tan(\theta-60^\circ) + 3$

Question:
Find the value of
  $$\tan\theta \tan(\theta+60^\circ)+\tan\theta \tan(\theta-60^\circ)+\tan(\theta + 60^\circ) \tan(\theta-60^\circ) + 3$$
  (The answer is $0$.)

My try: Let $\theta$ be $A$, $60^\circ -\theta$ be $B$, and $60^\circ + \theta$ be $C$. I simplified the result and got the expression
$$1 + 1/\cos A\cos B\cos C$$ but after that I can't simplify it.
Comment: Check the title, there may be brackets missing. Also please use brackets to clarify what you mean by $1/ \cos A \cos B \cos C$.
Comment: For me the expression in the title seems to simplify to $0$.
Comment: I dont think your conclusion of that expression is correct. $\cos A\cos B\cos C$ seems to be $\theta$ dependent
Comment: Question is edited and John yes you are right the answer is 0
Comment: Hey friends can I know why when I mostly post any questions it have so much down votes inspite of its difficulty
Comment: See https://math.stackexchange.com/questions/455070/proving-a-fact-tan6-circ-tan42-circ-tan12-circ-tan24-cir/455573
Comment: @user580093 People here are glad to see neat, clear description of the questions. So you'd better learn to type MathJax. Also, don't let us think you are imperative. Maybe you does not want to mean that but your post would be kind of commanding. Be polite.
Answer: $\cos A\cos B\cos C=\cos(60^\circ-\theta).\cos(60^\circ+\theta).\cos60^\circ$
Since, $\cos(60^\circ-\theta).\cos(60^\circ+\theta)={1\over2}(\cos120^\circ+\cos 2\theta)$
$\Rightarrow$ $\cos(60^\circ-\theta).\cos(60^\circ+\theta).\cos 60^\circ ={1\over2}(\cos120^\circ+\cos 2\theta).\cos60^\circ = {1\over2}({-1\over2}+\cos2\theta).1/2 $
Answer: Recall that
$$
\tan (A - B) = \frac {\tan (A )-\tan (B)} { 1+\tan (A) \tan (B)},
$$
which means
$$
1 + \tan (A) \tan (B) = \frac {\tan (A) - \tan(B)} {\tan (A-B)}.
$$
Thus the answer is
$$
\frac {\tan (\theta + 60^\circ) - \tan (\theta ) } {\sqrt 3} + \frac {\tan (\theta ) - \tan(\theta - 60^\circ)} {\sqrt 3} - \frac {\tan (\theta + 60^\circ) - \tan (\theta - 60^\circ)} {\sqrt 3} = 0.
$$
I have no idea how to transform this to $1 + (\cos(A) \cos(B)\cos(C))^{-1}$……
P.S. If the formula involving the tangent of sums seems unfamiliar, you may prove it by those formulae about sines and cosines.


Can a QTcpSocket release its descriptor

Question: Is it possible for a QTcpSocket to release its descriptor so ownership over the socket can be transferred to another QTcpSocket object on a different thread, or to a QSslSocket, without closing/interrupting the socket?
socket1.setDescriptor(descriptor);

// .....

descriptor = socket1.descriptor();
socket1.release();                       // <--- Is there a way to do this?
socket2.setSocketDescriptor(descriptor);

Answer: No, you can't release a socket descriptor once it has been assigned to a QTcpSocket.
But I'm not sure you would need to. The QTcpSocket can usually be moved to another thread with moveToThread, the constraints are the same as any moved QObject:

moveToThread should be called inside the thread to which the object currently belongs,
the object can't have a parent (you can remove it with theObject->setParent(0);, or move the parent instead of the object),

and because it is a QTcpSocket, the receiving thread should be running an event loop or you need to use the waitFor... functions in that thread.
This note seems to suggest that this only works for sockets since Qt 4.7.

Can a QTcpSocket release its descriptor


Does there need to be a specific command to have git recognize the movement of a file?

Question: I committed some changes to my project, and one of the things done was the movement of a file into another folder. I did the usual:
git add .
git commit -m "commit something"
git push origin

But on my github account, when looking at the project, the file I moved is still in the location before the movement. The file is also in the folder I moved it to. When looking at where it was moved, there is no commit info which I would think should happen, but there is on the old one. Is there a reason why this is? I am sorry if that is not very clear, please let me know if it needs to be made clearer.
Answer: When you move or rename a file, the old file reference is still there. You need to remove the file from git by...

git rm filename

And then commit.
Comment: What happens if I already deleted it and its not in my local git repo? How do I remove it from github to reflect that its also missing locally?
Comment: The same way. You can run this command, and see that git will remove this file.
Comment: I did, but its not reflected on github. It definitely removed it locally now for sure. But I can't push that change. DO I have to make a more significant change or something?
Comment: Nope, I was just being dumb. I didn't commit it apparently. At least not correctly. You have been most helpful. Is there another way that I can just remove files without telling github directly, and have it include it automatically as well as moving them? Thanks for the help though!
Comment: Well as far as I know, this is the only way. And it makes sense also, to manually ask git to remove a file, if it has been removed or renamed. You could try and check for other ways.
Answer: There is git mv old new; you use it like the normal mv command. If you already added the new file, remove the old one from git: git rm old
It's basically just sugar for the following commands:
mv old new
git add new
git rm old

Also have a look at What's the purpose of git-mv? for more information.
Comment: Thanks for that. Will definitely look at that,


Recursive feature elimination and dropping dummy features

Question: Is it advisable to use RFE for linear or logistic regression when we have some dummy features. Reason I am asking this is: in RFE we will eliminate some features which will also include dummy features and as per this answer for a categorical variable which is dummy encoded we should not keep some features & drop others, we should keep all dummy features of a categorical feature.
Reasoning given is :
"You should leave all five indicator variables in. Dropping predictors because they are non-significant leads to biased estimates for regression coefficients and inflated p-values."
"The problem with dropping the indicator is that you'll change the p-values of the remaining levels as well, as you're shifting the intercept (aka the reference group.)"
If ideal thing to do is keeping all levels/dummy features of a categorical variable then how do you use RFE for dummy features or how do you eliminate unimportant dummy or categorical features?
Comment: Dummy variables are one set, they represent the categorical variable which is parental to them. Normally one should drop or leave the complete set. Dropping just one dummy of the set is essentially merging of this category with the reference category.
Comment: @ttnphns If say 5 dummy variables of a parental categorical variable are highly significant & have high coefficients and 5 are insignificant, then wouldn't it be wrong to drop the complete set.
Comment: @ttnphns "Dropping just one dummy of the set is essentially merging of this category with the reference category">>>>I agree, so to overcome this merging of dropped dummy features  wouldn't it be better to use full encoding i.e. not dropping a level of categorical variable as reference category. If that's done then even if you drop 1 or more dummy features it would not create an issue as all dummy variables derived from a particular categorical variable would be independent in the sense that there is no reference cateory
Answer: This is a fairly old question but since it has no accepted answer I will give my two cents.
In logistic regression, it is typical to have a reference group, meaning we drop one category from the variable and lump it into the interpretation of the intercept. Consider a categorical variable with three levels: a,b, and c.  Suppose that by recursive feature elimination that you determine category c should be dropped. What is the effect of this?
By removing category c, you automatically change all observations of level c to level a. Since the variables are all dummied, the observations from category c have 0s in columns for a and b. Remove the column c, and you automatically make all observations of category c into category a. This can result in large bias.
If you are going to select categorical variables you need to select/eliminate groups of dummy variables at a time. Either the model has all the variables from that category, or it doesn't.
Comment: Rather than answering a FAQ for the n'th time, it would be better to search for duplicates (which there are), a good start is to look at the side bar under "Linked" and "Related"
Answer: I don't think you need to always keep all indicators. The ones that are dropped because of lack of significance (after dummying) can technically be considered as collapsed to one.
The inflation of p values happens to all features as a result of RFE.
Comment: @ldin If you drop some dummy variables then coefficients of remaining dummy variables would not be accurate and no inferences about features importance could be done or ranking of features to select the most important ones based on coefficients would not be possible. That's my concern –
Comment: Good point "The inflation of p values happens to all features as a result of RFE.".


Swipe to delete listview shows artifacts

Question: I am trying to implement Chet Haase's swipe to delete, but the example he has provided is leaving artifacts, and a ghost list view item, once the number of items is less than the number to fill the screen.
Also, if you remove the background container mentioned, then you can see more weird artifacts.

The source code for the example is taken from here: Graphics Geek Dev Bytes
Comment: Can't you use another library?
Comment: @ChintanRathod could you mention examples of some? We are already using pull to refresh, so a drop in replacement won't work for us.
Comment: You may need to reassign the adapter once the list is updated. It seems that the adapter may keep the previous ghost value that is displayed
Answer: Try to implement SwipeListView. It has same feature what you want.
Comment: the issue with this is, that this does not bring the other views up(or down) this simply shows another view behind the swiped list. We've done that, the issue is in removing the swiped item with animations.
Comment: thats why we came here, to see what modifications have been done, but it seems to be creating some problems, that we have no idea about
Comment: so isn't it possible to modify that code like removing views behind views and simply set background white colored?
Comment: @ChintanRathod will u please help me in this question will be thankfull to u http://stackoverflow.com/questions/20903545/how-to-call-framelayout-slider-in-diffrent-activties-in-android?noredirect=1#comment31377277_20903545
Comment: @ChintanRathod please help me in my issue ..please


looking for a random matrix of zeros and ones in python with a limited amount of ones

Question: I am generating a matrix of zeros and ones in python as
poblacionCandidata = np.random.randint(0, 2, size=(4, 2))

However, I need for it to be only two ones at most in each row.
I have checked this question, but it is too complex for me.
Can anyone help me with this
The result should be something like
[[1 1 0 0]
 [1 0 0 1]
 [1 0 0 0]
 [0 1 0 0]]

Best regards
Comment: Are you saying that each row should contain "at most" 2 1s? i.e., could there be none?
Comment: Yes, it could be none
Answer: You could just use a loop:
import numpy as np

def generate_matrix(rows: int, cols: int, max_ones_per_row: int) -> np.ndarray:
    """
    Generate a matrix with up to a specified number of ones per row.

    :param rows: The number of rows in the matrix.
    :param cols: The number of columns in the matrix.
    :param max_ones_per_row: The maximum number of ones to be placed in each row.
    :return: A numpy array representing the generated matrix.
    """
    matrix = np.zeros((rows, cols), dtype=int)
    for i in range(rows):
        ones_per_row = np.random.randint(0, max_ones_per_row + 1)
        ones_indices = np.random.choice(cols, ones_per_row, replace=False)
        matrix[i, ones_indices] = 1
    return matrix

poblacionCandidata = generate_matrix(rows=4, cols=4, max_ones_per_row=2)
print(poblacionCandidata)

Example Output:
[[1 0 0 0]
 [0 0 1 1]
 [0 0 0 0]
 [0 1 0 0]]

Comment: Your answer seems to have always two ones in each row, not two at most
Comment: Fixed. See update.
Comment: Now it works better than mine
Answer: In the end, I managed with creating a function
def generacionPoblacionCandidata(tamanioPoblacion, numColumnas, n):
    poblacionCandidata = np.zeros((tamanioPoblacion, numColumnas), dtype=int)
    for j in range(numColumnas):
        contador_unos = 0
        while contador_unos < n:
            columna_aleatoria = np.random.randint(0, 2, size=tamanioPoblacion)
            if np.sum(columna_aleatoria) <= n:
                poblacionCandidata[:, j] = columna_aleatoria
                contador_unos = np.sum(columna_aleatoria)
    return poblacionCandidata

I have tested it and seems to work fine
Comment: That'll be a very slow way to do what the answer you linked already does.


don't understand the derivation of logarithmic cost used in gradient descent

Question: I am learning Machine Learning.I have seen that in logistic regression there are two cost
1)$θ_j=θ_j − \frac{\alpha}{m}\sum_{i=1}^{m}(h_θ(x^{(i)})−y^{(i)})x^{(i)}$
2)$Cost(h_θ(x),y) = −ylog(h_θ(x))−(1−y)log(1−h_θ(x))$
While updating weights through gradient descent we use this $(h_θ(x^{(i)})−y^{(i)})x^{(i)}$ as derivation of cost function and after updating weights we calculate cost using $−ylog(h_θ(x))−(1−y)log(1−h_θ(x))$ cost. I don't understand that $\frac{\partial}{\partial\theta}( −ylog(h_θ(x))−(1−y)log(1−h_θ(x)) ) = (h_θ(x^{(i)})−y^{(i)})x^{(i)}$
according to my knowledge cost in the gradient is the derivation of logarithmic cost
Comment: I think you *might* be getting derivation and derivative mixed up. The process of getting a derivative is differentiation, not derivation.

But if this comment is wrong, I apologize
Answer: I think you are confusing cost (J) with the gradient of cost ($\nabla J$).
your first equation is equivalent to:
$$
\theta _j := \theta _j - \alpha /m \nabla J
$$
and then the second is the actual cost (J).
In each step, you are moving in the direction opposite of the gradient ($\nabla J$) and then the calculation of the cost is, probably, just to show that you are actually minimizing the value of the cost (J).
HTH
EDIT: Perhaps I misunderstood, but seems the OP wants the derivation of the derivative of the cost function.
To do that, first we have to note that
$$
h'_\theta (x) = x(h_\theta (x))(1 - h_\theta (x))
$$
Now, if we write the derivate of J above, we end up with (following normal rules of differentiation):
$$
\nabla_\theta J = -\frac{h'_\theta(x)}{(h_\theta (x))(1-h_\theta (x))}(y - h_\theta (x))
$$
If we substitute into the above the formula for $h'_\theta (x)$, we see that:
$$
\nabla J = x(h_\theta (x) - y)
$$
Comment: yes,  you are right I want to know what is the **∇** of cost function **J** where **J** = **−ylog(hθ(x))−(1−y)log(1−h(x))**
Comment: hθ(x) = 1 / 1 + e ^ (- θ * x) where θ = vector of features and x = vector of input values
Comment: I appreciate your efforts but I want just derivation of cost function(CF). In logistic regression or any ML algorithm, to reduce your cost to predict any value, you have to perform gradient descent on CF to get step size which will lead us to the global minimum. performing gradient descent on CF is nothing but a partial derivation(PD) of the cost function w.r.t θ. In logistic regression cost, the function is **−ylog(hθ(x))−(1−y)log(1−h(x))** .So if I want to reduce the cost, I have to have PD of above cost function. sources say that **(hθ(x(i))−y(i))x(i)** this the PD of cost function how?
Comment: sorry, I don't understand the question. It won't be possible to give all the steps of the derivation. However, I would encourage you to just differentiate the cost function w.r.t $\theta$. Keep in mind that, $\frac{d}{d\theta}log( h_\theta(x)) = \frac{h'_\theta(x)}{h_\theta(x)}$. if you do that then you should get the equation i have written for $\nabla_\theta J$. The **trick** is to recognise the particular form of $h_\theta(x)$ that will give you the identity above for $h'_\theta(x)$.
Comment: Okie that helped a lot thanks .....!!!
Comment: Cool. Please accept the answer if it clarified your question. Thanks.


Express a complex analytic function as a single power series

Question: Let $\Omega\subseteq\mathbb{C}$ be a connected open set, then $f:\Omega\rightarrow \mathbb{C} $ is analytic if for every $z_0\in\Omega$ there are $r>0$ and $(a_n)\subseteq\mathbb{C}$ such that $f(z)=\sum_{n=0}^\infty a_n(z-z_0)^n$ for every $z\in B(z_0,r)\subseteq\Omega $, and in fact $ a_n=\frac{f^{(n)}(z_0)}{n!}$.
How can we show that given some $ z_0\in\Omega$ the equality $f(z)=\sum_{n=0}^\infty \frac{f^{(n)}(z_0)}{n!}(z-z_0)^n$ actually holds for every $z\in\Omega$ and not just in some neighborhood of $z_0$?
Answer: You can not show this equality ! Example $ \Omega=\mathbb C \setminus \{1\}$, $f(z)=\frac{1}{1-z}$ and $z_0=0$.
We have $f(z)=\sum_{n=0}^\infty \frac{f^{(n)}(z_0)}{n!}(z-z_0)^n=\sum_{n=0}^\infty z^n$ only for $z \in \Omega$ with $|z|<1$.
Remark: if $ \Omega=\mathbb C$ and if $f$ is entire, then we have for each $z_0 \in \mathbb C$ that $f(z)=\sum_{n=0}^\infty \frac{f^{(n)}(z_0)}{n!}(z-z_0)^n$ for all  $z \in \mathbb C$.
Comment: And what if we also know that $\Omega$ is convex? Is it true in this case?


Math Notation understanding help?

Question: I'm trying to understand the following notation and I'm simply too new to more advanced mathematics, especially notation.
The purpose of this is for a reinforcement learning modification to utilize intrinsic rewards based on curiosity.
I know the left hand side of equals is the intrinsic reward for a specific time step. I believe η is a chosen value for scaling purposes. φˆ(st+1) is the result of a prediction of a future state while φ(st+1) is the true value of the future state.
The bars || I am unsure of, as I'm also unsure of the super/sub scripts of 2 on the end in this context. Even knowing what they refer to, I'm unsure of the order of operations intended with notation like this.
Any help at all would be greatly appreciated, but my hope is to get a full explanation of each value's meaning and a more simplified algebraic representation (ideally spelled out as plainly as possible).
This is taken from the following paper: https://pathak22.github.io/noreward-rl/resources/icml17.pdf
Comment: it means the two norm of your quantity, squared.
Answer: The bars are in reference to taking a Norm.  You have seen some norms before, I'm sure such as absolute value, or "length", or "max", etc...  They satisfy certain nice properties such as the triangle inequality.  Read more on the linked page.
The subscript here is in reference to which norm we are talking about.  We are talking specifically about the Euclidean Norm.  This is the norm that most people are used to when talking about distance.  Given a vector $v = [v_1,v_2,\dots,v_n]$ the Euclidean norm of this is $\|v\|_2 = \sqrt{\sum\limits_{i=1}^n v_i^2}$
The superscript here is a usual power, which effectively takes away the square root.
Depending on context, $\|\cdot \|_2$ might instead be in reference to the $\ell_2$ norm or the $L_2$ norm instead, both of which act similarly to the Euclidean norm just for different spaces.  See Lp Spaces.
Comment: Ty so very much. With a bit of research, I seen it made most sense for the bars to mean to normalize, but I had no idea the subscript corresponded to a specific method. If I understand correctly, it's still a bit confusing to me to take the two norm to a power of two if that effectively cancels out the square root. I'd think it could have just been the sum of the state differences squared.

Math Notation understanding help?


Why No Body Talk About Checkout Customization Of Magento 2? My Last Post On This Platform

Question: Why No Body Talk About Checkout Customization Of Magento 2? I Do So Much Search On Internet But I Can't Find Any Proper Solution For Customize Checkout Fieds. So I Decide I Ask Question On This Platform. I Post So many Question Of checkout Customization Here But No Body Have Guts For Answers My Questions.
This Is My Last Post This Platform If No Body Help Me.
Answer: Let's take your questions one by one:

How To Customize Checkout Page Using One Page Checkout extension Call IWD Agency Magento 2.2.6 Maybe you don't get an answer to this one because it's not a core related question and not a lot of people used the extension you are using.
Geting Error In Checkout Page Magento 2.2.6 This is the same question as the next one. Please stop asking the same question twice
Geting Error In Checkout Page Magento This one has an answer, and it looks like a valid one to me. But without your code we cannot guess where exactly is the problem. You need to put in some effort also.
How to Customize Checkout Page In Magento 2.2.6 Using checkout_index_index.xml This one is pretty vague. You are asking "How can I do this using that?". Maybe "using that" is not really the way to go. You should re-word the question and explain the desired result, what have you tried, and what problems you got. Dumping a file and a screenshot and expecting a fully working solution it's just lazy.
Customize Checkout Page And Remove Postal Code And Extra Fields this one has an answer and again, at a first glance, it looks valid. Or at least a nudge in the right direction. Just stating that it doesn't work for you shows laziness again. What does not work for you? what happens when you use that code? Where did you add that code? does it work in the luma theme? maybe there is something wrong with your theme.

And as a personal response (I'm not speaking for everyone else here), I'm usually avoiding bad formatted questions that might spawn 12 other followup questions because I don't have the time to do support. I try to answer straight to the point questions with clearly explained problems, or with problems that I've encountered myself.
Comment: Good shot Maruis :)


How would I use this substitution for this volume integral?

Question: I'm stuck on the following question, and would like some guidance or solution to this:
Let $V$ be the solid bounded by $z=2x$ above and below by $z=x^2 + y^2$.
First it tells me to express the volume $V$ in cylindrical coordinates, and I hope this is correct, please correct me if I'm wrong:
$$V = \int_{-\frac{\pi}{2}}^{\frac{\pi}{2}}\int_{2\cos\theta}^{2}\int_{r^2}^{2r\cos\theta}r \mathrm{d}z\mathrm{d}r\mathrm{d}\theta. $$
After this, it then tells me to employ the substitution:
$$x=1+u\cos v, \quad y=u\sin v, \quad z=w.$$
I found the determinant of the jacobian to be $u$, but I have no clue how to change the boundaries with the substitutions.
The integral in cartesian coordinates is (I derived this, I hope this is correct):
$$V=\int_{0}^{2}\int_{-\sqrt{1-(x-1)^2}}^{\sqrt{1-(x-1)^2}}\int_{x^2+y^2}^{2x}\mathrm{d}z\mathrm{d}y\mathrm{d}x$$
for clarity.
How would I change my volume integral using their substitutions?
Comment: The angle bounds look right. People often do zero to $2\pi$ for a full circle but the negative angle seems a lot more convenient here.
Comment: The Cartesian bounds look fine to me. I think the integration over $r$ should run from $0$ to $2\cos\theta.$
Comment: Thank you, and the $\theta$ bounds are fine right (I just changed it)? I don't ever recall having negative bounds for $\theta$ in polar substitutions, but it seems that it's necessary here.
Answer: The intersection of the paraboloid $z=x^2+y^2$ and the plane $z=2x$ is given by an ellipse, whose projection on the $xy$-plane is given by the conic with equation $x^2-2x+y^2=0$, that is a circle with unit radius centered at $(1,0)$. By setting $x=1+\rho\cos\theta$ and $y=\rho\cos\theta$ we have that on the given solid $z$ is bounded between $2+2\rho\cos\theta$ and $1+\rho^2+2\rho\cos\theta$, hence the wanted volume is given by
$$ \int_{0}^{2\pi}\int_{0}^{1}\int_{1+\rho^2+2\rho\cos\theta}^{2+2\rho\cos\theta}\rho\,dz\,d\rho\,d\theta = 2\pi\int_{0}^{1}\rho(1-\rho^2)\,d\rho = \color{red}{\frac{\pi}{2}}. $$
Comment: Ahhhh I see. So their given substitution is basically a "polar" substitution, except it """shifts""" our point of view of the origin, to the centre of the circle in the $x-y$ plane (so basically it's like we evaluate a triple integral, except we pretend that the projection was a circle centred at the origin)?
Comment: @Twenty-sixcolours: correct, and typo fixed.
Comment: That makes a lot of sense, thanks!


Earlgrey is slow when accessing NavBar/TabBar Items

Question: As EarlGrey runs in the process and there is no install/uninstall process involved as in XCUI test framework, I expected tests to run faster but I noticed it is almost the same speed as XCUI test framework. Any reasons?
It's very slow to get TabBar or NavBar items. How can I speed up the process?
I'm using this for TabBar elements to match
let tabButtonMatcher: GREYMatcher = grey_allOf([grey_accessibilityLabel("Something"), grey_accessibilityTrait(UIAccessibilityTraitButton),  grey_sufficientlyVisible()])
        EarlGrey.selectElement(with: tabButtonMatcher).perform(grey_tap()).assert(grey_sufficientlyVisible())

Similar for NavBar buttons also
    let navMatch: GREYMatcher = grey_allOf([grey_accessibilityID("Something"), grey_accessibilityTrait(UIAccessibilityTraitButton), grey_sufficientlyVisible()])
    EarlGrey.selectElement(with: navMatch).perform(grey_tap())

Comment: No difference. Is there any way to just go directly to UINavBar or TabBar items? Also it prints as in the hierarchy, but I can't use UITabBarButton or UITabBarItem with grey_isKindOf    ""
Comment: What matcher are you using?
Comment: Edited the question with the matchers
Comment: Can you check with grey_sufficientlyVisible() removed from the matcher?
Comment: You can. I don't see any reason not to tbh.
Answer: You must remove grey_sufficientlyVisible from your matchers because it doesn't make sense. This matcher is guaranteed to work well in the assert statement, but it seems it's inefficient to pass as a matcher parameter.
EarlGrey interacts with touch events on the run loop and, generally, it interacts with the application as well as a real user. Its unlikely tests will be fast in this case, especially compared with KIF which calls selectors on UI elements instead of passing touch events. That's not bad, it's an expected behavior for functional tests. By the way, you could speed up tests by disabling animations:
GREYTestHelper.enableFastAnimation()

Regarding your question related to matchers, I would suggest you try several approaches and find one which is suited in your case.
At first sight, it should be worth to just find a UITabBarItem using grey_kindOfClass.
Matcher example (not working)
grey_allOf([grey_kindOfClass(UITabBarItem.self), grey_text(title)])

But it's not the working solution.
Let's see on view hierarchy:

So if you rely on UITabBarItem it doesn't work, because there is no such element. You can see, that there is a private UIKit class called UITabBarButton which is not supposed to interact with. Moreover, it's not a subclass of UIButton, but it's a subclass of UIControl
Instead, I would recommend to select element on UITabBar using inRoot function.
Matcher example (working)
EarlGrey.selectElement(with: grey_text(tabbarTitle))
        .inRoot(grey_kindOfClass(UITabBar.self))
        .perform(grey_tap())

In this case, you find an element, which has the expected text and which is located on the UITabBar.
For selection elements on the navigation bar it's possible to use variations of this matcher:
Matcher example to find the element on navigation bar
EarlGrey.selectElement(with: grey_kindOfClass(UIButton.self))
        .inRoot(grey_kindOfClass(UINavigationBar.self))

Comment: I will try this and see if it improves and accept the answer.
Comment: @user1165756 please update when you get the result
Comment: Very small improvement, but will keep these tips in mind.


Why numpy converts 20000001 int to float32 as 20000000.?

Question: I am trying to put some numbers into numpy array
>>> np.array([20000001]).astype('float32')
array([ 20000000.], dtype=float32)

where did 1 go?
Comment: Possible duplicate of [Is floating point math broken?](http://stackoverflow.com/questions/588004/is-floating-point-math-broken)
Answer: You simply don't have enough precision.  The float32 has only approximately 7 digits of accuracy, whereas the float64 has approximately 16 digits of accuracy.  Thus, any time you convert to a float32, it's only guaranteed to be "correct" to within about a part in 10^7.  So, for example, you can try this:
>>> np.array([20000001]).astype('float64')
array([ 20000001.])

That's the expected answer.  (The dtype=float64 is automatically omitted, because that's the default.)  In fact, you can go further and find
>>> np.array([2000000000000001]).astype('float64')[0]
2000000000000001.0

but
>>> np.array([20000000000000001]).astype('float64')[0]
20000000000000000.0

At some point, no matter how high your precision, you'll always get to the point where floats drop the least significant digits.  See here for more info on floats.
On the other hand, python's int objects have many more digits they can keep track of.  In python 3, it's practically unlimited.  So ints have basically infinite precision.  See here for more info on ints.
Answer: with float32 you can't resolve it
>>> np.finfo(np.float32).eps
1.1920929e-07

eps here gives you "the smallest representable positive number such that 1 + eps != 1" which is a measure for float32 accuracy. Multiply that with 20,000,000 and it's just too large.
Less informally, if one wants to avoid computing the binary representation of n then eps * n / base is a convenient lower bound for the resolution around n. While as @hobbs points out eps * n is an upper bound.
Also note that for example 1 + 0.6*eps may actually return something != 1, this is, however, due to rounding. Subtracting 1 from the result returns eps, not 0.6*eps.
Comment: That's not exactly the right way to compute that... although it is within a factor of 2 of the correct value. The actual precision of a 32-bit float in the vicinity of 20,000,000 is exactly 2 (as it is for any value between 2^24 + 1 and 2^25).
Comment: @hobbs well, unless I'm completely mistaken eps x n / base does give you a lower bound for the smallest number you can add to n such that etc.
Comment: upper, rather. The precision at 1.99 is the same as it is at 1, not 1.99 times worse; it jumps at 2.
Comment: @hobbs and what use would an upper bound be here, hm? It is very simple: A lower bound for some y is a number that is guaranteed not to exceed y. If we want to show that 1 can't be effectively added to 20,000,000 we need to show that r > 1 where r is the rersolution at 20,000,000 if we have a lower bound b for r and b > 1 then we can conclude r > 1 because r >= b > 1. with an upper bound this does not work.
Comment: I don't disagree that an upper bound is not very useful; my point is that the value you provided *is* an upper bound, not a lower bound.
Comment: (Luckiliy, the lower bound is simply half that.)
Comment: @hobbs just to be sure you did see the 1 / base there? Or are we disagreeing on rounding? Something like 20,000,000 + 1.1 = 20,000,002? I'd say that doesn't count since you haven't added 1.1 you've added 2. If you check `np.float32(1) + np.float32(eps*0.6)` you'll also get something which is not 1, so the library agrees with me on that.
Comment: I missed the `/base`. Apologies.
Comment: @hobbs no prob, sorry for getting tetchy so easily. I'll clarify the post.
Answer: First of all, float64 works in this case:
>>> np.array([20000001]).astype('float32')
array([ 20000000.], dtype=float32)
>>> np.array([20000001]).astype('float64')
array([ 20000001.])

How does a float work under the hood:

What's the difference between float32 and float64?:

32bit (single precision float): 24 bit significand
64bit (double precision float): 53 bit significand

With float32, you get 23 bits to represent the digits plus 1 bit to represent the sign. Lets view 20000001 in binary:
0b 1 0011 0001 0010 1101 0000 0001  ---->
0b 1 0011 0001 0010 1101 0000 00

So the last two bits "01" will get cut off when converting from int to float32.
Interestingly, converting 20000003 will get you 20000004:
>>> np.array([20000003]).astype('float32')
array([ 20000004.], dtype=float32)

And that is:
0b 1 0011 0001 0010 1101 0000 0011  ---->
0b 1 0011 0001 0010 1101 0000 01

Comment: Very nice explanation. Please allow me to point out a small inaccuracy. Even though there are 23 bits for the significand the actual precision is 24bits because of the implicit leading 1 which needn't be stored. You can check this with `np.float32(20_000_002)` which is represented  exactly.


How can i show all taxonomies of WP for categories and tags only?

Question: I am trying here with this code,
$all_terms = get_object_taxonomies(get_post_types(array('public'   => true ), 'names', 'and' ));

but it is rendering the post_format, other types like product_visibility too, but I want only tags and categories, is there any function or process that i can get only tags and categories
Answer: You can use get_terms() check the below code.

For Tag.

$post_tag = get_terms( array(
    'taxonomy' => 'post_tag',
    'hide_empty' => false,
) );

For category.

$category = get_terms( array(
    'taxonomy' => 'category',
    'hide_empty' => false,
) );


How to use Netbox API to get data from a local script?

Question: Similar to This, I've installed NetBox via docker containers.
I wrote some python code(API) which take an IP range(local of course) as input and scan the range via Nmap python module and provide the result nice and neat as output.
What I wanna do is I want NetBox to have a section that I can place an IP range as an input, then it contacts my API and takes the result back and store them in its database (suppose results are organized)
For example say I have a local subnet 192.168.104.0/24 and there are several devices(each has attributs like MAC address, hostname, whether a vm or not...)
I give this range to Netbox and it places these devices in the database using the result my API provides for it.
Answer: You can achieve this by utilizing NetBox's custom script feature.
These scripts are written in Python, so you can move your nmap feature into this script. It would also be callable via NetBox's API at <netbox-url>/api/extra/scripts/<