How can i send an event while the program is in a loop?

Question: I work at a project and i need to understand very well how event-driven programming works. I've read a lot in the last few days and i understood how this is working but i cant figure some things out.
In a class called Application i got this:
public void Simulate() throws InterruptedException {

    int i = 0;
    while (1 == 1) {

        System.out.println(i);
        Thread.sleep(1000);
        i++;
    }

}

And i have this class:
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import javax.swing.JButton;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class Visual {

    private JFrame frame;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Visual window = new Visual();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public Visual() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 472, 381);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel panel = new JPanel();
        frame.getContentPane().add(panel, BorderLayout.NORTH);

        JButton btnStart = new JButton("Start");

        btnStart.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent arg0) {
                Application app = new Application();
                try {
                    app.Simulate();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });

        **JButton print = new JButton("Print");
        print.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                System.out.println("random text");
            }
        });**
        panel.add(print);
        panel.add(btnStart);
    }

}

What i want to do is when i run this program, i want to pres the putton Start to start the loop in the simulate method and then i want to press the button print, to print some random text while the counter is still running. The problem is that after i pres the start button, the print button becomes unavailable, and cant be pressed anymore. How can i solve this?
Comment: See [Concurrency in Swing](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/) for more details of how to proceed here (tip `SwingWorker`).
Answer: For buttons don't use addMouseListener, use addActionListener and override actionPerformed method, to be able to print your number while the loop is running, try to call your simulate method using new thread. Change your Visual class to the followng example:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Visual {

    private JFrame frame;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Visual window = new Visual();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public Visual() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 472, 381);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel panel = new JPanel();
        frame.getContentPane().add(panel, BorderLayout.NORTH);

        JButton btnStart = new JButton("Start");

        btnStart.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                Application app = new Application();

                (new Thread(new Runnable() {
                    public void run() {
                        try {
                            app.Simulate();
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                })).start();

            }
        });

        JButton print = new JButton("Print");
        print.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("random text");
            }
        });
        panel.add(print);
        panel.add(btnStart);
    }
}

Comment: Thank you very much for your help. I went to sleep right now and i will try what you sugested early in the morning and ill let you know if it worked.


Meteor: optimistic ui and appCache

Question: How does a meteor application deal with server-side methods for inserting and updating? especially:

if an application is temporarily offline (available through appCache-package) and a call to a server-side
method  happens: is optimistic-ui possible? how does it work?
do i
need to define the (usually server-side) methods in /libs
directory instead of /server?

Thank you
Answer:
You should put your collections under libs and use Collection.allowand Collection.deny to control the permission on both server and client side.

In meteor, most of the time you're dealing with client side data, Meteor will save them to the Minimongo and synchronize  your update to server when available.

Regarding to method definition, it really depends on where you want to use it, only a few things you'll put on server, e,g, authentication logic, encryption salt
Comment: Thanks, i saw this picture on the docs too. I was asking if meteor can deal with server-side methods when calling them in "offline" mode. I guess a "server only" method (not in `/libs`) can't be detected by the optimistic-ui, or?

Meteor: optimistic ui and appCache


Android Button Sizing

Question: I have several buttons in my application that are displayed at the bottom of the screen. Right now the buttons have text in them. When running on the emulator, the buttons with text fit nicely. Now, that I am running on the actual device, some buttons' text takes more than two lines and the screen is not very presentable. I could change the font to make it work for the device in question, but there is no guarantee that it will work on some other device. Should I create button images (with text embedded as part of the image) and then have multiple versions, depending on the size of the device screen being used? That seems like a lot of work, is there a simpler solution to this?
Thank You,
Gary
Comment: Can you post your screenshot with your layout code ?.
Answer: You need to give equal weights to all buttons.So that all of them look similar and occupy same amount of space.
Answer: You have to get screen resolution and set sizes as a proportion of this resolution.
Here is the sample code to obtain screen width and height.
<code>Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
</code>
Answer: You can find multiple screen size handling tutorial here:
Supporting Multiple Screens
your emulator may have specific resolution that is different than the one of your actual device.
Answer: It is not hard but little bit tricky.
In this purpose you can use built in draw-able folder. In android project there are many draw-able folder like drawable-hdpi, drawable-mdpi, drawable-xhdpi where you can put different size of images and it will automatically render image based on device screen. Check this tutorial for more understanding Supporting Multiple Screens
Or you can take screen size dynamically. Based on the screen size you can set the button height and width.

Android Button Sizing


Kafka Connect Filter Transformer

Question: I am using a Kafka-connect, and I want to filter out some messages.
This is how a single message in Kafka looks like.
{
  "code": 2001,
  "time": 11111111,
  "requestId": "123456789",
  "info": [
    {
      "name": "dan",
      "value": 21
    }
  ]
}

And this is how my transformer looks like
transforms:
  transforms: FilterByCode
  transforms.FilterByCode.type: io.confluent.connect.transforms.Filter$Value
  transforms.FilterByCode.filter.condition: $[?(@.code == 2000)]
  transforms.FilterByCode.filter.type: include

I want to filter out the messages that their code value is not 2000.
I tried to few different syntax for the condition, but could not find any that works.
All the messages are transformed, and no one is filtered.
Any ideas on how I should use the syntax for the filtering condition?
Comment: What is this YAML format you've shown? That's not used by Connect API
Comment: @OneCricketeer This is an internal infrastructure. This is working (I wrote my own transformer, but I want to add the Kafka-connect filter condition, that is what I am missing.
Answer: If you want to filter out all non 2000 codes, try [?(@.code != 2000)]
You may test it here - http://jsonpath.herokuapp.com/

Kafka Connect Filter Transformer


Guide to set-up DNS and Multiple domain on Ubuntu 12.04

Question: I would like to know, how  to set-up a DNS server and to run multiple websites on a single VPS server. I already have a VPS server and I've installed webmin for my ease.. I'm still confused how to set it up.
If I can set up both of them, I know how to change the NS record in the domain registrar. So, please advise me how to do or may be a clear guide to do.
Thanks in advance.
Answer: You should try looking at this site for info on how to configure your web server. I don't agree with some of the steps and choices but it's a good start.
The Perfect Server - Ubuntu 12.04 LTS (Apache2, BIND, Dovecot, ISPConfig 3)
Comment: Welcome to Ask Ubuntu! Whilst this may theoretically answer the question, [it would be preferable](http://meta.stackexchange.com/q/8259) to include the essential parts of the answer here, and provide the link for reference.
Answer: there are 2 software which i know, EHCP and bind9!
this is a very nice guide how to setup a web server to host multiple domains!
Set Up Ubuntu Server With EHCP (LAMP, DNS, FTP, Mail)
another good tutorial:
http://news.softpedia.com/news/How-to-Host-Your-Own-Domain-With-Bind9-on-Ubuntu-49585.shtml
Comment: Second link you mentioned will give me some idea to get through. Here's what I actually needed. I have a VPS & I need to host multiple domains by having my own name servers. DNS even I can use google dns to forward traffic in that case. I'm still stcuk.
Comment: Whilst this may theoretically answer the question, [it would be preferable](http://meta.stackexchange.com/q/8259) to include the essential parts of the answer here, and provide the link for reference.


File not found when executing a .exe from PyInstaller

Question: I have a script which contains several libraries, one of which is iapws.
When I create an executable using
pyinstaller --onefile myScript.spec
I get the following error:

FileNotFoundError: [Errno 2] No such file or directory: 'C:\Users\Miguel\AppData\Local\Temp\_MEI147002\iapws\VERSION

I tried upgrading all my libraries and using hiddenimports=['iapws'] on the spec file
As far as I understand, the problem is that the necessary files are not being extracted into the temp folder when executing the file.
Any workaround for this?
Thank you very much
Answer: You need to force pyinstaller to include iapws files, as it seems to have issues generating the appropriate hooks. This worked for me:
pyinstaller "your_script.py" --collect-all iapws

I reviewed command options here which helped:
https://pyinstaller.org/en/stable/usage.html
Comment: God bless you, your answer came just in time. Many thanks!


Simplify sum of factorials with mathematical induction

Question: I want to prove with mathematical induction that:
$$\sum_{i=1}^n i \cdot i! = (n+1)! - 1$$
So in the first step we define $n = 1$:
$$\sum_{i=1}^1 i \cdot i! = 1 \cdot 1! = 1 = 2! - 1$$
In the second step we define $n = n + 1$:
$$\sum_{i=1}^{n+1} i \cdot i! = \sum_{i=1}^n i \cdot i! + (n+1)(n+1)!$$
$$\implies (n+1)! - 1 + (n+1)(n+1)!$$
This can now be simplified to $(n+2)(n+1)! - 1$ but I do not see how...
We could do $(n+1)!(-1 + (n+1)) = (n+1)! \cdot n$ but still this will not be the same as above.
What did I miss?
Bodo
Answer: You are almost there.
Note that
$$
(n+1)! - 1 + (n+1)(n+1)! = -1 + (n+1)!( 1 + (n+1) ) = -1+ (n+2)(n+1)! = (n+2)! - 1.
$$
Comment: The rule $k\times (k-1)! = k!$, applied with $k=n+2$.
Comment: What "rule" allows the transformation from $-1 + (n+2)(n+1)! = (n+2)! -1$?
Answer: $(n+1)!-1+(n+1)(n+1)!=(n+1)!(n+1+1)-1=(n+1)!(n+2)-1$


NameError: name 'transforms' is not defined, while using google colab

Question: train = datasets.MNIST("", train=True, download=True,transform = transforms.Compose([transforms.ToTensor()]))
test = datasets.MNIST("", train=False, download=True,transform = transforms.Compose([transforms.ToTensor()]))`

After executing this on colab notebook, I am getting this error:
Traceback (most recent call last)
<ipython-input-6-b81aa6cf1cbe> in <module>()
----> 1 train = datasets.MNIST("", train=True, download=True,transform = transforms.Compose([transforms.ToTensor()]))
      2 test = datasets.MNIST("", train=False, download=True,transform = transforms.Compose([transforms.ToTensor()]))

NameError: name 'transforms' is not defined*

Comment: Why do you think it should be defined? Did you import it?
Answer: I'm guessing from the context that you're using Pytorch, in which case you need to make sure you have:
from torchvision import transforms

In your imports. By the looks of things you have already imported datasets from the same library.


Why do I get an "Access Level must be protected or weaker" after extending a protected class variable and marking it private?

Question: abstract class AbstractController
{
    protected $repository;
}

class GraphController extends AbstractController
{
    private $repository;
}

I get this error:

Fatal error: Access level to GraphController::$repository must be protected or weaker

Why?  What's the theory behind this?  On some level it feels wrong that I could have a weaker access level to a class property (i.e. public) when I extend a class, because I am in a way exposing a variable that was meant by parent class to be more restricted...
Answer: It's a rule of the inheritance. You can make the visibility weaker (more visible) of an inherited member, but you can't hide it more. So you can either make it protected, or public. The rationale being you shouldn't be able to hide members from the base class, or make members less visible than the base class author intended. Add to, yes, take away from, no.
Comment: alright, that makes sense, although I can take virtually any class, extend it, and make that class' variables public, thereby circumventing any encapsulation that class intended to have.  Not that I would do it on purpose but can be done nevertheless
Comment: You might think you could derive the base class and make the member vars more visible, but it won't work out the way you think, and end up a bit messy. I'll explain in another response.
Answer: This is a response to the comment above having to do with making member vars more visible... not necessarily a response to the original question.
Try running this fragment. You'll see there will still be a private var lurking underneath your public var by the same name, and depending on whether you access it through base-class methods or derived-class methods, you'll get different results since they are two distinct instance values.
class baseclass {
    private $hideme;
    public function getit() { return $this->hideme; }
    public function setit($value) { $this->hideme = $value; }
}

class derived extends baseclass {
    public $hideme;
}

function doobee(baseclass $obj) {
    echo $obj->getit() . "\n";
}

$a = new derived();
$a->hideme = "direct assign";
$a->setit("accessor assign");

?>
<?php
echo '$a->getit(); // ' . $a->getit() . "\n";
echo '$a->hideme; // ' . $a->hideme . "\n";
echo 'doobee($a); // '; doobee($a);

echo 'print_r($a);' . "\n";
print_r($a);
?>

Output:
$a->getit(); // accessor assign
$a->hideme; // direct assign
doobee($a); // accessor assign
print_r($a);
derived Object
(
    [hideme] => direct assign
    [hideme:baseclass:private] => accessor assign
)

It's not just PHP that behaves this way; C# for instance does likewise.
So I guess the take-away from all this is that it is not a good idea to try to change visibility of base class instance/members vars in derived classes.


Proving $\|a + b\|^2 \geq \frac{1}{2}\|a\|^2 - \|b\|^2$ for $a$, $b$ in $\Bbb{R}^d$

Question: I have encountered the following inequality in the optimization article.
For all $a, b \in \mathbb{R}^d$ the following inequality holds: $\|a + b\|^2 \geq \frac{1}{2}\|a\|^2 - \|b\|^2$.
The norm is a simple $l_2$-norm. This is all the information that was given.
It was written in the Appendix and was marked as "basic" inequality, without any sketch of proof or even naming. I have tried to prove it on my own or to find anything related to it, and failed.
Could you please explain to me how to prove it?
Comment: $\|a\|^2= \| (a+b) - b\|^2 \le (\|a+b\| + \|b\|)^2 \le 2\|a+b\|^2 + 2\|b\|^2$
Answer: See the parallelogram law.
\begin{align}
\|a\|^2 + \|a+2b\|^2
&= \|(a+b)-b\|^2 + \|(a+b)+b\|^2
\\
&= 2\|a+b\|^2 + 2\|b\|^2.
\end{align}
Dividing by $2$ and noting $\|a+2b\|^2\ge 0$ yields your equality.


Python Windows CMD mklink, stops working without error message

Question: I want to create symlinks for each file in a nested directory structure, where all symlinks will be put in one large flat folder, and have the following code by now:
# loop over directory structure:
# for all items in current directory,
# if item is directory, recurse into it;
# else it's a file, then create a symlink for it
def makelinks(folder, targetfolder, cmdprocess = None):
    if not cmdprocess:
        cmdprocess = subprocess.Popen("cmd",
                                  stdin  = subprocess.PIPE,
                                  stdout = subprocess.PIPE,
                                  stderr = subprocess.PIPE)
    print(folder)
    for name in os.listdir(folder):
        fullname = os.path.join(folder, name)
        if os.path.isdir(fullname):
            makelinks(fullname, targetfolder, cmdprocess)
        else:
            makelink(fullname, targetfolder, cmdprocess)

#for a given file, create one symlink in the target folder
def makelink(fullname, targetfolder, cmdprocess):
    linkname = os.path.join(targetfolder, re.sub(r"[\/\\\:\*\?\"\<\>\|]", "-", fullname))
    if not os.path.exists(linkname):
        try:
            os.remove(linkname)
            print("Invalid symlink removed:", linkname)
        except: pass
    if not os.path.exists(linkname):
        cmdprocess.stdin.write("mklink " + linkname + " " + fullname + "\r\n")

So this is a top-down recursion where first the folder name is printed, then the subdirectories are processed. If I run this now over some folder, the whole thing just stops after 10 or so symbolic links.
The program still seems to run but no new output is generated. It created 9 symlinks for some files in the # tag & reencode and the first three files in the ChillOutMix folder. The cmd.exe Window is still open and empty, and shows in its title bar that it is currently processing the mklink command for the third file in ChillOutMix.
I tried to insert a time.sleep(2) after each cmdprocess.stdin.write in case Python is just too fast for the cmd process, but it doesn't help.
Does anyone know what the problem might be?
Comment: This isn't really related to your problem, but have you considered using `os.walk()` rather than recursion? It'll probably be simpler.
Answer: Why not just execute mklink directly?
Comment: Because it's not a Windows command, it's a CMD command and needs to be run in CMD. `subprocess.call("mklink")` leads to `WindowsError: [Error 2] The system cannot find the specified file`
Comment: In that case it might be easier to use ctypes to call http://msdn.microsoft.com/en-us/library/aa363866.aspx directly.
Comment: Sorry, I didn't realise that. The next thing I'd try would be cmd /c mklink
Comment: Of course, that's what I did, but I wanted to create several thousand symlinks and thought that this is much faster if I only use one cmd.exe process for every mklink command. It didn't work out, however; my computer just seems to close the pipe after a few commands, I have no idea why. So I finally had to do it the way you said: `subprocess.call("cmd", "/c", "mklink", linkname, filename)` for each link. And with `shell = True` or something, I even managed to suppress the cmd windows.
Answer: Try this at the end:
if not os.path.exists(linkname):
    fullcmd = "mklink " + linkname + " " + fullname + "\r\n"
    print fullcmd
    cmdprocess.stdin.write(fullcmd)

See what commands it prints. You may see a problem.
It may need double quotes around mklink's arg, since it contains spaces sometimes.
Comment: I actually used quotes, but I tried your method nevertheless -- the commands are absolutely fine.
Comment: Maybe CMD can only take so many commands? Try feeding it something else, like `dir >>dummy.txt` repeated 100 times, see what happens.


Ruby Rendering Specific Variable

Question: I have a template which contains various variables for rendering.
Is there a way i can render specific variables in the template without exception.
e.g. template_content = "My name is <%=firstname%>. I live at <%=location%>"

variable_hash = {firstname: "eric"}

Erubis::Eruby.new(template_content).result(variable_hash)

Expected Output:
   "My name is eric. I live at <%=location%>"

My use case is render with first variable and get the rendered content.
However when i run above code it gives exception:
     "undefined local variable or method location"
I am using Erubis for rendering. I am fine with ERB rendering also. Needs to render with ruby script only.
Any way to make it work?
Comment: As a variant: `variable_hash = {firstname: "eric", location: "<%=location%>"}` ;)
Comment: What output are you expecting, when location data is missing? Do you want to default to empty string?
Comment: @NeilSlater expected output: "My name is eric. I live at <%=location%>"
Comment: It looks like you want to use this to render content provided by your users. In this case, I have to tell you that this is *NOT* safe, quite the contrary. Using ERB templates, the template author can execute arbitrary ruby code and to everything inside your application, including accessing your database, stealing all your data and wrecking havoc on your server. You definitely do not want to run erb templates provided from your users!
Comment: @HolgerJust the templates are not provided by users. Also there is no db operation going here. Templates are made by our internal devs. I need this to run validations on the partial rendered string. e.g. all links are correctly formatted. I don't have all the variables values at the time of validation.
Comment: @YevgeniyAnfilofyev thanks but that doesn't work. There could be unknown variables in the string :(
Answer: module MyModule
  def method_missing(method_name)
    super
    rescue NameError => e
     return method_name
  end
end

eb = Erubis::Eruby.new('My name is <%=firstname%>. I live at <%=location%>')
eb.extend(MyModule)
result = eb.result(:firstname =>'Ab')
puts result

Not sure if this is a good solution, there may be better solutions for this.

Ruby Rendering Specific Variable


Logistic Regression derivation

Question: From the Wikipedia article http://en.wikipedia.org/wiki/Multinomial_logistic_regression:
$ln \frac{\Pr(Y_i=1)}{\Pr(Y_i=K)}  = \beta_1 \cdot \mathbf{X}_i $
$ln \frac{\Pr(Y_i=2)}{\Pr(Y_i=K)}  = \beta_2 \cdots \mathbf{X}_i$
$\vdots$    $~~~~~~~~~~~~~~~~~~~~~\vdots$
$ln \frac{\Pr(Y_i=K-1)}{\Pr(Y_i=K)} = \boldsymbol\beta_{K-1} \mathbf{X}_i $
Exponentiate both sides and solve for the probabilities, you get:
$Pr(Y = j) = Pr(Y =k)e^{B_jx_i}$, for $j=1\dots K-1$.
Using the fact that the sum of all $K$ probabilities sum to 1, you get:
(*) $ \Pr(Y_i=K) = \frac{1}{1 + \sum_{k=1}^{K-1}e^{\beta_kx_i}}$
I don't understand the steps taken to arrive at (*).
Answer: Adding up $Pr(Y_i = j) = Pr(Y_i = K) e^{B_j {\bf X}_i} $ for $j=1\dots K-1$, and $Pr(Y_i=K) = Pr(Y_i = K) e^{B_K {\bf X_i}} $ where $B_K = 0$ you will get
$$ 1 = Pr(Y_i=K) \sum_{j=0}^K e^{B_j {\bf X_i}} $$
which is the same as (*) but no log.
Comment: Sorry, there wasn't supposed be a log in (*).

Logistic Regression derivation


Running a command completely indepenently from script

Question: I have recently come across some situations where I want to start a command completely independently, and in a different process then the script, equivalent typing it into a terminal, or more specifically writing the command into a .sh or .desktop and double clicking it. The request I have are:

I can close the python window without closing the application.
The python window does not display the stdout from the application (you don't want random text appearing in a CLI), nor do I need it!.

Things I have tried:

os.system waits.
subprocess.call waits.
subprocess.Popen starts a subprocess (duh) closing the parent process thus quits the application

And thats basically all you can find on the web!
if it really comes down to it I could launch a .sh (or .bat for windows), but that feels like a cheap hack and not the way to do this.
Answer: If you were to place an & after the command when called from os.system, would that not work?     For example:
import os
os.system( "google-chrome & disown " )

Comment: how is this for crossplatformness?
Comment: Add `nohup` or just add `disown` after `&`.
Comment: If python exits, the child process might be quit too.  Adding a `nohup` might do it, though.
Answer: import subprocess
import os
with open(os.devnull, 'w') as f:
    proc = subprocess.Popen(command, shell=True, stdout=f, stderr=f)

Comment: thanks for reading my op. :) this spawns a child process, not a full process
Comment: Perhaps I'm not understanding your question. Can you give an example when this does not satisfy your requirements?
Comment: This opens a child process. If the parent process exits with code 0 it is fine, but when I kill it in another way, like closing the terminal, it quits the child process too
Comment: That's odd. If I use `command = 'ls -lRa / > /tmp/out'`, I can run the script, close the terminal, open a new terminal and `ps axu | grep ls` shows `ls -lRa` is still running.
Answer: Spawn a child process "the UNIX way" with fork and exec. Here's a simple example of a shell in Python.
import os

prompt = '$ '
while True:
    cmds = input(prompt).split()
    if len(cmds):
        if (os.fork() == 0):
            # Child process
            os.execv(cmds[0], cmds)
        else:
            # Parent process
            # (Hint: You don't have to wait, you can just exit here.)
            os.wait()

Comment: This seems a bit complicated if I still have to do something else for windows but ill try it
Comment: This works well, I just changed the os.execv(cmds[0], cmds) line to os.system(cmds) and removed the .split(). Sadly, since all of these don't work for windows "command & disown" is easier.


Is it possible to swipe the Admin card correctly on the first try?

Question: Whenever I get the Admin card task, I spend ages trying to swipe it. I think I'm starting to nail down the correct speed for scanning it, but even still it's very finnicky - the quickest success I've been able to get is after 5 tries.
I've just found this "glitch"?, which will give a quick success, but it requires one to quickly swipe the card repeatedly (rather than just once). I have also heard plenty of anecdotal evidence that it's possible, but nothing conclusive.
Is it actually possible to scan the card correctly on the first try? Or is there some sort of 'minimum tries needed' to be able to get a success?
Answer: Yes, it can be done. A correct swipe is about 1/2 second at a uniform speed, slightly slower than the speed at which you would scan a card reader at a grocery store. It's admittedly easier to do on mouse (and when you're not stressed by an Impostor possibly stack-killing you).
Here's a video of a YouTuber named Alpharad swiping the card first try during a game:
Answer: I have heard that if you swipe slowly to the arrow and then really fast to the end you will actually complete the quest, I have actually tried this myself and It actually does work.!


Data is not updating into database

Question: I want to update the values of textboxes into my SQL Server database.
The code does not show any syntax error and redirects easily to the page I'm redirecting but still database is not updating the new data in it.
conn.Open();

string str_id = Session["userid"].ToString();

int id = Convert.ToInt32(str_id);
id = Int32.Parse(str_id);

string updatequery = "Update empdata set fname='" + updatename.Text + "',education='" + updateeducation.Text + "',position='" + updateposition.Text + "',email='" + updateemail.Text + "',address='" + updateaddress.Text + "',contact='" + updatecontact.Text + "',account='" + updateaccount.Text + "',postal='" + updatepostal.Text + "',password = '" + updatepwd.Text + "' Where id = '" +id.ToString()+ "'";

SqlCommand updateinfo = new SqlCommand(updatequery, conn);
updateinfo.ExecuteNonQuery();
updateinfo.Dispose();

updationmessage.Text="
Information updated successfully
";

Comment: https://xkcd.com/327/ thar be sql injection vulnerabilities here!
Comment: If you set a breakpoint at the line after setting updatequery, you can get the actual query that is being attempted.  Also, your code is vulnerable to sql injection.
Comment: Are the textboxes initial values being loaded from the database? It might be a PostBack issue
Comment: Can you show the code for insantiating conn?
Comment: is the viewstate enabled in the page?
Comment: What is the datatype for your column `id`?
Comment: Find out where your databse is and how many copies there are.
Answer: Firstly,switch to ParameterBinding, your code is prone to sql inection (and slower)
Secondly, check the return value of ExecuteNonQuery. If it is 0, then there was no change in the database, meaning no matching id has been found
Thirdly, check if you are within a transaction where you need to commit the transaction - otherwise you will not see anything in the database.

Data is not updating into database


How can I visualize the tracking of every non-zero elements in a 2D matrix?

Question: I have a 2D matrix in which the elements are either 1 or 0.

As as time progresses, this matrix gets updated w.r.t. some other variables. The update is such that the '1' elements of matrix moves through the coordinates to aggregate itself to a particular location (may be centre of the 2D matrix).
So I would like to track the motion of each '1' elements towards the centre. How can I realize this?
Comment: You must have some equation or algorithm that predicts the location of each 1 at the next time step, I assume. Why don't you just save these time steps? Maybe I don;'t understand the problem
Comment: You can use timeseries as @TheodorBecker said or try this way: in your algorithm you have '1'. It moves at other place. Save some value, for example '-1' at previous place (not zero). This '-1' must works like '0' value (any new point can gets up at this place). But you set different colours for it when create plot. So, points will be black, tracks - red, for example.
Comment: Are you looking for something [animated](http://stackoverflow.com/questions/11051307/approaches-to-create-a-video-in-matlab), or a 2d-Plot? Also, would it be possible to track each "one" as a single point with x-position and y-position?
Comment: If you want the history of each point, you may have to manage a graphic objet and an array for each single point. How many `1` are you talking about ... and for how long (how many animation steps or frames ?)
Comment: wow, I based my answer on your figure with `1000` non-zeros elements. I tried it and it still run ok, but things may be a bit sluggish with 2x10,000 graphic objects. You may have to skip/average some of the iterations in less frames indeed.
Comment: @MartinJ.H. : Yes I am looking for something animated. The path of track must be traced as lines.
Comment: @Hoki actually there are ~10,000 `1`s. The animation will be around ~1000000 iterations.
Comment: frames are much lesser.
Answer: This answer will help you with the visualisation of your points and their movement history, but it does not handle the tracking of your non-zeros elements.
Let's start with sample data:
%% // sample data
nMax = 10 ;               %// Max size of matrice
M0 = randi([0 1],nMax) ;  %// populate with random "0" and "1"

[x,y] = find(M0==1) ;     %// find coordinates of "1"s
npt = numel(x) ;          %// how many have we got

Then we draw the initial state. I used 2 graphic objects per 1: One single point display with a specific marker to show the "head" of the trace (the last position of the point), and one dotted fine line (with no markers) to show the history trace.
%% // Display initial state
hf = figure ; hax = axes('Nextplot','Add') ;

for ip = 1:npt
    %// draw the lasp point (the "head")
    hp(ip) = plot( x(ip) , y(ip) , 'Marker','o' , 'LineStyle','none' ) ;
    %// draw the history line (empty at the moment, will populate later)
    hl(ip) = plot( x(ip) , y(ip) , 'Marker','none' , 'LineStyle',':' ) ;
end

set( hax , 'XLim',[0 nMax],'YLim',[0 nMax]) %// to fix axis limits

Then the animation itself. To move the points, at each animation iteration I add a small quantity to the last coordinates. You'll have to replace that part with your own coordinate update.
Then I concatenate the new coordinate with the old ones, and update each graphic object:
%% // now do the animation
nHist = 30 ; %// number of history point to display on the trace

for animStep = 1:100
    %//                  Movement engine
    %// ---------------------------------------------------------
    %// Replace this block with your own point coordinate update
    x = [ x , x(:,end) + randi([-1 1],npt,1)/10 ] ;
    y = [ y , y(:,end) + randi([-1 1],npt,1)/10 ] ;
    x(x<0) = 0 ; x(x>nMax) = nMax ;   %// keep data within boundaries
    y(x<0) = 0 ; y(y>nMax) = nMax ;
    %// ---------------------------------------------------------

    %% // update display
    for ip = 1:npt
        %// update "Head" point
        set( hp(ip) , 'XData',x(ip,end)  ,'YData',y(ip,end) )

        %// update history trace
        idxTrace = max(1,size(x,2)-nHist):size(x,2) ;
        set( hl(ip) , 'XData',x(ip,idxTrace)  ,'YData',y(ip,idxTrace) )
    end
    drawnow
    pause(0.1)

end

Which produces the following:

You can adjust the variable nHist to change the number of history points you will display.
You can also change the "head" marker to something smaller if you have too many of them in your matrix.


For which values of $c$ does the matrices form a basis for $M_{2\times 2}(\mathbb{C})$?

Question: Given the matrices
$\begin{bmatrix}
    1       & c  \\
    0       & 0 \\
\end{bmatrix}$
$\begin{bmatrix}
    0      & 1  \\
    c       & 0 \\
\end{bmatrix}$
$\begin{bmatrix}
    0       & 0  \\
    1       & c \\
\end{bmatrix}$
$\begin{bmatrix}
    c       & 0  \\
    0       & 1 \\
\end{bmatrix}$
For which values of $c \in \mathbb{C}$ the above matrices form a basiss for the vector space $M_{2\times 2}(\mathbb{C})$?
Since $M_{2\times 2}(\mathbb{C})$ is of dimention 4, it suffices to find values of $c$ for which the matrices are linearly indepenedent.
So I looked a t the equation :
$a\begin{bmatrix}
    1       & c  \\
    0       & 0 \\
\end{bmatrix}+b\begin{bmatrix}
    0      & 1  \\
    c       & 0 \\
\end{bmatrix} + c\begin{bmatrix}
    0       & 0  \\
    1       & c \\
\end{bmatrix}+d\begin{bmatrix}
    c       & 0  \\
    0       & 1 \\
\end{bmatrix}=0$
Solving those for $c$ gives $c= \frac{-b}{a}=\frac{-a}{e}=\frac{-e}{d}=\frac{-d}{b}$ So then $ a,b,d ,e \neq 0$. I noticed that $c=1$ or $c=0$ gives rise to contradiction. I feel like given $c$ and $a$ we can solve the others, So the solution should be $\mathbb{C}-\{1\}$?
I'm not sure about my reasonings.
Comment: There is a certain 4 by 4 determinant you should look at...
Comment: First of all, fix your notation, because you use $c$ in two different contexts.
Comment: @kimchilover on my linalg course, determinants were a lot after such problems (but other metods to check linear dependence/independence were provided).
Answer: Wknow the canonical basis of $\mathcal M_{2\times2}(\mathbf C)$:
$$E_1=\begin{pmatrix} 1&0\\ 0&0\end{pmatrix},\quad E_2=\begin{pmatrix} 0&1\\ 0&0\end{pmatrix},\quad E_3=\begin{pmatrix} 0&0\\ 1&0\end{pmatrix},\quad E_4=\begin{pmatrix} 0&0\\ 0&1\end{pmatrix}.$$
In this basis, the deerminant of the given system of matrices is
$$\begin{vmatrix}
1&0&0&c \\ c&1&0&0\\
0&c&1&0\\
0&0&c&1
\end{vmatrix}.$$
Can you calculate this determinant, expanding by the first row, for instance?


Display images in ASP.NET Core MVC application that are also exported to pdf using IronPDF library

Question: I am working on displaying an image on a webpage that is exported to a pdf using the IronPDF library. The problem I am having is that changing the img tag in cshtml is causing the image to either display in the PDF or the webpage but not both.
Image file is stored in wwwroot/images folder.
Current img tag:

This displays the image in the PDF but not on the webpage. If I change the src to be .../images/Logo.png, that displays on the webpage but not the pdf.
PDF create method:
public string CreateAddendumPDF(string html, string agreementID)
{
    var render = new ChromePdfRenderer();
    render.RenderingOptions.MarginLeft = 17;
    render.RenderingOptions.MarginRight = 15;
    render.RenderingOptions.MarginTop = 14;
    render.RenderingOptions.FirstPageNumber = 1;

    var pdf = render.RenderHtmlAsPdf(html,@"wwwroot/images");

    string rootPath = _webHostEnvironment.WebRootPath;

    string path = Path.Combine(rootPath, ReportConstants.Temp + "Addendums\\" + agreementID + "_" +"Addendum.pdf");

    pdf.SaveAs(path);

    return path;
}

I tried different image src values and could not get one to work in both the webpage and the pdf document. Next solution is to use Jquery to change the image tag when the user clicks the download pdf button.
Comment: Try to use full urls for the images and not relative ones. Because the PDF tool doesn't know where the image is stored.
Answer: To ensure that the image can be found by IronPDF and displayed correctly on the website, the baseUrl of IronPDF and src="" attribute on HTML string need to be configured correctly. With the file hierarchy shown below set:

baseUrlOrPath to @"wwwroot/image"
src attribute to "../image/Sample.jpg"

wwwroot
└── image
    ├── Sample.jpg
    └── Sample.png

As I have tested the overlapped below the baseUrlOrPath and src attribute is necessary.
For example:
C# code
ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf("html.Result", @"wwwroot/image");

cshtml code

Please visit Use HTML with CSS and Images to Create PDF in C# to learn more.
Answer: If your "Logo.png" is in wwwroot/images/ you could try something like this:

or

with this you should be able to get your image.
I hope it helps.


How do you trigger doors in the Descent 1 level "Titanium Falcon Military Depot"?

Question: Of the Levels of the World levels for the original Descent 1, one of the most obtuse is "Titanium Falcon Military Depot" (a.k.a. "T.F. Military Depot").  It starts out in a single room with some enemies.  The only door which doesn't need a key (aside from the doors to the player spawn locations and the exit door) is opened by flying over a spot next to the convex corner that's closest to the door in the room.
Behind that door is … another door.  It doesn't open when touched/shot.  Presumably, it is opened by flying over another trigger spot in the room, but I can't for the life of me find that spot.  Does anyone remember where it is?
Frustratingly, I'm pretty sure I figured it out when I first played this level in the 90s.  But that memory is gone.
The only mention I can find of this level at all is a ReadMe-ish document, found here, which contains:
<code>Name of Mission: TiTANiUM FALCON MiLiTARY DEPOT

Description of mission: This level is a little tricky.....you must hit switches in order to open the
doors to get the keys....but once you use your imagination the path will come to you. Use the
clues i have provided.......they will help you out. What are behind the doors are either helpful
or harmful (most cases both), so be careful!.....find the keys in succession and then advance
your ship to the TiTANiUM FALCON to blow the reactor. *Intro as follows (optional):*

iNTRODUCTiON: THIS LEVEL IS A MILITARY DEPOT ON SATURN
COMPLETE WITH A HANGAR WHICH CONTAINS THE TiTANiUM FALCON, PTMC'S
NEWEST TOP SECRET ATTACK CRAFT, WHICH THE MECHS HAD BEEN STATIONED
THERE TO GUARD, BUT ONCE THEY WERE INFECTED WITH THE MYSTERIOUS
VIRUS, YOU MUST BE SENT IN BEFORE THE TITANIUM FALCON'S
SUPERCOMPUTER BECOMES INFECTED....EVERY SECOND THE ViRUS SLOWLY
EATS AWAY AT THE CIRCUITS.....UNTIL FINALLY IT WILL BECOME INFECTED AND
LAUNCH ITSELF.....PTMC'S HEADQUARTERS IS THE DESTINATION THAT IT WAS
TRACKING, AND IF IT OPENS FIRE ON THE HQ, IT WILL CAUSE MASSIVE
DESTRUCTION TO THE SPACE STATION.
YOU MUST NOT LET THAT HAPPEN........DESTROY THE FALCON'S REACTOR AND
VAPORIZE THE WHOLE DEPOT IMMEDIATLEY, BEFORE IT BECOMES INFECTED.
</code>
I like to think I'm pretty observant, but I haven't found any "clues" in the main room at all.  The trigger zone which opens the first door, I found by accident;  now, even knowing where it is, I still can find no clues that would have indicated its location.
Answer: After a ton of trial and error, I found the spot.  Fly around the other convex corner which is nearest to the convex corner where the first door's trigger is located.  Around that other corner is one of the many doors that requires the blue key;  approaching that locked door opens the inner of the two doors that leads to the blue key itself.
The yellow key is inside a blue wall panel in the first room.  It is triggered by passing through the blue door that leads to the second large room and entering the right side of the alcove that contains the energy replenishment field.
The red key is behind a regular door, the only one that cannot be directly opened after obtaining the blue and yellow keys.  It is triggered by flying through a very small area which is directly ahead of that door, a little ways from the opposite wall that is across the room from that door.


Kubuntu 14.04 : usb mouse movement wakes up from sleep

Question: I have the following problem: when the computer is in sleep mode (S4 mode) I can wake up it with a simple movement of my USB mouse. I'd like to disable this "fast" wake up, but I have some problems.
In /proc/acpi/wakeup I had this:
Device  S-state   Status   Sysfs node
RP01      S4    *disabled  pci:0000:00:1c.0
PXSX      S4    *disabled
RP02      S4    *disabled
PXSX      S4    *disabled
RP03      S4    *disabled  pci:0000:00:1c.2
PXSX      S4    *disabled  pci:0000:02:00.0
RP04      S4    *disabled
PXSX      S4    *disabled
RP05      S4    *disabled  pci:0000:00:1c.4
PXSX      S4    *disabled  pci:0000:03:00.0
RP06      S4    *disabled
PXSX      S4    *disabled
RP07      S4    *disabled
PXSX      S4    *disabled
RP08      S4    *disabled
PXSX      S4    *disabled
GLAN      S4    *enabled   pci:0000:00:19.0
EHC1      S4    *enabled   pci:0000:00:1d.0
EHC2      S4    *enabled   pci:0000:00:1a.0
XHC       S4    *enabled   pci:0000:00:14.0
HDEF      S4    *disabled  pci:0000:00:1b.0
PEG0      S4    *disabled
PEGP      S4    *disabled

So, following some tutorials online (see here) I typed:
sudo -s
echo EHC1 >/proc/acpi/wakeup
echo EHC2 >/proc/acpi/wakeup
echo XHC >/proc/acpi/wakeup

Now the situation is:
RP01      S4    *disabled  pci:0000:00:1c.0
PXSX      S4    *disabled
RP02      S4    *disabled
PXSX      S4    *disabled
RP03      S4    *disabled  pci:0000:00:1c.2
PXSX      S4    *disabled  pci:0000:02:00.0
RP04      S4    *disabled
PXSX      S4    *disabled
RP05      S4    *disabled  pci:0000:00:1c.4
PXSX      S4    *disabled  pci:0000:03:00.0
RP06      S4    *disabled
PXSX      S4    *disabled
RP07      S4    *disabled
PXSX      S4    *disabled
RP08      S4    *disabled
PXSX      S4    *disabled
GLAN      S4    *enabled   pci:0000:00:19.0
EHC1      S4    *disabled  pci:0000:00:1d.0
EHC2      S4    *disabled  pci:0000:00:1a.0
XHC       S4    *disabled  pci:0000:00:14.0
HDEF      S4    *disabled  pci:0000:00:1b.0
PEG0      S4    *disabled
PEGP      S4    *disabled

But nothing has changed, a tiny movement of my mouse wakes up my computer.
Do you have any solution?
Comment: Try to comepletely remove the mouse from the wake up file
Comment: Could you tell me how?
Comment: well you obviously see those old *Enabled ones. You can try to remove those lines.
Answer: You can fix this in your bios.   Get into your bios {F12 or F10 usually does it during boot, possibly the delete key).  Turn off "Wake on mouse" it should be in a section called "boot" or "power".  I can't give you specifics since all bios are a bit different.


nvm not download specific version

Question: i am trying to install version 12 of node via nvm, but even though python is installed, python not found error is given at checksum time.
this nvm and python version :
~ % nvm --version
0.33.0

~ % python --version
Python 3.10.5

this is nvm error :
~ % nvm install 12
Downloading and installing node v12.22.12...
Local cache found: $NVM_DIR/.cache/bin/node-v12.22.12-darwin-arm64/node-v12.22.12-darwin-arm64.tar.xz
Computing checksum with shasum -a 256
Provided checksum to compare to is empty.
Checksum check failed!
Removing the broken local cache...
Downloading https://nodejs.org/dist/v12.22.12/node-v12.22.12-darwin-arm64.tar.xz...

Computing checksum with shasum -a 256
Provided checksum to compare to is empty.
tar: Error opening archive: Unrecognized archive format
Binary download failed, trying source.
Local cache found: $NVM_DIR/.cache/src/node-v12.22.12/node-v12.22.12.tar.xz
Checksums match! Using existing downloaded archive $NVM_DIR/.cache/src/node-v12.22.12/node-v12.22.12.tar.xz
./configure: line 3: exec: python: not found
nvm: install v12.22.12 failed!

this is nvm debug :

~ % nvm debug
nvm --version: v0.33.0
$SHELL: /bin/zsh
$HOME: /Users/onur.ozkir
$NVM_DIR: '$HOME/.nvm'
$PREFIX: ''
$NPM_CONFIG_PREFIX: ''
nvm current: none
which node: node not found
which iojs: iojs not found
which npm: /opt/homebrew/bin/npm
npm config get prefix: env: node: No such file or directory
npm root -g: env: node: No such file or directory

Answer: This could be an nvm version issue if you are using an older version on nvm on the new M1 macs
install the latest version of nvm like this
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash

or using wget
wget -qO- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash

Remove the current references from your .zshrc or bash profile
You can also rm -rf ~/.nvm

nvm not download specific version


How to rotate also the body when the player is looking at the target if the player is moving the opposite direction from the target?

Question: <code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class LookAtTarget : MonoBehaviour
{
    public Transform lookAt;
    public Vector3 defaultFacing;
    public float angleLimit = 60f;
    public float rotationDamping = 3f;

    // Start is called before the first frame update
    void Start()
    {

    }

    // Using late update so animations don't overwrite my transform manipulations...
    void LateUpdate()
    {

        // For this example i'll be using the root objects forward vector as what i want to be my reference constraint vector.
        // You might want to use something else though.
        defaultFacing = transform.root.forward;

        // The direction from this transform, pointing at the look at target.
        Vector3 directionToLookAtTarget = lookAt.position - transform.position;

        float angle = Vector3.Angle(directionToLookAtTarget, defaultFacing);

        // Since i'm just using the root objects forward vector as a constraint, i can just use its rotation as my default rotation instead of calculation a Quaternion.LookAt.
        Quaternion defaultRotation = transform.root.rotation;
        // The look at rotation to the target if it were completely unrestrained.
        Quaternion lookAtCompleteRotation = Quaternion.LookRotation(directionToLookAtTarget);

        Quaternion finalRotation = Quaternion.identity;

        // If the angle is greater than our limit, return a rotation that is in the direction of the lookAtCompleteRotation but is limited to the angle we chose as a limit.
        // Otherwise, if its within our limit, we just return the rotation as is.
        if (angle > angleLimit)
            finalRotation = Quaternion.Euler(transform.forward);
        //finalRotation = Quaternion.Slerp(defaultRotation, lookAtCompleteRotation, angleLimit / angle);
        else
            finalRotation = lookAtCompleteRotation;

        transform.rotation = Quaternion.Slerp(transform.rotation, finalRotation, Time.deltaTime * rotationDamping);

    }
}
</code>
The script is attached to the character neck in the rig. So when running the game and the player is standing still if I'm moving the target(lookAt) around the player head will look at the target.
The problem is when the target is stay still and I'm moving the player so if I'm moving the player to another direction away from the target the player neck(head) is still rotating looking at the target but the body is facing the way it's moving so the head is looking at the target and the body is facing the moving direction.
I think the logic should be if I'm moving the player to some direction the head should be looking forward facing the moving direction and only if the player is moving to view area direction of the target then look at the target again.
but I'm not sure how to do it.  How to make that the neck will face the direction it's moving and only when moving to the area of the target then look at the target.
Answer: You should add a Bool function that returns true only if the player is able to see the enemy. The way you can do this is :

an if with a Physics.Raycast between player and enemy. Of course if this is true you can also return true from the function

in the same function you can use a variable of the angle you want to see and create 2 variables. One is tha angle multiplyed for a value less than 1 (0.5 for example) and one for a value bigger than 1 (1.5) and then check form the start angle to the last one with the RayCast and see if it hits the enemy. Of course. If you hit the enemy you should return true


Call a jquery function from an other jquery function

Question: I'm not very good in jquery. I will call a jquery function from another jquery function, but it won't work.

The publish function will be called by a button, that works well. From this function I will call the saveData function, and that fails. Something is wrong, can someone help me?
Comment: Define "it won't work". And why extend jQuery for non-jQuery functionality?
Comment: The function $.fn.saveData won't called
Answer: Since you try to define saveData in the same scope, and since it doesn't look like the current jQuery collection matters, there's no need for a custom jQuery method - just call a standard function:
const saveData = () => {
  // save something in database
}
$(".publish").click(function() {
  publish = true;
  saveData();
});

Live demo:

let publish = false;
const saveData = () => {
  // save something in database
  console.log('saving');
}
$(".publish").click(function() {
  publish = true;
  saveData();
});

<button class="publish">click</button>
Comment: Works just fine here, see snippet
Comment: I try this but it will not work, saveData will not be called
Comment: @NicovanWijk Why not?
Comment: Sorry, it works!!!

But what is this: const saveData = () =>          Is this a function?
Comment: @NicovanWijk That is a function.
Comment: But it looks like an constante
Comment: @NicovanWijk Yes, it's preferable to declare variables with `const` (IMO), because that makes it clear that they won't be reassigned. (Functions are variables too.)
Comment: Butt normaly in javascript you declare a function as Function dataSave() {}
Comment: @NicovanWijk I (and many others) prefer using `const` because it makes it clear that the variable cannot be reassigned (and because arrow functions can be more concise in some situations, and because function declarations are hoisted, which can be counter-intuitive). You can use the `function` keyword instead, if you want, both work
Comment: @NicovanWijk "*normaly*" - not really.  "Normally" (ie frequently) people namespace their functions, so it would be something like `var nico = {}; nico.saveDate = function() { ... }; nico.saveDate();` But that's overkill for an SO sample/demonstration, just that there are numerous different ways to generate a named function
Comment: Bit of a long read, but worth knowing the difference: https://stackoverflow.com/questions/34361379/are-arrow-functions-and-functions-equivalent-exchangeable (for fyi, not meant to answer the question)
Comment: @NicovanWijk When an answer solves your problem, you may consider upvoting and/or marking it as Accepted (check the checkbox on the left) to indicate that the issue is resolved :)


Way to get selected tab index from TabView in SwiftUI

Question: I've just added TabView, which is working fine, but I unable to fetch the selected tab index out if it.
I think I've kept my code perfectly fine, not sure what's wrong.
struct DefaultTabbar: View {

    @State private var selectedItem = 1

    var body: some View {
        TabView(selection: $selectedItem) {
            FirstView()
                .tabItem{
                    Image(systemName: "house")
                    Text("First Tab")
            }
            .tag(1)

            SecondView()
                .tabItem{
                    Image(systemName: "photo")
                    Text("Second Tab")
            }
            .tag(2)
        }
        .accentColor(.orange)
        .onTapGesture {
            print("selected tab: \(self.selectedItem)")
        }
    }
}

I'm receiving only 0 while switching tabs.
selected tab: 0.
selected tab: 0.
Comment: It is changed, just use it where needed. But you may not use `.onTapGesture` on `TabView`.
Answer: I think you have the right idea, but don't use onTapGesture, instead use OnChange():
struct DefaultTabbar: View {

    @State private var selectedItem = 1

    var body: some View {
        TabView(selection: $selectedItem) {
            FirstView()
                .tabItem{
                    Image(systemName: "house")
                    Text("First Tab")
            }
            .tag(1)

            SecondView()
                .tabItem{
                    Image(systemName: "photo")
                    Text("Second Tab")
            }
            .tag(2)
        }
        .accentColor(.orange)
        .onChange(of: selectedItem) { value in print("selected tab = \(value)") }
    }
}

Answer: You can use onAppear method for each tab. It's looks ugly but it's works.
struct DefaultTabbar: View {

    var lastSelectedTab = 0 {
        didSet {

        }
    }
    @State private var selectedItem = 1

    var body: some View {
        TabView(selection: $selectedItem) {
            FirstView()
                .onAppear(perform: {
                    lastSelectedTab = 0
                })
                .tabItem{
                    Image(systemName: "house")
                    Text("First Tab")
            }
            .tag(1)

            SecondView()
                .onAppear(perform: {
                    lastSelectedTab = 1
                })
                .tabItem{
                    Image(systemName: "photo")
                    Text("Second Tab")
            }
            .tag(2)
        }
        .accentColor(.orange)
    }
}


How do you impose a case insensitive unique constraint on a Firebird field value?

Question: I want to add a field called email to table AGENT. I want the values of AGENT.email to be unique across the table and I want this uniqueness to be case insensitive.
For example adding "firstname.lastname@example.com" would violate the constraint if "email@example.com" already exists in the table. How do I do this?
Answer: To impose a case insensitive constraint, the best way is to create the column with a case insensitive collation like unicode_ci_ai - this collation is also accent insensitive, which you may or may not want -, and add a unique constraint (or unique index) on that column:
create table addressbook
(
    id integer not null,
    emailaddress varchar(150) character set utf8 collate unicode_ci_ai,
    constraint pk_addressbook primary key (id),
    constraint uc_emailaddress unique (emailaddress)
);

or to add the field to an existing table:
alter table addressbook
    add emailaddress2 varchar(150) character set utf8
            constraint uc_emailaddress2 unique collate unicode_ci_ai

Alternative collations would be unicode_ci (only case insensitive) or other built-in case insensitive collations depending on the character set used, or to create your own specific collation.
The advantage of this solution over the one presented by Gurwinder is that it also allows you to select case (and accent) insensitively without having to use lower in your where clause.
Answer: You can add a unique index on lower of email column on the table like so:
create unique index email_unq_idx on agent computed by (lower(email));

Comment: You could also use a case insensitive collation for the column; I'll post a full answer later.
Comment: @Jonathan Cheers mate :)
Comment: And collation way would be better - that would allow the index to be used for SELECTs too. Expression index would almost only work for uniqueness check
Comment: I'm running Firebird 2.1


Improve speed of appending array elements if not already in array

Question: I have an array S, which has some number of unique elements. I want to append elements from array N which are not already in S.
A syntactically simple way to do this would be:
S = union( S, N, 'stable' );

I found manually appending could be quicker, using ismember or implicit expansion:
% ismember approach
S = [S; N(~ismember(N,S))];
% imp. expansion approach
S = [S; N(~any(S(:)==N(:).',1))];

However, this still feels pretty dirty to do inside a loop, and the implicit expansion can be expensive for large inputs.
Is there a more performant alternative?
If it helps, we can assume S and N contain only integers. However, we can't assume that S is sorted, new elements appended from N could be any positive integer.
Minimal example:
Ntest = [1 2 3 4
         2 5 3 6
         1 5 7 9];
S = [];
for ii = 1:3
    N = Ntest(ii,:).';
    S = union(S,N,'stable');
end
% S = [ 1; 2; 3; 4; 5; 6; 7; 9 ]

In the real case, I don't know the potential values of N up front like I did with Ntest above.
Here is some benchmarking code for 4 methods, with the following results. In my case, it's likely that I'll have a large loop for different values of N, and a small number of elements in each N. This corresponds to the right-most columns in this summary table, where you can see the implicit expansion method is much quicker.
range(Ntest): 1 to 1e4     1 to 1e4     1 to 1e4    1 to 1e4
size(Ntest):  [1e3,1e3]    [1e4,1e3]    [1e2,1e3]   [1e2,1e4]
union:        0.972 sec    1.217 sec    0.779 sec   9.341 sec
ismember:     0.763 sec    0.559 sec    0.492 sec   5.439 sec
implicit:     6.966 sec    too long!    0.295 sec   3.886 sec
setdiff:      0.599 sec    0.534 sec    0.477 sec   5.364 sec

rng(0);
Ntest = randi([1,1e4],1e3,1e3);

f = @()f_union( Ntest );
fprintf( 'union: \t%.3f sec\n', timeit( f ) );
f = @()f_ismember( Ntest );
fprintf( 'ismember: \t%.3f sec\n', timeit( f ) );
f = @()f_implicit( Ntest );
fprintf( 'implicit: \t%.3f sec\n', timeit( f ) );
f = @()f_setdiff( Ntest );
fprintf( 'setdiff: \t%.3f sec\n', timeit( f ) );

function f_union( Ntest )
    S = [];
    for ii = 1:size(Ntest,2)
        N = Ntest(:,ii);
        S = union(S,N,'stable');
    end
end
function f_ismember( Ntest )
    S = [];
    for ii = 1:size(Ntest,2)
        N = Ntest(:,ii);
        S = [S; N(~ismember(N,S))];
    end
end
function f_implicit( Ntest )
    S = [];
    for ii = 1:size(Ntest,2)
        N = Ntest(:,ii);
        S = [S; N(~any(S(:)==N(:).',1))];
    end
end
function f_setdiff( Ntest )
    S = [];
    for ii = 1:size(Ntest,2)
        N = Ntest(:,ii);
        S = [S;setdiff(N,S)];
    end
end

Answer: Since it is assumed that the data type is positive integer you can use logical matrix to store position of integers:
function f_logical( Ntest )
    S = false;
    for ii = 1:size(Ntest,2)
        N = Ntest(:,ii);
        S(N) = true;
    end
end

If the range of elements is large and the data has sparsity it may be beneficial to use sparse matrix:
function f_sparse( Ntest )
    S = sparse(false);
    for ii = 1:size(Ntest,2)
        N = Ntest(:,ii);
        S(N) = true;
    end
end

Comparing with the ismember solution in Octave:
Elapsed time for <ismember> is 1.54181 seconds.
Elapsed time for <sparse>   is 0.266474 seconds.
Elapsed time for <logical>  is 0.0189412 seconds.

Comment: This clearly saved a small amount of time for my wider algorithm's test cases. I was still surprised to then see it saved **~90%** of the processing time for large runs on my real data! I can handle the non-sparse arrays too, but thanks for the extra consideration.
Comment: This I a great perspective shift, thanks for the idea! I will try it out as soon as I'm back in the office
Comment: Glad to hear that. Thanks for bounty!
Answer: I guess you can use the following code to speed up
X = setdiff(N,S);
S(end + (1:length(X))) = X;

Remarks
X = N(~ismember(N,S)) and X = setdiff(N,S) are both fine to find the elements that in N but not in S, but the key step for speeding up the appending process is the following way

S(end + (1:length(X))) = X;

Performance Comparison

rng(0);
Ntest = randi([1,1e4],1e4,1e4);

f = @()f_union( Ntest );
fprintf( 'union: \t%.3f sec\n', timeit( f ) );
f = @()f_ismember_v1( Ntest );
fprintf( 'ismember_v1: \t%.3f sec\n', timeit( f ) );
f = @()f_ismember_v2( Ntest );
fprintf( 'ismember_v2: \t%.3f sec\n', timeit( f ) );
f = @()f_setdiff_v1( Ntest );
fprintf( 'setdiff_v1: \t%.3f sec\n', timeit( f ) );
f = @()f_setdiff_v2( Ntest );
fprintf( 'setdiff_v2: \t%.3f sec\n', timeit( f ) );

function f_union( Ntest )
    S = [];
    for ii = 1:size(Ntest,2)
        N = Ntest(:,ii);
        S = union(S,N,'stable');
    end
end

function f_ismember_v1( Ntest )
    S = [];
    for ii = 1:size(Ntest,2)
        N = Ntest(:,ii);
        S = [S; N(~ismember(N,S))];
    end
end

function f_ismember_v2( Ntest )
    S = [];
    for ii = 1:size(Ntest,2)
        N = Ntest(:,ii);
        X = N(~ismember(N,S));
        S(end + (1:length(X))) = X;
    end
end

function f_setdiff_v1( Ntest )
    S = [];
    for ii = 1:size(Ntest,2)
        N = Ntest(:,ii);
        S = [S;setdiff(N,S)];
    end
end

function f_setdiff_v2( Ntest )
    S = [];
    for ii = 1:size(Ntest,2)
        N = Ntest(:,ii);
        X = setdiff(N,S);
        S(end + (1:length(X))) = X;
    end
end

giving
union:  13.314 sec
ismember_v1:    5.836 sec
ismember_v2:    5.658 sec
setdiff_v1:     4.371 sec
setdiff_v2:     4.248 sec

Comment: Yep sorry, omitted from my question, this is slower for me than the `ismember` approach for determining the set difference, perhaps surprisingly.
Comment: @Wolfie yes, you are right, I guess `ismember` is the fastest so far among the three approaches i added in my answer, but has only tiny advantage than `setdiff` approach
Comment: @Wolfie I updated my solution, which now is much faster than `ismember` approach
Comment: What if you do `X=  N(~ismember(N,S))` and then append as you do with the `setdiff` method?
Comment: Thanks, I've added a benchmark to my question which might help you test this against my other options
Comment: Note that `tic/toc` is not recommended for accurate timing. Rather use [`timeit()`](https://mathworks.com/help/matlab/ref/timeit.html), which overcomes most limitations of a simple `tic/toc`. `tic/toc` should only be used for rough order-of-magnitude comparisons.
Comment: @CrisLuengo then it would be a bit faster than `setdiff` ....so maybe we can say that  `ismember` should be the most efficient one?
Comment: @Wolfie thanks for your benchmark template, I tried to run with different approaches and their variants, you can see the performance difference now... but I guess the speed may also be depending on the sizes of `Ntest`
Comment: @ThomasIsCoding thanks, yes in writing the benchmark I realised how dependent on the input size this problem is, which I didn't appreciate fully before. I'll test on my real data this afternoon, your appending method is likely an improvement
Comment: @Wolfie Yes, I think the major improvements comes from using `S(end + (1:length(X))) = X`. Good luck to your test!
Comment: That appending saves me ~18% on processing time, which is great! I'll hold out for any more answers as that doesn't actually address the union operation, and accept this if none come :)


Debounce operator breaks publisher in Combine

Question: Hi guys i have the following data model for registering a user in my app:
import Foundation
import Combine
import SwiftExtensions

class RegisterData {

    @Published var firstName: String = ""
    @Published var middleName: String = ""
    @Published var lastName: String = ""
    @Published var email: String = ""
    @Published var postcode: String = ""
    @Published var termsAggreed: Bool = false
    @Published var receiveNews: Bool = false
}

extension RegisterData: Publisher {

    typealias Output = Bool

    typealias Failure = Never

    func receive<S>(subscriber: S) where S : Subscriber, RegisterData.Failure == S.Failure, RegisterData.Output == S.Input {

        // works only if debounce transform is removed or moved after all combineLatest transforms
        let publisher = $firstName
            .combineLatest($middleName, $lastName) { !$0.isEmpty && !$1.isEmpty && !$2.isEmpty }
            .combineLatest($postcode, $email) { $0 && !$1.isEmpty && $2.isValidEmail }
            .debounce(for: .seconds(0.5), scheduler: RunLoop.main) // try to debounce only texts, but not working
            .combineLatest($receiveNews, $termsAggreed) { $0 && $1 && $2 }
            .removeDuplicates()
            .eraseToAnyPublisher()

        publisher.receive(subscriber: subscriber)
    }
}

I have a view controller with a couple of UITextFields and two UISwitches that populates an instance of this RegisterData class
I want to 'debounce' only the change of the properties that store Strings because they will be populated by the user from the text fields, but the way i am applying these transformations in func receive<S>(subscriber:) to come up with the Publisher that i need, makes it so that it does not send any new values. If i comment out the .debounce transformation it sends updates. If i put the .debounce transformation before .removeDuplicates() it sends updates, however it 'debounces' the booleans too.
How can i achieve debounce only for the Strings ?
I tried debouncing each one of them individually (lets say one of them holds potential username, that has to be checked on server if it is free, so i want to debounce the API call only on it) but it didn't work
Thanks in advance!
Comment: Perhaps your tests with individual debounce didn't work because you haven't declared `RegisterData` as `ObservableObject`?
Answer: The question is already old, but in case you didn't find a solution so far, perhaps the following is what you are looking for:
Your strings prefixed with $ are publishers in itself, therefore you can simply "debounce" them by applying the debounce operator on each of them.
Your code would look like the following:
let publisher = $firstName.debounce(for: .seconds(0.5), scheduler: RunLoop.main)
    .combineLatest(
        $middleName
            .debounce(for: .seconds(0.5), scheduler: RunLoop.main),
        $lastName
            .debounce(for: .seconds(0.5), scheduler: RunLoop.main)) {
                !$0.isEmpty && !$1.isEmpty && !$2.isEmpty
    }
    .combineLatest(
        $postcode
            .debounce(for: .seconds(0.5), scheduler: RunLoop.main),
        $email
            .debounce(for: .seconds(0.5), scheduler: RunLoop.main)) {
                $0 && !$1.isEmpty && !$2.isEmpty
    }
    .combineLatest($receiveNews, $termsAggreed) { $0 && $1 && $2 }
    .removeDuplicates()
    .eraseToAnyPublisher()

The code duplication is ugly, but perhaps you can make an extension for that.
Comment: Thanks for your answer, i haven't played with Combine in quite some time but soon i will find time to have a play again and check your solution


Google Datastore Use Select Query by ID using API in GAS

Question: I wish the Google API documentation was a little more newbie-proof.
I've worked my way through Selecting all entities, Updating an entity, inserting, and deleting. Now I would like to start selecting specific entities by criteria. The API https://datastore.googleapis.com/v1/projects/project-id-5200707080506492774:runQuery is for this purpose, and if I provide the payload of "query: {}" I get all entities. I can also filter by Kind. But I cannot figure out how to filter by a property. I try to get an entity by name with this JSON stringified payload:
var payload =

{
  "query": {
    "kind": [
      {
        "name": "Test"
      }
    ],
    "filter": {
      "propertyFilter": {
        "property": {
          "name": "id"
        },
        "op": "EQUAL",
        "value": {
          "stringValue": "5634472569470976"
        }
      }
    }
  }
}

But I get the 200 results batch:
{
  "batch": {
    "entityResultType": "FULL",
    "endCursor": "CgA=",
    "moreResults": "NO_MORE_RESULTS"
  }
}

AKA: Nothing was found.
Could someone enlighten me with regards to how to select by the entity's name/id or other field of data?

EDIT:
Here is the file structure of my entities. They are organized under the kind Test:
    {
      "batch": {
        "entityResultType": "FULL",
        "entityResults": [
          {
            "entity": {
              "key": {
                 "partitionId": {
                   "projectId": "project-id-5200707080506492774"
                 },
                 "path": [
                  {
                    "kind": "Test",
                    "id": "5634472569470976"
                  }
                ]
              },
              "properties": {
                "test": {
                  "stringValue": "Hi it is me"
                }
              }
            },
            "cursor": "CjsSNWogc35wcm9qZWN0LWlkLTUyMDA3MDcwODA1
                   MDY0OTI3NzRyEQsSBFRlc3QYgICAgN6QgQoMGAAgAA==",
            "version": "1503343869436000"
      },
      {
        "entity": {
           "key": {
            "partitionId": {
          "projectId": "project-id-5200707080506492774"
        },
        "path": [
          {
            "kind": "Test",
            "id": "5639445604728832"
          }
        ]
      },
      "properties": {
        "test": {
          "stringValue": "testtesttest"
        }
      }
    },
    "cursor": "CjsSNWogc35wcm9qZWN0LWlkLTUyMDA3MDcwODA1MDY0OTI3NzRyEQsSBFRlc3QYgICAgLyhggoMGAAgAA==",
    "version": "1503343008992000"
  },
  {
    "entity": {
      "key": {
        "partitionId": {
          "projectId": "project-id-5200707080506492774"
        },
        "path": [
          {
            "kind": "Test",
            "id": "5649391675244544"
          }
        ]
      },
      "properties": {
        "test": {
          "stringValue": "testtest"
        }
      }
    },
    "cursor": "CjsSNWogc35wcm9qZWN0LWlkLTUyMDA3MDcwODA1MDY0OTI3NzRyEQsSBFRlc3QYgICAgPjChAoMGAAgAA==",
    "version": "1503342946693000"
  },
  {
    "entity": {
      "key": {
        "partitionId": {
          "projectId": "project-id-5200707080506492774"
        },
        "path": [
          {
            "kind": "Test",
            "id": "5659313586569216"
          }
        ]
      },
      "properties": {
        "test": {
          "stringValue": "testtesttest"
        }
      }
    },
    "cursor": "CjsSNWogc35wcm9qZWN0LWlkLTUyMDA3MDcwODA1MDY0OTI3NzRyEQsSBFRlc3QYgICAgNrjhgoMGAAgAA==",
    "version": "1503343059530000"
  },
  {
    "entity": {
      "key": {
        "partitionId": {
          "projectId": "project-id-5200707080506492774"
        },
        "path": [
          {
            "kind": "Test",
            "id": "5715999101812736"
          }
        ]
      },
      "properties": {
        "test": {
          "stringValue": "hello world"
        }
      }
    },
    "cursor": "CjsSNWogc35wcm9qZWN0LWlkLTUyMDA3MDcwODA1MDY0OTI3NzRyEQsSBFRlc3QYgICAgLzVkwoMGAAgAA==",
    "version": "1503343819165000"
  }
],
"endCursor": "CjsSNWogc35wcm9qZWN0LWlkLTUyMDA3MDcwODA1MDY0OTI3NzRyEQsSBFRlc3QYgICAgLzVkwoMGAAgAA==",
"moreResults": "NO_MORE_RESULTS"
  }
}

Edit:
I completed a filter query to check against my test field, as requested, and got the below 200 response:
{
  "batch": {
    "entityResultType": "FULL",
     "entityResults": [
       {
         "entity": {
           "key": {
            "partitionId": {
               "projectId": "project-id-5200707080506492774"
            },
            "path": [
              {
                "kind": "Test",
                "id": "5715999101812736"
              }
            ]
          },
           "properties": {
              "test": {
               "stringValue": "hello world"
            }
           }
          },
         "cursor":
              "CjsSNWogc35wcm9qZWN0LWlkLTUyMDA3MDcwODA
               1MDY0OTI3NzRyEQsSBFRlc3QYgICAgLzVkwoMGAAgAA==",
          "version": "1503343819165000"
       }
     ],
      "endCursor": "CjsSNWogc35wcm9qZWN0LWlkLTUyMDA3MDcwODA1MDY0OTI3NzRyEQsSBFRlc3QYgICAgLzVkwoMGAAgAA==",
"moreResults": "NO_MORE_RESULTS"
  }
}

Comment: Do you have a `Test` entity with `id` `5634472569470976` and no ancestor?
Comment: The request looks correct. Is **id** a property of the entity or are you trying to search by entity key? If **id** is in fact a property, what is the data type? Just looking at the data (5634472569470976), it appears that it may be an Integer, but the filter is looking for a string type. Please double check/confirm.
Comment: I added my data structure from a kind query to my original post. Say I want to pull entity 5634472569470976 by its ID. How do I filter by it's key when the API only lets me filter by properties? Do I need to add a separate ID field just so I can pull by an ID?
Answer: At least in the ndb python datastore library id is not allowed as a property name. Which might be the reason your query is not working (as you expect) either.
After all you don't see any property named id within the properties structures of your entities, it is actually part of the key -> path structure.
Just to confirm, try using a valid property (i.e. one listed inside properties), for example:
"filter": {
    "propertyFilter": {
        "property": {
            "name": "test"
        },
        "op": "EQUAL",
        "value": {
            "stringValue": "hello world"
        }
    }
}

If you have the entity key ids you don't need to perform queries to get the entities (you might not even be allowed to do that inside transactions), you can directly pull the entities by keys, using the projects.lookup method. I think something along these lines:
{
    "keys": [
        {
            "path": [
                {
                    "kind": "Test",
                    "id": "5634472569470976"
                }
            ]
        }
    ],
}

Comment: Yep, I got a 200 success result, added to my original post. So how do I pull a transaction if I know it's entity ID in the key path but nothing else? Am I using the right method, or do I need to create custom ID's or something?
Comment: Thank you, Dan! I figured I was missing something.


Display words after numbers typed in

Question: I have a test question, where I was asked to write a simple program that reads in 2 integers (i.e one before the decimal point and one after it) and it is meant to display in words whether or not the number should be rounded up or not.
For Example:
Enter number between 1 and 5: 3
Enter number between 3 and 6: 5
3.5 was rounded up, it's now four

I can get most of it to work except the rounding up part. Please help me.
Below is my code and the output I get
import java.util.Scanner;
import java.util.Scanner;

public class Test {

    public static void main(String[] args) {
        Scanner in = new Scanner(System. in );
        System.out.print("Enter number between 1 and 5: ");
        int num1 = in .nextInt();
        System.out.print("Enter number between 3 and 6: ");
        int num2 = in .nextInt();

        System.out.print(EnglishName(num1, num2));
    }

    public static String EnglishName(int num1, int num2) {

        String numberInWords = "";
        String numberAndDecimal = "";

        if (num1 == 1) {
            numberInWords = "one";
        }
        if (num1 == 2) {
            numberInWords = "two";
        }
        if (num1 == 3) {
            numberInWords = "three";
        }
        if (num1 == 4) {
            numberInWords = "four";
        }
        if (num1 == 5) {
            numberInWords = "five";
        }

        if (num2 == 3) {
            numberAndDecimal = num1 + "." + num2 + " not rounded up its still " + numberInWords;
        }
        if (num2 == 4) {
            numberAndDecimal = num1 + "." + num2 + " not rounded up its still " + numberInWords;
        }
        if (num2 == 5) {
            numberAndDecimal = num1 + "." + num2 + " was rounded up, it's now " + (numberInWords + 1);
        }
        if (num2 == 6) {
            numberAndDecimal = num1 + "." + num2 + " was rounded up, it's now " + (numberInWords + 1);
        }

        return numberAndDecimal;
    }
}

Output:
Enter number between 1 and 5: 1
Enter number between 3 and 6: 3
1.3 not rounded up its still one

Enter number between 1 and 5: 3
Enter number between 3 and 6: 5
3.5 was rounded up, it's now three1

if I change the lines to
if (num2 == 5) {numberAndDecimal = num1 + "." + num2 + " was rounded up, it's now " + (num1 + 1);}
if (num2 == 6) {numberAndDecimal = num1 + "." + num2 + " was rounded up, it's now " + (num1 + 1);}

I get this output
Enter number between 1 and 5: 3
Enter number between 3 and 6: 5
3.5 was rounded up, it's now 3

Answer: OK, first of all: When you do (numberInWords + 1) you're adding an int to a String. So Java turns the integer into a string and concatenates them. That's how you get "three1" as an answer.
If you change the lines to
if (num2 == 5) {
    numberAndDecimal = num1 + "." + num2 + " was rounded up, it's now " +  (num1 + 1);
}
if (num2 == 6) {
    numberAndDecimal = num1 + "." + num2 + " was rounded up, it's now " + (num1 + 1);
}

the output will be 4 when you input 3.5; just not as words.
To translate numbers into words the translation to a string has to happen after potentially adding one. So the easiest solution would be to have a separate function which translates ints to Strings. Something like this:
public static String EnglishName(int num1, int num2) {

    String numberAndDecimal = "";

    if (num2 == 3) {
        numberAndDecimal = num1 + "." + num2 + " not rounded up its still "
                + translate(num1);
    }
    if (num2 == 4) {
        numberAndDecimal = num1 + "." + num2 + " not rounded up its still "
                + translate(num1);
    }
    if (num2 == 5) {
        numberAndDecimal = num1 + "." + num2 + " was rounded up, it's now "
                + translate(num1 + 1);
    }
    if (num2 == 6) {
        numberAndDecimal = num1 + "." + num2 + " was rounded up, it's now "
                + translate(num1 + 1);
    }

    return numberAndDecimal;
}

public static String translate(int num1) {

    String numberInWords = "";

    if (num1 == 1) {
        numberInWords = "one";
    }
    if (num1 == 2) {
        numberInWords = "two";
    }
    if (num1 == 3) {
        numberInWords = "three";
    }
    if (num1 == 4) {
        numberInWords = "four";
    }
    if (num1 == 5) {
        numberInWords = "five";
    }

    return numberInWords;
}

PS.: Please keep to Java coding conventions by naming your functions with names starting with lowercase letters. So in your case it should be something like englishName rather than EnglishName.
Comment: You're welcome. There are by the way other things that could be improved in your program; for example, I'd recommend using `else` in addition to `if` and maybe using `<` and `>=` for comparison rather than `==` in some places.
Comment: That worked perfect thanks. I now have to figure it out how to get it to returns the appropriate error messages when the user enter a wrong integer or else a letter.
Comment: while (!in.hasNextInt())
{
System.out.println("Invalid entry, please try again ");
in.next();
}
Comment: That line above will help me if the user enters a letter but how do I also include if a user enters an invalid number?
Comment: You could have a function `boolean checkNumber(int input)` which would test the number which was entered. All together it would look something like this: `while(true) {if(!in.hasNextInt()) {System.out.println("Invalid entry, please try again"); continue;} else {int input = in.next(); if(!checkNumber(input)) {System.out.println("The number you entered is invalid, please try again");} else { break; }}}`
Answer: Try this approach:
String num = num1 + "." + num2;
double number = Double.parseDouble(num);
int roundOffAns = (int)Math.round(number);

Comment: In any real scenario this would be a good idea, yes. It doesn't however solve the problem which lies in the order of execution and the concatenation of Strings.
Comment: you are right.My point was to tell her an optimized solution or an alternative.
Answer: When i ran the code with the correct fix at the bottom:
if (num2 == 5) {numberAndDecimal = num1 + "." + num2 + " was rounded up, it's now " + (num1 + 1);}
if (num2 == 6) {numberAndDecimal = num1 + "." + num2 + " was rounded up, it's now " + (num1 + 1);}

Enter number between 1 and 5: 3
Enter number between 3 and 6: 5
3.5 was rounded up, it's now 4
Comment: Yeah, but it's meant to write the word four not the number 4

Display words after numbers typed in


How to find $ker(A)$

Question: How can I find $ker(A)$ for
$A=
\begin{pmatrix}
2 & 1 & 1  \\
4 & 2 & 2 \\
3 & 0 & 1
\end{pmatrix}
$?
What does this represent?
Edit: OK, using the Hints i get
$2x+y+z=0$
$3x+z=0$
$y-x=0$
$y=x$
And now?
Comment: What does your textbook say about kernel?
Comment: Hint: kernel means the same as null space means the same as the solutions to $Ax = 0$
Comment: You have figured out that in order for a vector $\begin{bmatrix}x\\y\\z\end{bmatrix}$ to be in the kernel, you must have $x=y$.  From here, it is personal preference how you explicitly write the kernel, but a popular choice is to find a basis for it.  Can you come up with a set of linearly independent vectors such that they span the entirety of the kernel?  A way you can think of it is that $x$ and $y$ can be something, lets call it $c_1$ and $z$ can be something possibly different, call it $c_2$.  What does an element of the kernel look like then using $c_1$ and $c_2$ to describe it?
Comment: https://en.wikipedia.org/wiki/Gaussian_elimination
Comment: As an aside, $z$ will depend on $x$ as well, notice the third line means that $3x+z=0$ implying what, that $z=-3x$... so, we know even more specifics about the kernel in question
Answer: Straight from wikipedia:
$$\ker(A) = \left\{\mathbf{v}\in V : A\cdot \mathbf{x} = \mathbf{0}\right\}$$
In your case $V=\mathbb{R}^3$ so you want to find all vectors in the usual 3 space which make this true:
$$A\bf{x}=
\begin{pmatrix}
2 & 1 & 1  \\
4 & 2 & 2 \\
3 & 0 & 1
\end{pmatrix}\begin{pmatrix}x\\y\\z\end{pmatrix}=\begin{pmatrix}0\\0\\0\end{pmatrix}$$
The science here is getting $A$ to reduced row echelon form. If that reduced matrix is $B$, then $\ker(A) = \ker(B)$.
Answer: So before I answer this we have to be clear with what objects we are working with here. Also, this is my first answer and I cant figure out how to actually insert any kind of equations, besides what I can type with my keyboard. sorry!
We have
ker(A)={x∈V:A⋅x=0}
This means if a vector x when applied to our system of equations (Matrix) are takin to the Zero Vector. This question is interested in finding all such vectors that do this.
Let A=[(2,1,1),(4,2,2),(3,0,1)] denote the matrix given at the top of the post.
Now lets find the vector x, such that Ax=0.
Let x∈V, such that x=(x1,x2,x3)
Then
Ax=[(2,1,1),(4,2,2),(3,0,1)]*(x1,x2,x3)
Which row reduces too
[(1,0,1/3),(0,0,0),(0,1,1/3)|(0,0,0)]
That is x1=(-1/3)x3, x2=(-1/3)x3
So, x=(x1,x2,x3)=((-1/3)x3,(-1/3)x3,x3)=x3(1,1,-3)
Now we have
ker(A)={x∈V:A⋅x=0}=Span{(1,1,-3)}
Note, Span{(1,1,-3)}=a(1,1,-3), for all real numbers a. That is the same thing as x3(1,1,-3), I just replaced the x3 with "a" since they both represent any real number.
Comment: This site  uses MathJaX to format  maths. [Here](http://meta.math.stackexchange.com/q/5020/145141) you can find a basic tutorial.

How to find $ker(A)$


OpenCV resizing captured IPLImage?

Question: I'm trying to capture image with OpenCV and make it a stream and display in an user-interface. I've been using the following code to display the image:
OpenCVFrameGrabber grabber;
JLabel webCamScreen__ = null;

grabber = new OpenCVFrameGrabber("VIDEO IP-ADDRESS");
grabber.setImageHeight(webCamScreen__.getHeight());
grabber.setImageWidth(webCamScreen__.getWidth());

grabber.start();

while (true) {
    IplImage grabbedImage = grabber.grab();
    this.webCamScreen__.setIcon(new ImageIcon(grabbedImage.getBufferedImage()));

}

grabber.stop();

Captured image is displayed in JLabel-component and I'd like to resize the received image to fit inside the component. Image aspect ratio should be kept the same. Right now the received image overrides grapper's imageHeigth and imageWidth.
Comment: *"I'd like to resize the received image to fit inside the component"* So.. go for it. Or do you expect us to spoon feed the code to you? That's not how SO works. Make an attempt, and get back to us when you have a **specific** question.
Comment: For better help sooner, post a [MCVE] or [Short, Self Contained, Correct Example](http://www.sscce.org/).
Answer: Unless do you have a specific retrocompatibility issue, avoid using IPLImage which are deprecated from a long time.
Use Mat instead.
Comment: I have, so using something else but IPLImage is not possible. I tried using Mat but couldn't get it work.
Answer: I finally found the solution:
IplImage origImg = grabber.grab();
resizedImage = IplImage.create(webCamScreen__.getWidth(), webCamScreen__.getHeight(),
                        origImg.depth(), origImg.nChannels());
opencv_imgproc.cvResize(origImg, resizedImage);
this.webCamScreen__.setIcon(new ImageIcon(resizedImage.getBufferedImage()));

opencv_imgproc had a resize function by which I was able to resize the IPL-image.
Thank you for your help. :)

OpenCV resizing captured IPLImage?


How make work a Picker with an ObservedObject in SwiftUI?

Question: I'm trying to get a list of Datacenters from a Rest API and show them in a Picker, so the user can choose one. When I do it with a static list it works fine. However, retrieving the Datacenters dinamically seems not to work fine.
I'm using Xcode 11 (GM)
This is the Datacenter Object
struct Datacenter:Codable, Hashable, Identifiable{
    let id: String
    var location: String
}

This is the ObservedObject (it has the property datacenters that is an array of Datacenter objects)
@ObservedObject var datacenters_controller : DatacentersController
@State private var selectedDatacenter = 0

This was my first attempt:
Picker(selection: $selectedDatacenter, label: Text("Datacenter")) {
   ForEach(0 ..< datacenters_controller.datacenters.count) {
     Text(self.datacenters_controller.datacenters[$0].location)
   }
}

Swift complained with the following error:
ForEach<Range<Int>, Int, Text> count (4) != its initial count (0). `ForEach(_:content:)` should only be used for *constant* data. Instead conform data to `Identifiable` or use `ForEach(_:id:content:)` and provide an explicit `id`!

Then I switched to:
Picker(selection: $selectedDatacenter, label: Text("Datacenter")) {
   ForEach(datacenters_controller.datacenters) { datacenter in
      Text(datacenter.location)
   }
}

It "works" (no error), but the result is not the expected because although I can select a datacenter, it is not "stored", not shown in the Picker as selected.
Actual result

Expected result

Any idea? What I'm doing wrong?
Comment: Your post doesn't include the definition of `DatacentersController`. Perhaps the error is there. Did you remember to put `@Published` in front of `var datacenters` in `DatacentersController`?
Comment: Thanks for the answer. The DatacentersController works fine. When I click on the Picker Datacenter, I see the different Datacenters. The problem is that, although I select one, it is not shown after the selection
Comment: You say "The DatacentersController works fine", but you don't know why your view isn't working. So how do you know the controller works fine?
Comment: Because of two things. If I debug, I see that the variable DatacenterController.datacenters has the datacenters (obtained from the Rest API). And because if I click on the Picker, I see all datacenters, and I can select any of them. The problem is that after selecting one, I don't see it in the Form.
Comment: The error `ForEach, Int, Text> count (4) != its initial count (0)` (from your first attempt) seems likely to be caused by the `ObservedObject` changing without notifying. The problem in your second attempt is (as described by LuLuGaGa) that you have omitted the `tag` modifier from your pickable views. The type of `selectedDatacenter` must also match the type of whatever values you use as your tags (which presumably will be either `String` or `Datacenter`).
Answer: Here's a working example. The key is that selectedDatacenter needs to be the same type as Datacenter.id (in this case, String).
struct ContentView: View {
    @ObservedObject var datacenters_controller = DatacentersController()
    @State private var selectedDatacenter = ""

    var body: some View {
        NavigationView {
            Form {
                Picker(selection: $selectedDatacenter, label: Text("Datacenter")) {
                    ForEach(datacenters_controller.datacenters) { datacenter in
                        Text(datacenter.location)
                    }
                }

                // Just here for demonstration
                Text("selectedDatacenter (id): \(selectedDatacenter.isEmpty ? "Nothing yet" : selectedDatacenter)")
            }
        }
    }
}

Here's the supporting code
struct Datacenter:Codable, Hashable, Identifiable{
    let id: String
    var location: String
}

class DatacentersController: ObservableObject {
    @Published var datacenters: [Datacenter] = []

    init() {
        datacenters = [
            Datacenter(id: "ABQ", location: "Albuquerque"),
            Datacenter(id: "BOS", location: "Boston"),
            Datacenter(id: "COS", location: "Colorado Springs")
        ]
    }
}

Answer: I think you are missing tag on your picker:
Picker(selection: $selectedDatacenter, label: Text("Datacenter")) {
   ForEach(datacenters_controller.datacenters) {
     Text($0.location).tag($0)
   }
}

Apple docs on tag:

Sets the tag of the view, used for selecting from a list of View
  options.
Comment: It didn't work :( The result is the same. No error, I can see the datacenters after clicking on the Picker, but after selecting one, it is not "stored" or "shown" as selected.
Comment: FWIW, the `tag` is not needed. You only need if if you're not using whatever the collection is identified by.
Answer: In your second attempt, you need to use the tag modifier (as described by LuLuGaGa). You also need to change the type of selectedDatacenter to match. For example:
struct ContentView: View {
    init(_ controller: DatacentersController) {
        self.datacenters_controller = controller
        self._selectedDatacenter = State(initialValue: controller.datacenters[0].id)
    }

    var body: some View {
        NavigationView {
            Form {
                Picker(selection: $selectedDatacenter, label: Text("Datacenter")) {
                    ForEach(datacenters_controller.datacenters) {
                        Text($0.location).tag($0)
                    }
                }
            }
        }
    }

    @ObservedObject private var datacenters_controller: DatacentersController
    @State private var selectedDatacenter: String
}


How to Split a string via regular expressions and keep the pattern in output?

Question: I have some code here:
$testString = "text23hello54stack90overflow34test";
$testArray = preg_split("/[0-9]{2}/Uim", $testString);
echo "
".print_r($testArray)."
";

After execution of these commands i have an array containing:
{text, hello, stack, overflow, test}

And I want to modify it so i get:
{text, 23hello, 54stack, 90overflow, 34test}

How may I achieve this?
Answer: How about:
$testString = "text23hello54stack90overflow34test";
$testArray = preg_split("/(?=[0-9]{2})/Uim", $testString);
echo print_r($testArray);

output:
Array
(
    [0] => text
    [1] => 23hello
    [2] => 54stack
    [3] => 90overflow
    [4] => 34test
)

Answer: Using preg_replace():
$testString = "text23hello54stack90overflow34test";
$testArray = preg_replace("/([0-9]{2})/Uim", ', $1', $testString);

echo $testArray;
// text, 23hello, 54stack, 90overflow, 34test


Excel web add-in: How to detect ribbon click events?

Question: I am working with the Excel JavaScript API and I am trying to trigger an event when the user clicks on any ribbon button or tab, and get which button or tab was clicked, but I couldn't find a way to do it.
Can anyone help me?
Answer: This isn't a supported scenario in Office.js. Your add-in is running in a sandboxed environment (either within an IFRAME or an embedded browser, depending on the platform). Even in cases where the ribbon buttons are part of your add-in, the communication is one-way (clicking the button will trigger loading a page or firing a function from your add-in).
Comment: And Office.js is the only way to create an excel web add-in and interact with the document?
Comment: Office Web Add-ins and Office.js refer to the same thing, yes. This is the only cross-platform extensibility option today. Others such as VSTO have more options but only support the desktop version of Office for Windows
Comment: So, if I really need to implement this feature ( trigger an event when the user clicks on any ribbon button or tab, and get which button or tab was clicked), should I work with a VSTO add-in?
Comment: I'm not sure if you can intercept arbitrary ribbon button clicks using VSTO, I can only confirm that you cannot do this from a web add-in.