Making a DotPlot with colored sidebars correlating to clusters and gene expression

Question: I wanted to produce a DotPlot that adds an extra feature for linking the feature genes to the clusters they were taken from.
I can easily produce the standard DotPlot with dittoDotPlot:
p1 <- dittoDotPlot(Liver, top10_filter$gene, group.by = "DefClustering") + coord_flip() + theme(axis.text.x.bottom = element_text(colour = my_palette_Rui_colors))

And I found a website (https://davemcg.github.io/post/lets-plot-scrna-dotplots/#lets-glue-them-together-with-cowplot) where they tried adding labels, in this case relaing cluster with CellType (I want to associate gene with CellType instead)
labels <- ggplot(gene_cluster %>%
                   mutate(`Cell Type` = Group,
                           cluster = factor(cluster, levels = v_clust$labels[v_clust$order])),
                 aes(x = cluster, y = 1, fill = `Cell Type`)) +
  geom_tile() +
  scale_fill_brewer(palette = 'Set1') +
  theme_nothing() +
  xlim2(dotplot)

Right now I have produced this table that can easily correlate each gene to the cluster I am interested in.
head(top10_filter)
# A tibble: 6 × 7
# Groups:   gene [6]
      p_val avg_log2FC pct.1 pct.2 p_val_adj cluster  gene
      <dbl>      <dbl> <dbl> <dbl>     <dbl> <chr>    <chr>
1 0               3.19 0.957 0.004 0         Arteries GJA5
2 0               1.83 0.783 0.005 0         Arteries LMO7
3 1.42e-303       2.73 0.652 0.003 4.59e-299 Arteries COL8A1
4 1.72e-282       2.67 0.783 0.006 5.56e-278 Arteries SDC1
5 1.63e-262       3.11 0.522 0.002 5.26e-258 Arteries NPR3
6 1.76e-228       2.68 0.826 0.01  5.69e-224 Arteries NRG1

So how can I work with ggplot so I can get the plot I am aiming to get? right now I can produce the bar on the right handside but the colors in no way correlate to each cluster, they have been assigned proportionally.
labels <- ggplot( top10_filter %>%
                   mutate(cluster,
                          ),
                 aes(x = 1, y = cluster, fill = top10_filter$cluster), color = my_palette_Rui_colors) +
  geom_tile() +
  theme_nothing() +
  xlim2(p1)

p1 + labels

I do not fully get how the correlation between clusters and cell types was done in the example, and maybe it cannot be done the same way between genes and clusters in mine. Either way I do not know how to move forward. Thanks in advance!
Comment: check http://www.cookbook-r.com/Graphs/, especially chapter 11 "colors".
Answer: I think you where on the right track with geom_tile. You just have to define the desired aesthetics there as well.
Below I included a minimal example using the mtcars data set. Not the prettiest, but I hope it shows the idea.
You just have to make sure your x variable is character- or factor-type.
If you want your geom_tile on the right side of the plot, but before the legend, you can use the trick with "x = length(unique(data_tmp$cyl))+1"

data_tmp <- mtcars
data_tmp$type <- rownames(data_tmp)
data_tmp$cyl <- paste0(data_tmp$cyl, "_cylinder")

#type = gene
#cyl = cluster
color <- data_tmp$cyl
plot <- ggplot(data_tmp, aes(y=type, x=cyl)) +
  geom_point(aes(size=drat, color = qsec)) +
  geom_tile(aes(y=type, x = length(unique(data_tmp$cyl))+1, fill = cyl)) + # creates a bar on the rights side of your data, coloured by your x-variable
  scale_fill_manual(values=rainbow(8)) +
  theme_classic()

plot

To define colours, instead of rainbow(x), you could also use a named vector such as:
colours_used <- c("cluster1" = "red", "cluster2" = "blue", "cluster3" = "green")


Setting a Sharepoint Site Theme through a Web Service?

Question: Is it possible to change a Sharepoint 2007 Site Theme through a Web Service? I know it can be done through the Object Model with (i think) SPWeb.ApplyTheme, but I did not see anything in the available Web Services, apart from CustomizeCss in Webs.asmx, which does not seem to be exactly what I need.
Answer: This is not possible out of the box. However, you can write your own custom SharePoint web service that exposes this feature to you. A walkthrough on how to make your own custom web service in SharePoint can be found here:
http://msdn.microsoft.com/en-us/library/ms464040.aspx
Another way would be to create your own themesetter and invoke it via a request. An example of this can be found here:
http://www.sharepoint-tips.com/2006/03/automatically-applying-theme-to-site.html


How to minimize the number of functions to be projected on

Question: I have a set of functions $f_i,\, i=1,2,\ldots,n$ defined on an interval $[a,b]$,
and a function $F$ also defined on $[a,b]$. I would like to project F on a subset of functions $f_i$ so that the number of $f_i$ used to represent $F$ is minimum, but $\|F-\sum\limits^k_{i=1}f_iw_i\|\rightarrow0$, where $w_i$ are some weights.
Any help on this problem or a reference leading to its solution is very welcome.
Thank you.
Karla
Comment: What do you mean when you say "but $\|F-\sum\limits^k_{i=1}f_iw_i\|\rightarrow0$"?
Comment: I just wanted to say that the difference between $F$ and its projection is small for the minimum number of $f_i$, which is denoted by $k$.
Comment: The problem can also be reformulated as a function expansion problem:
expand $F$ into a sum $\sum\limits^k_{i=1}f_iw_i$ so that $\|F-\sum\limits^k_{i=1}f_iw_i\|\rightarrow0$.
Answer: One idea could be to sample the functions $F$ and $f_i$ at a bunch of points in the interval $[a,b]$, obtaining  vectors $G$ and $g_i$.  Then minimize $\| w \|_1 + \alpha \| G - \sum_{i=1}^n g_i w_i \|$ with respect to $w$.  (Here $\alpha > 0$ is a parameter you can tune.)  That's a convex problem so it could be solved efficiently.
A key point is that by penalizing the $1$-norm of $w$ we encourage $w$ to be sparse.  So most of the components of the optimal $w$ will be equal to $0$.
Comment: I've tried the idea with fminsearch in MATLAB, but the result is poor.
Comment: @Karla You could try solving the optimization problem using CVX, which might do better.  How many sample points did you use?  Did you try many different values of $\alpha$?  What about the results is poor?
Comment: I used 243 sample points and different values of $\alpha$ but it didn't help. The poor results mean a large value of $\|F-\sum\limits^n_{i=1}f_iw_i\|$, which is far a way from being optimal. Perhaps, I should try CVX.
Comment: What's your value of $n$?
Comment: $n=243$ and the length of the vectors $G$ and $g_i$ is also 243.
Comment: I see.  Is $\|G - \sum_{i=1}^n g_i w_i \|$ small, at least?  When $\alpha$ is large, if the optimization problem is being solved correctly, then $\|G - \sum_{i=1}^n g_i w_i \|$ should be nearly $0$.
Comment: $\| G - \sum_{i=1}^n g_i w_i \|$ is around several hundreds.
Comment: Assuming the vectors $g_i$ are linearly independent, you should be able to pick the $w_i$ so that $G - \sum_{i=1}^n g_i w_i$ is exactly $0$.  As a sanity check, you could try just minimizing $G - \sum_{i=1}^n g_i w_i$ by itself, and check that the minimum value is $0$.  Also, you could try putting the vectors $g_i$ into the columns of a matrix $M$.  Let w = M\G ; (using Matlab notation), and check that $G - \sum_{i=1}^n g_i w_i$ is $0$.
Comment: Of course, it is 0, but I'd like to have the minimum number of $g_i$.
Comment: Yes, just a sanity check.  I'd be interested in seeing the functions $F$ and $f_i$ explicitly, if it's not hard to write them.  Where does this problem come from, out of curiosity?
Comment: The problem is that I have neither $F$ nor $f_i$ in an explicit form. They are just a bunch of numbers. I can send you the data if you'd like.


Why should you begin plucking with the index finger when playing the bass?

Question: According to this question and answer and elsewhere I've seen and read online, you should start the plucking action with your index finger.
Naturally, for me, middle then index is more comfortable for normal playing and ring then middle then index is more comfortable for triplets.
Will this lead to poor performance down the road?  Should I retrain myself to lead with the index?  If so, please explain why?
Comment: Interesting question, personally I play the same way you do.
Answer: If you are planning to be a really good player, you should be able to start on either finger. This depending on which string you are starting on and which string the next note is on as well as which brain cell you are using. That last part is a joke however you won't want to make conscious decisions about which finger you start with. This will all be automatic to you. What do you consider "starting" anyway. Isn't it true that each time you go to a different string - it is a new start? And you go to the new string with the finger that did NOT just play the last note. I start on either finger with no difficulty and don't make choices about it. It happens in the moment. As long as you develop strict discipline about alternating fingers for each note played, you will be fine. Alternating for every note is far more important than what finger you start with.
Comment: what happens when you have to play the same pattern of uneven notes, do you start the serie always with the same finger (playing the first and last note with the same finger) or do you play it one time starting with one finger and the next starting with the other finger?
Comment: I found I play shuffle time (without meaning to) when leading with index, whereas I'm solid 4/4 when I start with middle.
Answer: I agree with @VariableLost as it really doesn't matter what you start with, although to be a truly strong player you should be equally good with all fingers. With bass there is less of a need to develop fingers other than your middle or index, but some of the most amazing bass players are equally strong with their ring fingers and even pinky. I'd say learn to develop your index finger and middle finger to be interchangeable, but I would strongly recommend practicing so you can alternate-pick with either finger in a strict alternating pattern across strings, starting with either finger, as this will greatly improve your dexterity moving from string to string, as various patterns you play in your life will require you to find your way around in tangling ways that are not always convenient - it's better if you are agile enough to handle all situations with ease.
Answer: Actually... you might need all your fingers. I wish I had learned the technique espoused by Gary Willis before I picked my dad's classical guitar 20+ years.
Answer: In the 3rd set, i usually use the fingers that dont already hurt…


Drawing random points in JApplet

Question: Real quick question here. In an attempt to generate 20,000 random points, I wrote the following code:
import javax.swing.JApplet;
import java.awt.*;

public class Points extends JApplet {
    int x, y;
    public void paint (Graphics page) {
        for (int i = 0; i < 20000; i++);
        {
            x = (int)(Math.random()*200);
            y = (int)(Math.random()*200);
            page.drawLine(x, y, x, y);
        }
    }

}

However, this resulted in only one point being (randomly) drawn. Can someone help me identify my mistake? Thank you in advance.
Answer: You have a semicolon just after your for. Erase it and your code will work.
for (int i = 0; i < 20000; i++) {
    x = (int)(Math.random()*200);
    y = (int)(Math.random()*200);
    page.drawLine(x, y, x, y);
}

Further Explanation: When you use the semicolon after a for declaration, it will end the for statement, resulting in something like
for(int i = 0; i < 20000; i++) {
}
x = (int)(Math.random()*200);
//rest of the code...

That's why your code display only 1 point.
Comment: Ah of course. Thanks so much, I knew there had to be a syntax error in there somewhere but I just couldn't find it.

Drawing random points in JApplet


Assistance with writing PowerShell script to search Active Directory for a machine name

Question: I'm writing a script to automate some AWS-launched Windows server instances.
I've got the DNS changes, and the join-domain part okay, but I'm having trouble iterating the namespace...for example;
machine is spun up with auto-generated name: WIN-JDK2349DFJR
I want the script to check AD and see if the name, say, imagesN, is in use, and if it is, to name the machine imagesN+1.
Server spins up, with auto name (WIN-JDK2349DFJR).
The script invokes-
Script checks AD: Three servers are named "images1, images2, images3"
The script changes the DNS to the local DC, changes the name to "images4", joins the domain, and reboots.
I'm not sure how to write a PowerShell script to check for the machine name imageN in Active Directory and increment N if a machine account with N exists in Active Directory with the name imageN.
Comment: What have you written so far to perform the "lookup, check for images1..N, and increment" bit? Which parts of that are working? Which are not?
Comment: Keep in mind, Windows computer name changes don't take effect until after a reboot. So if you rename *and* domain join without rebooting first, the computer will get joined to AD with the old name.
Comment: So you know I did test my answer on a Windows Server 2012 DC.
Comment: So, the AWS SSM allows me to push scripts out to machines as part of their creation- I'm also using an AD connector in my VPC to ensure that I have DNS resolution and AD access from inside the private-subnet on the VPC. When you spin up an instance, you can pass a bunch of variables and scripts to the image via SSM, and that's the plan. I've created two diff OUs for the  and  machines, and each OU will have their own iterated machine names. So, the script can process the  order just fine, and it's all hands-off
Comment: https://github.com/illiumrex/LocalR/blob/master/MAster1.ps1
Answer: Troy,
I think there are some problems from an order of operations point of view.
The answer to your question ("trouble iterating the namespace") is answered below. After my answer you will see why I think you are going to have other problems.
Answer to how you write a PowerShell script to iterate namespace.
<code>import-module ActiveDirectory
$counter = 0
$nameselected = "no"
$server = "image$counter"
$ErrorActionPreference = 'SilentlyContinue'

Do {
    Write-Host "Checking for existance of $server."
    if (Get-ADComputer -Identity $server) {
    Write-Host "Count is $counter."
    $global:counter++
    $server = "image$counter"
    Write-Host "New count is $counter."
    }
}
Until ( ( -not $( Get-ADComputer -Identity $server)) )
    $nameslected = "yes"
    Write-Host "The name will be $server."
    Write-Host "Replace this line with the with your function for changing DNS or joining the domain."
</code>
https://github.com/4D5A/Custom-PowerShell/blob/master/Scripts/Microsoft%20Active%20Directory/Get-AvailableComputerName.ps1
Likely problems you are going to have trying to do this.

You must change the name of the computer before you join the computer to the domain.
You must restart the computer after you change the computer name before you join the computer to the domain.
To run the PowerShell script the computer needs to have .NET Framework 3.5.1 installed https://technet.microsoft.com/en-us/magazine/gg413289.aspx
You describe a process of running this PowerShell script on a computer that is not joined to the domain. A possible solution to this is by using Remote PowerShell to a computer that is joined to the domain and does have .NET Framework 3.5.1 installed and does have RSAT installed and then getting the available computer name from that PowerShell session and using it on the local computer in a local PowerShell session.
Comment: Editing your answer to include those very details would improve it greatly. :)
Comment: How exactly does the member client perform the `Import-Module Active Directory` before its been joined to the domain? The OP's question goes: 1. changes the DNS to the local DC, 2. changes the name to "images4", 3. joins the domain, 4 reboot.
Comment: The order of the OP's question doesn't work for multiple reasons (including the reason Ryan pointed out). My answer also doesn't take into account the fact that the computer would need to install .Net and RSAT for it to be able to use 'import-module ActiveDirectory'. What the OP is trying to do as originally asked simply won't work. My answer does however address the part of the question about how to query AD for imageN and increment N if imageN exists which I think will give the OP he information he needs provided he rethinks the order of how he performs the swipe rate steps.
Comment: Here's what I have, adding the above scripting. REMEMBER: this is being passed to the machine via AWS-SSM, which *doesn't* require Remote-PS subsystems...and the .NET and Import-Module pieces are built into the AMI, so I don't have to do any additional config there.
Comment: https://github.com/illiumrex/LocalR/blob/master/MAster1.ps1
Comment: You will want to have `$computername = $server` and not `$computername = Read-Host`.


Value in SwiftUI not being passed

Question: I am trying to pass that a values to let my item know what group it should be added to in Core Data.
Here are some pictures of my App.
Please note that itemsInGroup fetches all of the items that should be in the group.
After adding breakpoints in my app, the value of the group where the Item entity is being add is equal to nil.  This should have a value (which is set when the add item button is pressed).
Thank you for your help in advance.
Main part of the code
import SwiftUI
import CoreData

struct ContentView: View {
    @Environment(\.managedObjectContext) private var viewContext

    enum ActiveSheet: Identifiable {
        case first, second

        var id: Int {
            hashValue
        }
    }

@FetchRequest(
    sortDescriptors: [NSSortDescriptor(keyPath: \Group.timestamp, ascending: true)],
    animation: .default)
private var items: FetchedResults<Group>

@State var activeSheet: ActiveSheet?
@State private var selectedGroup: Group? = nil

var body: some View {
    NavigationView {
        List {
            ForEach(items) { group in
                //                    Text("Item at \(item.timestamp!, formatter: itemFormatter)")
                Text(group.title ?? "New group")
                ForEach(group.itemsInGroup) { item in
                    Text(item.title ?? "New Item")
                }
                Button(action: {
                    selectedGroup = group
                    activeSheet = .second
                }, label: {
                    Text("Add Item")
                })
            }
            .onDelete(perform: deleteItems)
        }
        .toolbar {
            Button(action: {
                activeSheet = .first
            }) {
                Label("Add Item", systemImage: "plus")
            }
        }
    }
    .sheet(item: $activeSheet) { item in
        switch(item) {
        case .first: AddGroupName()
        case .second: AddItemView(group: selectedGroup)
        }
    }
}

private func addItem() {
    withAnimation {
        let newItem = Group(context: viewContext)
        newItem.timestamp = Date()

        do {
            try viewContext.save()
        } catch {
            // Replace this implementation with code to handle the error appropriately.
            // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            let nsError = error as NSError
            fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
        }
    }
}

private func deleteItems(offsets: IndexSet) {
    withAnimation {
        offsets.map { items[$0] }.forEach(viewContext.delete)

        do {
            try viewContext.save()
        } catch {
            // Replace this implementation with code to handle the error appropriately.
            // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            let nsError = error as NSError
            fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
        }
    }
}
}

private let itemFormatter: DateFormatter = {
    let formatter = DateFormatter()
    formatter.dateStyle = .short
    formatter.timeStyle = .medium
    return formatter
}()

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView().environment(\.managedObjectContext, PersistenceController.preview.container.viewContext)
    }
}

Where I add a new item
struct AddItemView: View {
@Environment(\.managedObjectContext) private var viewContext

let group: Group?
@State var title = ""
var body: some View {
    VStack {
        Form {
            TextField("Title", text: $title)
            Button(action: {
                let item = Item(context: viewContext)
                item.group = group
                item.title = title
                try? viewContext.save()
            }, label: {
                Text("Save")
            })
        }
    }
}
}

Where I add a new group
struct AddGroupName: View {
@Environment(\.managedObjectContext) private var viewContext

@State var title = ""

var body: some View {
    VStack {
        Form {
            TextField("Title", text: $title)
            Button(action: {
                let item = Group(context: viewContext)
                item.title = title
                item.timestamp = Date()
                try? viewContext.save()
            }, label: {
                Text("Save")
            })
        }

    }
}
}

My Core Data Model

Why is the group value not being passed and saved correctly?  It should be saved in the selectedGroup variable in the main part of the code.
When I try and add an item and save it to the core data database I get this error "Illegal attempt to establish a relationship 'group' between objects in different contexts"
Please note that I have tried setting selectedGroup equal to a value other than nil, but then this initial value is used when trying to add an item.
Answer: You should declare your group property using the @Binding property wrapper in AddItemView
 @Binding var group: Group

This way the @State property selectedGroup will be updated when the AddItemView is dismissed
Comment: @NightWing, any feedback on this?

Value in SwiftUI not being passed


sendmail from terminal to gmail not working

Question: Hello I´m trying to send an email from my centos terminal with sendmail and it doesn´t work, the command I use the default configuration because I just want to send emails. I need help. In the next I use email@example.com, this would be my real gmail user that I want to send emails. What I do is:
<code>[root@localhost ~]# echo "Subject: sendmail test gmail" | sendmail -v email@example.com
firstname.lastname@example.com... Connecting to [127.0.0.1] via relay...
220 localhost.localdomain ESMTP Sendmail 8.13.8/8.13.8; Fri, 3 Jun 2016 16:56:01 -0300
>>> EHLO localhost.localdomain 250-localhost.localdomain Hello localhost.localdomain [127.0.0.1], pleased to meet you 250-ENHANCEDSTATUSCODES 250-PIPELINING 250-8BITMIME 250-SIZE 250-DSN 250-ETRN 250-DELIVERBY 250 HELP
>>> MAIL From:<firstname.lastname@example.com> SIZE=29 250 2.1.0 <firstname.lastname@example.com>... Sender ok
>>> RCPT To:<firstname.lastname@example.com>
>>> DATA 250 2.1.5 <email@example.com>... Recipient ok 354 Enter mail, end with "." on a line by itself
>>> . 250 2.0.0 u53Ju1vI022862 Message accepted for delivery email@example.com... Sent (u53Ju1vI022862 Message accepted for delivery) Closing connection to [127.0.0.1]
>>> QUIT 221 2.0.0 localhost.localdomain closing connection
</code>
But the email is not being recieved in gmail, and i see a verify=fail in the log. The /var/log/maillog shows:
<code>Jun  3 16:56:01 localhost sendmail[22861]: u53Ju13j022861: from=root, size=29, class=0, nrcpts=1, msgid=<firstname.lastname@example.com>, relay=root@localhost
Jun  3 16:56:01 localhost sendmail[22862]: u53Ju1vI022862: from=<email@example.com>, size=330, class=0, nrcpts=1, msgid=<email@example.com>, proto=ESMTP, daemon=MTA, relay=localhost.localdomain [127.0.0.1]
Jun  3 16:56:01 localhost sendmail[22861]: u53Ju13j022861: email@example.com, ctladdr=root (0/0), delay=00:00:00, xdelay=00:00:00, mailer=relay, pri=30029, relay=[127.0.0.1] [127.0.0.1], dsn=2.0.0, stat=Sent (u53Ju1vI022862 Message accepted for delivery)
Jun  3 16:56:03 localhost sendmail[22864]: STARTTLS=client, relay=gmail-smtp-in.l.google.com., version=TLSv1/SSLv3, verify=FAIL, cipher=AES128-SHA, bits=128/128
Jun  3 16:56:04 localhost sendmail[22864]: u53Ju1vI022862: to=<email@example.com>, ctladdr=<email@example.com> (0/0), delay=00:00:03, xdelay=00:00:03, mailer=esmtp, pri=120330, relay=gmail-smtp-in.l.google.com. [18.104.22.168], dsn=2.0.0, stat=Sent (OK 1464983764 l40si4464056qtc.52 - gsmtp)
</code>
Answer: The mail was actually accepted on the gmail side. That is shown in the last line in which you receive the following back from the receiving server:
OK 1464983764 l40si4464056qtc.52 - gsmtp
The verify=fail is in regards to the TLS negotiation (I believe failing on the client side cert verification which is not typically enforced).
My first thought is that your mail may be getting dropped or at least added as spam based on your sender address. Additionally if you do not have PTR records configured for your server, then the server on their side cannot do a reverse lookup to verify you as the sender, which may also be getting it flagged as spam/non-legitimate mail.
Try and specify a valid sender/From address first to see if that will allow it to arrive.


How to apply two tranformations one after the other in manimce?

Question: I wanted to apply two linear transformations with matrices one after the other in manimce.
Here is the code for one transformation:
 from manim import *

class LT(LinearTransformationScene):
def __init__(self):
    LinearTransformationScene.__init__(
        self,
        show_coordinates=True,
        leave_ghost_vectors=True,
    )

def construct(self):
    matrix = [[1, 1], [0, 1]]
    self.apply_matrix(matrix)
    self.wait()

This works perfectly for a single transformation.
But I want to apply another transformation after this. I tried using self.apply_matrix again:
from manim import *

class LT(LinearTransformationScene):
    def __init__(self):
        LinearTransformationScene.__init__(
            self,
            show_coordinates=True,
            leave_ghost_vectors=True,
        )

    def construct(self):
        matrix1 = [[1, 1], [0, 1]]
        self.apply_matrix(matrix1)
        self.wait()

    def construct(self):
        matrix2 = [[2, 1], [3, 1]]
        self.apply_matrix(matrix2)
        self.wait()

with this code, only the last matrix was rendered. What might have happened?
This must be very simple. But I have no idea- didnt found anything in the documentation or search results.Any help is greatly appreciated.

Update:
As suggested by Nils Werner, I changed LinearTransformationScene.__init__(...) to super().__init__(...) and
included the two matrices in the same
def construct(self):.
from manim import *

class LT(LinearTransformationScene):
    def __init__(self):
        super().__init__(
            self,
            show_coordinates=True,
            leave_ghost_vectors=True,
        )

def construct(self):
    matrix1 = [[1, 1], [0, 1]]
    self.apply_matrix(matrix1)

    matrix2 = [[2, 1], [3, 1]]
    self.apply_matrix(matrix2)

    self.wait()

But this didn't work either. Shows error:
ValueError: operands could not be broadcast together with shapes (4,3) (12,3)

Full log:

 PS C:\Python38> manim LTmul.py -pql
    Manim Community v0.11.0

    [10/26/21 21:24:39] INFO     Animation 0 : Using cached data (hash :                         cairo_renderer.py:110
                                 3163782288_2165879958_531335182)
    ┌─────────────────────────────── Traceback (most recent call last) ────────────────────────────────┐
    │                                                                                │
    │ C:\tools\Manim\Lib\site-packages\manim\cli\render\commands.py:139 in render                      │
    │                                                                                │
    │   136 │   │   for SceneClass in scene_classes_from_file(file):                                   │
    │   137 │   │   │   try:                                                                           │
    │   138 │   │   │   │   scene = SceneClass()                                                       │
    │ > 139 │   │   │   │   scene.render()                                                             │
    │   140 │   │   │   except Exception:                                                              │
    │   141 │   │   │   │   error_console.print_exception()                                            │
    │   142 │   │   │   │   sys.exit(1)                                                                │
    │ C:\tools\Manim\Lib\site-packages\manim\scene\scene.py:213 in render                              │
    │                                                                                │
    │    210 │   │   """                                                                               │
    │    211 │   │   self.setup()                                                                      │
    │    212 │   │   try:                                                                              │
    │ >  213 │   │   │   self.construct()                                                              │
    │    214 │   │   except EndSceneEarlyException:                                                    │
    │    215 │   │   │   pass                                                                          │
    │    216 │   │   except RerunSceneException as e:                                                  │
    │                                                                                │
    │ C:\Python38\LTmul.py:16 in construct                                                             │
    │                                                                                │
    │   13 │   │   self.apply_matrix(matrix1)                                                          │
    │   14 │   │                                                                                │
    │   15 │   │   matrix2 = [[2, 2], [3, 3]]                                                          │
    │ > 16 │   │   self.apply_matrix(matrix2)                                                          │
    │   17 │   │                                                                                │
    │   18 │   │   self.wait()                                                                         │
    │   19                                                                                │
    │                                                                                │
    │ C:\tools\Manim\Lib\site-packages\manim\scene\vector_space_scene.py:1041 in apply_matrix          │
    │                                                                                │
    │   1038 │   │   **kwargs                                                                          │
    │   1039 │   │   │   Any valid keyword argument of self.apply_transposed_matrix()                  │
    │   1040 │   │   """                                                                               │
    │ > 1041 │   │   self.apply_transposed_matrix(np.array(matrix).T, **kwargs)                        │
    │   1042 │                                                                                │
    │   1043 │   def apply_inverse(self, matrix, **kwargs):                                            │
    │   1044 │   │   """                                                                               │
    │                                                                                │
    │ C:\tools\Manim\Lib\site-packages\manim\scene\vector_space_scene.py:1077 in                       │
    │ apply_transposed_matrix                                                                          │
    │                                                                                │
    │   1074 │   │   │   │   [angle_of_vector(func(RIGHT)), angle_of_vector(func(UP)) - np.pi / 2],    │
    │   1075 │   │   │   )                                                                             │
    │   1076 │   │   │   kwargs["path_arc"] = net_rotation                                             │
    │ > 1077 │   │   self.apply_function(func, **kwargs)                                               │
    │   1078 │                                                                                │
    │   1079 │   def apply_inverse_transpose(self, t_matrix, **kwargs):                                │
    │   1080 │   │   """                                                                               │
    │                                                                                │
    │ C:\tools\Manim\Lib\site-packages\manim\scene\vector_space_scene.py:1145 in apply_function        │
    │                                                                                │
    │   1142 │   │   │   + [Animation(f_mob) for f_mob in self.foreground_mobjects]                    │
    │   1143 │   │   │   + added_anims                                                                 │
    │   1144 │   │   )                                                                                │
    │ > 1145 │   │   self.play(*anims, **kwargs)                                                       │
    │   1146                                                                                │
    │                                                                                │
    │ C:\tools\Manim\Lib\site-packages\manim\scene\scene.py:888 in play                                │
    │                                                                                │
    │    885 │   │   │   return np.max([animation.run_time for animation in animations])               │
    │    886 │                                                                                │
    │    887 │   def play(self, *args, **kwargs):                                                      │
    │ >  888 │   │   self.renderer.play(self, *args, **kwargs)                                         │
    │    889 │                                                                                │
    │    890 │   def wait(self, duration=DEFAULT_WAIT_TIME, stop_condition=None):                      │
    │    891 │   │   self.play(Wait(run_time=duration, stop_condition=stop_condition))                 │
    │                                                                                │
    │ C:\tools\Manim\Lib\site-packages\manim\renderer\cairo_renderer.py:127 in play                    │
    │                                                                                │
    │   124 │   │   self.static_image = self.save_static_frame_data(scene, scene.static_mobjects)      │
    │   125 │   │                                                                                │
    │   126 │   │   self.file_writer.begin_animation(not self.skip_animations)                         │
    │ > 127 │   │   scene.begin_animations()                                                           │
    │   128 │   │   if scene.is_current_animation_frozen_frame():                                      │
    │   129 │   │   │   self.update_frame(scene)                                                       │
    │   130 │   │   │   # self.duration stands for the total run time of all the animations.           │
    │                                                                                │
    │ C:\tools\Manim\Lib\site-packages\manim\scene\scene.py:961 in begin_animations                    │
    │                                                                                │
    │    958 │   def begin_animations(self) -> None:                                                   │
    │    959 │   │   """Start the animations of the scene."""                                          │
    │    960 │   │   for animation in self.animations:                                                 │
    │ >  961 │   │   │   animation.begin()                                                             │
    │    962 │                                                                                │
    │    963 │   def is_current_animation_frozen_frame(self) -> bool:                                  │
    │    964 │   │   """Returns whether the current animation produces a static frame (generally a Wa  │
    │                                                                                │
    │ C:\tools\Manim\Lib\site-packages\manim\animation\transform.py:114 in begin                       │
    │                                                                                │
    │   111 │   │   │   self.mobject.align_data_and_family(self.target_copy)                           │
    │   112 │   │   else:                                                                              │
    │   113 │   │   │   self.mobject.align_data(self.target_copy)                                      │
    │ > 114 │   │   super().begin()                                                                    │
    │   115 │                                                                                │
    │   116 │   def create_target(self) -> Mobject:                                                    │
    │   117 │   │   # Has no meaningful effect here, but may be useful                                 │
    │                                                                                │
    │ C:\tools\Manim\Lib\site-packages\manim\animation\animation.py:184 in begin                       │
    │                                                                                │
    │   181 │   │   │   # the internal updaters of self.starting_mobject,                              │
    │   182 │   │   │   # or any others among self.get_all_mobjects()                                  │
    │   183 │   │   │   self.mobject.suspend_updating()                                                │
    │ > 184 │   │   self.interpolate(0)                                                                │
    │   185 │                                                                                │
    │   186 │   def finish(self) -> None:                                                              │
    │   187 │   │   # TODO: begin and finish should require a scene as parameter.                      │
    │                                                                                │
    │ C:\tools\Manim\Lib\site-packages\manim\animation\animation.py:284 in interpolate                 │
    │                                                                                │
    │   281 │   │   │   The relative time to set the aniamtion to, 0 meaning the start, 1 meaning      │
    │   282 │   │   │   the end.                                                                       │
    │   283 │   │   """                                                                                │
    │ > 284 │   │   self.interpolate_mobject(alpha)                                                    │
    │   285 │                                                                                │
    │   286 │   def interpolate_mobject(self, alpha: float) -> None:                                   │
    │   287 │   │   """Interpolates the mobject of the :class:`Animation` based on alpha value.        │
    │                                                                                │
    │ C:\tools\Manim\Lib\site-packages\manim\animation\animation.py:299 in interpolate_mobject         │
    │                                                                                │
    │   296 │   │   families = list(self.get_all_families_zipped())                                    │
    │   297 │   │   for i, mobs in enumerate(families):                                                │
    │   298 │   │   │   sub_alpha = self.get_sub_alpha(alpha, i, len(families))                        │
    │ > 299 │   │   │   self.interpolate_submobject(*mobs, sub_alpha)                                  │
    │   300 │                                                                                │
    │   301 │   def interpolate_submobject(                                                            │
    │   302 │   │   self,                                                                              │
    │                                                                                │
    │ C:\tools\Manim\Lib\site-packages\manim\animation\transform.py:152 in interpolate_submobject      │
    │                                                                                │
    │   149 │   │   target_copy: Mobject,                                                              │
    │   150 │   │   alpha: float,                                                                      │
    │   151 │   ) -> "Transform":                                                                      │
    │ > 152 │   │   submobject.interpolate(starting_submobject, target_copy, alpha, self.path_func)    │
    │   153 │   │   return self                                                                        │
    │   154                                                                                │
    │   155                                                                                │
    │                                                                                │
    │ C:\tools\Manim\Lib\site-packages\manim\mobject\mobject.py:2597 in interpolate                    │
    │                                                                                │
    │   2594 │   │   │   │   │                                                                         │
    │   2595 │   │   │   │   │   self.add(dotL, dotR, dotMiddle)                                       │
    │   2596 │   │   """                                                                               │
    │ > 2597 │   │   self.points = path_func(mobject1.points, mobject2.points, alpha)                  │
    │   2598 │   │   self.interpolate_color(mobject1, mobject2, alpha)                                 │
    │   2599 │   │   return self                                                                       │
    │   2600                                                                                │
    │                                                                                │
    │ C:\tools\Manim\Lib\site-packages\manim\utils\paths.py:43 in path                                 │
    │                                                                                │
    │   40 │                                                                                │
    │   41 │   def path(start_points, end_points, alpha):                                              │
    │   42 │   │   if arc_centers is None:                                                             │
    │ > 43 │   │   │   vects = end_points - start_points                                               │
    │   44 │   │   │   centers = start_points + 0.5 * vects                                            │
    │   45 │   │   │   if arc_angle != np.pi:                                                          │
    │   46 │   │   │   │   centers += np.cross(unit_axis, vects / 2.0) / np.tan(arc_angle / 2)         │
    └──────────────────────────────────────────────────────────────────────────────────────────────────┘
    ValueError: operands could not be broadcast together with shapes (4,3) (12,3)
Comment: Instead of `LinearTransformationScene.__init__(...)` you should call `super().__init__(...)`
Comment: Are you certain that you are using this exact code? The matrix sizes `(4,3)` `(12,3)` make it sound like you are not using 2x2 matrices.
Comment: Also, try a `self.wait()` inbetween the two calls.
Comment: @NilsWerner Yes, I am using this exact code.This is the only scene. I dont have an idea where the `(4,3) (12,3)` comes from.
Comment: @NilsWerner I got it! I tried using `self.wait()` as you said and it worked!! By the way, I  used `LinearTransformationScene.__init__(...)`  an not `super().__init__(...)` .
Answer: Apply the two matrices in the same construct() call.
from manim import *

class LT(LinearTransformationScene):
    def __init__(self):
        super().__init__(
            self,
            show_coordinates=True,
            leave_ghost_vectors=True,
        )

    def construct(self):
        matrix1 = [[1, 1], [0, 1]]
        self.apply_matrix(matrix1)

        self.wait()

        matrix2 = [[2, 1], [3, 1]]
        self.apply_matrix(matrix2)

        self.wait()

Comment: thats showing an error. A long list but the last line is ValueError: operands could not be broadcast together with shapes (4,3) (12,3)
Comment: Are you certain your matrices are exactly the ones in your post? Because I don't see any `(4, 3)` matrices. And what else do you have in your scene?
Comment: No, this is the only code present. Maybe it is a problem with the installation. Let me try it after reinstalling.
Comment: Thanks for the reply anyway. I think this will work
Comment: Can you post what corrections are be needed, so that I can adjust my answer and other people can benefit from this?
Comment: yes, ofcourse. I will post here as soon as I can make it work
Comment: I couldn't install manim. But still I think this will work. So, I am accepting this answer.
Comment: I tried after properly installing manim. Still shows "ValueError: operands could not be broadcast together with shapes (4,3) (12,3)". I have provided the full log by updating my question.
Comment: The code works perfectly for single transformations. The problem only arises when multiple transformations have to be implemented.
Answer: I just needed to add a self.wait() between the matrices!!
Thanks Nils Werner for suggesting this and to add the matrices in the same construct() call.
from manim import *

class LinearTransformationSceneExample(LinearTransformationScene):
    def __init__(self):
        LinearTransformationScene.__init__(
            self,
            show_coordinates=True,
            leave_ghost_vectors=True,
    )

def construct(self):
    matrix = [[1, 1], [0, 1]]
    self.apply_matrix(matrix)
    self.wait()

    matrix2 = [[2, 1], [3, 1]]
    self.apply_matrix(matrix2)

    self.wait()

Comment: I would appreciate if you marked my answer as correct...
Comment: Oh, I didn't see that you have edited the answer to include the `self.wait()`. Now I have accepted it. Will give the bounty in 5 hours


IPv6 with IPv4 over RRAS SSTP VPN from Client that only has IPv4 access

Question: I'm setting up Server 2012 R2 RRAS to be a SSTP VPN. I've got IPv4 working perfectly. My environment is dual stack (v4 and v6). When I enable IPv6 on the VPN my client gets a valid address but is unable to communicate to anything over the VPN using IPv6. If I ping a computer name it gets the ipv6 address but times out where if I ping it with -4 it gets the v4 address and pings perfectly fine. I've been banging my head on this for a few days now and nothings I've tried or any web searches have pointed me to a solution. I'm starting to wonder if maybe the VPN needs another port open for the IPv6 to tunnel through?
I've got the IPv6 Router (LAN and demand-dial) and IPv6 Remove access server options enabled on the general tab in RRAS as well as specified a prefix on the IPv6 tab. I've tried the prefix being it's own private prefix and using the same prefix as is in use on the network.
Does anyone else have this working? I have a feeling that it's probably a little thing somewhere that I've missed. Or does it not send the ipv6 traffic over the ipv4 vpn and you need to be on a client machine that has both ipv4 and ipv6 for ipv6 to work over the vpn?
Comment: When I do a tracert it always stops at the RRAS ipv6 address and won't go further. It looks like RRAS isn't passing the traffic for some reason.
Answer: I thought I'd provide a more generic Linux router scenario for users not using pfSense but a Linux based router (in my case DD-WRT).
ip -6 route add xxxx:xxx:xxxx:xxxx::/64 via xxxx:xxx:xxxx:xx::x dev br0

The configured IPv6 prefix in RRAS IPv6 tab needs to be added after the add
The IPv6 LAN IP address of the RRAS box is the via (essentially the gateway)
br0 is LAN interface of your router is. This is usually the default on DD-WRT, for other routers it could be another interface like eth0

The only problem I've discovered is while this static route allows IPv6 traffic to flow through to the outside, it doesn't provide access to other LAN IPv6 addresses within the IPv6 subnet of the LAN IP address of the server. Likely because the subnet is a different /64. To solve this, you need to add IPv6 static routes on the RRAS box itself to allow this connectivity.
Answer: Turns out it was a little thing and it took looking at the problem in a completely different way to figure it out.
The problem wasn't with RRAS it was with my router software setup (in this case pfSense). When on a VPN connected client I was getting an IPv6 address and name resolution was working but nothing would respond over IPv6. The problem was that my v6 packets would get into my network fine but that local machines didn't have any route information on how to get back to the VPN connected machine. I had to setup a static route in my router for the prefix used in RRAS to route that prefix on my network back to the RRAS box. Now when the internal box tried to talk back it would see a different prefix and send it to my router then my router would forward it to RRAS which would then send it to the VPN connected client.
Sure took a long time to track this down but it is finally working.


binary vtk for Rectilinear_grid from fortran code can not worked by paraview

Question: I used the code posted from stackoverflow and modified it as:
program VTKBinary

implicit none

real*4    :: x(2) = (0., 1.)
real*4    :: y(2) = (0., 1.)
real*4    :: z(2) = (0., 1.)

character :: buffer*80, lf*1, str1*8, str2*8, str3*8
integer   :: ivtk = 9, int,i

lf = char(10) ! line feed character

!open(unit=ivtk,file='test_bin.vtk',form='binary',convert='BIG_ENDIAN')
open(unit=ivtk,file='test_bin.vtk',access='stream',convert='BIG_ENDIAN')

buffer = '# vtk DataFile Version 3.0'//lf      ; write(ivtk) trim(buffer)
buffer = 'vtk output'//lf                      ; write(ivtk) trim(buffer)
buffer = 'BINARY'//lf                          ; write(ivtk) trim(buffer)
buffer = 'DATASET RECTILINEAR_GRID'//lf        ; write(ivtk) trim(buffer)

! WRITE GRID
write(str1(1:8),'(i8)') size(x)
write(str2(1:8),'(i8)') size(y)
write(str3(1:8),'(i8)') size(z)
buffer = 'DIMENSIONS '//str1//str2//str3//lf         ; write(ivtk) trim(buffer)
buffer = 'X_COORDINATES '//str1//'  float'//lf                 ; write(ivtk) trim(buffer)
!write(ivtk) x
write(ivtk) (x(i),i=1,size(x))
buffer = lf//'Y_COORDINATES '//str2//'  float'//lf             ; write(ivtk) trim(buffer)
!write(ivtk) y
write(ivtk) (y(i),i=1,size(y))
buffer = lf//'Z_COORDINATES '//str3//'  float'//lf             ; write(ivtk) trim(buffer)
!write(ivtk) z
write(ivtk) (z(i),i=1,size(z))

close(ivtk)

end program VTKBinary

This code is compiled well by gfortran and it runs well to generate vtk file.
Problem: there is an error when the vtk is read by paraview as following:
Warning: In C:\DBD\pvs-x64\paraview\src\paraview\VTK\Rendering\Core\vtkRenderer.cxx, line 1029
vtkOpenGLRenderer (000000000BF00BF0): Resetting view-up since view plane normal is parallel

Question: can you help me to solve this problem?
Many thanks.
Comment: One of the issues might be that `(a, b)` denotes the complex number `a+ib`. To specify an array use `[a,b]`. Unfortunately, that doesn't help me debug your problem...
Comment: Well, not really suggested: "*Also, convert=BIG_ENDIAN is non-standard and will not work with many compilers (e.g., gfortran, if I recall it correctly).*"  I didn't even remember this one I corrected the answer and it turned out that after doing that they are just duplicates. Maybe people should not accept answers which don't solve the problem.
Comment: Could you post the link you took the code from?
Comment: Since when does gfortran support `convert='BIG_ENDIAN'`?
Comment: Ok, don't know since when, but it does https://gcc.gnu.org/onlinedocs/gfortran/CONVERT-specifier.html#CONVERT-specifier
Comment: There is nothing to be sorry about, there was an issue, which was not explained in the answer there. Thanks for finding it.
Answer: The main issue was pointed out by @AlexanderVoigt. Arrays are specified as [0., 1.], not as (0., 1.), that would be a complex number equal to one imaginary unit i.
The other problem is missing lf at the end. Just use
buffer = 'X_COORDINATES '//str1//'  float'//lf             ; write(ivtk) trim(buffer)
write(ivtk) x, lf
buffer = 'Y_COORDINATES '//str2//'  float'//lf             ; write(ivtk) trim(buffer)
write(ivtk) y, lf
buffer = 'Z_COORDINATES '//str3//'  float'//lf             ; write(ivtk) trim(buffer)
write(ivtk) z, lf

It is better to always put the lf at the end so you do not forget it.
BTW you do not have to put the strings in a buffer and then trim it, you can even write them directly:
write(ivtk) 'X_COORDINATES '//str1//'  float'//lf

Comment: Maybe they are just duplicates after all.
Comment: you might want to change your other answer as well... The issue with the complex notation is copied from there.
Comment: I do, I see a cube from 4 points...
Comment: Many thanks Alexander,
Comment: I correct (a,b) to [a,b] and it work well. Thanks
Comment: @Cfdfan Glad I could help.
Comment: @Alexander: yes, you are right, just [a,b]


custom branch storage in git

Question: Can I have branches stored in some custom place, such as refs/custom_heads? Will not garbage collection treat commits from that branches as garbage?
Are there any convention of where branches should be placed, except refs/heads, refs/remotes and refs/tags?
Answer: A branch is a "ref" under refs/heads. This is how Git identifies a branch. If you try to check out any other sort of ref directly, such as a tag or something under refs/remotes, you will detach your HEAD and not be on any branch any more.
So, strictly, the answer to your question is no. Branches are exactly those refs which live under refs/heads.
You can store "refs" in any other location under the refs namespace but it won't be viewed as a branch by Git. Such refs won't be "garbage collected" or cleaned up automatically.
Comment: `Such refs won't be "garbage collected" or cleaned up automatically.` good news :). I could edit fetch configuration to fetch that branches: `fetch = +refs/custom_heads/*:refs/remotes/some_remote_name/*` to fetch that branches

custom branch storage in git


Como fazer um switch em C#?

Question: Vejo muitas pessoas dizendo que é errado fazer switch no código, pois acaba pesando e é feio.
É correto a maneira que eu estou usando e qual seria uma alternativa ao uso dele? Encher o código de if/else?
      int TipoOsFiltrada = 0;

      switch (TipoOsFiltrada)
      {
        case 0:
          field = "nome";
          fieldValue = "'" + usuarioLogado.NOME + "'";
          break;
        case 1:
          field = "codcar";
          fieldValue = codCar.ToString();
          break;
        case 2:
          field = "codset";
          fieldValue = codSet.ToString();
          break;
        default:
          field = "nome";
          fieldValue = "'" + usuarioLogado.NOME + "'";
          break;
      }

Comment: Depende muito da situação, o swtich case pode ser muito bom em determinados casos, conforme a própria documentação já explica "A instrução switch geralmente é usada como uma alternativa para um constructo if-else se uma única expressão é testada com três ou mais condições. Por exemplo, a instrução switch a seguir determina se uma variável do tipo Color tem um dos três valores:" [documentação](https://docs.microsoft.com/pt-br/dotnet/csharp/language-reference/keywords/switch)
Answer:
Vejo muitas pessoas dizendo que é errado fazer switch no código, pois acaba pesando e é feio

Não vejo isso. Pode ser que eu use bons programadores como referência :)
switch é elegante e rápido, por isso toda linguagem moderna, como as antigas, possuem ele. Sabendo usar ele é muito poderoso e facilita bastante, além de ser mais rápido que outras opções na maioria dos cenários. De fato ele existe por otimização de execução em primeiro lugar, e elegância em segundo, portanto não consigo imaginar de onde surge essas ideias.
Bom, até imagino em outro cenário. Existem umas pessoas que falam isso porque porque é menos orientado a objeto. Mas se você perguntar porque é ruim, em geral elas não sabem dizer, leram em algum lugar e ficam repetindo. Elas não dão contexto, como ocorre com quem tem entendimento incompleto das coisas (algo que você está buscando se livrar aqui). Claro que em algum contexto não é tão adequado usá-lo, mas isto vale para todos os recursos da linguagem de programação, sem exceção, vale para variáveis, literais, operadores, todos os comandos, até um simples ponto e vírgula.
Se a comparação é com if eu diria que ele costuma ser mais elegante nos casos onde ele pode ser usado (nem todos ele pode). O caso mostrado na pergunta é bem básico e o mais ideal para sua adoção. Ele fica mais rápido e mais bonito, ainda que bonito seja algo subjetivo (seria mais se não fosse obrigado usar break).
Claro que considerando a primeira linha, ele nem faz sentido porque é garantido que só o primeiro será executado.
Tem uma pergunta que fala mais sobre o funcionamento dele: Como funciona o switch por baixo dos panos? (apesar de ser outra linguagem, funciona igual)
Também pode ser útil ler:

Qual a diferença entre Switch, Case e If, Else?
Por que usar String em um bloco switch é mais eficiente do que em um bloco if-else?
Usando Switch Case para intervalos

Nem falei no seu uso como pattern matching que é muito mais poderoso e interessante, e está disponível no C#, apesar de muitos não saberem disto. E na versão 8 poderá ser usado como expressão.
Coloquei no GitHub para referência futura.
Comment: Pesado "Não vejo isto. Pode ser que eu use bons programadores como referência :)" kkkkk Mas obrigado!
Answer: A Questão do uso do Switch/Case não pode ser pautada entre deixar o código bonito ou feio, mas sim se é válido ou não.
Vejo switch/case sendo comumente usado para fazer a atribuição de variáveis de ambiente por exemplo. Seu exemplo de código se encaixa nessa premissa pois trata de um filtro pré estipulado.

Como fazer um switch em C#?


How to understand pvalue with controls/covariates

Question: Suppose I have a study with a response variable $y$ and two explanatory variables $x_1, x_2$. I do a regression such as lm(y~x1) and get a p-value of $p_1'$ for $x_1$. Then I control for $x_2$ and run lm(y~x1 + x2) and get $p_1''$ for $x_1$ and $p_2''$.
Question 1
How would I interpret the following cases in terms of if my model benefits from adding the covariate?

$p_1'>p_1''$
$p_1'<p_1''$
$p_1'=p_1''$

Question 2
Will the answer extend to more explanatory covariates?
Question 3
What role does $p_2''$ play in my analysis/interpretation?
Answer: You don't interpret whether some p-values are smaller or larger than each other,  that's a meaningless comparison.
You would usually focus on one of the p-values (assuming both are meaningful analyses) and pre-specify that in your protocol before seeing the data. The other analysis might be a supportive analysis that you also look at or something that you look at, because it answers a different question, which you are also interested in.
Comment: Is my model better or worse with adding the covariate?
Comment: It may be better,  it might be worse, one of them might be totally inappropriate for three question you are asking and so on,  there is no generic answer to that question,  it depends on the context.
Comment: The goal is to assess whether or not the additional variables are confounders. That is, do I need to control for them, or are they irrelevant. How do I determine this?
Comment: By logically considering for situation, looking at p-values would be a terrible way of doing that. In fact, in an observational study adjusting for just one potential confounder would be a strong signal that the model and/or the collected data are inadequate.
Comment: I think I need to formulate a new question asking specifically what I'm trying to get at.


Non-convex cone and the Polar

Question: I would like help with exercise:
Be $S = \{ d\in\mathbb{R}^2\mid d \ge 0,d_1d_2=0  \}$.
$(a)$ Show that $S$ is a non-convex cone;
$(b)$ To determine $P(s) = \{p\in\mathbb{R}^2\mid p^{T}d\le 0, \forall d \in S\}$
$(c)$ Geometrically represent the sets $S$ e $P(S)$
What did I do:
$(a)$  Just take $u = (1,0)$ and $v = (0,1)$ and choose $t = \frac{1}{2}$. To have, $(1-t)u + tv = (1-t)(1,0) + t(0,1) = (1-t, t) = (\frac{1}{2},\frac{1}{2})$ that is not in the set.
$(b)$ Be $d \in S$ e $P=(x,y)\in\mathbb{R}$ we have to $p^{T}d = (x \ y){d_1 \choose d_2} = xd_1 + yd_2 \le 0$  I can't finish.
$(c)$ I do not know how to do it.
if anyone can help me, I appreciate it. Sorry for the English, because it is not my native language.
Answer: For a point $d=(d_1,d_2)$ to be in $S$ you need at least one of $d_1$ or $d_2$ to be zero. Both of them have to be non-negative also. So, $S$ is the union of the positive $X$ semi-axis and the positive $Y$ semi-axis, including the origin.
$P(S)$ is the set of points (vectors) that form an obtuse angle with all the vectors in $S$. Clearly, these are the points in the third quadrant (just draw the picture), that is $P(S)=\{(d_1,d_2):\, d_1\le 0, d_2\le 0\}$.
Hope this helps.
Comment: Thank you very much.

Non-convex cone and the Polar


Change VideoCapture size based on loop value

Question: So I have this code below and I was expecting it to change the width size of the frame based on loop i value from 1 to 1000 in live time, to put that in visualization, when I executed the code I was expecting it to changes the windows width size while it was running.
import cv2
import numpy as np

vid = cv2.VideoCapture("C:\\users\\USER\\downloads\\man.mp4")
while True:
    ret,frame = vid.read()
    for i in range(1,1000):
        frame = cv2.resize(frame,(i,450))
        size = 16
        # Create motion blur kernel
        kernel_motion_blur = np.zeros((size,size))
        kernel_motion_blur[int((size-1)/2), :] = np.ones(size)
        kernel_motion_blur = kernel_motion_blur / size
        # Apply motion kernel motion blur
        result = cv2.filter2D(frame, -1, kernel_motion_blur)
        cv2.imshow('Motion Blur Applied',result)
        cv2.imshow('Original',frame)
        if cv2.waitKey(1) == ord('q'):
            break

cv2.destroyAllWindows()
vid.release()

Its works but the problem is when I executed the code the video frame gets glitchy and the video frame doesn't display the correct image of what contains in the actual video. So how do I fix that?
The video before and after
Comment: pictures please?
Comment: Put both imshow and waitKey outside of for loop condition block.
Comment: @Christoph Rackwitz Done
Comment: @toyota Supra Your solution doesn't work for me and the same problem still occurs
Comment: not sure what you're expecting. that looks like you took a single column slice out of the video frame (or the resize() did that), and then either the imshow window was created to be resizable (WINDOW_NORMAL) or the image was resized to be that size again... but your code contains neither of those operations. is that **the exact code** that produces those screenshots? I don't think it is.
Comment: and those two screenshots don't appear to correlate. I took slices of the first picture and none of them look exactly like the second screenshot.
Comment: @Christoph Rackwitz I copied the exact code but I think it doesn't looked correlated because I get rid of the 'Motion Blur Applied' title for 'frame' video
Answer: I'm not sure I totally understand the question, or why you have a for loop inside of a while loop, but I think I was able to achieve the effect you are going for. Take a look:
import cv2
import numpy as np

# control how fast the image slides left to right
step_size = 10

vid = cv2.VideoCapture("videos\demo.mp4")
while True:
    ret,frame = vid.read()
    if ret == False:
        break
    width = frame.shape[1]
    for n in range(0, width, step_size):
        frame_to_show = frame[:,:n+step_size]
        size = 16

        # Create motion blur kernel
        kernel_motion_blur = np.zeros((size,size))
        kernel_motion_blur[int((size-1)/2), :] = np.ones(size)
        kernel_motion_blur = kernel_motion_blur / size
        # Apply motion kernel motion blur
        result = cv2.filter2D(frame_to_show, -1, kernel_motion_blur)
        cv2.imshow('Motion Blur Applied',result)
        cv2.imshow('Original',frame_to_show)
        key = cv2.waitKey(1)
        if key == ord('q'):
            break

    cv2.destroyAllWindows()
    vid.release()

Or perhaps this is more what you are looking for:
import cv2
import numpy as np

# control how fast the image slides left to right
step_size = 10

vid = cv2.VideoCapture("videos\demo.mp4")
end = 0
while True:
    ret,frame = vid.read()
    if ret == False:
        break

    width = frame.shape[1]
    if end > width:
        end = 0
    end += step_size

    frame_to_show = frame[:,:end]
    size = 16

    # Create motion blur kernel
    kernel_motion_blur = np.zeros((size,size))
    kernel_motion_blur[int((size-1)/2), :] = np.ones(size)
    kernel_motion_blur = kernel_motion_blur / size
    # Apply motion kernel motion blur
    result = cv2.filter2D(frame_to_show, -1, kernel_motion_blur)
    cv2.imshow('Motion Blur Applied',result)
    cv2.imshow('Original',frame_to_show)
    key = cv2.waitKey(1)
    if key == ord('q'):
        break

cv2.destroyAllWindows()
vid.release()


Dependency property is not working for me on a WPF UserControl

Question: I created my own user control with dependency properties and added it to my main window, where I now want to be able set the dependency properties. The properties are not taking the value I set in the XAML of the main window and I am not sure what I am missing. In the code I set the default value for the FillBrush property to Yellow. In the XAML I set it to Red. When I click the Test button, it shows the property to be Yellow. Here is the code:
Window XAML
<Window x:Class="Test.Window2"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:test="clr-namespace:Test"
    Title="Window2" Height="200" Width="600">

    <StackPanel>
        <test:TestUserControl x:Name="myControl"
            FillBrush="Red" VerticalAlignment="Center" Margin="20"/>
        <Button Height="24" Width="300" Content="Test" Click="Button_Click" />
        <TextBox x:Name="debugTextBox" Margin="20"/>
    </StackPanel>
</Window>

Window Code Behind
public partial class Window2 : Window
{
    public static readonly DependencyProperty FillBrushProperty =
        DependencyProperty.Register("FillBrush", typeof(Brush), typeof(Window2),
        new UIPropertyMetadata(Brushes.Yellow));

    public Brush FillBrush
    {
        get { return (Brush)GetValue(FillBrushProperty); }
        set { SetValue(FillBrushProperty, value); }
    }

    public Window2() { InitializeComponent(); }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        this.debugTextBox.Text =
            "Red: " + Brushes.Red +
            "  Yellow: " + Brushes.Yellow +
            "  Actual: " + this.FillBrush;
    }
}

User Control XAML
<UserControl x:Class="Test.TestUserControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             mc:Ignorable="d"
             d:DesignHeight="300" d:DesignWidth="300">
    <TextBlock Text="User Control"/>
</UserControl>

User Control Code Behind
public partial class TestUserControl : UserControl
{
    public static readonly DependencyProperty FillBrushProperty =
        DependencyProperty.Register("FillBrush", typeof(Brush), typeof(TestUserControl),
        new UIPropertyMetadata(Brushes.Cyan));

    public Brush FillBrush
    {
        get { return (Brush)GetValue(FillBrushProperty); }
        set { SetValue(FillBrushProperty, value); }
    }

    public TestUserControl()
    {
        InitializeComponent();
    }
}

What am I missing?
Answer: In the XAML you are setting the Fillbrush value on TestUserControl to Red, but when the button is clicked it shows the Fillbrush value for Window2, not TestUserControl. And since the Fillbrush value for Window2 is not set in XAML it still has the default value of Yellow.
Comment: Oh, geez! That was seriously messed up, my bad!


$(A \lor B) \to C$ and $(A \to C) \lor (B \to C)$ Which one entails the other?

Question: For a homework assignment I have to prove that one of the statements entails the other.
The statements are:
$(A \lor B) \to C$
$(A \to C) \lor (B \to C)$
The only thing that I got so far is either $\lnot(A \lor B) \to C$ or $(A \to C) \land (B \to C)$.
I can use the rules of Modus Ponens, Modus Tollens, Simplification, Conjunction, Disjunction, Conjunctive and Disjunctive Syllogism, Hypothethical Syllogism and Conditional Proof.
The equivalence rules I can use are Double Negation, De Morgan's Laws, Biconditional Equivalence,and I think, Transposition and Material Implication, too.
Is there someone who can help me? I've tried so much already...

Edit:
The answer they wanted to hear was:

(A v B) -> C
A supp/CP
A v B disj
C 1,3MP
A -> C 2-4 CP
(A -> C) v (B -> C)  5 disj
Answer: HINT: Use the fact that $p\to q$ is equivalent to $\neg p\lor q$. Thus,
$$(A\lor B)\to C)\equiv\neg(A\lor B)\lor C\equiv(\neg A\land\neg B)\lor C\equiv(\neg A\lor C)\land(\neg B\lor C)\;,$$
where I've also used De Morgan's law and distributivity. Now expand use the same fact to convert this to an expression involving $A\to C$ and $B\to C$, and compare that with $(A\to C)\lor(B\to C)$; one of the two expressions is easily shown to imply the other.
Comment: In your last step (¬A∧¬B)∨C≡(¬A∨C)∧(¬B∨C), is there a rule for this equivalence? Because I know this intuitively, but I have to justify every step I make
Comment: @marieke: That's distributivity of $\lor$ over $\land$: $$(p\land q)\lor r\equiv (p\lor r)\land(q\lor r)\;.$$ You might see it with the $r$ on the left of the $p\land q$, in which case you'd also need to use commutativity.
Comment: Okay, but than I only see how to get (A -> C) ^ (B -> C), where the ^ should be an v... there is, for as far as I know, no way to make those two the same. Even though the or is inclusive
Comment: @marieke: It's not clear to me what you're trying to say. However, I just noticed that my suggestion in the answer is unnecessarily complicated; give me a moment or two, and I'll improve it.
Comment: @marieke: Ah, I think that I just realized what you meant. Are you saying that if you follow the current version of my answer, you get $$(A\to C)\land(B\to C)$$ from the first expression? That's true. Now, which of $p\land q$ and $p\lor q$ implies the other?
Comment: I'm not sure, I would say that p v q implies p ^ q, since the or is inclusive. On the other hand p ^ q can be simplified and than with a disjunction you can make p v q... not sure which one is more 'official'
Comment: @marieke: [Conjunction elimination](https://en.wikipedia.org/wiki/Conjunction_elimination) tells you that $p\land q$ entails $p$, and [disjunction introduction](https://en.wikipedia.org/wiki/Disjunction_introduction) tells you that $p$ entails $p\lor q$. Therefore ... ?
Comment: So in total it would look like this?

 1)  (A∨B)→C           prem
2)  ¬(A∨B)∨C        1 Material Implication
3) (¬A∧¬B)∨C       2 De Morgan's Laws
4) (¬A∨C)∧(¬B∨C) 3 commutativity
5) (¬A∨C)              4 simplification
6  A -> C                5 Material Implication
7 (A→C)∨(B→C)  6 disjunction

If so, my mistake was that I thought I was only allowed to say (A→C)∨B for example
Comment: @marieke: (4) is from (3) by distributivity, not commutativity, but otherwise that looks good.
Comment: aah okay, thanks. Sorry for the mess in the last comment ;)
Comment: @marieke: No problem; you're welcome!
Comment: Am I also allowed to say:
1) (A∨B)→C) prem
2)      A  supp/ CP
3              A v B supp/CP
4              C       1, 3 MP
5  A -> C       2-4 CP
6 (A -> C) v (B - > C)  5 disj
Comment: @marieke: If I'm reading that right, it would only show that $A$ together with $(A\lor B)\to C)$ entail $(A\to C)\lor(B\to C)$.
Answer: As Wikipedia notes,

A valid logical argument is one in which the conclusion is entailed by the premises, because the conclusion is the consequence of the premises.

So to answer the question we need to ask which of these two statements could be the conclusion of the other. Using a truth table we can see that they do not entail each other:

However, the first sentence does entail the second:

We can create a natural deduction proof of that as well. The desired natural deduction proof should look like the following:

The answer they wanted to hear was: (A v B) -> C
A supp/CP
A v B disj
C 1,3MP
A -> C 2-4 CP
(A -> C) v (B -> C) 5 disj

That such a proof would work can be verified by using a proof checker.

Kevin Klement's JavaScript/PHP Fitch-style natural deduction proof editor and checker http://proofs.openlogicproject.org/
"Logical Consequence" Wikipedia https://en.wikipedia.org/wiki/Logical_consequence
Stanford Truth Table Tool http://web.stanford.edu/class/cs103/tools/truth-table-tool/


Android FAB HideBottomViewOnScrollBehavior statys hidden after changing fragments

Question: I am using a drawer navigation (combined with android navigation jetpack component) to navigate between several fragments. I am using app:layout_behavior="com.google.android.material.behavior.HideBottomViewOnScrollBehavior" on my Floating Action Button (which is placed inside a coordinator layout) to hide the FAB when i scroll up and then it reappears when i scroll down. My layout is as follows:
activity_main.xml
<androidx.drawerlayout.widget.DrawerLayout
    android:id="@+id/Drawer_Main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ui.main.main.MainActivity">

    <androidx.coordinatorlayout.widget.CoordinatorLayout
        android:id="@+id/Layout_Coordinator_Main"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true">
...

       <com.google.android.material.floatingactionbutton.FloatingActionButton
            android:id="@+id/FAB_Add"
            style="@style/Locky.FloatingActionButton.Normal"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom|end"
            android:layout_margin="@dimen/fab_margin"
            app:layout_behavior="com.google.android.material.behavior.HideBottomViewOnScrollBehavior"
            app:srcCompat="@drawable/ic_add" />

</androidx.coordinatorlayout.widget.CoordinatorLayout>

</androidx.drawerlayout.widget.DrawerLayout>

The behaviour is working as expected. However if i scroll up and it hides the FAB and then i switch screen, the FAB stays hidden. I could've scrolled down for the FAB to reappear but in some cases when i can't scroll down (when my recyclerview is empty), there is no way for the FAB to reappear.
I tried to do something like this:
MainActivity.kt
private fun navigationDestinationChangeListener(navController: NavController) {
    navController.addOnDestinationChangedListener { nc, nd, _ ->
        when (nd.id) {
            nc.graph.startDestination,
            R.id.Fragment_Card,
            R.id.Fragment_Device -> {
                _binding.DrawerMain.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED)

                //Show all the FABs
                showFabs()
            }
            else -> {
                _binding.DrawerMain.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED)

                //Hide all the FABs
                hideFabs()
            }
        }
    }
}

I added a navigation destination change listener where i force the FAB to reappear in my showFabs() function but it's not working.
Can someone help me with a workaround on how to fix this? Or maybe a better way to code this in case I've been coding this the wrong way.
Thank you for your help.
Comment: Can someone please help me ?
Comment: I have a same problem :(
Comment: I tried several ways to use fab.show() but apparently the behaviour is not performing hide() on the view. Please do share the answer if you find it in the future. :(
Answer: Change your "showFabs" by this
Kotlin
fun showFab(fab: FloatingActionButton, isVisible: Boolean) {
    val layoutParams: ViewGroup.LayoutParams = fab.layoutParams
    if (layoutParams is CoordinatorLayout.LayoutParams) {
        val behavior = layoutParams.behavior
        if (behavior is HideBottomViewOnScrollBehavior) {
            if (isVisible) {
                behavior.slideUp(fab)
            } else {
                behavior.slideDown(fab)
            }
        }
    }
}

Java
public void showFabs(FloatingActionButton fab, boolean visible) {
    ViewGroup.LayoutParams layoutParams = fab.getLayoutParams();
    if (layoutParams instanceof CoordinatorLayout.LayoutParams) {
        CoordinatorLayout.Behavior coordinatorLayoutBehavior =
            ((CoordinatorLayout.LayoutParams) layoutParams).getBehavior();
        if (coordinatorLayoutBehavior instanceof HideBottomViewOnScrollBehavior) {
            @SuppressWarnings("unchecked")
            HideBottomViewOnScrollBehavior<FloatingActionButton> behavior =
                (HideBottomViewOnScrollBehavior<FloatingActionButton>) coordinatorLayoutBehavior;
            if (visible) {
                behavior.slideUp(fab);
            } else {
                behavior.slideDown(fab);
            }
        }
    }
}

Until it's fixed by google, it's the only solution I found that works.
Comment: You saved me here mate! It works like a charm! Thank you so much


keycloak.authenticated is alway false even after successful login in @react-keycloak/web

Question: I have a very simple react app and I want to add keycloak authentication to it's pages. I'm using following versions

react v18
keycloak 18.0.0 (with quarkus)
react-keycloak/web: 3.4.0
keycloak-js: 20.0.3
react-router-dom: 6.8.1

These are my classes
index.tsx
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

const root = ReactDOM.createRoot(
  document.getElementById('root') as HTMLElement
);
root.render(
  // <React.StrictMode>
    <App />
  // </React.StrictMode>
);

reportWebVitals();

App.tsx
import { BrowserRouter, Route, Routes } from "react-router-dom";
import HomePage from "./pages/Homepage";
import keycloak from "./Keycloak"
import { ReactKeycloakProvider } from "@react-keycloak/web";
import './App.css';

function App() {

  return (
    <ReactKeycloakProvider authClient={keycloak} initOptions={{ onLoad: "login-required" }}>
      <BrowserRouter>
        <Routes>
          <Route path="/" element={<HomePage />} />
        </Routes>
      </BrowserRouter>
    </ReactKeycloakProvider>

  );
}

export default App;

Keycloak configs
import Keycloak from "keycloak-js";
const keycloak = new Keycloak({
url: "http://localhost:8180",
realm: "Demo",
clientId: "react-app",
});

export default keycloak;

HomePage.tsx
import { useKeycloak } from "@react-keycloak/web";
import { useState, useEffect } from "react";

const Home = () => {

  const { keycloak } = useKeycloak();
  const [isLoggedIn, setIsLoggedIn] = useState(false)

  useEffect(()=>{
      setIsLoggedIn(keycloak.authenticated || false)
  }, [keycloak])

  console.log("-----------is logged in:", isLoggedIn)

  return isLoggedIn ?
Welcome

                      :
{`User is NOT authenticated`}
;

};

export default Home;

After I npm start and go to home page even I get keycloak login page.

But after login with correct credentials following page is shown. This page is shown when keycloak.authenticated is false.

Console output

I really appreciate if anyone can figure out why I'm not authenticated even after successful login.
github url: https://github.com/ruchiranawarathna/react-with-keycloak-auth
Comment: I posted this solution, hope it helps you.https://stackoverflow.com/a/77925275/1794262
Answer: try making the access public by going to client details -> Capability config then turn off Client authentication and turn on Standard flow
Answer: change the object passed to the Keycloak constructor to have these parameters
{
  "realm": "Your realm name",
  "auth-server-url": "http://localhost:8081/",
  "ssl-required": "external",
  "resource": "client name here",
  "public-client": true,
  "confidential-port": 0
}

OR you can as well click on Download adapter config from the action buttton dropdown in this screenshot and use the generated json object


How can one learn to reproduce notes with one's voice?

Question: Background. I have recently become interested in music, music theory and practice. I'm starting off with ear training, but I am pretty much at null right now. Or maybe even below null – it seems like every other untrained person could probably do better.
Using the software solfege, I've tried distinguishing between the very basic intervals minor second/major second and perfect fourth/perfect fifth. I get about 80% with the former and less than 60% with the latter (and I try really hard – listening to the intervals multiple times and so on). So I'm just slightly better than someone guessing randomly.
I tried distinguishing the intervals by using solfege, that is by filling the intervals with do-re-mi-fa-sol and so on, but I with almost no success.
Eventually I found that I don't even feel confident about whether I am even able to reproduce the same notes with my voice. I can reproduce notes by trial and error if the notes have the same sound: For example, I could reproduce the exact intervals when I used a virtual keyboard outputting to a midi synthesizer with the same instruments that the played intervals have been synthesized with. But I cannot confidently hear a unison of two differently-sounding notes.
Question. How can I effectively learn to reproduce a note? Do I need a teacher to do that or can I teach it myself? Or is it even impossible to learn? How can I gain certainty with hearing unisons?
And since ear training is not technically singing, what kind of teacher should I approach?
Comment: I'm not qualified to give a real answer... but I would try training with one of those electronic tuners that tell you if you're too low or too high.
Answer: Answering a question with a question. Can you sing tunes, melodies, songs? Most folk can, not necessarily with all the words, but hum, lah, whistle. If that's you, then approach it a different way. Use two notes from a song - the beginning two is a good start. Work out what interval is made.Amazing Grace, for example, is P4.
I've been singing for decades, and would still have to think what the interval between notes is. It's not too helpful. Academic, but not too practical.
The problem with hearing unison notes played on different instruments could well be the harmonics that are almost inevitably contained. They can throw you off the scent easily, so don't worry too much for now. Keep singing, and in a song, listen out for, say, any maj3s. Take one interval a day, as prescribed!
Comment: I am also not confident with tunes. I do not know if I sing them correctly.
Comment: Get used to singing them, record them, listen back. Sometimes record yourself singing along with the track playing too. Get others to listen and be truthful with their comments. It is possible to be tone deaf, but quite rare. Leave the 'theory' part of music alone until the 'practical' part makes you need it. Reading about stuff does not make you good at doing it. Doing stuff does that.
Comment: Thanks for the advice. I also like what you have written, but technically it doesn't answer my question. Still, thanks.
Comment: There are four of them there! The best answer, oft quoted here, is go to a teacher.
Answer: I don't think you actually need a teacher.  Neither do I think you're going to get this on your own, not even with online ear training websites (which I find often do more harm than good).  What you need, I believe, is an ear-training practice PARTNER.  (You help each other.)
Don't try to bite off too much at once.  Start with learning the difference between octaves and fifths.  (Unless you have an actual hearing problem, which you might want to check into, this should come pretty quickly.)  One of you plays at random various octaves and fifths at various pitches.  The other one sits with back to you and identifies them.  The first person makes corrections when you're wrong.  ONLY when you have fifths and octaves perfectly 99% of the time do you add in fourths to the mix.  Now, as you're already discovered, it gets tricky.  But fifths sound hollow and fourths don't.  You'll eventually get this.
Note that this doesn't happen really quickly necessarily.  It might take a session or two, but you'll get it.  Once you are telling fifths and fourths apart with 90% success (and don't forget to throw in the occasional octave), you can start adding in other stuff.  Drill on the difference between major and minor triads, in root position.  Do your interval drill too, and start to throw in thirds (both major and minor) and when you get that, sixths.
Don't attempt seconds, sevenths, and tritones until you have all of the above 90% of the times.  The problem is, your ear (and brain) get overwhelmed by trying to keep track of all the possibilities.  Keep the progression simple, and you'll cope better.
Once you're pretty confident with the partner bit, you can start going it alone.  And NOW (and not before) is where the voice comes in.  (This following works best with a keyboard by the way.)  Play a note.  Sing that same note as best you can.  (Don't worry about whether you have the pitch perfectly or not.) Now POINT to another note, a third, fourth, or fifth away, and sing the pitch you THINK that note will have.  Now play that note to see how far off you are.  Keep doing this at different pitches and intervals until you are getting it right most of the time.
Don't expect to get this overnight or even in a week.  Be patient.  Unless your hearing is actually defective (unlikely) you'll eventually get it.  I'm not making this stuff up by the way.  As a piano teacher for more than fifty years, and a theory, ear training, and composition teacher for half that, and as a voice student for fifteen, I'm pretty confident I know what I'm talking about.
Comment: Thanks! This seems like very good advice. Why is it important to have a training partner instead of using a software to get played random intervals? What makes the difference?
Comment: I should also in my answer have mentioned that you should quit any ear training session when your ear and brain go 'tilt' or your head starts to hurt.  And even if that doesn't occur, stop after a half hour.  Take at least a ten minute break before doing any more.
Comment: There are several reasons.  1. The tone quality of the online ear training drills leaves a lot to be desired, even if you use headphones or good speakers.  2. The sites I have seen go through the intervals in the same order every time you run them, rather than randomly.  A partner will be truly random (if they're any good).  3. Most importantly, the websites I have seen try to get you to bite off more than you can chew.  You really do need to progress through all this VERY SLOWLY, mastering one type of differentiation before you attempt the next.  Thus you avoid overwhelming your ear/brain.
Comment: About the software solfege itself: The tone quality is that of your midi synthesizer and your playback setup (which I find sufficient in my case), it does run through the intervals really randomly (way more than a human partner would do) and it allows to train (a preset of) specific interval distinctions. Anyways, I still think it's a good idea to seek a training partner! I imagine the feedback to be more instructive than "yes"/"no". Thanks for your reply!
Answer:
How can I effectively learn to reproduce a note?

I'm pretty sure the concept that is missing in your understanding is beat frequencies.
A beat frequency is what we hear when we hear two notes that are almost, but not quite, the same pitch. When an instrument is out of tune, it sounds bad with the rest of the instruments because the notes it plays are producing distracting beat frequencies with the other instruments.
Here is the science (by "different periods", he is talking science for "different notes"):

And here is a more musical demonstration (the first 15 minutes of this video are the math and science again):

Hopefully, watching that second video will help you learn to hear the beat frequencies. Once you can hear beat frequencies, you can move on to the second phase of being able to sing the correct notes. You have to train your mind to change the note you're singing to eliminate the beat frequencies when you are trying to sing the same note as another singer or instrument. Singing along with an instrument or other singer and minimizing the beat frequencies in real time is an excellent way to learn to sing the correct pitches.
An important note about minimizing beat frequencies: The closer the notes are to each other, the slower the beat frequency. So when you're trying to match a note, you might not know whether to move up or down, so try one way or the other and if the beats slow down, you're getting close. If they speed up, you're going the wrong way.
Eventually, you can learn to hear even quieter beat frequencies between two different notes that are not the same note. For instance, if you play a C on a piano and then sing a G with your voice, if the G is not quite right, you can hear a beat frequency even though the note you're playing on the piano is a completely different note. It may take several years to get to this point, but once you're tuning your voice to instruments that aren't even playing the notes you're singing, then you're really ready to be a lead singer, at least in terms of hitting the notes.
Also, as you work hard and use your brain to adjust your vocal chords to eliminate beat frequencies, you'll start to learn to do it automatically and you won't have to think about it as much, but you'll still have to practice. Also, your ability to hear beat frequencies will keep improving over time, so eventually you'll realize that you aren't quite hitting notes that you thought you were hitting just fine. This is all normal when learning to hit pitches while singing.
Any voice teacher, especially one who works with beginners a lot, should be able to explain and demonstrate this to you. If you're learning on your own, you will really need an instrument to play and hold notes that you can practice matching pitches with.
Comment: That second video isn't too bad; what I do to demonstrate beats is use two harmonics on guitar, say 5th fret E and 7th fret A. The two can sound simultaneously, then when one is changed with the machine head, the beats can be made faster/slower until they disappear. Not so easy to follow on uke, with tuning breaks.  Also, any vibrato that a voice has will act as a red herring.

How can one learn to reproduce notes with one’s voice?


How to unit test a class, which is using Console class?

Question: I have class, which is using Console class and sets this variables in constructor.
  public Scene() {
        Height = Console.WindowHeight;
        Width = Console.WindowWidth;
    }

and test class, which tests this constructor:
public class SceneTests {
    [Fact]
    public void Contructor_None_ShouldReturnScene() {
        var testScene = new Scene();
        Assert.Equal(Console.WindowHeight, testScene.Height);
        Assert.Equal(Console.WindowWidth, testScene.Width);
    }
}

But while running this test I've got Exeption:
Exception has occurred: CLR/System.IO.IOException
An exception of type 'System.IO.IOException' occurred in System.Console.dll but was not handled in user code: 'Nieprawidłowe dojście'
at System.ConsolePal.GetBufferInfo(Boolean throwOnNoConsole, Boolean& succeeded)
at System.ConsolePal.get_WindowHeight()
at System.Console.get_WindowHeight()

I guess, that's because I don't have actual Console window.
Can I somehow simulate that? Maybe simple creating buffer manually and adding it to Console will solve the problem.
Comment: You handle this the same way you handle IoC anywhere else. You code against an abstraction instead of a concrete implementation. Right now you have a hard dependency on System.Console. So the solution is to write a wrapper around System.Console and then create an interface for that wrapper to inherit from. Then in your unit test, you can mock that interface. Of course, it's likely someone else has run into this before, and therefore made an abstraction and wrapper already. There is one for [System.IO](https://github.com/System-IO-Abstractions/System.IO.Abstractions).
Comment: What's the type of the project? Did you try to change it to Console Application?
Comment: Check this [thread](https://stackoverflow.com/questions/5852862/mocking-system-console-behaviour) to see how it could be resolved
Comment: What do you mean? It's ClassLib if you ask about that.
Answer: In the normal fashion...
Create an interface that describes your access to the console.  Implement that interface in a class that simply uses the System.Console.  Inject that into your running code using your favorite "Dependency Injection" mechanism.
Then create another class for use during testing that implements that same interface, but without using the System.Console class (for example, simply hard-code the WindowHeight and WindowWidth properties, have Console.ReadLine always return the same string, write Console.Write or WriteLine to some other place).  Inject that class into your unit test code.
Comment: This was well said


Rules: get content created by user account being cancelled?

Question: Case: using Rules module, when a user account is cancelled, create a new node of type Archive and (a) copy select data from that account to the new node of type Archive, and (b) copy select data from a single node of type XYZ authored by the cancelled user to the new node of type Archive.
I have this rule:
EVENT
After a user account has been deleted
CONDITIONS
None
ACTIONS
Create a new entity
(set data values here)
Save entity

In Actions, the new node created is of type Archive. In between creating and saving this new node, data values are set (i.e. "Set data value") on it. The values are derived from the account being cancelled.
However, how can I access a node of type XYZ authored by this account, and use that to also set data values on the new node of type Archive? There seems to be no way to access the fields of XYZ in the Data Selector. The available fields pertain only to the account, and not to content authored by that account.
As a comparison, in Views I would establish a Relationship to open up access to fields of related entities. What's the equivalent in Rules?
Thanks
Answer: You can use the Views Rules module, as further detailed below.
1. About the Views Rules module
The Views Rules module makes Views data available in Rules, enabling intuitive rule configuration for dynamic data. Some details from its project page:

... provides two types of elements in Rules, configured with a "Rules" view display:

Views loop: A views loop is similar to a regular Rules loop, but allows looping over rows of view results.

Collect view result rows (action): This action collects each variable in all view result rows into list variables for use in Rules.

Tip: When selecting the data type for variables in the view, if the field is an entity identifier (e.g. Node ID), you can set the data type to the entity type (i.e. Node) to directly use the variable in Rules as an entity!

2. Create a view of display type 'Rules'
After you enable the Views Rules module, you can use Views to create a view of your "node of type XYZ authored by this account" (as in your question). Add of view of display type Rules (important, that's the key to make it work!). Here is how you can add such display:

Next configure the row variables, by using the link that says "edit field info", as shown here:

3. Create a rule using the view of display type 'Rules'
Adapt your Rulew Actions, using these guidelines:

Use the link that says Add view loop to add a Views loop, and select the "Rules" display created in the previous step.
Configure the parameters and variable names.
For each node contained in your Views loop (I seem to understand you will only have one), perform whatever Rules Action that fits your requirement, using the variables you configured at the end of the previous step (you may have to revisit the previous step to add more similar variables there if needed).