Apache Pig - ERROR 2118: For input string: "4f8:0:a111::add:9898"

Question: We recently upgraded the cluster to use Hadoop 2.0.0-cdh4.4.0.
After the change, we needed to reinstall pig, which used to work absolutely fine. After the installation as described here, the simplest HBase job does not get created.

raw_protobuffer = LOAD 'hbase://data_table' USING
  org.apache.pig.backend.hadoop.hbase.HBaseStorage('external_data:downloaded',
  '-limit=1
  -gte=0 -lte=1')
  AS (data:bytearray);

Which fails with the magical:

Failed Jobs: JobId    Alias   Feature Message Outputs
  N/A   raw_protobuffer MAP_ONLY    Message:
  org.apache.pig.backend.executionengine.ExecException: ERROR 2118: For
  input string: "4f8:0:a111::add:9898"  at
  org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigInputFormat.getSplits(PigInputFormat.java:288)
    at
  org.apache.hadoop.mapred.JobClient.writeNewSplits(JobClient.java:1063)
    at
  org.apache.hadoop.mapred.JobClient.writeSplits(JobClient.java:1080)
    at org.apache.hadoop.mapred.JobClient.access$600(JobClient.java:174)
    at org.apache.hadoop.mapred.JobClient$2.run(JobClient.java:992)     at
  org.apache.hadoop.mapred.JobClient$2.run(JobClient.java:945)  at
  java.security.AccessController.doPrivileged(Native Method)    at
  javax.security.auth.Subject.doAs(Subject.java:415)    at
  org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1408)
    at
  org.apache.hadoop.mapred.JobClient.submitJobInternal(JobClient.java:945)
    at org.apache.hadoop.mapreduce.Job.submit(Job.java:566)     at
  org.apache.hadoop.mapreduce.lib.jobcontrol.ControlledJob.submit(ControlledJob.java:319)
    at
  org.apache.hadoop.mapreduce.lib.jobcontrol.JobControl.startReadyJobs(JobControl.java:239)
    at
  org.apache.hadoop.mapreduce.lib.jobcontrol.JobControl.run(JobControl.java:270)
    at
  org.apache.pig.backend.hadoop23.PigJobControl.run(PigJobControl.java:160)
    at java.lang.Thread.run(Thread.java:744)    at
  org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MapReduceLauncher$1.run(MapReduceLauncher.java:257)
  Caused by: java.lang.NumberFormatException: For input string:
  "4f8:0:a111::add:9898"    at
  java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:492)     at
  java.lang.Integer.parseInt(Integer.java:527)  at
  com.sun.jndi.dns.DnsClient.(DnsClient.java:122)     at
  com.sun.jndi.dns.Resolver.(Resolver.java:61)    at
  com.sun.jndi.dns.DnsContext.getResolver(DnsContext.java:570)  at
  com.sun.jndi.dns.DnsContext.c_getAttributes(DnsContext.java:430)  at
  com.sun.jndi.toolkit.ctx.ComponentDirContext.p_getAttributes(ComponentDirContext.java:231)
    at
  com.sun.jndi.toolkit.ctx.PartialCompositeDirContext.getAttributes(PartialCompositeDirContext.java:139)
    at
  com.sun.jndi.toolkit.url.GenericURLDirContext.getAttributes(GenericURLDirContext.java:103)
    at
  javax.naming.directory.InitialDirContext.getAttributes(InitialDirContext.java:142)
    at org.apache.hadoop.net.DNS.reverseDns(DNS.java:85)    at
  org.apache.hadoop.hbase.mapreduce.TableInputFormatBase.reverseDNS(TableInputFormatBase.java:219)
    at
  org.apache.hadoop.hbase.mapreduce.TableInputFormatBase.getSplits(TableInputFormatBase.java:184)
    at
  org.apache.pig.backend.hadoop.hbase.HBaseTableInputFormat.getSplits(HBaseTableInputFormat.java:87)
    at
  org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigInputFormat.getSplits(PigInputFormat.java:274)
    ... 16 more

We suspected permissions to tmp folder but they seem to be fine (i.e. the job directory gets created with the pig runner (!) being its owner). Any suggestion what we might have missed would be much appreciated.
Comment: Looks like an IPv6 address to me - suggest you investigate disabling IPv6 functionality on your cluster
Comment: Thank you very much, @ChrisWhite, that was the right hint. If you could add this as an answer, I would be able to accept it.
Answer: Looks like an IPv6 address to me - suggest you investigate disabling IPv6 functionality on your cluster
Comment: The steps to disable it on Ubuntu can be found, for example here: http://www.rohitmenon.com/index.php/how-to-install-hadoop-on-ubuntulinux-mint/. Also, in my case I needed to remove IPv6 entries in /etc/resolv.conf.


find the torsion and the curvature of this curve... (it's horrible)

Question: Let's consider the following curve:
$\varphi(t)=\begin{cases}
(t,0,e^{-\frac{1}{t^{2}}}) & t>0\\
(0,0,0) & t=0\\
(t,e^{-\frac{1}{t^{2}}},0) & t<0
\end{cases}
 $
I have to compute the curvature and the torsión of the curve. Well first of all, I computed $\varphi',\varphi'',\varphi'''$ (it was horrible....). This curve is not parametrized by arc length, so I have two options
$i)$ Find that reparametrization
$ii)$ Compute $\varphi',\varphi'',\varphi'''$ and then use the formula for the torsión and curvature. (I computed $\varphi',\varphi'',\varphi'''$ and it was horrible....) But computing a cross product it's something worst than horrible... specially in this problema, I have to compute by three cases , $t<0 , t=0 , t>0$ I think that computing this kind of things it's stupid but it's a homework Dx ... someone knows some tricky way to do this?
Answer: When $t=0$, $\dot \varphi(0)=\ddot \varphi(0)=(1,0,0)$. (You can compute it by direct computation using definition of derivative.)
Thus its curvature is 0 and torsion is not defined.
Furthermore, You can see that $\varphi(t)$ is actually plane curve when $t>0$ or $t<0$. Therefore its torsion is $0$ when $t\neq  0$. Curvature can be computed by direct computation or...
Curvature formular for plane curve $y=f(t)$ is
$\frac{|f''(t)|}{(1+f'(t)^2)^{3/2}}$. In this case, $f(t)=e^{-1/t^2}$.
(You can derive this formular from $\gamma(t)=(t,0,f(t))$ and $\kappa=\frac{||\dot\gamma \times \ddot\gamma||}{||\dot\gamma||^3}$   )
Comment: I am also learning student. So please correct me if I'm wrong. Thank you.


IsMouseOver trigger doesn't work when using ShowDialog and borderless window

Question: I have two Windows for an application. One of them is MainWindow and the other is for settings. SettingsWindow opens when settings button is clicked by using ShowDialog and setting its Owner to MainWindow.
On the SettingsWindow I have a button at the very bottom of the window and it changes the color to red when IsMouseOver is True and blue for False. But it doesn't change when the cursor is over the MainWindow. The image is below to be clear. How can I fix this problem?
CASE: The cursor is out of SettingsWindow but it keeps the red color, no change.

Xaml code:
<Window x:Class="AltoSS.SettingsWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="SettingsWindow"
        Height="150"
        Width="360"
        WindowStyle="None"
        AllowsTransparency="True"
        WindowStartupLocation="CenterOwner">

  <Button Grid.Row="2" Content="KAYDET"
          FontSize="15"
          FontWeight="Bold"
          BorderBrush="Gray"
          BorderThickness="0,2,0,2">
    <Button.Style>

    </Button.Style>
  </Button>
</Window>

Comment: how are you triggering? share your xaml
Comment: Oh, sorry. I forgot it to add. I am gonna update the Q.
Comment: @jstreet, I want to make a borderless window. If the problem is AllowTransparency, how can I get through it?
Comment: That is not working. I also tried `ResizeMode="NoResize"` and `AllowTransparency="False"`, but it is still the same. `BorderThickness ` property doesn't effect when it is zero. `Resize` borders remains. I think the main problem is having a borderless window. No matter which values are used.
Comment: But we have a problem there again. If `Window.Show` method is used, it works well. I am confused about it. An expert can figure out it, I think.
Comment: I was able to reproduce it, but my guess is that you've found some sort of bug. When you use ShowDialog() but don't set the owner , and the dialog starts in a position outside the main window, it works. But when you set the owner or the dialog starts over the main window, it doesn't. I would guess that the IsMouseOver event gets lost due to the main window. I will do some more research ...
Comment: The .Show is going to work, because is non-modal, which means that the parent window is not tied to its child. ShowDialog, however, displays the window modally, meaning that you can't go to the parent window. But you should use the ShowDialog to get the expected behavior that you want
Comment: So does this mean it needs complex code to get a normally working trigger behavior using ShowDialog?
Comment: or...we can workaround this by implementing the Show behavior as it was a ShowDialog. We can block the call to Show until the window is closed and return control to the main window...I think this would work and is quite simple. But we haven't addressed the original bug, what do you think?
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/122435/discussion-between-ali-tor-and-forlani).
Answer: Alright, after doing some research, I couldn't find any logical reason for this to occur. It seems more like a bug to me. So if anyone knows exactly why this happens, let us know!
Anyway, I've come up with a workaround. Basically, we can use Show() and add some code to get closer to a modal behavior - like disabling the parent window until the dialog gets closed or the user has selected OK or Cancel for instance.
Example:
SettingsWindow settingsWindow = new SettingsWindow();
this.IsEnabled = false; //disables the main window
settingsWindow.Owner = this; // main window is the settings window owner
settingsWindow.Show();
settingsWindow.Closed += (o, e1) => { onWindowClosed(o,e1); }; // this is the close event

After subscribing for the settingsWindow closed event, we can now enable the parent window again when settingsWindow gets closed:
private void onWindowClosed(object sender, EventArgs e)
{
    this.IsEnabled = true;
}

Triggers will now work correctly and parent window gets disabled until its child is closed.
Comment: the problem is, that the dialog window is not part of the visual tree from main window. If you leave the window by moving the cursor, the property IsMouseOver and RoutetEvents (MouseLeave) aren't performed, because the mouse is not in window scope.

To get the bahaviour you like to have you must integrate your dialog into MainWindow (as workaraound) and toggle Visibilty for example to show/hide your dialog. If your mouse then leaves the bounds of your button the IsMouseOver property is performed.
Comment: I think you are right @Fabian , that is the reason for this to occur. It's a weird behavior though
Answer: I think you have to observe the mouse position manually. For this you could use the code behind posted by Peheje here.
I used this to program a working example. While leaving your window, the Button gets the correct style.
using System.Runtime.InteropServices;
using Point = System.Drawing.Point;

[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool GetCursorPos(ref Point lpPoint);

public bool IsMouseOverButton {
    get { return _isMouseOverButton; }
    set {
        if (value == _isMouseOverButton) return;
        _isMouseOverButton = value;
        OnPropertyChanged();
    }
}

public SettingsWindow()
{
    InitializeComponent();

    new Thread(() =>
    {
        while (true)
        {
            //Logic
            Point p = new Point();
            GetCursorPos(ref p);

            //Update UI
            Application.Current.Dispatcher.Invoke(() =>
            {
                double btnLeft = DlgWindow.Left;
                double btnRight = btnLeft + DlgBtn.ActualWidth;
                double btnBottom = DlgWindow.Top + DlgWindow.ActualHeight;
                double btnTop = btnBottom - DlgBtn.ActualHeight;

                IsMouseOverButton =
                    p.X >= btnLeft && p.X <= btnRight &&
                    p.Y >= btnTop && p.Y <= btnBottom;
            });

            //async wait (non blocking)
            (new ManualResetEvent(false)).WaitOne(100);
        }
    }).Start();
}

xaml
<Window x:Name="DlgWindow"
        DataContext="{Binding RelativeSource={RelativeSource Self}}"
        AllowsTransparency="True">

  <Button x:Name="DlgBtn"
          Height="50"
          VerticalAlignment="Bottom"
          BorderBrush="Gray"
          BorderThickness="0,2,0,2"
          Content="KAYDET"
          FontSize="15"
          FontWeight="Bold">
    <Button.Style>

  </Button.Style>
</Button>

Answer: This works for me: Define a style resource (for the button) under settings Window.Resources - This style then sets the new Template (a border), the default background as blue, and the IsMouseOver trigger to change it to red. Reference the style either explicitly for implicitly (both worked for me).
Link to small test project: https://1drv.ms/u/s!AhlMAmchX3R6nDJ1MXS6DxlRXtnA
<Window x:Class="IsMouseOverTriggerSecondWindow.SettingsWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:IsMouseOverTriggerSecondWindow"
        mc:Ignorable="d"
        Title="SettingsWindow" Height="170" Width="330">

    <Window.Resources>

        </Style>
    </Window.Resources>

    <Grid>
        <TextBlock Text="This is the settings window" />
        <Button Content="KAYDET" Height="30" VerticalAlignment="Bottom" Foreground="White" FontWeight="Bold" />
    </Grid>
</Window>

Comment: Thanks for trying to help. But in your project both Windows must be borderless. So you need to set `AllowsTransparency="True" WindowStyle="None"`. I know it is working with bordered windows. We need to work with borderless windows.
Comment: you're right. that does make a difference. If you only need to get rid of the border, then removing AllowsTransparency="True" resolves the issue, but i'm sure you have tried this already.
Comment: Setting only WindowStyle="None" doesn't work, at that situation resizing borders still remains. So `AllowsTransparency="True" WindowStyle="None"` or `ResizeMode="NoResize" WindowStyle="None"` have to be used


Create Newtonsoft.Json.Linq.JArray from another array with different structure

Question: I have first Newtonsoft.Json.Linq.JArray with this structure:
[
  {
    "Fields": [
      {
        "Value": "child",
        "Key": "Relationship"
      },
      {
        "Value": "Alex",
        "Key": "FirstName"
      }
    ]
  }
]

And another Newtonsoft.Json.Linq.JArray:
[
  {
    "Relationship": "child",
    "FirstName": "Alex"
  }
]

Is it real to turn second one to the first one? Have not much experience in c# and Linq.
Answer: To transform your first JSON sample to your second, you may use LINQ to JSON as follows:
// Parse (or load from a stream) the incoming JSON as a JArray
var array = JArray.Parse(jsonString);

// For each object in the array, query they Key/Value properties of each Fields[*] object and turn then into a single JPropery,
// then add those properties to a new JObject
var query = array.Select(i =>
    new JObject(i.SelectTokens("Fields[*]").Select(o => new JProperty((string)o["Key"], o["Value"]))));

// Create a new JArray from the query
var newArray = new JArray(query);

The trickest part is here:
i => new JObject(i.SelectTokens("Fields[*]").Select(o =>
    new JProperty((string)o["Key"], o["Value"])))

This expression:

Uses SelectTokens() to query all Fields[*] objects in the root array item;
then gets the "Key" and "Value" properties of each object;
then turns them into a single JProperty;
and finally combines the JProperty instances into a single JObject.

Note that, if one of the [*].Fields[*].Key properties is missing, the code above will throw an exception, so you might want to check for that.
Demo fiddle #1 here.
Similarly, to transform your second sample to your first, you can do:
var query = array
    .OfType<JObject>()
    .Select(o =>
           new JObject
           {
               {"Fields", new JArray(o.Properties().Select(p => new JObject{{"Key", p.Name}, {"Value", p.Value}}))},
           });

var newArray = new JArray(query);

Here I am using C#'s dictionary collection initializer syntax to initialize my JObject instances, which I can do because JObject implements IDictionary<string, JToken>.
Demo fiddle #2 here.
Comment: Thanks a lot for this brilliant answer.  Actually I asked to turn the second array into the first one, but even your example is enough for me to do it myself. Thanks again
Comment: @NickANV - updated to add reverse transform.


Store a client datetime into UTC in php

Question: When the client sends a string like:
2019-07-20T10:00+02:00

I want the API to store the datetime in a UTC DateTimeImmutable as:
2019-07-20T08:00

How can this be easily achieved?
new DateTimeImmutable('2019-07-20T10:00+02:00');

always stores it as 2019-07-20T10:00
Answer: You can change the timezone with the setTimezone method.
$dateTime = new DateTimeImmutable('2019-07-20T10:00+02:00');
echo $dateTime->format(DateTimeInterface::RFC3339_EXTENDED) . PHP_EOL;
// 2019-07-20T10:00:00.000+02:00
$dateTime = $dateTime->setTimezone(new DateTimeZone("UTC"));
echo $dateTime->format(DateTimeInterface::RFC3339_EXTENDED);
// 2019-07-20T08:00:00.000+00:00

Comment: works like a charm. I was hoping that it's possible with fewer lines of code, though. I may need to write a helper class then. Thanks!

Store a client datetime into UTC in php


Volume of Revolution of a Transformed Ellipse?

Question: I'm looking at an ellipse (a bunch of them actually) transformed by $h$ on the $x$-axis away from the center and rotated by an angle of $Q$ from the $xy$ axis.
I got the following equation: the $x$ is transformed as $(x + h)$ and the rotation is done by $x\cos Q + y\sin Q$ and $x\sin Q - y\cos Q$.
Now I want to try and find the volume of solid of revolution. I'm not quite sure where I should begin. Is it even possible to do this? Or should I do the integration for the new $x$ and $y$ axis?
Thanks!
Comment: Do you know [Pappus' theorem](https://en.wikipedia.org/wiki/Pappus%27s_centroid_theorem#The_second_theorem) on volumes of rotation?
Comment: Not quite familiar with it, so pardon if I say something a tad bit insane. But I'm having a bit of trouble visualising how it would apply to an ellipse that's been rotated and moved away from the centre. Would I use the same equation of A.d for the normal ellipse but add the transformations alongside it? Thanks!
Comment: As I understand it, you have an ellipse with semi-axes $a$ and $b$ (at arbitrary angular orientation), the center of the ellipse lies at distance $h$ from an axis of rotation $\ell$ that does not touch the ellipse, and you want the volume swept out under rotation about $\ell$. Assuming that's right, by Pappus' theorem, the volume is $(2\pi h)(\pi ab)$.
Comment: Hmm..well what about rotating the transformed ellipse across the x-axis? The shape should be different from an oblate spheroid, right? So i'd have to integrate it by hand?
Comment: It's not entirely clear to me what your picture is: Does the ellipse cross the axis of rotation (here, the $x$-axis), so that revolving "covers" part of the swept region more than once?
Comment: The ellipse is similar to this, https://commons.wikimedia.org/wiki/File:Rotated_ellipse.svg. So it does cross the x-axis. I don't know whether it covers the axis of rotation more than once, I think since it's in 3-d it wouldn't sweep the same area again. Though, I'm not quite sure to be honest, I only learnt about this very recently.
Comment: Ah; in that situation you can't apply Pappus' theorem, at least not without additional work. After the ellipse has made half a rotation about the $x$-axis, _part_ of it overlaps with a region already swept out; naive use of Pappus' theorem over-counts this overlap. Unfortunately, calculating the volume of overlap is a bit messy.
Comment: Ah, I see. In that case integration by hand is the way to go, I assume? But out of curiosity, where do i start by researching how i can calculate the overlap volume?
Answer: (I've changed notation to conform to the mathematics convention of spherical coordinates.)
For definiteness, the issue is that when the ellipse
$$
\frac{x^{2}}{a^{2}} + \frac{z^{2}}{b^{2}} = 1
$$
is rotated through an angle $\phi_{0}$ and revolved about the $z$-axis, the "profile" intersects itself after half a turn.

As indicated by the radial segments in the diagram, however, the volume swept out can be expressed conveniently in spherical coordinates. The unrotated ellipse satisfies
$$
\frac{\rho^{2} \sin^{2} \phi}{a^{2}} + \frac{\rho^{2} \cos^{2} \phi}{b^{2}} = 1,
$$
or after rotation by $\phi_{0}$ and rearrangement,
$$
\rho = R(\phi)
  = \frac{ab}{\sqrt{b^{2} \sin^{2}(\phi - \phi_{0}) + a^{2} \cos^{2}(\phi - \phi_{0})}}.
$$
The solid swept out by revolving about the $z$-axis is described by the inequalities
$$
0 \leq \theta \leq 2\pi,\quad
0 \leq \phi \leq \pi,\quad
0 \leq \rho \leq R(\phi).
$$
The volume swept out is
$$
2\pi \int_{0}^{\pi} \int_{0}^{R(\phi)} \rho^{2} \sin\phi\, d\rho\, d\phi
  = \frac{4\pi (ab)^{3}}{3} \int_{0}^{\pi/2} \frac{\sin\phi\, d\phi}{\bigl[b^{2} \sin^{2}(\phi - \phi_{0}) + a^{2} \cos^{2}(\phi - \phi_{0})\bigr]^{3/2}}.
$$
Offhand this looks elementary (i.e., "possible to evaluate in closed form"), but I don't see a good way of integrating.
Comment: So we used the spherical coordinates of the ellipse? Why couldn't we have used polar or cartesian coordinates? Isn't there another way to utilise them to take care of the are swept twice? If we couldn't have done so, how do we add a vertical translation across the x axis for spherical coordinates? for a general equation it'd be (x+h)^2, how would what translate to spherical coordinates? Thanks so much for the help!
Comment: Converting to spherical coordinates is just one approach, which happens to avoid the overlap issue. Accounting for the area of the overlap and integrating in Cartesian coordinates is another; I couldn't see a nice way of doing so, but didn't look especially hard. If you translate the ellipse away from the axis (but the ellipse still crosses the axis), spherical coordinates are probably not a good strategy.
Comment: So what would the overlap area look like? I'm sorry, but I'm having a bit of trouble visualising it. If I know it's shape I can probably integrate to find it. Thanks!
Comment: For the ellipse with its center on the axis, the overlap is swept by the curved diamond shape in the middle.
Comment: I see. since the intersection comes after half s turn would the shape swept out be three dimensional? How would I start by finding the volume of the area? Do I try to find a function whose solid of revolution produces that diamond like shape?


Choosing which download to have

Question: Is it possible to download ubuntu 16.04 for an i3 based machine which doesn't connect to the internet by first downloading to an amd based machine and then creating a bootable usb? (The download page detects the amd and starts to download the version for that, so I need to be able to choose one suitable for an i3 processor and get that one, I already have ubuntu on the amd machine).
Comment: To be fair, the versions are called "amd" and "i386", but the difference is really whether your machine is 32-bits (i386) or 64-bits (amd). Your i3 based machine is 64-bits, so the amd version is the one you need. [Here](http://www.ubuntu.com/download/alternative-downloads) is a page with all download links.
Comment: Ah - all is clear now - thank you so much for this answer. I will download the amd version then since the target machine (and the one I am downloading onto) are both 64 bit machines. Thanks for the prompt reply and clear explanation.
Comment: There are no versions "for amd" or "for intel". It is unclear what are you asking. "amd64" works on both Intel and AMD 64-bit CPUs.
Comment: Hi @Jos, you're free to post your comment as an answer. Then it can be [accepted](https://askubuntu.com/help/someone-answers) by Steve and you can earn some reputation. :)
Answer: AMD64 is just another name for the x86_64 CPU architecture. Points relevant to you:

Your CPU supports it. There a no 32bit-only Intel i3s.
It's faster than i386, often demonstrably.
Less relevant these days is that 64bit applications do use slightly more RAM. But you can have more directly addressable RAM. And RAM is cheap.

On balance, 64bit is the clear winner these days.
Get that, ignore that it says AMD in the arch name. It's just a name.

Choosing which download to have


Topology, Showing that two metric spaces are topologically equivalent

Question: Can someone verify if this is true?
$X=\left(-\frac{\pi}{2},\frac{\pi}{2}\right)$
 . $d$
  is the standard metric on $\mathbb{R}$
  and $d'(x,y)=d\left(\tan(x),\tan(y)\right)$
 . We want to show that $\left(X,d\right)$
  and $\left(X,d'\right)$
  are topologically equivalent. I will just show the case if U
  is an open set in $\left(X,d\right)$
  then U
  is also open in $\left(X,d'\right)$
 . Let $x_{0}\in U$
 . There exists $0<r\in\mathbb{R}$
  such that $B_{r}(x_{0})=\left\{ y\,|\,d(x_{0},y)<r\right\} \subseteq U$
 . Since $\tan(x)$
  is a monotonic function and continuous, there exists $0<r'\in\mathbb{R}$
  such that the the greatest $\delta>0$
  that satisfies $d(x_{0},y)<\delta\Rightarrow d(\tan(x_{0}),\tan(y))<r'$
  , is smaller than $r$
 . Since the function is monotonic $r'$
  exists. And therefore $B_{r'}^{'}(x_{0})=\left\{ y\,|\,d^{'}(x_{0},y)=d(\tan(x_{0}),\tan(y))<r'\right\} \subseteq B_{r}(x_{0})\subseteq U$
 . Therefore $U$
  is open in $\left(X,d'\right)$
 .
The part that I am not sure of, justifying the existence of r'
 . Is there a way of choosing r'
  more specifically ? Thanks!
Answer: I will just comment on this paragraph here:

Since $\tan(x)$ is a monotonic function and continuous, there exists
  $0<r′\in\mathbb{R}$ such that the the greatest $\delta>0$ that
  satisfies $d(x_0,y)<\delta\Rightarrow d(\tan(x_0),\tan(y))<r'$ , is
  smaller than $r$ . Since the function is monotonic $r'$ exists.

I don't know what you need $\tan(x)$ to be monotonic for, and I also doubt that monotonicity makes the argument about "the greatest $\delta>0$..." work. Let me know, if I just fail to understand your idea.
The way I think about it is:
I want to prove existence of an $r'$, such that
$$B'_{r'}(x_0)\subseteq B_r(x_0).$$
This means that whenever $d(\tan(x_0),\tan(y))<r'$, I must have $d(x_0,y)<r$. But this property is continuity of $\tan^{-1}(x)$, the inverse of tangent. Letting $v_0=\tan(x_0)$, and $w=\tan(y)$, I know by continuity of $\tan^{-1}(x)$ that there exists a $\delta>0$, such that
$$d(v_0,w)<\delta\Rightarrow d(\tan^{-1}(v_0),\tan^{-1}(w))<r,$$
which is the same as
$$d(\tan(x_0),\tan(y))<\delta\Rightarrow d(x_0,y)<r.$$
In the above, I can thus choose $r'=\delta$.
Comment: given an $\epsilon$ we can find $\delta$ from the continuity, so I was just trying to go back, I want to find a delta that is suitable for my $r$. I just had to look at the inverse function, I don't know why I didn't think about that. Thank you!


Inverse Function Theorem: Proving Global Invertibility.

Question: My question states: Prove that the following coordinate transformation is invertible everywhere, at all values of $(x, y)$ .
$$u = \arctan(x - y)$$
$$v = \sinh(3x) + 2\sinh(y)$$
That is x and y can be functions of both $u$ and $v$: (i.e. $x(u,v) = x, y(u,v) = y$ )
So, I say $$g(u,v) = (\arctan(x-y), \sinh(3x) + 2\sinh(y))$$ . The inverse function theorem says that g will be locally invertible near a specific point a iff its Jacobian Matrix, [Dg], is invertible at a.
So naturally, since I want to prove that $g(x,y)$ is invertible everywhere, I thought to show that [Dg] is invertible everywhere.
Since the Jacobian of $g(x,y)$ is a $2\times2$ matrix, it's clear that any matrix A equal to: \begin{bmatrix}a&b\\c&d\end{bmatrix}
is not invertible if $ad = bc$.
So, since my Jacobian is the matrix of partial derivatives, A is equal to:
\begin{bmatrix}(1/(1+(x-y)^2)&-1/(1+(x-y)^2)\\3cosh(3x)&2cosh(y)\end{bmatrix}
I naturally set up $$ad = bc: 2\cosh(y)/(1+(x-y)^2) = -3\cosh(3x)/(1+(x-y)^2)$$which, by simple multiplication, yields:
$$2\cosh(y) = -3\cosh(3x).$$
Now I don't have any experience with hyperbolic cosine functions but graphing
$$2\cosh(y) = -3\cosh(3x)$$
yields no solutions, which would prove that $g(x,y)$ is invertible everywhere. Proving it is difficult, though.
My question is: how do I prove that the system $2\cosh(y) = -3\cosh(3x)$ has no solutions for any $(x,y)$?
My apologies for the lackluster formatting; I'm new to math stackexchange and don't know a ton of coding.
Thank you in advance!
Answer: Just use the definition of cosh:
$$ cosh(z) := \frac{e^{z}+e^{-z}}{2} > 0 \Rightarrow 2cosh(y)+3cosh(3x) > 0$$
The image of the exponential function is always greater zero. This contradicts:
$$\exists x,y \in \mathbb{R}:2cosh(y)=-3cosh(3x) \Leftrightarrow 2cosh(y)+3cosh(3x) =0 $$


Error LNK2019 when compiling TwinCAT ADS program

Question: I get error messages from Visual Studio 2022 linker when compiling. After looking through similar issues on this forum and trying as many solutions as I can find, I still can't resolve the problem.
I am building a test program to test TwinCAT 3 ADS communications from an external C++ program. The sample code I am testing is from here:
https://infosys.beckhoff.com/content/1033/tc3_adsdll2/124823307.html?id=7185691884721905562
This is the beginning of my code:
<code>// Test program to read and write an ADS variable from/to TwinCAT

#include <iostream>
#include <windows.h>
#include <conio.h>

#include "C:\TwinCAT\AdsApi\TcAdsDll\Include\TcAdsDef.h"
#include "C:\TwinCAT\AdsApi\TcAdsDll\Include\TcAdsApi.h"

int main()
{
    long nErr, nADSPort;
    AmsAddr Addr;
    PAmsAddr pAddr = &Addr;
    ULONG lHdlVar, nData;
    UINT nIntToRead;
    char szVar []={"MAIN.nCounter"};

    // Open communication port on the ADS router
    nADSPort = AdsPortOpen();
    nErr = AdsGetLocalAddress(pAddr);
    if (nErr) std::cerr << "Error: AdsGetLocalAddress: " << nErr << '\n';

    // TwinCAT 3 PLC1 port = 851
    pAddr->port = 851;
</code>
The required library 'TcAdsDll.lib' is installed and referenced as instructed here:
https://infosys.beckhoff.com/content/1033/tc3_adsdll2/123108747.html?id=7769290066237179923
For every call to the TwinCAT library I get an error:
<code>Build started...
1>------ Build started: Project: ADSTest, Configuration: Debug Win32 ------
1>ADStest.obj : error LNK2019: unresolved external symbol _AdsPortOpen@0 referenced in function _main
1>ADStest.obj : error LNK2019: unresolved external symbol _AdsPortClose@0 referenced in function _main
1>ADStest.obj : error LNK2019: unresolved external symbol _AdsGetLocalAddress@4 referenced in function _main
1>ADStest.obj : error LNK2019: unresolved external symbol _AdsSyncWriteReq@20 referenced in function _main
1>ADStest.obj : error LNK2019: unresolved external symbol _AdsSyncReadReq@20 referenced in function _main
1>ADStest.obj : error LNK2019: unresolved external symbol _AdsSyncReadWriteReq@28 referenced in function _main
1>C:\Users\rainer.bars\Data\puppu\ADStest\Debug\ADSTest.exe : fatal error LNK1120: 6 unresolved externals
1>Done building project "ADSTest.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
</code>
I am out of ideas. I suspect the cause is something fairly simple, but my skills are not sufficient to solve this.
Any help is greatly appreciated.
Comment: "and referenced" did not work out for some reason.  When you change the setting, be sure that the comboboxes at the top of the dialog are correct.  Best to select "All Configurations" and "All Platforms" since you always need to link that library.
Answer: Make sure you are building the project for the same Configuration and Platform that you configured your linker input in the Project Properties.
Besides, you have to make sure your compiler is the same as the one used to compile the library (.lib) you are linking to.
Answer: Thank you for your help! Problem solved. The problem (apparently) was:
a) the library is 32-bit and I was trying to build a 64-bit solution
b) the library path that was referenced seemed to be faulty for some reason
Not sure what was the problem's root cause. Now I can't seem to replicate it.


Flutter; Sort List of Widgets

Question: I currently have a list of widgets
List<LessonItem> _lessons = [];

One Widget inside this list, added by the user should look like this
LessonItem('Bio', 'Mrs Pithan', 'A1.012', HourMinute('08', '00'),
        HourMinute('11', '50'), Colors.green), //lesson, teacher, room, from, to, color

Now I want to sort the list by a specific property from the widgets. How can I do that?
Thanks for any help!
Comment: Does this answer your question? [Dart comparison operators](https://stackoverflow.com/questions/55297580/dart-comparison-operators)
Comment: can you elaborate the property by which you want to sort...like time difference or so?..
by the way you can use sort() function with comapreTo function to get your target result. See here [Sort method](https://api.dart.dev/stable/2.13.0/dart-core/List/sort.html#:~:text=sort%20method%20Null%20safety&text=Sorts%20this%20list%20according%20to,must%20act%20as%20a%20Comparator.&text=The%20default%20List%20implementations%20use,compare%20if%20compare%20is%20omitted.)
Comment: The 'from' property in a 'ListItem' is kept inside another widget 'HourMinute' (two strings). I want to merge these two strings (in this example '08' and '00'), convert them to integers, then to minutes (first string * 60) and then compare them with the other widgets. Finally I want to reorder them from the lowest to the highest number.
Answer: I would try with the sort method in dart.
You choose a property you want to sort by, and then define how any two elements will be compared.
Here I'm comparing each element by id (smaller id would en up first after sort):
  _lessons.sort((LessonItem a, LessonItem b) => a.id - b.id);

In this case I'm sorting by name (with the compareTo() method from String):
  _lessons.sort((LessonItem a, LessonItem b) => a.name.compareTo(b.name));

You can find more detailed info and some examples in:
dart documentation
and
this helpful post
Comment: I had to wrap it inside an ```initState()```. Thanks for your help!
Comment: Yes, thanks,it looks good. Where can I insert this sort method? If I do it directly under the list, I get an error with my stateful widget. Do I need a new function for this?
Comment: Well, it depends in the structure of your widget. You generally should be able to call sort() right after you fill your list with items. So some questions i should ask are: 1) How does your code look? and 2) What error message are you getting?

Flutter; Sort List of Widgets


Findability test and the length of time it takes for a user to find an icon

Question: At a company I work for we want to find out how much time our users would need to find a specific icon in our UI. To accomplish this we plan to conduct a "Time to locate test" with users who are already familiar with our UI. However, as our company has not done much user testing in the past, we do not have any previous data to reference.
I'm wondering if there are any industry standards or rules of thumb that define a successful findability in UI design? Some approximate time frame?
Thank you all in advance!
Answer: I'd suggest that you consider doing either an eye-tracking study or 1:1 usability tests where you watch and record the user's mouse movements (and ideally get them to talk back as they work to let you know what they expect and what they are thinking). Either of these could be useful in helping you determine the findability of your icon.
There's a lot to consider here, of course... who are your users and what are they trying to do on this page? How frequently are they visiting this page, is this an "expert" interface - something they need to learn but will then be in frequently - first time users (who are likely to scan the page for "hooks" that are relevant to their needs), or something in between? How many possibly actions are there already on this page, how high is the priority of this one, how well are the options grouped with each other or with relevant info, and how far around the screen do their eyes need to travel to find each one? These are all things that might help determine how to test and how to design the page.
You can find some general standards about timing and user expectations across the web, including some Norman Nielsen articles on performance SLAs (these being more about time than space), and this somewhat more relevant piece discussing the very general "15 second rule," which may or may not apply to your context... but it's a place to start.
Comment: Hey, thank you for your answer, I appreciate it. We are testing an icon for expand and collapse sidebar of the application. Sidebar was already implemented in the UI but this will be the first time it will have expand / collapse feature. And yes, you could say it is kind of an expert mode (at least this is the idea of PM) when the sidebar is collapsed. It is expected that the experienced user will use it in collapsed mode and inexperienced user will use it expanded mode.
Answer: There is no hard and fast rule or industry standard for how long it should take users to locate an icon in a UI.
However, there are some general guidelines that can be used as a starting point. In this article  (https://www.nngroup.com/articles/powers-of-10-time-scales-in-ux/) Jakob Nielsen wrote that users should be able to find a target within a UI in 10 seconds or less. This guideline is based on the fact that users tend to lose focus and interest after this amount of time, and may become frustrated or give up altogether.


design a divide and conquer algorithm that takes O(n log n) determinations

Question: I am given a set of balls and my ultimate goal is to find if at least half of the set of balls are the same color. I can only pick two balls each time and determine whether they are the same color or not. so how to design a divide and conquer algorithm that takes O(n log n) determinations to solve this problem? if there anybody has any idea on this problem, thank you so much!
Comment: I think this question needs to be edited to include a better explanation of the word "query". Specifically, what are the capabilities and limitations of a query?
Comment: Thank you for your tips, I have made a little change, hope it is easy to understand right now.
Comment: @JasonLee Do you have a fixed number of colors? Can they be ordered in some way? Or only compared for equality.
Comment: Unfortunately, they can only be compared for equality...
Answer: Perhaps you can do it sort of backwards - if you don't know the answer in n(log n) comparisons, then less than half the balls are of the same color. Sort of merge-sort-group them...
r g r b r y r r  // worst case arrangement

rg rb ry rr
    ↓            // 3 * (n / 4) comparisons
rr gb rrr y
    ↓            // 3 * (n / 8) comparisons
rrrrr gby

Comment: Seems to be what I want, Thank you so much!
Answer: I assume that you can order the colors (e.g. you can just compute a hash for the color into integers which can be sorted; I cannot think of any data type that cannot be hashed). Then you can simply sort the balls by their color in O(n log n) time, and then sweep once through the sorted collection, and determine the runs of consecutive same-colored balls. Your answer is, whether the number of balls in the largest run is >= the number of balls.
Edit
The problem is actually O(n). Use a hash table with O(1) insertion for the n balls. Whenever you have it already in, increase the count on the element in the hash-table group, and keep track of the largest group count somewhere else.
You can even do an early exit whenever the max count reaches n/2, which should half the average run time on random sets.
Edit2
Sketch of an exemplary proof of O(n^2)
I strongly believe, that there is no O(n log n) solution when only equality comparisons are allowed. Look at the following example, which should yield true, there are exactly half As, the rest are all different:
First divide
n = 16
AAAAAAABCDEFGHIA
AAAAAAAB CDEFGHIA
AAAA AAAB CDEF GHIA
AA AA AA AB CD EF GH IA

now conquer. We need to find all groups in each conquer step, since each group could potentially be merged with another large group so that it is the majority of all groups.
In this example, int the left half A is clearly the winner, but we need one additional A in the right half. Since the right half does not have a knowledge of the left half in a divide and conquer setting, the right side also tries to find the largest group, ending with n/2 groups of size 1, before the final merge.
In the following notation I use a number before a letter to denote a found group of that size.
2A 2A 2A 1A1B 1C1D 1E1F 1G1H 1I1A  1+1+1+1 +1+1+1+1 =4+4 =8
4A       3A1B 1C1D1E1F  1G1H1I1A   1*1+2*1 +2*2+2*2 =3+8 =11
7A1B          1C1D1E1F1G1H1I1A     1*2     +4*4     =2+16=18
8A1B1C1D1E1F1G1H1I                        2*8            =16
                                           53
n log2 n = 16*4=64

On the right I note the number of comparisons needed to merge the groups. To merge a set with x groups and a set with y groups, you need O(x y) comparisons, needed when the two sets are disjunct (i.e. compare each group of one set with each one of the other).
53 comparisons are needed in this example, which is below the n log2 n of 64.
The comparisons on the left side behave very linear. If you analyze the pattern you get (for n>7)
Log2(n)-2+ Sum{i=0..Log2(n)}(2^i) = n/2 - 3 + Log2(n)

But wait, there is a square term at the right number of comparisons. Let's examine that. Each row (except the last merge) doubles the previous, and it ends with (n/4)^2 comparisons. This gives
Sum{i=0..Log2(n)-2}( (n/4)^2 (1/2)^i ) = 1/8 (n^2 - 2*n)

So, indeed, with this divide and conquer approach, our worst case number of comparisons is O(n^2), which seems logical. If all entries are different, and we only can test two for equality each time, we need to test each against each to find if there is really no pair.
Don't know if I miss something, but the problem seems for me to be not solvable in O(n log n) with divide and conquer when only comarisons are allowed.
Comment: Actually it is an algorithm question, so limited and restrict. I think you gave the proper solution in real-world project, Thank you anyway!
Answer: We can reduce your problem to following.
If the balls in the given set are grouped by colors, you wish to find if largest group is at least half the size of the set.

This is easier to solve recursively. (This problem is not defined for empty set, handle it separately.)
class Group { // with appropriate constructors
    int size;
    Color color;
}

Group findLargestGroupWithSameColors(Set<Ball> ballSet) {
    if (ballSet.size() > 1) {
        // Divide set into two (preferably equal) sets.
        Group first = recursive call on first half.
        Group second = recursive call on second half.
        if (first.color.equals(second.color)) {
            return new Group(first.color, first.size + second.size);
        } else {
            if (first.size > second.size) {
                return first;
            } else {
                return second;
            }
        }
    } else {
        return single element's color and size = 1
    }
}

Good luck
Comment: If you only ever return the largest group, I fear, that there are configurations, where you miss the largest group that may form by a subsequent merge of the smaller sets.
Comment: e.g. A B A B A C A C. On the 2 element sets (AB)(AB)(AC)(AC) your algorithm always returns the second element (2xB)(2xC), leaving out completely the As.
Comment: A little different from what I want... Thank you!


How to get previous months ranges in postgres

Question: I am trying to get date ranges of the last 12 months starting from now.
however as month's days are not the same, I am wondering if it is possible to compute those dates on database level or if I have to compute the values outside and pass them as variables.
for example we are in September I need
'september', ["2020-09-01 00:00:00+00","2020-10-01 00:00:00+00"]
'august', ["2020-08-01 00:00:00+00","2020-09-01 00:00:00+00"]
'july', ["2020-07-01 00:00:00+00","2020-08-01 00:00:00+00"]
'june', ["2020-06-01 00:00:00+00","2020-07-01 00:00:00+00"]
...

Answer: You can use date_trunc() with the month parameter to adjust for variations of weeks among months.
SELECT
  to_char(now() - series.n * '1 month'::interval, 'month') AS "month",
  tstzrange(
    date_trunc('month', now()) - series.n * '1 month'::interval,
    date_trunc('month', now()) - (series.n - 1) * '1 month'::interval,
    '[]'
  ) AS range_dates
FROM (
  SELECT generate_series(0, 11) AS n
) AS series

Produces:
'september',["2020-09-01 00:00:00+00","2020-10-01 00:00:00+00"]
'august', ["2020-08-01 00:00:00+00","2020-09-01 00:00:00+00"]
'july', ["2020-07-01 00:00:00+00","2020-08-01 00:00:00+00"]
'june', ["2020-06-01 00:00:00+00","2020-07-01 00:00:00+00"]
'may', ["2020-05-01 00:00:00+00","2020-06-01 00:00:00+00"]
'april', ["2020-04-01 00:00:00+00","2020-05-01 00:00:00+00"]
'march', ["2020-03-01 00:00:00+00","2020-04-01 00:00:00+00"]
'february', ["2020-02-01 00:00:00+00","2020-03-01 00:00:00+00"]
'january', ["2020-01-01 00:00:00+00","2020-02-01 00:00:00+00"]
'december', ["2019-12-01 00:00:00+00","2020-01-01 00:00:00+00"]
'november', ["2019-11-01 00:00:00+00","2019-12-01 00:00:00+00"]
'october', ["2019-10-01 00:00:00+00","2019-11-01 00:00:00+00"]

Comment: @bihireboris You should edit the question to post a table of results you're trying to produce. Also, in `generate_series(0, 3)`, you can change the `3` to a greater number and that will produce more weeks and ranges.
Comment: I need the months dates not the weeks, I edited the question to remove misleading part of weeks, I am trying to get the date ranges of last 12months
Comment: could you kindly take a look on the edit, I put the type of ranges I need


proper way to run conduit on top of siding

Question: I'm looking at running a new main line to upgrade my electrical service to 200 AMP and using some 2" metal conduit run horizontally for 12' on a sided house.  What's the proper way to do it?  This will have siding around it on the house
I'm worried mostly about flashing details.  Does the pipe need to be extended away from the wall?  Should I use blocking to hold the screws / pipe away from the wall so the siding can fully go underneath.  What attention should be paid to the screw holes?  Am I overthinking this?  Do the screw holes need to penetrate the siding, or is there a safe way to slide the siding around without causing water problems.
Comment: What type of conduit are we talking about here? Also, by "power main" do you mean some type of service conductor?
Comment: Yes as ThreePhaseEel asked. The type of conduit determines the spacing of support. Any type of steel conduit would only take 2 supports if spaced properly but PVC may need another support according to its listing. The type of support would be by approved means.
Comment: Hopefully that's more details.  The mechanical / electrical details I feel I've got down pretty well already.
Comment: We still need to know what type of conduit is being used (PVC has this habit of doing the worm on you if you don't fit expansion joints, and the fitment of expansion joints influences where the supports go)
Comment: Do you have the option to fit the conduit so that it's not where there will be siding?
Comment: Is this service feeder before the meter, after the meter, or after the first means  of disconnect. This would apply to the type of conduit I would recommend. I am also assuming you would be running this exterior to the flashing exposing this to sunlight.
Comment: Conduit is metal EMT.  We are between the companies line and the Meter box.  It is exposed to sunlight.

I have to go up over a door, and past a breezeway, so it's entirely where siding will go.  This keeps me 4' from my existing box which I'll be replacing when I upgrade from 100 Amp 20 breakers -> 200 AMP 40 breakers.  The old run went over my garage which the AEP engineer said needed to change.
Answer: Reading your question and comments I am assuming you are trying to install a service drop to a meter. In that case you would want it to be as short as possible and use GRC. I am not sure if you can read the image or not but if you use 2" GRC you can use that as an unsupported riser for the drop any other conduit you may wind up installing a support bracket. That's what I am trying to show you in the image below.

Remember I said it should be as short as possible. Generally what we try and do is get down to the meter and in this case install a 200A enclosed breaker. Then from there you can run to a main lug only panel and from there you can use any allowable conduit EMT, PVC, etc. Because it is exposed to sunlight over 10' on the exterior you need to factor in derating per NEC Article 310.15 (B)(3)(c). Also Article 310.15 (B)(3)(a) exception will allow you to use Type XHHW-2 insulation on you conductors and you do not have to derate.
Finally in your comment you mentioned an AEP engineer disallowed a run over the garage. Are you sure you have to move the meter? In the state I am in we are allowed to raise the service drop to meet overhead clearances.

These images are from the Oncor book which is our utility company in this state. I don't know which utility you are using or where you are but I am pretty sure they have something similar to this. If it were me I would make sure that the engineer would just allow you to readjust the drop to meet the modern clearances before I would start the project you are proposing.
Comment: Thanks,
 https://www.aepohio.com/global/utilities/lib/docs/builders/meter/2016_Meter_and_Service_Guide_091416nb.pdf which is what I must meet.  Looking at it, I can either go 10 feet vertical then 15 feet horizontal, or 30+ feet vertical to go over the roof.  The advantadge of the horizontal is I don't have to break through the eave.  It seems you're advocating for purely vertical.

Still doesn't answer my main question of flashing. Do I mount the conduit directly to the Tyvek, should I add aluminum behind for rain protection, or should I use blocking so the pipe is a few inches out.
Comment: I understand your question. The problem lies is you are asking if you should use flashing and then you ask if you should use blocking and if the siding should go underneath the conduit. So there's confusion on my part to visualize through text what is actually being asked. Maybe if you edited your question and attached a small sketch or a picture of the existing situation we as a group could give you a more complete answer. Thanks
Answer: If you are installing the siding after the service conduit I would consider attaching trim board to the framing and attach the conduit to the trim board.
Then flash the siding out over the trim board on the top for drainage and add J-channel on the underside of the trim board.
This is a little more obvious, maybe even objectionable depending on where it is mounted and who is looking at it, but it alleviates the problems with penetrating the siding or adding the siding after the service conduit.
I will post a picture of what I did on my outbuilding later.
Good luck and stay safe!


How can I launch a python program from the desktop

Question: I have written a python (3.8.5) program (TrackMyInvestments.py) using Tkinter (8.6.10). The program works fine. I want to be able to launch it from my Ubuntu 20.04 desktop. I have created a shortcut on the desktop. The code in the desktop "icon" is:
[Desktop Entry]
Comment=
VERSION=1.0
Encoding=UTF-8
Exec='/home/bushbug/TKinterFiles/TrackMyInvestments.py'
Icon=
Name=InvestmentTracker
StartupNotify=true
Terminal=false
TerminalOptions=
Type=Application

I have set the Permissions in the launcher's properties as Allow Executing as executable and entered chmod +x /home/bushbug/TKinterFiles/TrackMyInvestments.py in the Terminal.
When right clicking the icon I have "enabled" Allow Launching. This causes a "no-entry" sign to be shown on the icon. The problem is that when I double click the icon nothing happens. The .py file is in /home/bushbug/TKinterFiles while the desktop file is in /usr/share/applications and has a .desktop extension.
I have tried everything I could read up about creating desktop launch icons but cannot get the thing to work. Just as aside, I have a Gambas program with a desktop icon (Logbook.desktop) and when I enable its "Allow launching" the Gambas program launches so I am at a loss about the .py program.
Can anyone please help?
Kind regards.
Comment: Try in the .desktop file change the Exec=''/home/bushbug/TKinterFiles/TrackMyInvestments.py" to Exec=/usr/bin/python3    /home/bushbug/TKinterFiles/TrackMyInvestments.py
Comment: I think you should remove quotes from the `Exec=` line. The .desktop file format does not require quoting and the quotes may be mistakenly interpreted as part of the filename ("no entry" sign you mention may be a hint to this)
Comment: @yangmandi make it an answer. That is how to do it ;-)
Comment: @Rinzwind, thx.
Answer: Try in the .desktop file, change the Exec='/home/bushbug/TKinterFiles/TrackMyInvestments.py' to Exec=/usr/bin/python3 /home/bushbug/TKinterFiles/TrackMyInvestments.py
Comment: Or just add the appropriate shebang at the beginning of the .py file: `#!/usr/bin/python3`. Why do people omit this?
Comment: Thank you to all of you. yang mandi's advice worked perfectly. I cannot believe how much time I wasted trying to solve this. I will sleep happy tonight.
Comment: @raj, Yes, it's right but my answer is still working, I have tested it.
Comment: Of course it will work. But adding the appropriate "shebang" line at the beginning of a script (any script, not just Python one - it may be perl, Tcl, expect and so on...) is a "canonical" Linux/Unix method to make the script executable.


Play PS2 data on remastered PS3 game

Question: I have reading up on this online but I haven't found anything. Say I were to copy data from my PS2 memory card and transfer it to my PS3, using Sony's memory card adapter. Could I then use this data on a game made for the PS3? The game is Tomb Raider Anniversary, it has been re-made for the PS3 along with Legend and Underworld.
So could anyone confirm if I could play my PS2 save game on the PS3 version of the game?
Thanks very much.
Answer: Original PS2 and PS1 games running on the PS3 (this applies both to the disc versions and the downloadable versions from the PSN store) save and load to virtual memory cards on the system. If you use the adapter on your original memory cards, they'll transfer into these virtual cards and be usable by the original versions.
Remastered (i.e. HD) versions of PS2 games, however, use the PS3 save data format, and don't access the memory cards at all. So unfortunately, no, this won't work.
Comment: Thanks, I guess I will have to stick to my PS2 until I start playing one of them on PS3 to start with :)

Play PS2 data on remastered PS3 game


Why does my new garbage disposal drain poorly unless turned on?

Question: I've installed a new garbage disposal and noticed a problematic behavior: the new garbage disposal drains very poorly, unless it's turned on. I can barely even wash my hands without noticing a little water accumulation. When doing dishes I have to turn it on over 5 times to prevent undesired water build-up. What to do?
Comment: Please [edit] to show a picture of the drain plumbing from the garbage disposal.
Comment: Voted to re-open, (editing the picture in here is the correct way to get that done) but could you try another picture that shows the whole of the drain from the disposal to the wall, not mostly hidden behind the disposal?
Comment: I was about to but the question got closed.
Comment: Hey do you mind re-opening the question. I tried posting a new one to attach the image but he tells me that  a similar one already exists.
Comment: Closed questions can always be edited, @Ya. Deleted ones not so much, but you can always edit your closed question. As a matter of fact, the blue banner that tells you it's closed contains an _extra_ link for you to click to edit it in an attempt to get it reopened. You've been on SO and [unix.se] long enough, you should know that - it's all the same system...
Comment: The reason I tried closing this one because I've opened another one: https://diy.stackexchange.com/questions/284629/why-does-my-new-garbage-disposal-drain-poorly-unless-turned-on with more documentation. Never had to deal with this because I've never had anyone close out a question on me within a few hours just because they didn't get the requested info. Anyway to ease the confusion I propose that we delete this question and keep the other one open.
Answer: Turns out the new rubber 'flap' is too 'hard' and won't permit enough flow through. Broke it in a bit and it drains better now.
Comment: Are you talking about the upper rubber "flap" piece that goes in the sink drain?
Comment: Yes, edited for clarification
Comment: Interesting. I've never run into this issue, but I'll definitely keep it in mind should I ever have difficulties like this in the future. Glad you got it resolved! Please come back and click the check mark next to this answer to indicate that this was the solution to the problem. I think the system will make you wait 24 or 48 hours before allowing you do so.
Answer: This is typical of installing a garbage disposal, which drains lower than the sink drain did, without adjusting the plumbing into the drain pipes, and then expecting water to flow uphill into the drain.
Correction is typically either "don't have a disposal" (easy) or "break open the wall and put in a new sanitary Tee somewhat lower" (hard.) You can put a cleanout plug in the old sanitary Tee drain opening.


require() a custom package?

Question: I am trying to install an npm package from a custom registry through npm, in a project's build step, in TeamCity.
I create a build step with the following settings:
Runner type: Command Line
Step name: Install
Run: Executable with parameters
Command executable: npm
Command parameters: install
And have specified the custom registry in the .npmrc file:
registry=http://...

But, When I start the build, I get this error:

[16:29:20]    npm ERR! Linux 3.13.0-36-generic
[16:29:20]    npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm"
  "install"
[16:29:20]    npm ERR! node v6.6.0 [16:29:20] npm ERR! npm  v3.10.8
[16:29:20]    npm ERR! code E404
[16:29:20]    npm ERR! 404 Not found : @mohito/libsvc
[16:29:20]    npm ERR! 404
[16:29:20]    npm ERR! 404  '@mohito/libsvc' is not in the npm registry.
  [16:29:20]    npm ERR! 404 You should bug the author to publish it (or
  use the name yourself!)
[16:29:20]    npm ERR! 404 It was specified as a dependency of
  'm-api-server' [16:29:20] npm ERR! 404
...
Process exited with code 1

Why is npm not able to locate my @mohito/libsvc custom package?
Answer: Reinstalling TeamCity somehow made it work

require() a custom package?


How to reuse bats unit tests

Question: I'm looking forward to reuse code for bats unit tests on different environments. What I want to know if it's possible to have common @test code for both files
in one place.
My first unit test file is to be run on my development environment:
#!/usr/bin/env bats

load 'test_helper/bats-support/load'
load 'test_helper/bats-assert/load'

setup() {

    # Development environment
    PROJECT_PATH="/d/develop/myproject"
}

@test 'check project path' {
    cd $PROJECT_PATH
    run git fetch origin
    refute_output --partial 'fatal: not a git repository (or any of the parent directories): .git'
}

My second unit test file runs same test and is to be run on deployment or production environment:
#!/usr/bin/env bats

load 'test_helper/bats-support/load'
load 'test_helper/bats-assert/load'

setup() {

    # Production environment
    PROJECT_PATH="/var/myproject"
}

@test 'check project path' {
    cd $PROJECT_PATH
    run git fetch origin
    refute_output --partial 'fatal: not a git repository (or any of the parent directories): .git'
}

As you see code for test is the same and only change $PROJECT_PATH value on the setup function.
Thanks for taking your time to read this question.
Answer: There are several ways you could solve this:

Simply remove the setup function and set PROJECT_PATH outside the tests.
Set a sensible default (and overwrite that in development).
Make the PROJECT_PATH variable required (and make the test fail if it is not set).
If more tests require environment specific settings, set ENVIRONMENT outside the test(s) and set PROJECT_PATH depending on the value of ENVIRONMENT.

(Please note that only the setup function needs to be changed for this, the  check project path @test function stays as-is)
As talk is cheap and code speaks louder than words, here are some examples to demonstrate what I mean with each of these options:
Option 1. Set PROJECT_PATH outside the tests
Remove setup entirely and set PROJECT_PATH before calling BATS:
export PROJECT_PATH="/var/myproject"
bats ./my_test.bats

Option 2. Set a sensible default
Set the production value as a default and allow it to be set from outside the test:
setup() {
    PROJECT_PATH="${PROJECT_PATH:-/var/myproject}"
}

Option 3. Make PROJECT_PATH required
To abort and fail the test if PROJECT_PATH has not been set, replace your current setup with:
setup() {
    if [[ ! -v "${PROJECT_PATH}" ]]; then
        skip 'Required environment variable "$PROJECT_PATH" not set!'
        return 1
    fi
}

Option 4. Use ENVIRONMENT
Instead of depending on PROJECT_PATH directly, set an $ENVIRONMENT when calling BATS and set PROJECT_PATH based on that:
setup() {

    if [[ "${ENVIRONMENT}" == 'development' ]];then
        PROJECT_PATH="/d/develop/myproject"
    elif [[ "${ENVIRONMENT}" == 'production' ]];then
        PROJECT_PATH="/var/myproject"
    else
        skip "Unknow \$ENVIRONMENT: '${ENVIRONMENT}'"
        return 1
    fi
}

Conclusion
Which solution is the best depends on what your desired setup is. Of course, cross-overs between these solutions is also possible. I'll leave that as an exercise tot the reader...

How to reuse bats unit tests


Liquid in Clothes Washing Machine for balance?

Question: When my washer was brand new (not connected to any hoses), I noticed a liquid sloshing sound whenever I moved it around. The washer has been disconnected for about 2 years now and the liquid sloshing sound is still there, so I don't think this is water that has accumulated from washing clothes. I have done some research and I think that it is used as weight to help balance the washer as the drum spins around.
My questions are: what is this liquid, its true purpose, and will it freeze/expand if left in a non-climate-controlled location? I have moved the washing machine to a new storage location that is covered and sealed from the elements, but has no heating or cooling.
Comment: What make and model is your washer? If such a counterweight existed it would be readily apparent on a parts diagram or listed as a replacement part.
Comment: Either there was water left in the machine as a result of it being tested or the sound you hear is *like* liquid sloshing but not actually that - the dampers and/or springs could make a very similar sound. If there is water in it, freezing is unlikely to cause a problem if it is not restricted in its expansion.
Answer: The washers are shipped with water in them. The reason is that, at the factory, they have to test them before shipping. Which means you hook them up and turn them on. Washing machines don't drain 100% of the water from the drum, so what you're hearing is the remainder of that test. In most cases, it's probably 1-2 gallons.
The water doesn't hurt the machine(it's designed to hold this residual water, after all). As to freezing, if the water was frozen the liquid water it would add to start a new wash cycle would likely melt it enough to not harm the machine.
A Sears salesman confirmed this on their site

All washers are tested for leaks with water. It's not uncommon to find a slightly wet spot on the box. The spin basket also has a balance ring attached at the top which is half filled with water that you may be hearing sloshing around. This is normal and the balance ring is sealed to prevent the water from escaping. The balance ring is not likely leaking and the wet spot is likely from when the washer was tested.
Comment: For sure *1-2 gallons of water would leak* in transit!  I strongly believe that OP's case was about liquid in dynamic balancers, mentioned in other answers.
Answer: Usually the balance mechanisms are mechanical. Washers are shipped without drain hoses so any liquid in the bottom would drain out. If it is in a cold area you might want to remove the drain hose at the bottom or lay the hose flat on the ground and let it empty the bottom of the machine.
Answer: Many front loaders use a fluid dynamic balance system. They balance the drum at the higher speeds that front loaders spin. Since most of these systems are proprietary designs you would need to contact the manufacturer to find out the specifics for your particular model.
Answer: The  liquid sloshing sound is normal if your machine is a top loader. Some top loader washing machines are balanced with a liquid in the top of the inner tub. This liquid is a type of anti-freeze, so it will not freeze in cold conditions.


RBAC for kubectl and helm

Question: Can I create RBAC for kubectl and helm command. Requirement is particular set of user can only run kubectl describe command and other can run apply/create/delete command.
Comment: Yes, you define `Role`/`ClusterRole` objects and bind them to individual users and ServiceAccounts with `RoleBinding`/`ClusterRoleBinding` objects. It is described at length in the [Kubernetes documentation](https://kubernetes.io/docs/reference/access-authn-authz/rbac/).
Comment: Helm version 3 is a little friendlier than version 2 in this space: version 2 uses an in-cluster management component (Tiller) which needs [special RBAC setup](https://v2.helm.sh/docs/using_helm/#role-based-access-control), but in version 3 it just runs with the credentials and permissions of the user running the command.
Answer: Yes, you define Role/ClusterRole objects and bind them to individual users and ServiceAccounts with RoleBinding/ClusterRoleBinding objects. It is described at length in the Kubernetes documentation
When considering helm use v3. Helm version 3 is a little friendlier than version 2 in this space: version 2 uses an in-cluster management component (Tiller) which needs special RBAC setup, but in version 3 it just runs with the credentials and permissions of the user running the command.

RBAC for kubectl and helm


Error with extra arguments within VStack (SwiftUI)

Question: I am new to Swift/SwiftUI and I am running into an issue.
I have a VStack with several item in it, e.g. Text("1"), Text("2"), Text("3")… Text("13") and I am getting the error Extra arguments at positions #11, #12, #13 in call.
If I use just with few items, it works well.
The code looks like this
import SwiftUI

struct ContentView: View {
    var body: some View {
        VStack() {
            Text("1")
            Text("2")
            Text("3")
            Text("4")
            Text("5")
            Text("6")
            Text("7")
            Text("8")
            Text("9")
            Text("10")
            Text("11")
            Text("12")
            Text("13")
        }
    }
}

Thanks,
Santhosh
Comment: show us your code that replicates the problem/error. Did you do the tutorial at: https://developer.apple.com/tutorials/swiftui/ ?
Comment: You probably have too many items in your VStack, I think the limit is 10. Create sub views and divide your items between them.
Comment: @JoakimDanielson, Thank you, when using just 10 items it works. I guess the solutions is to use sub views as you mentioned.
Answer: The maximum number of items you can have on the same level (in this case within the VStack()) is 10.
In your specific example it would be Text("1") to Text("10").
If you need more, you can use groups. Now you can have 10 groups on the same level and each group can contain 10 items on its own.
E.g.:
VStack() {

    // Group #1
    Group() {
        Text("1")
        Text("2")
        Text("3")
        Text("4")
        Text("5")
        Text("6")
        Text("7")
        Text("8")
        Text("9")
        Text("10")
    }

    // Group #2
    Group() {
        Text("11")
        Text("12")
        Text("13")
        Text("14")
        Text("15")
        Text("16")
        Text("17")
        Text("18")
        Text("19")
        Text("20")
    }
}

So you are able to create 100 items (10*10). If you need more, you even can nest groups into groups.
E.g.:
VStack() {

    // Outer Group #1
    Group() {

        // Inner Group #1_1
        Group() {
            Text("1")
            ...
            Text("10")
        }

        // Inner Group #1_2
        Group() {
            Text("11")
            ...
            Text("20")
        }
    }

    // Outer Group #2
    Group() {

        // Inner Group #2_1
        Group() {
            Text("101")
            ...
            Text("110")
        }

        // Inner Group #2_2
        Group() {
            Text("111")
            ...
            Text("120")
        }
    }
}

Btw. If you want to create lists like that, you also can use a ForEach loop (instead of VStack() you also can use a List() element):
VStack() {
    ForEach(1..<14) { i in
        Text("\(i)")
    }
}

Or if you use an array, you can iterate over the array:
VStack() {
    ForEach(values, id: \.self) { value in
        Text("\(value)")
    }
}

Here we go with a full example:
//
//  ContentView.swift
//  SwiftTest
//
//  Created by Sebastian on 10.08.22.
//

import SwiftUI

struct ContentView: View {

    let values: [Int] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

    var body: some View {
        HStack {

            VStack() {
                Text("Groups")
                // Outer group
                Group() {
                    Text("1")
                    Text("2")
                    Text("3")
                    // Inner group #1
                    Group() {
                        Text("4")
                        Text("5")
                        Text("6")
                        Text("7")
                        Text("8")
                        Text("9")
                        Text("10")
                        Text("11")
                        Text("12")
                        Text("13")
                    }
                    // Inner group #2
                    Group() {
                        Text("14")
                        Text("15")
                        Text("16")
                        Text("17")
                        Text("18")
                        Text("19")
                        Text("20")
                        Text("21")
                        Text("22")
                        Text("23")
                    }
                }
            }

            VStack() {
                Text("ForEach with a defined range")
                ForEach(0..<14) { i in
                    Text("\(i)")
                }
            }

            VStack() {
                Text("ForEach with an pre-defined array")
                ForEach(values, id: \.self) { value in
                    Text("\(value)")
                }
            }
        }
    }
}

Best,
Sebastian


How to insert a CKEditor plugin in a Rails 3 app?

Question: I'm trying to use the wordcouter plugin for CKEditor. I was following along with this, but it doesn't seem to work. After poking around for a bit, I've discovered that there are numerous different config.js files and numerous plugin directories. Which one(s) am I supposed to use?
app/assets/ckeditor/plugins/
app/assets/ckeditor/_source/plugins/
app/assets/javascripts/ckeditor/plugins/
app/assets/javascripts/ckeditor/_source/plugins/
app/assets/javascripts/ckeditor/_source/core/plugins.js
app/assets/ckeditor/_source/core/plugins.js

When I unzip wordcount, it gives me a directory titled wordcount_1.05, am I supposed to rename this to just wordcount?
I'm typing the following into my config.js files:
config.extraPlugins = 'wordcount';

config.wordcount = {

      // Whether or not you want to show the Word Count
      showWordCount: true,

      // Whether or not you want to show the Char Count
      showCharCount: false
};

but this doesn't seem to do anything at all. If I modify it slightly (this only works in my app/assets/javascripts/ckeditor/config.js file) to make it:
CKEDITOR.config
then my text boxes stop displaying at all. So I feel like this is the correct file to be modifying.
Thanks for the help!
Comment: did you ever figure this out?  I'm running into the same problems
Comment: @scientiffic, I actually ended up completely scrapping the project and rebuilt it with Rails4. My best bet is that it was just some jumbled legacy code that wouldn't let me budge it. If you can start from scratch, salman's answer should work.
Comment: hm, that's not really an option for me, but thanks for the response.
Comment: @scientiffic, I didn't think that was an option for me either, but 2 years later here I am with a brand new app haha!
Comment: @XMLSlayer, Were you using the 'ckeditor' gem in this case? I seem to have run into the same problem
Comment: @PlagueHammer I was using every sort of ckeditor possible, which was probably the problem in the first place. I inherited the app from someone else, and they were using the gem, plus the plugin code in vendor, and public, and everywhere else imaginable.
Comment: I am having the same issue here and am unsure of where to put my plugin! I am using the gem 'CKEditor'. My folder structure is currently: app/assets/javascripts/ckeditor/config.js This is working, but unsure where to add the plugins folder!
Answer: Put the plugin directories in app/assets/javascripts/ckeditor/plugins/ (works for me in Rails 4.)
Comment: hey could you please provide the step by step info ?


How to get css animation to scale to appropriate screen size

Question: I'm trying to make an animation for a webpage I'm tinkering with at the moment. I want the animation of a ball to start from the bottom of the screen, go to the middle, then expand to the whole page. I'm having a problem when it comes to the expanding part. When it expands since I'm using transform: scale it expands beyond the width and height of the viewport causing me to scroll. How is it possible to make it fit into the viewport and not having to scroll. I tried putting it in a  container and putting overflow:hidden but it doesn't seem to work. Here is my code
    <!DOCTYPE html>

        <link rel="stylesheet" type="text/css" href="ballcopy.css">
        <meta name="veiwport" content="width=device-width, initial-scale=1.0">

    *, *::after, *::before {box-sizing: inherit;}

html{
    box-sizing: border-box;
}

body{
    margin: 0;
    padding: 0;
}

.ball{
    background-color: #eb8c28;
    width: 100px;
    height: 100px;
    border-radius: 0%;
    position: absolute;
    bottom: 0%;
    left: 50%;
    animation: rise;
    animation-duration: 2s;
    animation-iteration-count: 1;
    animation-fill-mode: forwards;
}

@keyframes rise{
    0%{
        border-radius: 50%;
    }
    50%{
        border-radius: 50%;
        transform:translateY(-400px);
    }

    75%{
        border-radius: 40%;
    }

    80%{
        border-radius: 30%;
    }

    90%{
        border-radius:20%;
    }
    100%{
        transform: scale(20,20);
    }
}
```

Answer: body{
  height: 100vh;
  width: 100vw;
  overflow: hidden;
}

this fixes it so that your animation doesn't overflow and make you scroll.
Answer: For overflow: hidden to work on main you need to set position: relative and a height:

*,
*::after,
*::before {
  box-sizing: inherit;
}

html {
  box-sizing: border-box;
}

body {
  margin: 0;
  padding: 0;
}

main {
  position: relative;
  height: 100vh;
  overflow: hidden;
}

.ball {
  background-color: #eb8c28;
  width: 100px;
  height: 100px;
  border-radius: 0%;
  position: absolute;
  bottom: 0%;
  left: 50%;
  animation: rise;
  animation-duration: 2s;
  animation-iteration-count: 1;
  animation-fill-mode: forwards;
}

@keyframes rise {
  0% {
    border-radius: 50%;
  }
  50% {
    border-radius: 50%;
    transform: translateY(-100%);
  }
  75% {
    border-radius: 40%;
  }
  80% {
    border-radius: 30%;
  }
  90% {
    border-radius: 20%;
  }
  100% {
    transform: scale(20, 20);
  }
}

Or you could set overflow: hidden on the body:

*,
*::after,
*::before {
  box-sizing: inherit;
}

html {
  box-sizing: border-box;
}

body {
  margin: 0;
  padding: 0;
  overflow: hidden;
}

.ball {
  background-color: #eb8c28;
  width: 100px;
  height: 100px;
  border-radius: 0%;
  position: absolute;
  bottom: 0%;
  left: 50%;
  animation: rise;
  animation-duration: 2s;
  animation-iteration-count: 1;
  animation-fill-mode: forwards;
}

@keyframes rise {
  0% {
    border-radius: 50%;
  }
  50% {
    border-radius: 50%;
    transform: translateY(-100%);
  }
  75% {
    border-radius: 40%;
  }
  80% {
    border-radius: 30%;
  }
  90% {
    border-radius: 20%;
  }
  100% {
    transform: scale(20, 20);
  }
}

Also, it's a good idea to set transform: translateY to a relative value so it's scalable to different screen-sizes as well, i.e. transform: translateY(-100%)
Comment: Great, thank you for the input, ran just what I wanted.
Comment: Just a quick question, let's say I wanted to have other elements on the page scrollable since the body would be overflow: hidden. is there any way I can put this animation in a container and it still work?
Comment: No problem @AlejandroVargas. If you set the containers height and `position: relative; overflow: hidden` it should work


KineticJS Container.getIntersections very slow

Question: I need to detect collisions in my HTML5 canvas (I'm using the KineticJS library), and thus far have used my own methods to detect if a certain point is within a certain shape.
I recently noticed that there's a method from the Container class, getIntersections(point) which should do exactly what I want. However it seems to be EXTREMELY slow, so when moving an object on the canvas and using the method for every new position, it becomes unusable.
Has anyone used this method for collision detection? If not, are there any tips on collision detection in a HTML5 canvas? I'm having trouble detecting if a point is inside a rectangle that is rotated by a certain amount of degrees.
Comment: can you make an example code? I have some usage of more than 10000 shapes with animation and its not slow using mouseover. I do hovever use many different layers and place the mouse events on the layer and put different shapes into different layers. (kineticjs 4.1.2 version)
Answer: I have used getIntersection() in a mobile game (a simulation for air traffic control) and it worked quite well given that it was called multiple number of times to detect a collision among all the existing planes in the game frame. In case you have to detect just one specific point, a possible solution could be to add a very small dummy rectangle for that place and get list of all objects intersecting with it and iterate over this list. Naming the objects of interest can speed up your condition verification.
Answer: I have noticed the same thing, getIntersections takes a long time. It is also called for mouse events etc. which makes it even worse.
I don't know how to make it faster, but one thing that affects the speed considerably is the number of Shapes you have on your stage. So one way to speed things up would be to remove unnecessary Shapes when they are not needed and bring them back dynamically when needed.
Comment: Thanks for your feedback. I've actually tried it with just 1 other shape in the layer, but it still slows the application down to the unusable.
Comment: Is this correct? I was under the assumption that on mouseover used the getIntersections and that is fast for that (see http://www.html5canvastutorials.com/labs/html5-canvas-interactive-scatter-plot-with-20000-nodes-using-kineticjs/)
Comment: @Jonke I based my comment to the fact that when I run Chrome profiler against my kineticjs project to see where it uses CPU time, it says Kinetic.Stage.getIntersection takes over 46%! When I click to open it to see where it is used, it displays three places: Kinetic.Stage._mousemove, _mousedown and _mouseup. Mousemove takes 45% so basically all of the getIntersection cpu time.
Comment: @pillar yes getIntersection does take CPU time but does it takes cpu time more than it should? (aka slow code)? I think that the OP uses getIntersection for a home brew collision detection and maybe he should override the current behavior when on mouse[move] so he don't fire getIntersection multiple times.
Comment: @Jonke According to this, yes it does: [link](https://github.com/ericdrowell/KineticJS/issues/150).
Answer: https://github.com/ericdrowell/KineticJS/issues/150
This is exactly what you need.

okay, to be clear, there are two ways to get an intersected shape
  based on mouse position:
1) getIntersection() - preferred 2) getIntersections() - very slow,
  and should be used for special situations
the getIntersection() method is blazingly fast, and returns an object
  containing information about the intersection point, such as a
  reference to a KineticJS shape if one is there, or pixel color
  information.
the getIntersections() method does the same thing, except that it
  iterates through and redraws every single node in the stage in order
  to return a collection of intersections that may have been layered on
  top of eachother.
99 times out of a 100, you're probably just interested in the visible
  intersected node which is at the top of nodes beneath it.
I've actually considered removing the getIntersections() method
  entirely, but haven't because there are some special situations when
  you actually do need a collection of intersections. At this time, I
  haven't been able to find a way to speed up getIntersections, although
  I'll keep looking into it.


Wiring new transformer

Question: Looking to replace my old transformer with a new 120V to 16V transformer to power a new smart doorbell. The new transformer has standard white, black, and green wires. Old transformer only had white and black.
The wiring of the old transformer confuses me. Here's a picture of the wires in the junction box: https://imgur.com/a/WkJNG9C

All 3 of the whites were pigtailed to the old transformer white.
The black was pigtailed to the old transformer black.
The 2 reds were not wired to anything?!
The ground was not wired (old transformer has no ground)

How do I safely wire my new transformer?
Update
I have a handyman with electrical experience looking into it right now. Here are some updates photos of interior: https://imgur.com/a/9VOzOqO

If the whites were all joined before, your detector is probably giving a false reading on the one it thinks is hot.

Actually, that white is just hot hot. Hopefully this guy can wire it up safely. He's going to be installing an actual electrical box inside the wall to hold all of the wires, which I believe a few of y'all said should be done. I'm not sure what he's planning on doing about the hot white - for now he's just put a cap on it.
Comment: Usually the recommendation is to wire the new as the old one was.  Ground is just for your safety, so ground to ground.   The problem is with the extra wires.  White should always be paired with a black or a black and red.  Two extra whites and two reds without two blacks is odd(except for conduit, which you do not seem to have).
Comment: First for safety sake,  consider a new junction box. what you have is a box extension .
Comment: Will need to take that (code-violating fire-hazard) mess apart and see what's going on behind it. Is there a box buried back there with some wires "lost to view?" Seems likely as no cables come into the visible box extension from there, but wires do. In any case, it needs to be fixed. If the whites were **all joined before**, your detector is **probably** giving a false reading on the one it thinks is hot.
Comment: With my death stick voltage tester: The top red wire is hot, and one of the white wires is hot.
Comment: Thanks for the responses. I've gotten a few different quotes from handymen & electricians: one for $200 and one for $400. $400 seems high... but I'm not sure. I want this fixed right. What ballpark should I expect? Or tough to provide an accurate quote without more info?
Comment: The latter. We can see that something is *very* wrong here, but how deep the rabbit hole goes (and thus, how long it will take to fix it right) is anyone's guess. "Normally" you just hook the transformer up the way it was before, plus use the ground wire. But **normally** does not involve opening a box and finding a glaring code violation/hazard.
Comment: Thanks, FWIW, edited my question with a short update.
Comment: Can you post the picture you took before disassembling? You did take one?
Comment: I unfortunately don't have a picture, but I tried to summarize what I saw in my original post. I should've taken a photo.
Answer: I can tell from the drywall work that this isn't a "finished" space in the home.  And they were kind enough to screw down that board, so I would de-energize this stuff and take it apart and see what's behind it.
I'm guessing maybe the last guy did that abortion with the wood because they had a 4"* octagon box extension box, but the box in the wall was 4x4 or a Handy-Box.  If so, great - we can just get a 4x4 extension  either for 4x4 or for Handy-Box, and mount the transformer on the 4x4 lid or on a side KO.
If it's just a bunch of cables flopping around, then we would need a box big enough to land all the cables in appropriate cable clamps (e.g. there are cable clamps into a 1/2" knockout for almost any wire type) and then mount the box physically.  Then the transformer can go on the lid or a knockout.

* And what the BLEEP is up with octagon box sizes? You notice they have "major sides" and then "corner clips" like paper on Battlestar Galactica (2004). To get the actual trade size, you have to measure across the diagonal "corner-clips".  You will get 3-1/2" or 4", which are box sizes (4" is far more common).  If you measure across the flats, the measurement will be 1/2" shy of correct. That's an easy way to get 3-1/2 and 4" boxes confused.
Comment: Thanks for the answer. Also, there's no box in the wall - see my update on my original question. I have a handyman installing a new box right now.

Wiring new transformer


How to group records in CoreData by column value?

Question: I have the next table in CoreData entity:
`title`
`description`
`category`

Now I want to group all records by category. For example:
("A", "B", "Cat")
("C", "D", "Dog")
("E", "F", "Cat")

I want to get them in a dictionary like: [Category: [Items]]
Where Category is struct like (title, description) and Items is my above described structure like (title, description, category).
So as a result I want to get dictionary
[Category("Cat"): [Items("A", "E")], Category("Dog"): [Items("C")]]

How can I do that in Swift?
I've tried to do with distinct but I've got wrong results there.
Comment: You could use `Dictionary(grouping:by:)` https://developer.apple.com/documentation/swift/dictionary/2919592-init. If you want to display in a `UITableView`, you could use a `NSFetchedResultsController` with the `sectionNameKeyPath` set to your `category`
Comment: Nice @Adrian, I learned something new today. :) .
Comment: Not the "silver bullet" you're looking for, but you could use a sort descriptor to get the results sorted by category and then enumerate that and build the groups yourself.
Answer: Based upon your example with limited info re: what your data model looks like, I would take whatever entity array you've got and create a dictionary  using Dictionary(grouping:by:), as referenced in my comment.
Assuming an Core Data entity with the attributes you reference, you would create a dictionary as follows:
let dictionary = Dictionary(grouping: entityArray) { $0.category }

This assumes you've got an array of entities with a title, description, and category properties.
Comment: Where should this code be used? Should I change Codegen of CoreData entity to Manual/None or Category/Extension, create a subclass and put this code there?


How to wrap a span around the 'PM' and 'AM' in a string?

Question: I want to wrap a span around the AM or PM in a time string. For example:
between 10:00AM and 14:00PM

becomes:
between 10:00AM and 14:00PM

Any clue on how to get the replace method to do this?
Answer: I think a simple replace() would do it:
$('.time').each(function() {
  var newMarkup = $(this).html().replace(/AM/g, 'AM')
                                .replace(/PM/g, 'PM');

  $(this).html(newMarkup);
});

Inspired by: Fastest method to replace all instances of a character in a string
Comment: @Marcel, I'm pretty that IS a regex. :)
Comment: Alternatively, you can add the spans with 'suffix' class beforehand, and then test for AM/PM existence in the markup and call jQuery's addClass('am') or addClass('pm') on the span.
Comment: Uhm, yes, you're right. :) But `.replace('AM', 'AM', 'g')` doesn't use a regex, which is rather costly (but perhaps the JavaScript engine does internally use one).
Comment: it IS a regex! at least the /AM/g part. if you wanted to make it case insensitive you could add an i. for example /AM/gi would make it match AM or am.
Comment: Regarding the costly comment, I wouldn't totally disagree - that's why I provided an alternative idea that only applies CSS classes, instead of manipulating the DOM.
Comment: Can manipulate the DOM though any other means that JS, no access to HTML, so this answer is the right one as is.
Answer: Could you capitalize the am/pm class names? In that case this would be a solution:
$('.time').html(function(i, v) {
    return v.replace(/(AM|PM)/g, '$1');
});

Live demo: http://jsfiddle.net/pVWh6/

How to wrap a span around the ‘PM’ and ‘AM’ in a string?


how to set different color every bar ApexChart

Question: I'm using ApexChart for a project, and I want to set different colors for each bar. I pass the data array and the color array to the component, based on the color array index the relevant data bar should be colored.
Current implementation as below, I tired colors: method but it only gets the first color of the color array.
const options: ApexOptions = {
    chart: {
        height: 200,
        type: 'bar',
        offsetY: 16,
        toolbar: {
            show: false,
        },
    },
    plotOptions: {
        bar: {
            horizontal: true,
            barHeight: '85%',
        },
    },
    dataLabels: {
        enabled: false,
    },
    xaxis: {
        position: 'top',
    },
    yaxis: {
        show: false,
    },
    grid: {
        padding: {
            top: 0,
            right: 0,
            bottom: 0,
            left: 0
        },
    },
};

const series = [
    {
        data: exampleChartData.data || [],

    }
];

return (
    <Chart
        options={options}
        series={series}
        type="bar"
        height={740}
        className="apex-charts"
        dir="ltr"
    />
);

Answer: You need to add distributed: true option inside bar key of plotOptions as well as adding the colors option as array. You can take a look at this stackblitz for a live working example. And your final code will be like this:
const options: ApexOptions = {
    chart: {
        height: 200,
        type: 'bar',
        offsetY: 16,
        toolbar: {
            show: false,
        },
    },
    plotOptions: {
        bar: {
            distributed: true, // this line is mandatory
            horizontal: true,
            barHeight: '85%',
        },
    },
    colors: [ // this array contains different color code for each data
        "#33b2df",
        "#546E7A",
        "#d4526e",
        "#13d8aa",
        "#A5978B",
        "#2b908f",
        "#f9a3a4",
        "#90ee7e",
        "#f48024",
        "#69d2e7"
    ],
    dataLabels: {
        enabled: false,
    },
    xaxis: {
        position: 'top',
    },
    yaxis: {
        show: false,
    },
    grid: {
        padding: {
            top: 0,
            right: 0,
            bottom: 0,
            left: 0
        },
    },
};

const series = [
    {
        data: exampleChartData.data || [],
    }
];

return (
    <Chart
        options={options}
        series={series}
        type="bar"
        height={740}
        className="apex-charts"
        dir="ltr"
    />
);

Comment: Nice and solid, Thanks for the answer. I also used  distributed: true but the graph was suddenly disappeared  from the canvas, just check and found some html issues, fixed all and good now.
Comment: This was what I was missing also thanks. Just wanted to add that for my project I had legends added when setting distributed: true, I have labels I need on the Y axis. So I checked the API and indeed there is a simple option to add:

legend: {
      show: false,
    }


Why do anti-mold products avoid stating it kills mold?

Question: I've noticed almost all products for treating mold/mildew say something like "mold stain remover", rather than indicating they can actually kill the mold/mildew.
I'm wondering, are these products generally reliable?  I imagine the product is intended to kill mold/mildew, but they have to avoid stating this specifically to avoid litigation for damages.
Or are they misleading shams that do nothing more than remove stain without actually doing anything to treat the mold?
I am avoiding naming specific products, since it seems a pretty common pattern in these products.  I would imagine there's a broad reason for this pattern in how they describe their product.
Usually if I evaluate an off brand medicine, I would look at the active ingredient and do some searching on that ingredient to determine its efficacy, and that clears up any doubts about what it actually does.
Answer: Products that remove mold stains are generally cleaning products, not designed to deal with the mold spores. Killing the spores, in a meaningful sense, involves specific products to kill spores (like this one).
The reason why you need a spore killer specifically, is that cleaning surfaces (like with bleach) can kill the mold on the surface, however it does not prevent mold regrowth. So you can bleach a surface and still have mold come back and be just as bad as it was before.


Dimension Theorem and Understanding Nullspace and Range in regards to 1-1 and Onto

Question: My understanding of this topic is incredibly limited, and for now I'd just like some short explanations that might clear up the confusion I'm having with this topic:
From my understanding, given a linear map $T:V\to W$ where V is finite dimensional, Dimension Theorem says $\dim(N(T)) + \dim(R(T)) = \dim(V)$, where $N(T)$ is the nullspace of $T$ and $R(T)$ is the range of $T$. Given a basis, we can find the basis of the nullspace by finding where the basis gives the output of $\vec O_v$.
One thing I don't understand is if we find a basis that gives us this, what is the dimension of $N(T)$? In order to find the dimension of the range, we just take the number of other basis that $\not=$ the basis for the nullspace. Once we have both of those, we add them up to get the dimension of $V$.
Comment: One of my questions was finding the dimension of N(T), and the second was just confirmation if my line of understanding was correct.
Answer: I am not sure what do you mean by "we can find the basis of the nullspace by finding where the basis gives the output of $\vec O_v$". The null-space
$$N(T)=\{ v \in V \mid T(v)=\vec 0_W \}$$
is a set of all vectors mapped by $T$ to zero vector; these vectors form a vector subspace of $V$. If we take basis $e_1,\ldots,e_k$ of $N(T)$ and extend it with vectors $e_{k+1},\dots,e_n$ to the basis of the whole space $V$, it turns out that
$$T(e_{k+1}),\ldots,T(e_n)$$
is a basis of $R(T)$. Indeed, these vectors span $R(T)$ since every vector $v \in R(T)$ can be written, for some scalars $\lambda_1,\ldots, \lambda_n$, as
$$ v = T(\lambda_1 e_1 + \cdots + \lambda_n e_n) = \lambda_{k+1} T(e_{k_1}) + \cdots + \lambda_n T(e_n)$$
since $T(e_1)=\cdots = T(e_k) = 0$. On the other hand,
$$\lambda_{k+1} T(e_{k_1}) + \cdots + \lambda_n T(e_n) = T(\lambda_{k+1} e_{k+1} + \cdots + \lambda_n e_n) = \vec 0_W$$ implies $\lambda_1 = \cdots = \lambda_n = 0$, otherwise $\lambda_{k+1} e_{k+1} + \cdots + \lambda_n e_n$ would belong to $N(T)$. Thus vectors $T(e_{k+1}),\ldots,T(e_n)$ are also linearly independent.
Answer: Without knowing other information of a linear map $T:V\to W$ than linearity itself, one cannot tell what is the dimension of $N(T)$.
In the proof of the rank-nullity theorem ("Dimension Theorem" you call), one does not find what is the dimension of $N(T)$.   What one does is assuming $\dim N(T)=m$ for some nonnegative integer $m$ and show that $\dim(R(T))=\dim(V)-m$.
The "Dimension Theorem" tells you a relation between $\dim N(T)$ and $\dim R(T)$ but not what specific numbers they are.
Comment: Sorry, I was just conjecturing further if we had information such as the basis for V, etc.
Comment: As I said in the answer, one *cannot* know the dimension of $N(T)$ in general if one only knows $T$ is a linear transformation, no matter what information you have about $V$.