What is the most effective way to destroy an MCOM in Bad Company 2 with C4?

Question: When using C4 to destroy an MCOM station in Bad Company 2, what is the most effective way to destroy the target? Does it make a difference if you plant all the charges at once and blow them, or is it more effective to plant them individually?
Does it matter where you plant them on the target? For example, I find that if I plant them in the room around the target, I can get a wider explosion and sometimes catch enemy soldiers in the explosion, too, but I'm not sure if this is making a difference in how much damage I'm doing to the target itself.
Answer: I would suggest planting as many as possible before triggering them. Your chances of dying before re-planting are high, so you may not get a chance to re-plant. Also, if you die while planting C4, your C4 will stay there, and your team or the enemy may set off your C4, which will still give you points for MCOM damage and any resulting enemy deaths.
It is very common for your C4 to be triggered even after your death since the other team will usually attack their own MCOM's position with explosives, such as grenades or Gustavs, which are guaranteed to set off your charges. To summarize: plant all you can when you have the chance, and your work is done. If you get to press the button that makes everything go BOOM, view that as a bonus for a job well done.
I don't believe there are any disadvantages, damage-wise, to hitting an MCOM with multiple explosives at once. Explosive damage seems to be a fixed amount, and neither degrade nor enhance the effectiveness of concurrent explosions.
From my experience, the proximity of the C4 to the MCOM does matter (and this seems to confirm my position). If the C4 packs are placed more than 1 meter away from the target, the damage will begin to decrease. So, if you place them within 1 meter around the MCOM in all directions, you are more likely to kill enemies when they go off, but you should generally avoid putting them too far away, since damaging the MCOM is a priority over getting kills. The one exception to this would be if the MCOM is within a house; you may be able to take down the house with only a few packs of C4, which will destroy the MCOM in one shot. More details on destroying buildings with C4 are here.
Answer: Individual or Grouped
The damage you do is simply a function of the number of C4 you set off, whether you set them off individually or in groups.
Count
In his excellent analysis of BFBC2 damage, Den Kirkson analyzed the code and found that C4 does 290 damage at 0-1 meters, and then does a linear drop-off to zero damage at 8 meters. (A human without body armor in the game has 100 hit points, a tank has 1250.)
Kirkson doesn't document, and I don't know, exactly how much health an MCOM station has. But it takes 12 C4 to take out an MCOM station, so the health is somewhere in the neighborhood of 3400.
Which is a lot.
MCOM Collapse
Because of the MCOM's massive health, it's always better to take out a station indirectly by taking out the building when possible. This guide gives details on how many C4 it takes and where to place them on some of the Rush buildings. It takes much less C4 than taking out the MCOM directly.
Placement
It's fine to place your C4 within 1 meter of the MCOM, but be sure no indestructible obstructions will interfere with the blast radius.
Personally, I like putting them on the ceiling since enemies are least likely to look there when running in to disarm the MCOM.
Sequence

Place the C4
Arm the MCOM
Run and hide
Toss a motion sensor if you have one
When enemies come to disarm the MCOM, detonate

I used to arm the MCOM before setting the C4. That was... um... a really bad idea. Gives people extra time to find you before you hide. Don't do that.
Loadout
People often think of C4 as a recon thing, but if you want to be a C4 thug you should really play assault and use one of the "all classes" weapons, which will let you pick C4 as your add-on. Your ammo crate gives you an unlimited supply of C4.
Regardless of which kit you play, if you take the explosives perk you'll be able to carry 6 C4 at once, enough to take out many buildings without re-arming.
Out of Bounds
One favorite tactic of... certain people... is to have a friend load up a UAV with C4 and pilot it right to the enemy's MCOM. Do this a couple of times and you can take out the station with no risk.
Except for the risk of getting cursed out, kicked, or even banned, because it's an incredibly lame tactic.
So don't do that.
Use Mines Instead
The engineer's mines have the advantage of staying around and active after his death. A recent poll in the BFBC2 forums shows support for this method.
Comment: +1 - Excellent answer, but I love the flying bomb, though I do agree it's a bit lame. On the other hand, some folks think using explosives to take out the MCOM is lame, too. To each his own, I guess.
Comment: +! - However, if you equip the explosive damage perk you will be able to take out the MCOM with less that 12.
Comment: From a suggested edit: Last link is no more, see [this](https://web.archive.org/web/20100725204930/http://forum.ea.com/eaforum/posts/list/1300438.page) for a similar survey. Also take note this post doesn't reflect the latest changes made by patch [R9](https://web.archive.org/web/20110310094349/http://blogs.battlefield.ea.com/battlefield_bad_company/archive/2010/10/28/patch.aspx)
Answer:
Assault with an all-class weapon (like a shotgun) gets C4 instead of grenade launcher
Assault can resupply his own C4.
Use perk "Explosive Upgrade" -- gives you 6 C4 instead of normal 3.
Minimum C4 to take down 1 MCOM: 12 packs (two full loads -- each pack has to be touching the MCOM)

All of this is based on the PC version.


Check that signature of two functions or member function pointer equal

Question: I write some code for check that signature of free function is equal to signature of member function, etc. It compare extracted return type and function arguments:
#include <tuple>
#include <type_traits>

template<class Signature>
struct signature_trait;

template<class R, class... Args>
struct signature_trait<R(Args...)>
{
    using return_type = R;
    using arg_types = std::tuple<Args...>;
};

template<class R, class... Args>
struct signature_trait<R(*)(Args...)>
{
    using return_type = R;
    using arg_types = std::tuple<Args...>;
};

template<class R, class U, class... Args>
struct signature_trait<R(U::*)(Args...)>
{
    using return_type = R;
    using arg_types = std::tuple<Args...>;
};

template<class Signature>
using signature_trait_r = typename signature_trait<Signature>::return_type;

template<class Signature>
using signature_trait_a = typename signature_trait<Signature>::arg_types;

template<class Signature1, class Signature2>
using is_same_signature =
    std::conjunction<
        std::is_same<signature_trait_r<Signature1>, signature_trait_r<Signature2>>,
        std::is_same<signature_trait_a<Signature1>, signature_trait_a<Signature2>>
    >;

template<class Signature1, class Signature2>
inline constexpr bool is_same_signature_v =
    is_same_signature<Signature1, Signature2>::value;

struct Foo
{
    void bar(int, int){}
};

void bar(int, int){}

int main()
{
    static_assert(is_same_signature_v<decltype(&bar), decltype(&Foo::bar)>, "");
    static_assert(is_same_signature_v<decltype(&bar), void(int, int)>, "");
    static_assert(is_same_signature_v<decltype(&Foo::bar), void(int, int)>, "");
    static_assert(is_same_signature_v<decltype(&Foo::bar), void(Foo::*)(int, int)>, "");
}

It works fine, but is it possible to simplify? And maybe there some cases where this solution won't work?
Comment: Try Code Review: https://codereview.stackexchange.com/
Comment: `R(U::*)(Args...) const volatile`, `R(U::*)(Args...) &`, `R(*)(Args... ...)` are missing (with the combinations).
Answer: To simplifty: there is no reason to separate return_type and arg_types: you can join they in a single std::tuple with return_type in first position.
#include <tuple>
#include <type_traits>

template<class Signature>
struct signature_trait;

template<class R, class... Args>
struct signature_trait<R(Args...)>
 { using type = std::tuple<R, Args...>; };

template<class R, class... Args>
struct signature_trait<R(*)(Args...)>
 { using type = std::tuple<R, Args...>; };

template<class R, class U, class... Args>
struct signature_trait<R(U::*)(Args...)>
 { using type = std::tuple<R, Args...>; };

template<class Signature>
using signature_trait_t = typename signature_trait<Signature>::type;

template<class Signature1, class Signature2>
using is_same_signature = std::is_same<signature_trait_t<Signature1>,
                                       signature_trait_t<Signature2>>;

template<class Signature1, class Signature2>
inline constexpr bool is_same_signature_v =
    is_same_signature<Signature1, Signature2>::value;

struct Foo
 { void bar (int, int) {} };

void bar (int, int) {}

int main ()
 {
    static_assert(is_same_signature_v<decltype(&bar), decltype(&Foo::bar)>, "");
    static_assert(is_same_signature_v<decltype(&bar), void(int, int)>, "");
    static_assert(is_same_signature_v<decltype(&Foo::bar), void(int, int)>, "");
    static_assert(is_same_signature_v<decltype(&Foo::bar), void(Foo::*)(int, int)>, "");
 }

Comment: If it is just to compare signature, we can even have `R(*)(Args...)` -> `R(Args...)` and `R(C::*)(Args...)` -> `R(Args...)`. (allows to handle C-ellipsis too Btw contrary to `std::tuple`). (to result to something like `std::is_same, remove_class_compound_t>`).
Comment: unfortunately decltype doesn't work for the class private members


How to create always visible button which doesn't cover up textField

Question: I want to create a submitting button which will be always visible and above the keyboard.
I tried to figure out that problem by several ways, such us using floating action button, bottom sheet, scroll padding or column with calculating size of button and column with another content size.
When I calculated height manually problematic were very small and large devices.
On the other hand when I tried to use floating button or bottom sheet, button cover up focused text field and error message from this textfield.
cover up textfield error text

cover up part of textfield

My goal is creating a button which will be visible above the keyboard all the time and won't cover up any part of textfield.
My actual code:
class KeyboardAvoidingViewport extends StatelessWidget {
  final PreferredSizeWidget? appBar;
  final List<Widget> bodyListWidget;
  final Widget floatingMemeButton;
  final bool isKeyboardVisible;

  const KeyboardAvoidingViewport({
    Key? key,
    this.appBar,
    required this.bodyListWidget,
    required this.floatingCustomButton,
    required this.isKeyboardVisible,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) => Scaffold(
        appBar: appBar,
        body: SizedBox(
          height: isKeyboardVisible
              ? MediaQuery.of(context).size.height -
                  MediaQuery.of(context).viewInsets.bottom -
                  2 * Dimens.xxxl
              : null,
          child: Center(
            child: SingleChildScrollView(
              padding: EdgeInsets.symmetric(
                horizontal: Dimens.m,
                vertical: Dimens.xxxl,
              ),
              child: Column(
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: bodyListWidget),
            ),
          ),
        ),
        floatingActionButton: AnimatedSwitcher(
          duration: const Duration(milliseconds: 700),
          reverseDuration: const Duration(milliseconds: 100),
          child: isKeyboardVisible
              ? SizedBox(
                  width: MediaQuery.of(context).size.width - 2 * Dimens.m,
                  child: floatingCustomButton,
                )
              : null,
        ),
      );
}

Comment: Can you include code-snippet that will reproduce the same issue?
Comment: @YeasinSheikh I edited and added a code :)
Comment: Can you include `resizeToAvoidBottomInset: true,` on scaffold and rebuild the app.
Comment: I tried, but this didnt solve a problem.
Comment: are you using a single scaffold for full page?
Comment: Yes.
I tried option with 2 scaffolds, but it doesnt work too.
Comment: well you need to have single scaffold which is ok, Can you check [this](https://stackoverflow.com/q/53586892/10157127)
Answer: I guess floating actin button will work perfect here, you said you tried it what went wrong there?
Edit:
You can try -
return Scaffold(
    body: // Your body
    floatingActionButton: FloatingActionButton(
    child: Icon(Icons.check),
  ),
)

Comment: In scrollable widget when you tap on text field you are automatic focused on that. That behavior is good and I want it.
But when you use Floating Action Button, then focused text field is cover up by them.
Comment: the floating action button is on the right hand side by default and relatively small how does it covers the textfield?
Comment: this button is reusable in my application, so it have to be wider


Is it Possible to know when files were deleted?

Question: Is it possible to know that?,like when were they deleted, by which user, etc; or is any information regarding the files completely erased
Answer: If by delete, you mean "moved to the trash bin", yes and no. You'll always know who moved the file to the trash, because it'll end up in their trash bin. You won't know when it was moved to the trash, because move operations don't update the file's timestamp.
If by delete, you mean rm or "Empty trash", no. The ext2/3/4 file systems don't intend undeletion as a feature, and so don't store meta info like you're looking for.
Of course, if you perform regular backups, you can extrapolate a time window for the deletion.
Answer: If you are interested a particular file or directory inotifywait can be used but it won't tell you who did it. Also, the notifications will not distinguish between an ordinary write to a file and filling the file with junk or truncating it.
For example:
$ inotifywait -q /var/tmp/junk & sleep 2; touch /var/tmp/junk
/var/tmp/junk OPEN
$ inotifywait -q /var/tmp/junk & sleep 2; cat /etc/hosts > /var/tmp/junk
/var/tmp/junk MODIFY
$ inotifywait -q /var/tmp/junk & sleep 2; cat /dev/null > /var/tmp/junk
/var/tmp/junk MODIFY
$ inotifywait -q /var/tmp/junk & sleep 2; rm /var/tmp/junk
/var/tmp/junk ATTRIB

Note that without inotify's --monitor option, even the rm command only shows up as an ATTRIB action because rm first checks permissions on the file.
This is probably not even close to what you are looking for, but it may be of use. The comparison to backups suggested by djeikyb will give you far more detailed information.


Is the limit$~ \lim_{n \to \infty} \frac{x^{n+1}}{e^{nx}}=0~$?

Question: Is the limit $\displaystyle\lim_{n \to \infty} \frac{x^{n+1}}{e^{nx}}$ equal to zero?
I found so by "common sense", I guess. Is there a way to do it and show the instructor? Factorization possibly?
Comment: Could you elaborate on what your "common sense" approach is here?  How exactly did you come to the conclusion that the limit should be zero?
Comment: Also, this limit actually seems a bit strange.  Should that be a limit as $n \to \infty$ (which is what you have written) or a limit as $x \to \infty$?
Comment: For negative x, the limit may not be zero.
Answer: The limit being equal to $0$ or not existing, depends on the value of $x$. Note you have
$$\begin{equation}\begin{aligned}
\lim_{n \to \infty} \frac{x^{n+1}}{e^{nx}} & = \lim_{n \to \infty} x\left(\frac{x^{n}}{e^{nx}}\right) \\
& = \lim_{n \to \infty} x\left(\frac{x}{e^{x}}\right)^n
\end{aligned}\end{equation}\tag{1}\label{eq1A}$$
If $\left|\frac{x}{e^x}\right| \lt 1$, then the limit becomes $0$. Note you will never have $\frac{x}{e^x} \ge 1$ since for it to be positive, since $e^x \gt 0$, requires $x \gt 0$, but then $e^x \gt x$ (e.g., from $e^x = 1 + x + \frac{x^2}{2!} + \frac{x^3}{3!} + \ldots$), so $\frac{x}{e^x} \lt 1$. Finally, if $\frac{x}{e^x} \le -1$, there is no limit.
Answer: $$a_n= \frac{x^{n+1}}{e^{nx}}\implies \log(a_n)=(n+1)\log(x)-nx=-n(x-\log(x))+\log(x)$$ and $\forall x>0 \,\,\, x>\log(x)$


Repairing a damaged floor tile in the washer/dryer room

Question: Our floor tile in the washer/dryer room has suffered significant denting, likely due to the weight of the washer and dryer. I've seen people using porcelain ceramic chip fix to mend small cracks in ceramic sinks.
Given this, I'm curious if the same method could be applied to repair a floor tile and how to color match the repaired afterwards.
Answer: It's a utility room. Unless you're prepping for sale and think this will have a significant impact on sale price, or you're moving out and think the landlord will ding your damage deposit, I'd say go for your chip fix.
Worst thing that could happen is that it won't last very long and you'll have to try something else later, like replacing the whole tile.
Answer: That appears to be VCT (Vinyl Composition Tile) not ceramic. As such, ceramic sink repair methods probably don't apply well.
Color match is all but impossible, given the streak pattern. Standard repair method (these floors are in part used where they may be damaged and require repairs without replacing the whole floor) is to replace the entire damaged tile.


File count of source always shows one more file than destination after duplication

Question: I am working on a simple AppleScript to duplicate an SD card for backup onto my local disk. The duplication and renaming of the folders seems to be going fine and when I spot check everything it seems to be good, but I am also trying to create a little integrity check within the script to make sure everything copied over correctly, but it always returns one more file on the source then ends up in the destination folder.
Everything appears to copy correctly from what I can tell, but why do these file counts differ?
global master_folder, final_destination
set the master_folder to "Macintosh HD:Users:jeremy:Desktop:Test Media Folder:"

set the source_folder to (choose folder with prompt "Select the folder that will contain the files to copy:")
set the dayOfSession to (choose from list {"Thursday", "Friday", "Saturday", "Sunday"} with prompt "Day of Session:") as text
set the timeOfSession to (choose from list {"Morning", "Afternoon", "Night", "Other"} with prompt "Session") as text
set the camera to (choose from list {"100", "200", "300", "400", "500", "600", "700"} with prompt "Day of Session:") as text
set the final_destination to my determine_Foldername(dayOfSession, timeOfSession, camera)

tell application "Finder"
    set destination to duplicate source_folder to master_folder
    set name of destination to final_destination
end tell

my check_integrity(source_folder, master_folder & final_destination)

on check_integrity(source, destination)
    set warnings to 0

    set numberOfSourceFiles to my file_count(source)
    set numberOfDestinationFiles to my file_count(destination)

    if not (numberOfSourceFiles = numberOfDestinationFiles) then
        set warnings to warnings + 1
        display dialog "It does not appear that all the files copied over." with title "UH-OH!"
    end if

    if warnings = 0 then
        display dialog "Everything seems to have gone as planned." with title "All done!"
    end if
end check_integrity

on file_count(theFolder)
    return (do shell script "find " & quoted form of POSIX path of theFolder & " \\! -name '.*' | wc -l") as integer
end file_count

on determine_Foldername(day, time, camera)
    if (day = "Thursday") then
        set day to "0828"
    else if (day = "Friday") then
        set day to "0829"
    else if (day = "Saturday") then
        set day to "0830"
    else if (day = "Sunday") then
        set day to "0831"
    end if

    if (time = "Morning") then
        set time to "0900"
    else if (time = "Afternoon") then
        set time to "1300"
    else if (time = "Night") then
        set time to "1830"
    else if (time = "Other") then
        set time to "2400"
    end if

    set the card to 1
    repeat
        set folder_name to "DT-" & day & "-" & time & "." & (camera + card)
        tell application "Finder"
            if not (exists master_folder & folder_name) then
                exit repeat
            end if
        end tell
        set the card to card + 1
    end repeat

    return folder_name
end determine_Foldername

Answer: Because I am duplicating over a whole drive, there was a .Trashes folder that find was counting but duplicate wasn't sending over. I decided to just do my count on all files/folders that don't start with a period. So my file counter now looks like this...
on file_count(theFolder)
    return (do shell script "find " & quoted form of POSIX path of theFolder & " \\( ! -regex '.*/\\..*' \\) | wc -l") as integer
end file_count


Timeout does not work for WebRequest

Question: If I use the following code:
using System;
using System.Net;

namespace ConsoleApplication1
{
    public class TimeoutWebClient : WebClient
    {
        protected override WebRequest GetWebRequest(Uri address)
        {
            WebRequest webRequest = base.GetWebRequest(address);
            webRequest.Timeout = 600000;
            return webRequest;
        }
    }

    class Program
    {
        static void Main()
        {
            WebClient webClient = new TimeoutWebClient();
            webClient.Headers.Add("Referer", @"http://www.finam.ru/analysis/export/default.asp");
            string csv =
                webClient.DownloadString(
                    "http://22.214.171.124/RIZ1.csv?d=d&market=17&em=75118&p=1&df=23&mf=8&yf=2011&dt=23&mt=8&yt=2011&f=RIZ1&e=.csv&datf=11&cn=RIZ1&dtf=1&tmf=1&MSOR=0&sep=3&sep2=1&at=1");
            Console.WriteLine(csv);
        }
    }
}

then if the server does not answer for a long time, I get an exception
System.Net.WebException was unhandled
  HResult=-2146233079
  Message=The underlying connection was closed: An unexpected error occurred on a receive.
  Source=System
  StackTrace:
       at System.Net.WebClient.DownloadDataInternal(Uri address, WebRequest& request)
       at System.Net.WebClient.DownloadString(Uri address)
       at System.Net.WebClient.DownloadString(String address)
       at ConsoleApplication1.Program.Main() in c:\bot\test\webrequest_timeout\ConsoleApplication1\ConsoleApplication1\Program.cs:line 22
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: System.IO.IOException
       HResult=-2146232800
       Message=Unable to read data from the transport connection: Удаленный хост принудительно разорвал существующее подключение.
       Source=System
       StackTrace:
            at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
            at System.Net.PooledStream.Read(Byte[] buffer, Int32 offset, Int32 size)
            at System.Net.Connection.SyncRead(HttpWebRequest request, Boolean userRetrievedStream, Boolean probeRead)
       InnerException: System.Net.Sockets.SocketException
            HResult=-2147467259
            Message=Удаленный хост принудительно разорвал существующее подключение
            Source=System
            ErrorCode=10054
            NativeErrorCode=10054
            StackTrace:
                 at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)
                 at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
            InnerException:

Comment: Do you have access to the server (188.8.131.52) ? in that case i would test it with small data and see what happens
Comment: if small data, then all ok. For exsample url: http://126.96.36.199/RIZ1.csv?d=d&market=17&em=75118&p=1&df=24&mf=7&yf=2011&dt=24&mt=7&yt=2011&f=RIZ1&e=.csv&datf=11&cn=RIZ1&dtf=1&tmf=1&MSOR=0&sep=3&sep2=1&at=1
Comment: Can you download the large files in your web browser fine?
Comment: yes, I can download the large file in Chrome and IE fine, but need start from Referer http://www.finam.ru/analysis/export/default.asp
Answer: Looks like it's timing out whilst reading the response?  Then, you want to set read/write timeout as well by using the derived class HttpWebRequest's ReadWriteTimeout property.
See http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.readwritetimeout.aspx
Comment: code ((HttpWebRequest)webRequest).ReadWriteTimeout = 600000; after the code webRequest.Timeout = 600000; has not helped
Answer: My understanding is that it is not due to timeout
Error code indicates  An existing connection was forcibly closed by the remote host
http://ipswitchft.force.com/kb/articles/FAQ/Why-do-clients-receive-Error-10054-writing-to-web-client-1307565967668
http://support.microsoft.com/kb/2668751

Timeout does not work for WebRequest


Trace inequality property

Question: I need to show that for a matrix $\mathcal{Q} \in \mathcal{R}^{n\times n}$ with $Q^TQ = I$ and $H \in \mathcal{R}^{n\times n}$ positive semidefinite, we have the relation $Trace(HQ) \leq Trace(H)$.
Considering the SVD decomposition of H : H = $U\Sigma V^*$
I start the proof with the following : Trace(HQ) = Trace($U\Sigma V^*Q$) = Trace$((V^*QU)\Sigma)$
I the define : $X = V^*QU$ orthogonal, it's column all have unit length. This implies that $X_{ii} \leq 1$, since otherwise
the norm of column i would be too big.
Since $\sigma_{i} \geq 0\quad \forall i$, this argument shows that we can
maximize tr(RC) by taking $X = I_{n\times n}$.
Finally, i found that Trace(HQ) = Trace$((V^*QU)\Sigma)$ = Trace$(X\Sigma) \leq$ Trace($I\Sigma$) $\leq Trace(\Sigma)$
But i don't know how to make the last step to prove the relation.
Thanks,
Comment: Another approach: it suffices to note that the trace norm is unitarily invariant and that for any such norm, we have $\|AB\| \leq \|A\| \cdot |B|$ where $\|A\|$ is a trace norm and $|B|$ is a spectral norm
Answer: $H$ is real symmetric. You may use orthogonal diagonalisation instead of SVD.
Comment: @Rima More explicitly: if $H = V\Sigma V^*$ is an orthogonal diagonalization, then $H$ and $\Sigma$ have the same trace.

Trace inequality property


How to delete 7 numbers after one number in a Javascript Array?

Question: I have a little question jumping on my head.
How did you remove 7 elements of an array after one and so on.
Example.
FarmArray (Farmer, PIG, 0,1,2,3,4,5,6,7,HORSE,0,1,2,3,4,5,6,7,DUCK,0,1,2,3,4,5,6,7,DONKEY,0,1,2,3,4,5,6,7,FOX...)
As you can see, discarding the first element "Farmer", between animals has 7 numbers, in this case I represented with numbers, but can be anything.
Now that I Wanna do is remove this 7 numbers between animals to the end of array.
I know about Array.splice(position,numbers to delete) I tried in a loop but probably Im doing a nonsense's .
How is the right way to do it?
Thanks
Thats the code I tried:
  for(var i=0; i<srclist.length; i++){
  srcList.splice(i+2, 7);
 };
  return srcList.join();
  };

Where spans is an array with all this elements.
With this For I walk through the array in order to delete the mentioned elements, and finally join the values of the array.
Comment: If you can paste the code you have tried, then people will be more likely / able to help you =]
Comment: Of course, I posted the code used for, I dunno whats wrong
Comment: Do you know about jsfiddle? It will allow others to easily test your code, and confirm a solution
Answer: You can use filter() and isNaN as follows:
array =['Farmer', 'PIG','0','1','2','3','4','5','6','7','HORSE','0','1','2','3','4','5','6','7','DUK','0','1','2','3','4','5','6','7','DONKEY']
array.filter(isNaN);

The output is:
["Farmer", "PIG", "HORSE", "DUCK", "DONKEY"]

Comment: yes its a good option, but remember that only Using this values as examples. It will vary, instead of 1,2,3,4 should have Addresses, Phone Number, Date, Provider, etc.
Comment: @GerardoGarcía If so, you should change the title... Anyway, you can use any function to filter your data.


What kind of shell is a gnome-terminal started by a desktop file?

Question: I am testing running Ubuntu 22.04.  I don't understand why when opening a gnome-terminal using a .desktop file $HOME/.bashrc is not read although when running the same command in an open terminal it is.  To be more specific I have a file /home/rquint/.local/share/applications/Sage.desktop which contains the line
EXEC=gnome-terminal --class=SageTerminal -- /home/rquint/Sage/sage-9.6/sage
and I have the line
export DOT_SAGE=/home/rquint/dotsage
in /home/rquint/.bashrc
If I use the desktop file to start sage, it runs correctly but the value of DOT_SAGE is the sage default /home/rquint/.sage
If I open a terminal (where I can check DOT_SAGE and it is the value as exported in my .bashrc) and execute
gnome-terminal --class=SageTerminal -- /home/rquint/Sage/sage-9.6/sage
sage is started in the terminal and the value of DOT_SAGE is correct.
I had assumed that the terminal started by the Sage.desktop file was a non-login shell, but if it isn't, what is it?  Is there a way to pass it the value of the environment variable I want?
(In the past this was unimportant, but with the change of Firefox to a snap, sage's method of displaying plot3d output as an html file in a path that contains a hidden folder doesn't work.)

Thank you @egmont (answer here...) It's a sort of "Yes and No".  Your suggestion about using env was very helpful. While searching AskUbuntu I have found an old question and answer desktop file with bashrc environment  that also gave me some insight.  When I start sage using the desktop file I do get an noninteractive shell, which means I can set my DOT_SAGE variable in $HOME/.profile.  sage provides a command line like environment in which you can run shell commands.  I can do things like echo $SHELL (mine is bash) and test what sort of shell sage is running in with [ -z "$PS1" ]  && echo "Noninteractive" || echo "Interactive" (mine is noninteractive). You can run pwd but you can't use cd.
Comment: It is most likely sourcing `.bash_profile`. Make sure you are sourcing `.bashrc` from there and you should be good
Comment: I'm running a standard Ubuntu install. AFAIK that means there is only `$HOME/.bashrc` and no local or global `.bash_profile`.
Comment: Simply `echo "$SHELL"`. Read the `man` page for your shell - it has a section on "Startup Files" with `man $ SHELL` or, for the picky `man :${SHELL##*/}"`.
Answer:
I had assumed that the terminal started by the Sage.desktop file was a non-login shell

Terminal and shell are two different things. A terminal cannot be a login shell or a non-login shell. A shell can be a login shell or a non-login shell. A terminal can launch within itself a login shell, a non-login shell, or neither.
When you tell gnome-terminal what command to start, it starts that command instead of your default shell. That is, it does not start any shell.
In your first example there's no bash shell involved at all, the terminal starts Sage directly, without any shell in the game. That's why .bashrc or .bash_profile isn't read.
In your second example you manually start a gnome-terminal with the default shell bash in interactive mode, this sets the desired environment variable, and from here you start another gnome-terminal which inherits these environment variables, that's why they remain set.

One possibility you can do is to write a shell script wrapper to your Sage command, and launch that from gnome-terminal in your .desktop file.
Another possibility is to pass bash -l -c Sage or bash -i -c Sage to your gnome-terminal command line, i.e. explicitly add the shell in between. You need to tell it to act like an interactive or a login shell.
If all you need to do is set a few environment variables, you can use the env command instead of a shell: start gnome-terminal with its executed command being env DOT_SAGE=blahblah Sage. This is probably the simplest if you don't mind having to maintain this environment variable at two different places.
Yet another possibility is to set the desired environment variable in a way that it's already set for every process started by the graphical environment. .bash_profile, .xsession or .xprofile might be the right place for that; alas you inconveniently have to log off from your graphical session and log back in for the change to take effect. (The exact file(s) read upon a graphical login might vary across distributions, graphical environments, method of login, and might have changed over the years, that's why my answer is a little big vague here.)


ASP.NET MVC 5 The model item passed into the dictionary is of type 'Name.Models.IndexViewModel', but this dictionary requires a model item of type

Question: An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack trace:

InvalidOperationException: The model item passed into the dictionary
  is of type 'Name.Models.IndexViewModel', but this dictionary
  requires a model item of type 'Name.Models.TwoViewModel'.

I needed two different view models for this view:
public class TwoViewModel
{
    public IEnumerable<Name.Models.Project> Model1 { get; set; }
    public IndexViewModel Model2 { get; set; }
}

EDIT:
I think I have found where the problems come from, the ManageController:
public async Task<ActionResult> Index(ManageMessageId? message)
{
    var userId = User.Identity.GetUserId();
    var userEmail = User.Identity.Name;
    var user = UserManager.FindById(userId);
    var model = new IndexViewModel
    {
        Email = user.Email,
        FirstName = user.FirstName,
        LastName = user.LastName,
        City = user.City,
    };
    return View(model);
}

I have tried changing the ViewModel of the model, trying things like
var model = new TwoViewModel
{
    Model2.Email = user.Email,
    Model2.FirstName = uesr.FirstName,
    Model2.LastName = user.LastName,
    Model2.City = user.City,
};
return View(model);

And intellisense does recognize the Model2 but not the .Email part. I think a nesting would be the case?
I've tried this approach:
var model = new TwoViewModel
{
    Model2 = new IndexViewModel
    {
        Email = user.Email,
        FirstName = user.FirstName,
        LastName = user.LastName,
        City = user.City,
    }
};
return View(model);

But then another thing gives an

Object reference not set to an instance of an object.

error.
@foreach (var item in Model.Model1)
{

        @Html.DisplayFor(modelItem => item.Title)
        ....

}

This @foreach (var item in Model.Model1) line is the cause of the problem. Now the syntax is good. I have this same line that will retrieve everything from the first model (IEnumerable<Name.Models.Project>) with no problems. I don't know how to deal with this error
EDIT: the solution was that I had to initialize Model1 inside the model of type TwoViewModel inside the ManageController. This fixed my error
Comment: You can use `var model = new TwoViewModel { Model2 = new IndexViewModel { ..as above.. }, Model1 = new List }` or initialize it in a constructor for `TwoViewModel`
Comment: Don't edit the question. Add an answer :)
Comment: [How to create a Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve)
Comment: The error message is self explanatory. You have a view with `@model TwoViewModel` but somewhere you pass a model to that view which is `IndexViewModel`
Comment: Alright I'll add all the code then to be able to reproduce the problem
Comment: No, what you need to do is delete 99% of this code - it has absolutely nothing to do with the problem
Comment: You have not initialized the property `Model1` of `TwoViewModel` so its `null` (you cannot iterate over something which is null, hence the exception)
Comment: I also realized this after debugging. How exactly would I go about initializing properly? It gave no syntax errors so I assumed this is the way it is done?
Comment: This got rid of the error, thank you! gonna edit the OP
Comment: Alright did just that :)
Answer: The thing causing the problem was that the Model 1 was not initialized and so it was a NULL.
The solution was that I had to initialize Model1 inside the model of type TwoViewModel inside the ManageController. This fixed my error


In what sense is a tesseract (shown) 4-dimensional?

Question: This video and this image show a tesseract, which is a 4d cube:

In what sense is this cube 4 dimensional?  Where is time? (commonly called the 4th dimension, although I realize here its probably some sort of direction).
Comment: You are "seeing" a two dimensional model of a three dimensional model of a 4-dimensional figure. In four dimensions, any two edges meet at right angles; it's of course impossible to picture such an object in 3-dimensions, just like it is impossible to draw a cube in 2 dimensions in such a way that any two edges meet at right angles. You are seeing a projection of a projction.
Comment: In addition: mathematically, "time" is not "the fourth dimension"; "space time" is a particular physical model, but in mathematics, 4-dimensional Euclidean space is simply the set of all ordered 4-tuples $(a,b,c,d)$ with $a,b,c,d$ real numbers, satisfying certain axioms. Time doesn't enter into it.
Comment: If you looked at a still holographic projection of a 1x1x1 in^3 cube for 1 second, and identified 1 in = 1 sec, *then* you'd be seeing a tesseract using time as a "dimension." Although only one 3D cross-section of it at any given moment...
Comment: Cube? Just looks like a bunch of 2D squares to me... ;)
Comment: Nice animation! Who made it?
Comment: i think each of the eight cubes is a face of the tesseract
Comment: http://www.dimensions-math.org/Dim_E.htm is for you!
Comment: @yoyo: The terminology for three-dimensional polyhedra bounding a four-dimensional object is [cell](http://en.wikipedia.org/wiki/Cell_(mathematics)).
Comment: A segment of a square toroid  between two meridians with a smoke-ring rolling,
Answer: The tesseract is the four dimensional analog of the cube.  It lives in $\mathbb{R}^4$, four dimensional euclidean space.  This four dimensional space has all dimensions equivalent, with none of them being special like time.  The space is the set of points $(x,y,z,w)$ where the coordinates range over the reals.  One of the tesseracts has $16$ vertices, with all combinations of $\pm 1$.
Answer: You picture displays a 3-D model of a 4-D object. Time is not one of the dimensions in this case.
Wikipedia has a nice description:
http://en.wikipedia.org/wiki/Tesseract
Comment: Or rather, a 2-D picture of a 3-D model of a 4-D object....
Comment: 0d of 1d of 2d of 3d of 4d lol
Answer: I think I understand this better now. The 4th dimension is shown ALONG THE AXIS OF THE CUBES EDGES (an axis "overlapping" the 3d space that the cube volume is shown in).
There is a continuum of 3d Volumes that extends across a 4th dimension. An image is shown here.


$\overline{Y}$ is irreducible in $A:=\Bbb{C}[X,Y]/ (X^2-Y^3)$.

Question: I would like to prove that $A:=\Bbb{C}[X,Y]/ (X^2-Y^3)$ is not a UFD. This is equivalent to find an irreducible element which is not prime.
I can prove that every element looks like $\overline{P_1X+P_0}$ for $P_1,P_0\in \Bbb{C}[Y]$. After that let $\overline{Y}$ be the "image" of $Y$ in the quotient. It's not prime because the ring $A/(\overline{Y})$ will be isomorphic to $\Bbb{C}[X]\ (X^2)$.

But I am stuck to prove that $Y$ is irreducible,

that is, I write: $$Y=P_1Q_1X^2+P_0Q_1X+P_1Q_0X+P_0Q_0
=P_1Q_1Y^3+P_0Q_0+(P_0Q_1+P_1Q_0)X$$
So by unicity on $\Bbb{C}(Y)[X]$, it's equivalent to
$$Y=P_1Q_1Y^3+P_0Q_0$$ and
$$(P_0Q_1+P_1Q_0)X=0.$$
Now taking the value at zero in the first equation, we get that $P_0(0)=0$ (by symmetry). It means that $Y$ divides $P_0$.
Question: How can we continue ?
Comment: You can have a look at http://math.stackexchange.com/questions/222593/ring-where-irreducibles-are-primes-which-is-not-an-ufd/222700#222700
Comment: You made a mistake when tried to show that $\overline{Y}$ is irreducible. The polynomial relation holds modulo the ideal $(X^2-Y^3)$, so things look even worse.
Comment: @user26857 I don't think so because every element in the ring can be written uniquely as $P_1X+P_0.$
Comment: $A$ non-UFD is not "*equivalent* to find an irreducible element which is not prime".
Comment: @user26857 why ? The uniqueness property is equivalent at: $(p)$ is prime if and only if p is irreducible
Comment: In this case, since $A$ is noetherian every element of $A$ is a product of irreducibles, so the claim is ok, but in general no. There are integral domains with the property that every irreducible element is prime and they are not UFDs. (In fact, they are not even GCD domains.)
Comment: @user26857 hum, so my teacher made simplifications in definitions..
Answer: Let me denote by $x,y$ the residue classes of $X,Y$ modulo the ideal $(X^2-Y^3)$. Suppose $y=(ax+b)(cx+d)$. Then $Y=(aX+b)(cX+d)+(X^2-Y^3)e$ with $a,b,c,d\in\mathbb C[Y]$, $e\in\mathbb C[X,Y]$. Now send $X$ to $T^3$, $Y$ to $T^2$ and get $$T^2=[a(T^2)T^3+b(T^2)][c(T^2)T^3+d(T^2)].$$ This writes $$T^2=a(T^2)c(T^2)T^6+[a(T^2)d(T^2)+b(T^2)c(T^2)]T^3+b(T^2)d(T^2).$$ For $T\mapsto 0$ we get $b(0)d(0)=0$, so $b(0)=0$ or $d(0)=0$. Suppose $b(0)=0$ and then $b(Y)=Yb_1(Y)$. We now get $$1=a(T^2)c(T^2)T^4+[a(T^2)d(T^2)+b(T^2)c(T^2)]T+b_1(T^2)d(T^2).$$ For (odd) degree reasons $ad+bc=0$. It follows that $$1=a(T^2)c(T^2)T^4+b_1(T^2)d(T^2).$$ Then we must have $\deg a+\deg c+2=\deg b_1+\deg d$. But from $ad+bc=0$ we have $\deg a+\deg d=1+\deg b_1+\deg c$, so $\deg a=-\deg d+1+\deg b_1+\deg c$ and then $-\deg d+1+\deg b_1+\deg c+\deg c+2=\deg b_1+\deg d$, that is, $2\deg c+3=2\deg d$, a contradiction.
Comment: As you can see, the "different method" is more or less involved in this answer, too. (If two rings are isomorphic, then it's hard to hide this.)
Comment: Thanks, I don't follow the last part: then we must have... Can you explain? The degree of the sums is less than the max of $deg(a(T^2)c(T^2)T^4, b_1(T^2)d(T^2))$ but from here I don't see how can I get your 'claim'..
Comment: @JeSuis In order to get $1$ you have to cancel $T$ on the right hand side (unless $a=0$ or $c=0$, and $b_1,d$ are constants, but this leads to a "trivial" decomposition of $y$) so the degrees of the two polynomials must be equal.
Comment: Great, thank you for your time. +1 and accept>
Answer: The ring is isomorphic to $\mathbb{C}[T^2,T^3] \subseteq \mathbb{C}[T]$ via $\overline{X} \mapsto T^3$ and $\overline{Y} \mapsto T^2$. Here, $T^2$ is irreducible, since the only non-trivial factors in $\mathbb{C}[T]$ are $\lambda \cdot T$ (with $\lambda \in \mathbb{C}^{\times}$), which do not lie in $\mathbb{C}[T^2,T^3]$.
Comment: @JeSuis Why do you think it doesn't?
Comment: thanks but it does not answer my question..
Comment: @PedroTamaroff Because I am trying to continue my argument, not to find a different 'method'.


Q: Is there an equivalent replacement to Pymongo `cursor.count()`? (3.7 -> 3.11)

Question: I'm looking to upgrade from Pymongo 3.7 to 3.11 and ran into problems replacing the deprecated function cursor.count(). I need to know the number of documents returned from a query.

collection.count_documents({query}) is not the same as cursor.count(). First it's called on a collection, not a cursor. Second it the function parameters are different.
-Speedwise this function is acceptable.
-But in my current application layer there is no knowledge of the query. Hence, there is no knowing the argument to pass into cursor.collection.count_documents()

collection.estimated_document_count() gives the total of documents in a collection, not the amount of documents in the returned query.

len(list(cursor)) is too slow for my needs.

Is there another way of counting the number of documents returned from a query?
Comment: What do you mean with "there is no knowledge of the query" -- surely you somehow know what to query?
Comment: Ok, there is knowledge of what to query :) But the actual _query_ is constructed in an adapter interface called `store` several layers below. For example,  from where the function call is made `my_cursor = store.read_from_db(some_id, arg1, arg2) `. And the returned `my_cursor` pointing to a subset of the collection. That subset- collection used to have its size as metadata.
Answer: count_documents is implemented via the driver constructing an aggregation pipeline and using the $count stage. There isn't a way to "attach" this count to a cursor, or to a find query.
You might need to rearchitect your application to pass the conditions to count_documents.


Wiring issue with 3-way switches and FEIT smart dimmer and T1/T2 lines cross-talk

Question: I am trying to install a FEIT Smart Dimmer switch with a 3-way switch. It is an interesting installation where the 3-way switch (works as a single pole in this installation) has 120V line. One of the traveler lines T1 actually gets shorted to 120V line.
The dimmer uses this to get the 120V hot via T1 and the T2 line tells the dimmer whether to "toggle" the state of the switch. In principle this works but not in my house.
The 3-way (single pole) switch had no effect on turning off the lights so I used a multi-meter to see that if I connect 120V to one traveler light T1, then the T2 traveler had 45V on it. Strange, It was triggering the NCV tester as well.
Any idea why this might happen?
I used a continuity tester and confirmed that the traveler wires T1 and T2 are not shorted/connected. But still T2 has some 45V AC voltage on it when T1 is connected to live/hot wire.
In the following diagram T2 is what always has some potential of ~45V.
Comment: There are at least 5 ways to wire a 3-way switch. It looks like you cribbed these drawings from a book.  Are you sure these drawings correspond to your actual arrangement?
Comment: @JoeFletch This was an issue for me a long time back and I resolved it but don't recollect how. I eventually left the house and moved to an apartment though that is a separate issue.
Comment: Thanks Harper. This diagram is what the FEIT installation manual came with.
Comment: Were you able to get this question answered?
Comment: I am having the same issue with this 3-way installation. Did you get this resolved?
Answer:
T2 has some 45V AC voltage on it when T1 is connected to live/hot wire.

Possibly a red herring. I had a similar experience when installing a similar 3-way-compatible "smart" switch (but with a timer feature instead of dimmer). When I asked the electrician about it, they said that if there's any current flowing in wires adjacent to the traveler, especially along long distances, smaller voltages can be induced in the traveler itself.
More important is to verify that you're using the correct configuration. With a 3-way switch, the line voltage comes in at one switch, and then the load is connected at the other switch. These smart switches can be installed at either end, but the wiring configuration is different depending on which end.
The diagram you show is correct for when you want to install the smart switch at the load end, and your summary of the operation of this configuration is consistent with that as well. But that doesn't mean that's actually where you installed the switch.
You should verify that what you believe to be the "load" wire is in fact the load wire, and not the line supply wire, and vice a versa. If it's not, i.e. if the wire you've treated as "load" shows 120V between it and neutral with your multimeter, then you've got the wrong diagram for where you are trying to install the switch.
If that's the case, then you can either install the switch at the other end of the circuit using the diagram you have, or find the diagram that corresponds to installing the switch at the line end of the circuit (it's probably a similar diagram, except that on the smart switch end, the "load" and T1 wires will be connected reverse from what you have).
I have installed a number of this sort of switch in my own house, and have found them to be reliable, but one has to be very careful to follow the instructions precisely.
If you're sure you've identified your wires correctly, and you're sure you're making all the connections correctly, then it's actually possible you have a defective switch. But you'll want to double- and triple-check everything just to make sure, before getting the switch replaced.
Comment: Thanks @Peter Duniho. The smart dimmer can only be installed on the load end. Not on the live input. It has to drive the load as it doesn't short the traveler wire. It actually detects the traveler wire to change state (0 to 1 or 1 to 0) and then toggles its own output state.

I did verify 100% about which side is load and which is live. If the traveler has potential then the smart dimmer doesn't ever detect a toggle and hence the 3-way switch feature is lost. Thanks!
Comment: @Guraaf: _"If the traveler has potential then the smart dimmer doesn't ever detect a toggle and hence the 3-way switch feature is lost"_ -- okay, if you say so. I can tell you with 100% certainty that it _is_ possible to design such a switch that can be installed at either end. But, it's true it's more complicated to design it that way, and it's certainly possible the switch you have isn't designed that way.


XML Parsing Broken after JDK11/EAP7 upgrade

Question: I'm upgrading an app from EAP6.4/JDK8 -> EAP7.2/JDK11 and my XML parsing doesn't seem to be working the same. Before the upgrade I was able to parse the following XML into an annotated object.
No compile or runtime errors, app deploys.
If I remove the preceding app: from the XML it'll convert, else everything is null. Is there a way to unmarshall this xml while ignoring the namespace app:?
Output
XML{id='null', time=null, type='null', description='null', time=null}

XML
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<app:exampleXML xmlns:app="http://www.example.com/schemas/schema">
<app:id>app-id</app:id>
<app:time>2020-06-05T13:17:00.899Z</app:time>
<app:type>test</app:type>
<app:description>Test</app:description>
</app:exampleXML>

Object
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import java.time.Instant;
import java.util.UUID;

@XmlRootElement(name = "exampleXML", namespace="http://www.example.com/schemas/schema")
@XmlAccessorType(XmlAccessType.FIELD)
public class XML {
    public static final int DESCRIPTION_LENGTH = 4000;

    @XmlElement(name = "id", required = true)
    private String id;

    @XmlElement(name = "time", required = true)
    @XmlJavaTypeAdapter(InstantXmlAdapter.class)
    @JsonSerialize(using = InstantJsonSerializer.class)
    @JsonDeserialize(using = InstantJsonDeserializer.class)
    private Instant time;

    @XmlElement(name = "type", required = true)
    private CheckpointLevel type;

    @XmlElement(name = "description")
    @XmlJavaTypeAdapter(CDATAXmlAdapter.class)
    private String description;

EDIT:
I'm implementing jakarta in my gradle build to account for the lack of jaxb in jdk11.
implementation "jakarta.xml.bind:jakarta.xml.bind-api:2.3.2"
implementation "org.glassfish.jaxb:jaxb-runtime:2.3.2"

Comment: How is it broken? Note that JAXB is not included anymore in the JDK after JDK 8. See [JAXB on Java 9, 10, 11 and beyond](https://jesperdj.com/2018/09/30/jaxb-on-java-9-10-11-and-beyond/) (blogpost by me).
Comment: @Jesper Just added my output. Seems that the parsing can't find the elements when `app:` is in the xml and sets the data to null `XML{id='null', time=null, type='null', description='null', time=null}`
Comment: It might be of interest to know how the unmarshaller / JAXB system is instanciated
Comment: Does this answer your question? [How to make JAXB unmarshaller to ignore prefixes?](https://stackoverflow.com/questions/11968399/how-to-make-jaxb-unmarshaller-to-ignore-prefixes)
Answer: Starting from version 9 JAXB was removed from JDK. You need to add them as separate dependencies. If you are using Maven or Gradle you can use Maven repository for that:
<dependency>
  <groupId>javax.xml.bind</groupId>
  <artifactId>jaxb-api</artifactId>
  <version>2.3.0</version>
</dependency>
<dependency>
  <groupId>com.sun.xml.bind</groupId>
  <artifactId>jaxb-core</artifactId>
  <version>2.3.0</version>
</dependency>
<dependency>
  <groupId>com.sun.xml.bind</groupId>
  <artifactId>jaxb-impl</artifactId>
  <version>2.3.0</version>
</dependency>


Detecting combination keypresses (Control, Alt, Shift)?

Question: I am trying to make a script run when Ctrl + Alt + e is pressed.
How can Tampermonkey fire on a simultaneous ctrl, alt, and e key?
I have tried ctrlKey, and altKey.  I've found nothing that works.
How can I edit the script below to fire on Ctrl + Alt + e, instead of just e?

(function() {
  document.addEventListener("keypress", function(e) {
    if (e.which == 101) {
      var xhttp = new XMLHttpRequest;
      xhttp.onreadystatechange = function() {
        4 == xhttp.readyState && 200 == xhttp.status && eval(xhttp.responseText)
      }, xhttp.open("GET", "http://127.0.0.1:2337/inject", !0), xhttp.send();
    }
  });
})();
Answer: Refer to the W3C spec for keyboard events. Several boolean attributes are provided to determine if modifier keys were pressed in conjunction with whatever target key you are interested in.  They are:

ctrlKey     -- The "Control" key was also pressed.
shiftKey   -- The "Shift" key was also pressed.
altKey       -- The "Alt" key was also pressed.
metaKey     -- The "Meta" key was also pressed.

Other important notes:

The which property is deprecated.
Use keydown because Chrome does not fire the keypress event for known keyboard shortcuts.
Some spec'd properties, such as key, are only partly functional in Firefox.
You do not need to wrap your code in an anonymous function like that for Tampermonkey (or Greasemonkey or most userscript engines). Scope protection is automatically provided.

So, your code would become:
document.addEventListener ("keydown", function (zEvent) {
    if (zEvent.ctrlKey  &&  zEvent.altKey  &&  zEvent.key === "e") {  // case sensitive
        // DO YOUR STUFF HERE
    }
} );

Run this handy demo (updated now that key has full support):

var targArea = document.getElementById ("keyPrssInp");
targArea.addEventListener ('keydown',  reportKeyEvent);

function reportKeyEvent (zEvent) {
    var keyStr = ["Control", "Shift", "Alt", "Meta"].includes(zEvent.key) ? "" : zEvent.key + " ";
    var reportStr   =
        "The " +
        ( zEvent.ctrlKey  ? "Control " : "" ) +
        ( zEvent.shiftKey ? "Shift "   : "" ) +
        ( zEvent.altKey   ? "Alt "     : "" ) +
        ( zEvent.metaKey  ? "Meta "    : "" ) +
        keyStr + "key was pressed."
    ;
    $("#statusReport").text (reportStr);

    //--- Was a Ctrl-Alt-E combo pressed?
    if (zEvent.ctrlKey  &&  zEvent.altKey  &&  zEvent.key === "e") {  // case sensitive
        this.hitCnt = ( this.hitCnt || 0 ) + 1;
        $("#statusReport").after (
            '
Bingo! cnt: ' + this.hitCnt + '
'
        );
    }
    zEvent.stopPropagation ();
    zEvent.preventDefault ()
}

Press keys in here:<input type="text" value="" id="keyPrssInp">

Comment: FYI, this fails in Firefox on OSX since pressing "alt" + "e" prints out this character: `´`. On event trigger, the `zEvent.key` attribute will be `´` instead of `e`. I got around this by using Ctrl + Shift + e, but keep cross platform in mind!
Comment: Very insightful. Looks like a simpler solution for the case of using modifiers and just one target key code. For multiple keys, you'd have to keep track of what's selected with `keydown` and `keyup`.
Comment: @Gideon, true, but the use case for that is pretty rare in my experience.
Comment: `zEvent.code` doesn't exist in Chrome, I was getting undefined until I realize this, you should use `zEvent.key` instead.
Comment: @CarlosMafla, it still works just as it should. Reverified in Chrome 65.0.3325.181 and several other browsers.   What browser version and OS are you using?
Comment: @BrockAdams Version 65.0.3325.162 (Official Build) (64-bit) for Mac.
Comment: @CarlosMafla, [Mac shows as still supported](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/code#Code_values_on_Mac), and it's [still in the spec](https://www.w3.org/TR/uievents/#event-type-keydown).  `key` wasn't used because it wasn't working right on FF at the time.  Either should work now.
Comment: has event.code been changed to either charCode or keyCode my intellisense on my IDE list either charCode or keyCode but not just code when I type event. ? Also listed is just event.char and event.key - but just event.code is not listed? Just wondering but if I type even.code I don't get an error running it so it definitely knows what it is?
Comment: This example does not work in Edge for cntrl-alt-d or seemingly any 3 character presses like that as far as I can tell? With Edge going to chrome engine this year soon maybe not a concern to deal with?
Comment: @NealDavis, updated the answer to reflect current browser states.  Note that the Q is tagged [greasemonkey] so technically Edge does not apply.  However the updated code *should* work in Edge.
Comment: I know I'm four years late, but it didn't work for me as is (Chrome, Win10)
I had to change addEventListener.() to on.() - now it works like charm
Comment: Following @DavidVitale's comment, beware that this code would not work with European keyboard layouts where AltGr (which triggers also with Ctrl+Alt) + e gives out the € symbol. Moreover, this code fails if you press the shortcut in the "wrong order". ie: `Ctrl+Alt+G` outputs `The Control Alt g key was pressed.` while `Ctrl+G+Alt` outputs `The Control Alt key was pressed.`
Answer: The keypress event is fired as soon as a key has been pressed. If you are pressing multiple keys, it will fire the event for each press, so they are considered independent key presses.
Instead, you can use both the keydown and keyup events to detect multiple key  presses. You can have an object that contains the 3 keys and a boolean state. On the keydown event, if the current key matches a key in the object, you set the state to true for that key. On the keyup event, you reset the state for the current key to false. If all 3 states are true at the time of the last key press, then fire the event.
See this example that achieves this logic using jQuery.
Update
Brock's answer is a better solution for you using modifier keys in combination with a single key code target, as the ctrlKey and altKey modifiers are detected in combination, not handled independently. If you want to detect multiple key codes like, E and F together, for example, you'd need to keep track of them using keydown and keyup as per above.
Comment: This is not a good approach for ***modifier*** keys like "Control", "Shift", "Alt", etc.
Comment: I couldn't get Firefox to recognize the Alt Gr in combination with a letter key, only the combination with a plain Alt. So I used this method, though I had to modify it and fix it. It has some not so optimal logic. But the core idea of it works, of course. Be aware though that if your key event function is an async function containing an await, then the keyup event never fires! So extra logic is needed for that problem. But in the end, after all this was working nicely. I found the real solution, the event.getModifierState('AltGraph') which is what I was actually searching for from the start.
Answer: Quick note. If you're detecting shift, then you need to capitalize whatever letter you're checking. Shift capitalizes the normally lowercase letter.
if (zEvent.shiftKey && zEvent.key === "T")
vs
if (zEvent.ctrlKey && zEvent.key === "t")
if (zEvent.altKey && zEvent.key === "t")
Answer: If you, like me, came here to find out how to detect the combination of the "Alt Gr" key with a letter key, then the properties like for example event.altKey cannot be used for this, since there is no event.AltGrKey property.
In that case you can use
event.getModifierState('AltGraph')

For more details see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/getModifierState
Answer: I'm using hotkeys-js to abstract the functionality, but still had to let the user choose his own custom shortcut (without knowing it in advance).
I then tried @Brock Adams's answer to get an equivalent format of hotkeys-js of the shortcut pressed in an input box.
Things I've found while experimenting (on an Italian QWERTY keyboard layout on Chrome 92):

Every AltGr character "loses" the modifier attributes. AltGr can be substituted with Ctrl+Alt combination. So Ctrl+Alt+E (as in OP question) gives out €. Same it's true for Ctr+Alt+5. Other combinations have the same problem, like Ctrl+Alt+ò which on Italian keyboards gives out @
Every Shifted character is found in e.key as it's shifted counterpart, keeping the modifier attributes, so Shift+5 prints out as Shift+% which is questionable (given the AltGr behaviour).
Some combinations don't trigger the event no matter what. I've found as examples Ctrl+Shift+9, Ctrl+Shift+0, Ctrl+Shift+L and Ctrl+Shift+Alt+D on my keyboard. That might be a limitation of membrane keyboards.

The second point was critical for me, since our clients are used to Ctrl+Shift+[Number] combinations.
I've solved it by handling the special case of keyCode being between 48 and 58 and converting manually to the corresponding digit. It still doesn't solve any other special character modified with Shift though, but given that they are extremely depended on the keyboard layout, I don't see any universal solution. Still, I've never known anyone that wanted a shortcut with special characters.

const input = document.getElementById("keyPrssInp");
input.addEventListener('keydown', e => {
  input.value = `${e.ctrlKey ? 'ctrl+' : ''}${e.shiftKey ? 'shift+' : ''}${e.altKey ? 'alt+' : ''}${e.metaKey ? 'meta+' : ''}${["Control", "Shift", "Alt", "Meta"].includes(e.key) ? "" : (e.keyCode < 58 && e.keyCode > 47 ? e.keyCode - 48 : e.key)}`
  e.preventDefault();
});
Press keys in here: <input type="text" value="" id="keyPrssInp">

If readability is not a requirement and/or you know in advance the key combination you want to check, using event.keyCode instead of event.key is probably safer.


Hibernate works on server but NOT in Eclipse when new entities added

Question: I have looked at countless posts on here and none have seemed to fix my problem. I have an enterprise Java application with Hibernate and JUnit, but this seems to be more of a test environment problem. Multiple developers are experiencing this issue separately on their local systems in Eclipse. Everything works perfectly fine on a remote Tomcat server.
I added 4 new entities and all are experiencing the same issue so I will focus on 1. I have absolutely ruled out spelling mistakes, not adding the entity to persistence.xml, and JPA validation. It validates in Eclipse and compiles perfectly, etc.
NOTES:

I have tried both a NAMED QUERY as well as a NATIVE QUERY, and neither work. Native Query throws org.hibernate.MappingException: Unknown entity: com.xx.xx.db.entity.Dog exception. Named query throws  org.hibernate.MappingException: Named query not known: Dog.findByDogName
We do not use hibernate-cfg.xml or something of that nature. We use persistence.xml and my snippet is attached below.
All of the old entities that were already there (and corresponding
named queries, annotations, etc) work fine. It's only the new ones
that are causing problems.
We are using Eclipse Kepler and Eclipse Juno running on CentOS 5.9. Testing framework is JUnit

entity:
package com.xx.xx.db.entity;

import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;

import java.util.*;
import javax.persistence.*;

import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Type;
import com.xx.xx.db.dbenums.*;
import com.xx.xx.db.helper.*;
import com.xx.xx.db.dao.DaoHelper;

@Entity
@Table(name = "DOG")
@NamedQueries({
    @NamedQuery(name = "Dog.findAll", query = "SELECT a FROM Dog a"),
    @NamedQuery(name = "Dog.findByDogName", query = "SELECT a FROM Dog a WHERE a.dogName = :dogName")
    })

public class Dog implements Serializable
{

private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@Column(name = "DOG_ID", length = 16)
private Long dogId;
@Basic(optional = false)
@Column(name = "DOG_NAME", length = 16)
private String dogName;

public Dog()
{
    super();
}

public Dog(Long dogId)
{
    this.dogId = dogId;
}
public Dog(Long dogId, String dogName)
{
    this.dogId = dogId;
    this.dogName = dogName;
}

public Long getdogId()
{
    return dogId;
}

public void setdogId(Long dogId)
{
    this.dogId = dogId;
}

public String getdogName()
{
    return dogName;
}

public void setdogName(String dogName)
{
    this.dogName = dogName;
}
}

DAO:
public Dog findByDogName(String dogName)
{
   try
    {
        dogName = dogName.toUpperCase();
        Query query = entityManager.createNamedQuery("Dog.findByDogName");
        query.setParameter("dogName", dogName);

        List<Dog> mcList = query.getResultList();
        if (mcList != null && mcList.size() > 0)
        {
            return mcList.get(0);
        }
        _log.debug("dog match not found");
        return null;

    } catch (Exception e)
    {
        return null;
    }
}

snippet from persistence.xml:
<class>com.xx.xx.db.entity.xxxxxxxxxxx</class>
<class>com.xx.xx.db.entity.xxxxxxxxxxxxx</class>
<class>com.xx.xx.db.entity.Dog</class>

Comment: I guess you are using a separate bin directory for running you app locally. If so can you check if the persistence.xml is copied every build (and/or time you change it) to the bin location. Just lost a day on a similar issue with JPA and eclipse Mars (buggy as hell) not copying the persistence.xml file.
Comment: hi! I see that persistence.xml is being built into the target directory of the war, I think this is what you mean? I wonder if there is some kind of 'cache' you can clear for eclipse other than the workspace...? tried that one.
Comment: Usually when you go to **project -> clean** it discards all build information, is that what you mean by clear eclipse cache?
Comment: yeah i'm kinda grappling at straws here. in the past, i've had issues with various frameworks and plugins and just cleared my workspace then re-imported projects and the bugs would be fixed. but i'm not having success with that approach this time. project -> clean doesn't seem to help either :(
Comment: Ok, extremely weird: Work around 1001: use a Tomcat in Eclipse to test with.
Answer: Turns out our application has multiple persistence.xml files (1 for each sub-project) and even though the "Dog" entity was in the persistence.xml for the sub-projects where the Dogs were being used (and tests were being run), Maven was not able to handle that. It was reading from a persistence.xml first that did not have the Dog entity listed and was unable to merge I guess.
Adding the new entity to all of our persistence.xml files solved the problem, after lots and lots of digging.


Jquery .ajax beforeSend seems to remove the click event handler from a button?

Question: I'm trying to work with wordpress to stop an ajax request sent by Jquery and re-submit it with some additional data.
Here's how its working:

User clicks a submit button.
Wordpress submits the ajax request
I have a global beforeSend function set up using .ajaxSetup in this way:
$.ajaxSetup( {beforeSend: monitorRequests } );
When wordpress submits the request, its intercepted by my function, which calls another function that submits another ajax request, while monitorRequests' returns false, which cancels the original ajax request.
My own ajax request is sent, without any problems.

However here's the issue. After doing this once, if the user clicks the submit button again, wordpress's click handler is not called. I'm wondering why this is, whether this has anything to do with the ajax request being cancelled? Or anything else? What should I do to make it so that the click handler continues to be called?
Comment: are you removing/changing the button at all? if so, that may be removing the click event. however I can't really tell since no code is provided.
Comment: @kennypu I'm not doing anything to the button except adding/removing a css class to it..
Comment: Ahh.. it seems wordpress disables it during the request.
Answer: Figured it out, Wordpress disables the button during the ajax request, and it remains disabled since wordpress's callback is never called.
Answer: $.ajaxSetup globally affects ajax calls in your page. You have no idea how many AJAX implemented in WP plugins and How each its custom implement.
Try narrow your scope to specific element. You may uses
$('.submit').bind('click', function(){ /* your fn */ });
//You can have many 'click' binding eg..
$('.submit').bind('click', function(){ /* another */ });
$('.submit').bind('click', function(){ /* yet another */ });

insert your script before existing one. You function will be called first.


How do I output an XML document object that is populated with SQL query data containing HTML content to an XML file in ColdFusion?

Question: I have written a script in ColdFusion that grabs all of the HTML content for my website in a database table and creates an XML document object. Below is my code so far.

<cfquery name="qPageInfo" datasource="#application.datasource#">
    SELECT top 800 id, title, info, app
    FROM sitePublic
</cfquery>

<cfdump var="#qPageInfo#">

 <cfxml variable="xmlPageInfo">
    <page>
        <cfoutput query="qPageInfo">
            <id>#qPageInfo.id#</id>
            <pagecontent>#Trim("#XMLFormat(qPageInfo.info)#")#</pagecontent>
        </cfoutput>
    </page>
 </cfxml>

 <cffile action="write" file="%filepath%/webcontent.xml" output="#qPageInfo#">

I was able to successfully do a cfdump on the XML document object and it dumped all content for all web pages in the browser window.
However, the part I cannot seem to get working is the last line, <cffile> to output the XML data to an XML file. Below is the error I get when trying to run execute this.

The expression has requested a variable or an intermediate expression result as a simple value. However, the result cannot be converted to a simple value. Simple values are strings, numbers, boolean values, and date/time values. Queries, arrays, and COM objects are examples of complex values.  The most likely cause of the error is that you tried to use a complex value as a simple one. For example, you tried to use a query variable in a cfif tag.

I am new to ColdFusion so I could be leaving something out in my code, does anyone have an idea on how to fix this?
Comment: Nothing to do with your issue, but you do not need quotes or extra pound signs when nesting function calls. ie Use `#Trim( XMLFormat(qPageInfo.info) )#` instead of  `#Trim("#XMLFormat(qPageInfo.info)#")#`.
Comment: Shouldn't `output="#qPageInfo#"` be `output="#xmlPageInfo#"` You build the xml but then use the query output to write not the xml.
Comment: My apologies for the delayed response. Thank you Leigh and haxtbh for pointing those details out to me.
Answer: I have a large and small concern about this
First

<cfxml variable="xmlPageInfo">
<page>
    <cfoutput query="qPageInfo">
        <id>#qPageInfo.id#</id>
        <pagecontent>#Trim("#XMLFormat(qPageInfo.info)#")#</pagecontent>
    </cfoutput>
</page>
</cfxml>

This is going to generate lots and lots of <id> and <pagecontent> tags
Consider
<pagecontent id="#qPageInfo.id#">#Trim(XMLFormat(qPageInfo.info))#</pagecontent>

Second
<cffile action="write" file="%filepath%/webcontent.xml" output="#qPageInfo#">

Now the real problem, qPageInfo is the query. I suspect that you wanted to write the xml.
The simpler approach is to deal with the XML as a string
<cfsavecontent variable="xmlPageInfo">
<page>
    <cfoutput query="qPageInfo">
        <pagecontent id="#qPageInfo.id#">#Trim(XMLFormat(qPageInfo.info))#</pagecontent>
    </cfoutput>
</page>
</cfsavecontent>

<cffile action="write" file="%filepath%/webcontent.xml" output="#xmlPageInfo#">

OR
If you want to make sure you are processing xml and not just a string that is xml
<cfxml variable="xmlPageInfo">
<page>
    <cfoutput query="qPageInfo">
        <pagecontent id="#qPageInfo.id#">#Trim(XMLFormat(qPageInfo.info))#</pagecontent>
    </cfoutput>
</page>
</cfxml>

<cffile action="write" file="%filepath%/webcontent.xml" output="#ToString(xmlPageInfo)#">

Comment: I used the `` method.
Comment: Which approach did you end up using? `` or `` ?
Answer: Not sure if you posted the actual code with your question or not but you have % percent signs instead of # hash tags around your filepath variable.
This:
<cffile action="write" file="%filepath%/webcontent.xml" output="#qPageInfo#">

Should be this:
<cffile action="write" file="#filepath#/webcontent.xml" output="#xmlPageInfo#">

updated to use the correct variable xmlPageInfo for writing the file as others have mentioned.
Comment: Hi Miguel, thank you for your response. I should have made a comment on this. I just put the %filepath% there as a placeholder for me so I know to put the full file path later. Sorry about that.


How do I safely farm mid while Pudge is missing?

Question: Here's the situation, I like playing QE Invoker mid, but I have troubles when I play against Pudge. I will always crush him in lane. I always harrass him so he never comes in for any last hits. I will keep creeps in between us so he cannot hook me. Basically, the laning phase is very easy.
But once Pudge hits level 6+, (if he's good) he will start to nonstop roam around the map and gank. I am then presented with these problems:

If he's good, he will get smoke, and wards become useless. I will never really know where he is on the map.
Because I do not know where he is I can't position myself to block a hook.

When it reaches that point in the game where I don't know where Pudge is, what do I do to safely continue farming gold/exp? It seems there is nothing I can do to stop the risk of being helplessly hooked by a smoked-up Pudge.
PS. This question works for any hero really, but if you have some tips that could be applied to Invoker specifically that would be nice.
Answer: Well if you are really affraid of being hooked versus Pudge, having wards high ground is the best solution.
You can ask your support to put up wards so you will always see where pudge is (see screenshot at the end).
Then as an Invoker you can put an early point in wex just fot ghost walking away. This might delay your dual forge spirit (in the QE built) but if you really feel insecure that might be the best way to go.
With any mid hero you have to not make the basic mistake versus pudge which is : try to escape the rot by running. If you ever get hooked, trade hit with pudge and burst him with your spell. If you try to run you're almost certainly dead. Pudge has a really low armor at low level so your right click damage will hurt him badly, plus remember that the rot inflict damage to himself too so you can often turn a hook into a kill for yourself, just dont be afraid to manfight him. Pudge players tend to get overconfident when they land a hook, prove them they should not.
Another great tip is : rot does not dispell healing salve until its level 4, so you can use a salve to get some hp back between 2 hit and that might save your life.
Screenshots
Those wards' position can be used to avoid any kind of early ganks. You can watch the minimap to have an idea on what vision it gives.
When you are on the Radiant side :

When you are on the Dire side :

This last observer is usefull to scout mid highgrounds at all time to avoid hooks (you can place it on both side but preferably the enemy's side) :
Comment: Those are some good wards, those should solve my problems. One thing is that in 6.79 [smoke goes through truesight](http://en.reddit.com/r/DotA2/comments/1oq11m/true_sight_does_not_reveal_smoke_of_deceit_in_679/). Still, looks like this will keep you safe most of the time. I guess if you see Pudge has smoke you just have to be really carefull.
Comment: +1 nice answer, and couldnt resist: http://hydra-media.cursecdn.com/dota2.gamepedia.com/9/9a/Anti_blink_03.mp3
Comment: @JesusPlusPlus11 yo'ure welcome, the point about smoke bug me, gotta check that this seem a bit too OP for me but that 6.79 patch is weir anyway ;)
Comment: @JesusPlusPlus11 oh god its true, why would icefrog do that T_T, well anyway the ward spots are good, just play safe. Smoke break within 1025 range and level 7 hook has 1300 range so you have a fairly low margin to react
Comment: Yeah I guess you could just have an escape spell ready (tornado, def. blast, ghost walk) if you see he has smoke, and pray to god you can cast it fast O_o
Answer: You can farm with your forge sprites if you can or try to keep them around you depend on your location so they will get hooks. But being a Pudge player, it's kinda hard to do anything to Pudge if you get hook and you're Invoker. You can buy a Eul's and tornado yourself as soon as you get hooked to give you some time to think. You can also Force Staff away before you get dismembered.
Comment: Welcome to Arqade.  Can you edit this post to make it read a bit clearer?
Answer: Do not allow your wave of creeps to be far from your tower.


JS split string on positive lookahead, avoid overlapping cases

Question: I have a set of data that includes dated notes, all concatenated, as in the example below.  Assume the date always comes at the beginning of its note.  I'd like to split these into individual notes.  I've used a positive lookahead so I can keep the delimiter (the date).
Here's what I'm doing:
  const notes = "[3/28- A note. 3/25- Another note. 3/24- More text. 10/19- further notes. [10/18- Some more text.]"
  const pattern = /(?=\d{1,2}\/\d{1,2}[- ]+)/g
  console.log(notes.split(pattern))

and the result is
[ '[',
  '3/28- A note. ',
  '3/25- Another note. ',
  '3/24- More text. ',
  '1',
  '0/19- further notes. [',
  '1',
  '0/18- Some more text.]' ]

The pattern \d{1,2} matches both 10/19 and 0/19 so it splits before both of those.
Instead I'd like to have
[ '[',
  '3/28- A note. ',
  '3/25- Another note. ',
  '3/24- More text. ',
  '10/19- further notes. [',
  '10/18- Some more text.]' ]

(I can handle the extraneous brackets later.)
How can I accomplish this split with regex or any other technique?
Answer: To get your wanted output, you can prepend a word boundary in the lookahead, and you can omit the plus sign at the end of the pattern.
(?=\b\d{1,2}\/\d{1,2}[- ])

Regex demo

const notes = "[3/28- A note. 3/25- Another note. 3/24- More text. 10/19- further notes. [10/18- Some more text.]"
const pattern = /(?=\b\d{1,2}\/\d{1,2}[- ])/g
console.log(notes.split(pattern))
Answer: I would avoid split() here and instead use match():

var notes = "[3/28- A note. 3/25- Another note. 3/24- More text. 10/19- further notes. [10/18- Some more text.]";
var matches = notes.match(/\[?\d+\/\d+\s*-\s*.*?\.\]?/g);
console.log(matches);

You may do a further cleanup of leading/trailing brackets using regex, e.g.
var input = "[10/18- Some more text.]";
var output = input.replace(/^\[|\]$/, "");

Comment: Thanks, this works on my example but not on longer notes that involve multiple sentences on one date, or the user didn't use a period, e.g. "[3/28- A note. With more details. 10/7 i hate punctuation 11/9 Last note."  The issue with `match` is that I don't have a way to guarantee where the note will end, other than detecting the next date.
Answer: Try .replaceAll() and this regex:
/(\[?\d{1,2}\/\d{1,2}\-.+?)/
// Replacement
"\n$1"

Figure I - Regex

Segment
Description

(\[?
Begin capture group - match literal "[" zero or one time

\d{1,2}\/
match a digit one or two times and a literal "/"

\d{1,2}\-
match a digit one or two times and a literal "-"

.+?)
match anything one to any number of times "lazily" - end capture group

Figure II - Replacement

Segment
Description

\n
New line

$1
Everything matched in the capture group (...)

const notes = "[3/28- A note. 3/25- Another note 3/24- More text. 10/19- further notes [10/18- Some more text.]";
const rgx = new RegExp(/(\[?\d{1,2}\/\d{1,2}\-.+?)/, 'g');
let result = notes.replaceAll(rgx, "\n$1");

console.log(result);
Comment: Thanks, see my comment on Tim Biegeleisen's answer: your regex works on my simple example but not if the user left out periods.
Comment: @AaronDuniganAtLee answer is updated. You should update your question with the new criteria.


API Integration | Benefits of OpenAPI Specification & YAML or JSON File

Question: My question is probably best aimed at API developers dealing with API integration.

Do developers gain any benefit for integrating an API (e.g. within a 3rd party application) if they do receive the OpenAPI specification via a YAML- or JSON file?

Is there a coding advantage of having the actual YAML- or JSON file, which can be directly imported into the IDE compared to a simple access to the OpenAPI documentation (e.g. via SWAGGER UI)?

Potential benefits I could think of could be faster integration or less copy and paste effort from API Portal. Though, I would like to know if that is really the case.
Answer: This is a fairly subjective question, so perhaps a subjective answer is acceptable. My own personal uses for the OpenAPI file itself:

run a local mock server so I don't need to hit the main API (possibly incurring costs or inflicting load) while I'm developing
use my own documentation rendering (I have some accessibility needs, not all API documentation is equal)
import the OpenAPI into Postman for some quick API exploring
maybe generate some client/SDK code to get the integration started quickly

In summary, yes, developers benefit greatly from receiving the actual OpenAPI description, and I'd recommend you publish the OpenAPI alongside any API documentation.


Efficiency for Path.GetFileName storing in a string or reusing method call

Question: I am just very curious to find out which would be the best practice/efficient way to do.
I have a method where I have an OpenFileDialog. There I must use Path.GetFileName(openFileDialog.FileName) in 5 places inside the method. Which is the best way: either I call to GetFileName or save it in a string variable and then use that string variable?
" " + Path.GetFileName(openFileDialog.FileName) + " "

string fileName = Path.GetFileName(openFileDialog.FileName);
" " + fileName + " "

Comment: @DGibbs You may be right (I was assuming there is a loop, which is why I recommended `StringBuilder`). It was a bit silly to recommend Adrian optimising for *readability* and give some premature performance optimisation tips in the very same comment...
Comment: Is this an actual performance bottleneck? Unless it really is, I'd go for *which is more readable*. Otherwise, you should maybe have a look into `StringBuilder` too to make your string concatenations more efficient.
Comment: @Mudu I may be wrong here but wouldn't `String.Concat/String.Join` be better performing here? `StringBuilder` is better at concatenations within a loop (assuming this code isn't run within a loop).
Comment: @DGibbs The string concatenating using `+` is compiled to `string.Concat` in IL anyway..
Comment: @SimonWhitehead so i guess neither the `StringBuilder/Concat` will help in this case ;)
Answer: Apart from the considerations on readability and maintenance already outlined by other answers this little prog will demonstrate the (little) gain in performance of the string storing option
void Main()
{
    string p = @"d:\temp\file.txt";
    string result;

    Stopwatch sw = new Stopwatch();
    sw.Start();
    for(int i = 0; i < 100000; i++)
    {
        result = " " + Path.GetFileName(p) + " ";
    }
    sw.Stop();
    Console.WriteLine("PathGetFileName:" + sw.Elapsed.ToString());
    sw = new Stopwatch();
    sw.Start();
    string file = Path.GetFileName(p);
    for(int i = 0; i < 100000; i++)
    {
        result = " " + file + " ";
    }
    sw.Stop();
    Console.WriteLine("string concat:" + sw.Elapsed.ToString());
}

result:
PathGetFileName: 205632

string concat: 65234

Of course, this is microoptimization and should not be given much consideration.
In this case the readability of code is more important.
Comment: In a realistic use case (i.e. one call to Path.GetFileName each time the OpenFileDialog.Show() is called) there won't be any difference. And I suspect the major part of the CPU time in your example to be used for string concatenation.
Comment: Absolutely true, but the string concatenation exists in both examples
Comment: regarding strings concatenation: should I use string.format or stringBuilder? which is most efficient?
Comment: @AlexaAdrian Again, you're micro-optimizing. Either one will be suitable unless you're processing hundreds of thousands/millions of pieces of data per second.
Comment: I just want to get used using best practices and in each day I am learning something new, so I want to fix this too :)
Comment: @AlexaAdrian - Try the example in the post but add a StringBuilder and see the results. Typically StringBuilder is better but it depends on the amount of loops (I assume due to the time it creates to make an instance of StringBuilder), but if the loop was 1000000000000 then I would guess StringBuilder is better, however, in this case I got faster results with string.
Comment: StringBuilder is better in this wicked case (100000 iterations), for small scale concatenations like the OP says it is Always more performant a simple string.Concat. (the + operator resolves to string.Concat internally) See some tests here http://www.dotnetperls.com/stringbuilder-performance
Answer: Just store the result of Path.GetFileName in a local variable.
It'll reduce the size of the code, be more readable (if the variable has a useful name) and will consume less CPU (even if you won't notice any difference).
Answer: If you use the file-name at 5 places in the same method, use a local variable fileName. That's readable, efficient and without side effects.
If you may change the file often and it's a (public) property or field use Path.GetFileName(openFileDialog.FileName), othwerwise it migt be possible that the variable is not the current file-name of the openFileDialog.
However, care more about readability and proper functioning than performance which is negligible in most cases.
Answer: If it's the same file name (eg, the user only specifies the file name once), then save it to a variable.
Saving it to a string is easier to read, maintain and should be quicker than calling the property of an object since you're calling a immutable reference type. However, I will point out that the only real advantage is probably that it's easier to read since calculation time may be different on paper but I doubt your application would show any differences in speed/performance.
Comment: Did you just say `string`'s are mutable.. ?
Comment: @SimonWhitehead Yes I did - the problem with fast typing! Thank you for pointing that out! Corrected!
Answer: If you plan on reusing the filename in the same block of code/scope, then just save it to a string and reference that as needed. This is not only far more readable but also more memory efficient. E.g.
string fileName = Path.GetFileName(openFileDialog.FileName);
//Reference fileName as needed


Is an ally character killed by a Geo Chain count as an Ally Murder

Question: from what i understand on what's required for the good ending, you need to have no ally murders, i try my best to avoid my character being in any line of fire of my own attacks cause it never turns out good if they are.
When i was in the Item World getting Geo Chains to boost up the Bonus Gauge to level up some classes to unlock the newer ones one of my guys (well girl) i accidentally left on a geo panel when the chain started, she was bellow level 5 with no amour so you can imagine what happened.
anyway, i'm wondering if this counts as an ally murder
Answer: No, they do not.
From the Disgaea wiki on Ally Kills:

Ally kills do not include:

Killing Specialists
In Disgaea 2 and later, throwing Prinnies or characters killed in the subsequent explosion
Throwing an enemy into the Base Panel
Making a tower of characters, ending the turn and killing a character with the inflicted damage (in Disgaea 1)
Killing a clone
Being killed in a Geo Chain
Being killed by poison , even if inflicted by an attack by the player


In werewolv.es does the Ring of Tenacity cancel out the Disruption Orb if both items are held by the same player?

Question: The Ring of Tenacity states:

The Ring of Tenacity prevents its bearer from being Roleblocked.

Whilst the Disruption says:

A Disruption Orb will roleblock anyone visiting you that is not Night Immune. Unfortunately it will also roleblock you at the same time.

Since the Ring of Tenacity doesn't make someone night immune, will they still be role-blocked whilst holding the Disruption Orb?
Answer: The Ring of Tenacity will win over the Orb's role-blocking here.
This is because the Ring of Tenacity adds an aura (visible to the Aura Seer) to its owner that gives them role block immunity which is active all the time. The Disruption Orb resolves at the end of the night phase and attempts to role-block its owner and everyone visiting its owner. The role-block is the same used by the Direwolf and Courtesan and includes the normal checks to bounce if the target is immune to role-blocks.
There discrepancy in the wording of the Orb's description because when it was made, the only protection against role-blocks was night immunity. That changed when the Ring of Tenacity and Potion of Resilience were made, and an additional property to players was added ImmuneToRoleBlocks. Existing night immune roles (such as the Vampire) had role-block immunity carried over when this change was made.
Comment: Follow-up question: does the Orb of Disruption block the holder every night, regardless of whether they are visited or not, or does it only block the holder if they are visited?


How to understand the Python code I wrote for a problem

Question: If I give 2 output is
2 2 2
2 1 2
2 2 2

and for 3 is
3 3 3 3 3
3 2 2 2 3
3 2 1 2 3
3 2 2 2 3
3 3 3 3 3

The code is as follows:
def square(arr, val):

    if val is 1:
        return [[1]]    //self understandable

    n = val + (val - 1)       //getting array size, for 2 its 3

    sideAdd = [val] * n
    arr.insert(0, sideAdd)      //for 2 it add [2,2,2] at first
    arr.append(sideAdd)         //append [2,2,2]

    for i in range(1, n-1):      //for inner elements add val to either sides
        arr[i].insert(0, val)    // like, for 2 [val,1,val]
        arr[i].append(val)

    return(arr)

array = square([[2, 2, 2], [2, 1, 2], [2, 2, 2]], 3)

# print(array)
for i in array:
    print(*i)

The output goes like:
3 3 3 3 3
3 2 2 2 3
3 2 1 2 3
3 2 2 2 3
3 3 3 3 3

which is a correct answer.
But when I tried to complete the whole solution by giving values through for loop and sending returned array as parameter again through the same function like
n = 3
arr = []

for i in range(1, n+1):

    arr = square(arr, i)

the whole code is
def square(arrx, val):

    if val is 1:
        return [[1]]

    n1 = val + (val - 1)

    sideAdd = [val] * n1
    arrx.insert(0, sideAdd)
    arrx.append(sideAdd)

    for i in range(1, n1-1):
        arrx[i].insert(0, val)
        arrx[i].append(val)

    return arrx

n = 3
arr = []

for i in range(1, n+1):

    arr = square(arr, i)

for i in arr:
    print(*i)

This returns the answer as:
3 3 3 3 3
3 3 2 2 2 3 3
3 2 1 2 3
3 3 2 2 2 3 3
3 3 3 3 3

which is wrong
I already tried running in debug mode in pycharm, there I got an unusual thing. Check the screenshot below. When j = 1 (index), the code inserts 2 in blue underline but also in red which should not because the red underline index is 3 (insertion of 2 should occur at j = 3), and when j = 3 again insertion at index 1 (j = 1) is happening which makes the output 3 3 2 2 2 3 3 instead of 3 2 2 2 3.
I can't understand how that's happening. The screenshot is as follows:
https://imgur.com/yce47Pi
Comment: Add the expection you got in the question, instead of adding a screenshot of it
Comment: Hi devesh, the program runs without any errors or exceptions.
Answer: I think you are making this more complicated than it needs to be. You can determine the correct value of any cell from their indexes alone. Given a size n and row/column [i,j], the value is:
max(abs(n - 1 - j) + 1, abs(n - 1 - i) + 1)

For example:
def square(n):
    arr = []

    for i in range(n + n-1):
        cur = []
        arr.append(cur)
        for j in range(n + n -1):
            cur.append(max(abs(n - 1 - j) + 1, abs(n - 1 - i) + 1))
    return arr

Then
> square(3)

[[3, 3, 3, 3, 3],
 [3, 2, 2, 2, 3],
 [3, 2, 1, 2, 3],
 [3, 2, 2, 2, 3],
 [3, 3, 3, 3, 3]]

> square(5)

[[5, 5, 5, 5, 5, 5, 5, 5, 5],
 [5, 4, 4, 4, 4, 4, 4, 4, 5],
 [5, 4, 3, 3, 3, 3, 3, 4, 5],
 [5, 4, 3, 2, 2, 2, 3, 4, 5],
 [5, 4, 3, 2, 1, 2, 3, 4, 5],
 [5, 4, 3, 2, 2, 2, 3, 4, 5],
 [5, 4, 3, 3, 3, 3, 3, 4, 5],
 [5, 4, 4, 4, 4, 4, 4, 4, 5],
 [5, 5, 5, 5, 5, 5, 5, 5, 5]]

Edit
The problem with current code is this:
sideAdd = [val] * n
arr.insert(0, sideAdd)
arr.append(sideAdd)

You adding a reference to the same array (sideAdd) twice. So later when you add columns with:
arrx[i].insert(0, val)
arrx[i].append(val)

these two array are the same if they were added in an earlier loop. Adding to the first array also adds one to the second and adding to the second adds to the first. So you end up doing it twice. There are a couple ways to fix that, but the easiest is adding  a copy the second time:
sideAdd = [val] * n
arr.insert(0, sideAdd)
arr.append(sideAdd[:]) # Make a copy — don't add the same reference

Comment: Thanks, for your valuable answer Mark, which makes me see the problem on another angle. But, if you see in my first code block,  I hardcoded the parameter and the code shows the correct answer. but if I call the function above in for loop the code shows the wrong answer would you please explain that. that's the intent of my question. solution wise yours is superior. thanks again.
Comment: @arulprakash, yes that's a tricky bug. See the edit; I think it identifies the problem.
Answer: We can make use of numpys broadcasting rules here:
>>> np.maximum(np.abs(np.arange(-2, 3)[:, None]), np.abs(np.arange(-2, 3))) + 1
array([[3, 3, 3, 3, 3],
       [3, 2, 2, 2, 3],
       [3, 2, 1, 2, 3],
       [3, 2, 2, 2, 3],
       [3, 3, 3, 3, 3]])

So we can render the cube with:
import numpy as np
def cube(n):
    ran = np.abs(np.arange(-n+1, n))
    cub = np.maximum(ran[:, None], ran) + 1
    return '\n'.join(' '.join(map(str, row)) for row in cub)

For example:
>>> print(cube(1))
1
>>> print(cube(2))
2 2 2
2 1 2
2 2 2
>>> print(cube(3))
3 3 3 3 3
3 2 2 2 3
3 2 1 2 3
3 2 2 2 3
3 3 3 3 3
>>> print(cube(4))
4 4 4 4 4 4 4
4 3 3 3 3 3 4
4 3 2 2 2 3 4
4 3 2 1 2 3 4
4 3 2 2 2 3 4
4 3 3 3 3 3 4
4 4 4 4 4 4 4
>>> print(cube(5))
5 5 5 5 5 5 5 5 5
5 4 4 4 4 4 4 4 5
5 4 3 3 3 3 3 4 5
5 4 3 2 2 2 3 4 5
5 4 3 2 1 2 3 4 5
5 4 3 2 2 2 3 4 5
5 4 3 3 3 3 3 4 5
5 4 4 4 4 4 4 4 5
5 5 5 5 5 5 5 5 5


How to start a mysql container in Kubernetes with sample data?

Question: I need to start a MySQL container in Kubernetes with a database and a schema and sample data.
I tried to use the parameter "command" in the Kubernetes yaml, but at the time of execution, the db is still not started.
<code>        - image: mysql:5.7.24
          name: database
          command:
            [
              '/usr/bin/mysql -u root -e "CREATE DATABASE IF NOT EXISTS mydbname"',
            ]
          env:
            - name: MYSQL_ALLOW_EMPTY_PASSWORD
              value: "1"
</code>
Comment: Possible duplicate of [How to initialize mysql container when created on Kubernetes?](https://stackoverflow.com/questions/45681780/how-to-initialize-mysql-container-when-created-on-kubernetes)
Comment: https://stackoverflow.com/questions/45681780/how-to-initialize-mysql-container-when-created-on-kubernetes
Answer: Solved adding
<code>      volumeMounts:
        - name: initdb
          mountPath: /docker-entrypoint-initdb.d

...
  volumes:
    - name: initdb
      configMap:
        name: initdb-config

...
---
apiVersion: v1
kind: ConfigMap
metadata:
  name: initdb-config
data:
  initdb.sql: |
      mysqlquery
</code>
Comment: can u explain with more datails pls, I have some doubt
Answer: you can first create the container of mysql and later import the data of mysql it will that way.
you can create the pvc volume and start the container black without any database.
you can use the command exec to import the sql while and data to the database which will create the database and sample data inside the container.
start the container and go inside the container using exec mode and create a database and after that run this command
<code>kubectl exec -i <container name> -- mysql -h <hostname> -u <username> -p<password> <databasename> > databasefile.sql
</code>