import a static method

Question: How can I import a static method from another c# source file and use it without "dots"?
like:
foo.cs
namespace foo
{
    public static class bar
    {
        public static void foobar()
        {
        }
    }
}

Program.cs
using foo.bar.foobar; // <= can't!

namespace Program
{
    class Program
    {
        static void Main(string[] args)
        {
             foobar();
        }
    }
}

I can't just foobar();, but if I write using foo; on the top and call foobar() as foo.bar.foobar() it works, despite being much verbose. Any workarounds to this?
Comment: If you write `using foo;` then `bar.foobar()` is all you need to invoke it. With a static method, you're always going to have at least one dot.
Comment: is writing bar.foobar() so verbose?
Comment: You might wanna change the accepted answer - this question has a big enough view count to occasionally be updated.
Comment: switch to VB.Net? "Module" in VB does the "trick" - kind of tribute to VB.classic users I guess.
Comment: Java supports static method imports. Just saying... :)
Answer: With C# 6.0 you can.
C# 6.0 allows static import (See using Static Member)
You will be able to do:
using static foo.bar;

and then in your Main method you can do:
static void Main(string[] args)
{
    foobar();
}

You can do the same with System.Console like:
using System;
using static System.Console;
namespace SomeTestApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Test Message");
            WriteLine("Test Message with Class name");
        }
   }
}

EDIT: Since the release of Visual Studio 2015 CTP, in January 2015, static import feature requires explicit mention of static keyword like:
using static System.Console;

Comment: Note that static import does not work for extension methods at least up to .Net 8. More details [here](https://stackoverflow.com/q/38984853/2987814).
Answer:
This is the accepted answer, but note that as the answer below states, this is now possible in C# 6

You can't
static methods needs to be in a class by design..
Why do static methods need to be wrapped into a class?
Answer: Declare an Action Delegate variable in a suitable scope as follows and use it later:
Action foobar = () => foo.bar.foobar();

or even easier
Action foobar = foo.bar.foobar;

I shall also pay attention to Extension Methods (C# Programming Guide). If you're having methods with parameters, often it's quite cosy to have:
public static class bar
{
    public static void foobar(this string value)
    {
    }
}

and utilize it:
 string s = "some value";
 s.foobar();

This is actually a much better approach.
Comment: `Action` isn't a keyword, it's a type. This is a clever response, but _please_ don't actually use it.
Comment: @KonstantinVasilcov No, you didn't, but thkang did. That's what I was responding to.
Comment: `Action foobar = foo.bar.foobar;` would be slightly lighter weight, not to mention less verbose.
Comment: @thkang it's not a keyword. It's a delegate See [Action Delegate](http://msdn.microsoft.com/en-us/library/system.action.aspx)
Comment: @PaulPhillips I guess you should explain your comment in greater detail
Comment: @KonstantinVasilcov Where they said "I have to declare Action for every function in a static class" gave me a chill. It's rather demanding to have "no dots" and just hiding what is probably a deeper design problem. I imagined opening a method that used this trick on 5-10 different static functions, and I would not want to inherit that code.
Comment: @PaulPhillips I never said "replace everything". While in some circumstances moderate usage of this may improve readibility of the code.
Comment: @PaulPhillips missed that. Definitely agree with you.
Comment: @phoog Thanks! Edited my answer to reflect your comment
Comment: Never knew there was an "Action" keyword. however, this means I have to declare `Action ... ` for every function in a static class I want to use...
Answer: To add to the answers already here it's important to note that C# is a very typed language. Therefore, unless the method exists in the class you're in, you would never be able to do something like what you're looking for.
However, if you add the using:
using foo;

You can then access it with just the type and method like this:
bar.foo();

import a static method


Overflow hidden and child's backface visibility goes crazy

Question: The problem is that the 2nd article (.settings) should be rotated 360° and so its backface should be shown. (This even works if I delete the overflow in the .flip)
The only thing I can see is the frontside flipped 180 on Y axis
Possibly a bug in chrome?

PS: Yes I want the 'Really long text node display?' see as it isn't turned at all.
HTML:

        "Text longer than 2nd article"

        ...

CSS:
.flip article{
    overflow: hidden;
    -webkit-backface-visibility: hidden;
}

.fliped{
    -webkit-transform: rotateY(180deg);
}

http://jsfiddle.net/LatpP/1/
Answer: i had a hard time fixing your code, i also found some duplicate properties, so i decided to rewrite it from scratch since i think i got what you want to achieve.
basically you dont need to go from 360 to 180 you can just go from 180 to 0 and if you need another rotation from 0 to -180 ;)
when you put the same class which has a 180deg rotation on parent and child divs like this:

.fliped {
-webkit-transform: rotateY(180deg);}

what you got is the sum of degrees, that is 360 which equals to 0! also you don't always have to specificate when a div is at 0deg since this is by default.
so here is the code i wrote, the animation triggers on hover (i commented the class involved in this).
 i also added another wrapper to keep the perspective more realistic, if you dont like it just delete the very first class.
if you want to see the static backface only (as you asked) you just have to add the .hover class to the .flip-container div without messing with your css, like this:

EDIT
i forgot about the overflow issue which is easily solved by applying the overflow:hidden; property directly to the last single container of your markup. in my case directly to .front or .back divs (or both). here is the final Fiddle updated for your needs.
Comment: Well I really appreciate what you did it is awsome work (I would upvote if I could but I don't have enough reputation). But I can't change the article tag to the div tag since there is a bit of javascript.
https://student.sps-prosek.cz/~eisead11it/web/Anketa/prihlaseni
Login as Akxeone with password mnbvcx.
The rotation is triggered by clicking on the small wheel.
Comment: i saw your script and i don't think im going to rewrite that too... i would trigger this with a simple jquery like this `$(function() {
    $("#rotate").click(function() {
        $(".flip-container").toggleClass("hover");
    });
}); `
here is the new fiddle http://jsfiddle.net/sFV22/4/. hope this helps
Comment: Don't take me wrong, but you made the back flip 360° as well as I did since you turned the whole thing and then .back. My main problem is that when I add overflow hidden to  the "flipper" div the thing goes crazy
Comment: well you're actually right and i actually forgot about the overflow issue. just apply the `overflow:hidden;` directly to the to the div you want to apply it for example to `.front` or `.back` or both. Here is an updated Fiddle http://jsfiddle.net/sFV22/5/ i'm updating my answer also.
Comment: And do you know why the backface-visibility:hidden disable itself if I set the main div overflow? Cause I you may see on my page there are no. Div or anythink I could set the owerflow. (Look on it with debugger and watch carefuly what happends to tags) I like the animation that come with it but I would love to not see the overflow over the parent.
Comment: have you tried to set `overflow:hidden;` to your `.settings` class? i don't really know why backface-visibility is behaving like that, but after a brief research i came across some discussions with problems similars to yours involving this property.
[here](http://stackoverflow.com/questions/7455502/webkit-backface-visibility-not-working?rq=1) and [here](http://stackoverflow.com/questions/11378517/css-animation-wont-work-with-overflow-hidden) this one seems to be more similar to your issue and applies my solution as well
Comment: Yes I tried but since it is the div who makes the card to resize it doesn't really works. But screw it, I have a really nice problem now again I found that half of the backface react to click and the other don't. (try clicking inputs on there) any ideas?


Laptop directly booting to Ubuntu, grub repair fails, BIOS screen won't show up. Is there a way I can access Windows again?

Question: I am an absolute beginner in Linux and I think I have trashed my laptop the first time I tried a Linux distro.
I am using Asus A555L.
I installed Ubuntu 18.04 to dual boot with Windows 10 (64 bit). It was working well up untill I forced shut my laptop down by long pressing the power button when I was in Windows.
Since then when I switch my laptop on, it goes directly to Ubuntu, forget GRUB, even the Asus screen won't show.
I tried grub repair from within Ubuntu, it fails. Here's the pastebin link:
http://paste.ubuntu.com/p/yJWq6yRGzH
I have a Windows recovery flash drive but I can't access bios. Every single time I press f2 with the power button or ESC with the power button (the method that Asus website listed to access bios) my laptop just goes to a pitch black screen even though it's switched on.
My basic question is- Is there a way to access Windows again?
Also since the force shutdown incident, when in Ubuntu my screen keeps blinking. It was fine before that. Answers to similar questions say that it's because of the graphics card but it never created a problem up till now. Is it related?
Edit: It just needed another boot repair after completely draining out battery. Then went into windows safe mode, uninstalled a couple of things and was then able to access bios.
Comment: Possible duplicate of [Unable to mount Windows (NTFS) filesystem due to hibernation](https://askubuntu.com/questions/145902/unable-to-mount-windows-ntfs-filesystem-due-to-hibernation)
Comment: Possible duplicate of [Ubuntu 13.04 is unable to mount a disk drive from ex-windows system](https://askubuntu.com/questions/313872/ubuntu-13-04-is-unable-to-mount-a-disk-drive-from-ex-windows-system)
Answer: I had a similar problem, was false alarm for me personally. For some reason, I simply had to hold the power button for much longer (about 15 seconds) so that it truly shutdown.
No explanation why, but it shut off the display, back-lit keyboard, etc, but apparently was not actually shut down, and was stuck in some limbo state.
Comment: That's what brought OP in this state, so is unlikely to be a solution to his problem.  Very Hard Reboot (VHR) is really bad advise; use [REISUB](https://askubuntu.com/questions/926461/whats-the-difference-between-the-magic-reisub-reset-and-holding-down-the-power) instead. ¯\\_(ツ)_/¯  cc @karel
Comment: In my situation, which was in fact the solution to fix it, that did not work. Hence my answer. The state was not caused by a VHR, it was caused by an attempt to VHR without holding long enough.


How to make parent's Exception throw message defined in child?

Question: As I get it, since the Exception is thrown in the parent, the message is as it is defined in parent - null (System.Exception: "Exception_WasThrown", message: "Exception of type 'System.Exception' was thrown."). How to work around this issue?
Program, roughly:
internal abstract class Figure
    {
        protected string BadFigExceptionMessage { get; set; }
        public Figure(params int[] measurements)
        {
            if (measurements.Any(x => x<=0)) throw new Exception(BadFigExceptionMessage);
        }
    }

    class Triangle : Figure
    {
        public Triangle(params int[] sides) : base(sides)
        {
            BadFigExceptionMessage = "Such a triangle does not exist.";
        }
    }

My test with NUnit:
    [Test]
    [TestCase(-2, -2, -6)]
    [TestCase(0, 0, 0)]
    public void CalculateSquareOf_ImpossibleTriagSides_ReturnExceptionNoSuchTriag(int a, int b, int c)
    {
        Exception ex = Assert.Throws<Exception>(() =>
SquareCalculatorLib.Calculator.CalculateSquareOf(a, b, c)); //involves the Triangle constructor
        Assert.That(ex.Message, Is.EqualTo("Such a triangle does not exist."));
    }

Comment: Does this answer your question? [How to catch exception from a constructor in a derived class with C#?](https://stackoverflow.com/questions/17266105/how-to-catch-exception-from-a-constructor-in-a-derived-class-with-c)
Comment: @McNets not quite. I need to throw exception with a particular message which differes from child to child. But it is always thrown with the message set in the parent (null)
Comment: @McNets I actually just figured it's because of the constructors' execution order however I still don't know how to work around this issue other than raise 1 exception with the message "Such a figure does not exist"
Answer: Injecting the exception message into the constructor is one way to do this:
internal abstract class Figure
{
    public Figure(string exMsg, params int[] measurements)
    {

        if (measurements.Any(x => x <= 0)) throw new Exception(exMsg);
    }
}

class Triangle : Figure
{
    public Triangle(int a, int b, int c) : base("Such a triangle does not exist.", a, b ,c) { }
}

Comment: Personally I would define the error message as `virtual` in the `Figure` class and override it in the `Triangle` class in order not to pass it as a parameter - https://dotnetfiddle.net/MreQXn - but everyone has a different opinion about what is 'good practice'.
Comment: Doh! I barely read the code and missed the params...
Comment: @YoNa, it's fine. You could have several constructors, including a default constructor that each initialize the base class in different ways if you wanted.
Comment: I answered your question without addressing other important issues wrt to you code however. Most important, triangles always have 3 sides and your code allows for them to have 1 or more. You'd probably want to make that `Triangle(int a, int b, int c) base("Such a triangle does not exist.", a, b, c).
Comment: It worked except the parameters should be reversed! Is it a good practice though if it looks like `public Figure(string exMsg = "Bad Figure", params int[] measurements)` and then I call `Triangle triangle = new Triangle(0, 0, 0);` ?


Why does JavaScript return an array of node names and not node HTML elements?

Question: I am trying to see if a radio button is checked and if so, to set each radio button in the group to have an attribute "data-set" set to true.
Looking at my code, I am looping through each input, looking for any with the attribute of "radio" and then seeing if it is checked or not. If one of the inputs is checked then I want to set the dataset set to true for both elements that have the same name attribute.
The problem is that when I traverse up into the parent node and then view the children, I get an array of nodes such as [input#male, input, male: input, gener: input#male] instead of getting an array of HTML DOM elements such as [<input type="radio" name="gender" value="male"/>,<input type="radio" name="gender" value="female"/>].
Later, I try to see if these children elements are checked, however, these return undefined. I presume that this is because JS is returning name references instead of the actual HTML elements. Am I interpreting this correctly?
Below is an example, with self.inputs being the group of all inputs in the row, of how I traverse the DOM elements after looping through each input in the form row.
if ( self.inputs[a].length > 1) {
    //if there are a group in inputs such as input = text then go through
    //each one and see if it is empty or has a value
    for ( b = 0; b <= self.inputs[a].length -1; b++) {
         //if a radio button is checked then all other radio buttons with the same name
        //need to have the data-set value to true
        if ( self.inputs[a][b].getAttribute('type') == 'radio' ) {
           if (self.inputs[a][b].checked == false) {
            } else {
              //if the radio button is checked then make sure that all named grouped items are set to true
              var name = self.inputs[a][b].getAttribute('name');
              var this_parent = self.inputs[a][b].offsetParent;
              console.log( this_parent.childNodes[0].checked);
              var this_children = this_parent.getElementsByTagName('input');
              console.log( this_children);
           }
        } else {
        //if the form element has a value then we need to set the data-set to true;
            self.inputs[a][b].setAttribute('data-set', true);
        }
    }
}

Comment: post your relative `html` also
Comment: where does `self.inputs[a]` come from?
Comment: Your code retuns an array of HTML DOM elements (including text nodes of course) So your code is correct.
Answer:
The problem is that when I traverse up into the parent node and then
  view the children, I get an array of nodes such as [input#male, input,
  male: input, gener: input#male] instead of getting an array of HTML
  DOM elements such as [,].

Thats because you are using this_parent.childNodes[0] , which as the name suggests will return node.
If you want to get the element, use this_parent.children[0]
Here is the fiddle


What are the device numbers reported by lsof?

Question: What are the device numbers reported by lsof?
I read the man page, Identify devices from lsof, and this.
Still I do not know what is its meaning. In particular, for this case, what can I infer from the numbers?
$ lsof -ai tcp -c vino-server
lsof: WARNING: can't stat() tracefs file system /sys/kernel/debug/tracing
      Output information may be incomplete.
COMMAND    PID     USER   FD   TYPE  DEVICE SIZE/OFF NODE NAME
vino-serv 4011    user1   12u  IPv4   27353      0t0  TCP *:5900 (LISTEN)
vino-serv 4011    user1   11u  IPv6   27352      0t0  TCP *:5900 (LISTEN)
vino-serv 4011    user1   14u  IPv4 7506511      0t0  TCP XXXXXXXXXX (ESTABLISHED)

Answer: In this case, each of these is the inode number of the corresponding socket. You have listed open TCP sockets, and sockets are identified by their inode number. You can see the same numbers if you do ls -l /proc/<pid>/fd or ls -Lli /proc/<pid>/fd (in this case, <pid> is 4011). You can use the inode number when looking for information about that socket (e.g., in /proc/net/tcp or the ss command).
Comment: Ask for extended information with `-e` (e.g., https://stackoverflow.com/a/29340794/2072269)
Comment: So the output of `ss` (with a suitable flag, whatever that is) would contain `27352`, `27353` and `7506511`?
Haven't seen it with the flags I used so far.


How do I send an email when a Google Form is submitted?

Question: How do I send a notification email after a form has been submitted?
I have a Google Form, I open it and I go to menu More->Script Editor and add a script:
function OnSubmit(e) {
  MailApp.sendEmail ("email@example.com", "Form Submited: Foo feedback " + Date.now(), "Form Submited: Foo feedback");
}

I save the script and test it works by pressing the run button. The email gets delivered to firstname.lastname@example.com.
Then I fill in the Google Form, but the email does not arrive in firstname.lastname@example.com mailbox.
P.S.
I do not want to use "Email Notifications for Forms" plugin because it requests access to to many privileges. I do not want to use "Form Notifications" because for some reason it does not work for me (the emails do not get delivered).
Comment: Kindly try manually creating a "On form submit" trigger and attaching it to your function. Let me know if this work.
Answer: To send an email when a form is submitted you need to copy the following script to your script editor, run createTrigger once and accept the necessary permissions. This function looks for the 'on form submit' triggers, and if it finds none it creates a new one. After that you can submit the form and it will send an email specified in onFormSubmit function
function createTrigger() {

  var form = FormApp.getActiveForm(); // active form

  var formTriggers = ScriptApp.getUserTriggers(form); // form triggers

  var noTrigger = true; // assuming there is no 'onFormSubmit' trigger

  for (let t = 0; t < formTriggers.length; t++) {
    let trigger = formTriggers[t];
    if (trigger.getEventType() == ScriptApp.EventType.ON_FORM_SUBMIT) {
      noTrigger = false; // trigger exists
      break;
    }
  }

  if (noTrigger) {
    Logger.log('Creating trigger');
    var form = FormApp.getActiveForm();
    ScriptApp.newTrigger('onFormSubmit')
      .forForm(form)
      .onFormSubmit()
      .create();
  } else {
    Logger.log('OnFormSubmit trigger already exists')
  }

}

function onFormSubmit() {
  MailApp.sendEmail ('email@example.com', 'New form submission', 'Form submitted on ' + new Date());
}

Comment: As you wrote the code it will create a new trigger every time the function get called...very bad idea !  The trigger creation function must be in a separate function that runs only once. And also it would be be nice to explain your answer to make it useful.
Comment: @Sergeinsas thanks, done! Can you remove the -1 pls?
Comment: Yeah, just noticed it it sends several emails now instead of one. Do you know how to register the trigger only once?
Comment: check if a trigger already exists using https://developers.google.com/apps-script/reference/script/script-app  and use the result in a condition before creating a new one
Answer: Finally found it, well hidden under

Edit form mode
Responses tab
... menu button
Get email notifications for new responses.
Comment: this sends only notification not the data in email. Is there other setting which sends data as email notification.
Comment: thanks, this works without requiring an add-on! Amazing
Answer:
The easier way, now, is to use the "Notification rules..." item under "Tools".
Comment: Where can I find this menu. I don't see this menu on Google Form!
Comment: @Krunal See my answer, I just found it.


create empty files using touch command from words contained in a test.txt file

Question: I am trying to write a one line command to create 20 empty files with names extracted from a .txt file in another folder directory with the same txt extension.
I tried
for i in $(cat test.txt); do grep -w $i | touch $i.txt ; done

and
cat test.txt| while read line ; do grep $line ; touch $line.txt ; done

as well as
for filename in $(cat testfile.txt) ;  do touch head -20 $filename.txt; done

It does not work.  I do not know how to specify the 10 first words of the test.txt file.
Comment: Please [edit] your question to include a minimal example of your `test.txt` file - the format matters e.g. whether there is one word per line, multiple words per line etc.
Comment: @Fred007... you mean 20 first words?
Comment: How about `for i in $(head test.txt); do touch $i.txt ; done`?
Comment: ...or rather `for i in $(head -n 20 test.txt); do touch $i.txt ; done`, since you want 20 entries.
Answer: Does this work for you?
while IFS= read -r i; do
  touch "$i".txt
done < <(head -20 filename.txt)

Comment: Not sure why this was downvoted - although I'd suggest replacing the command substitution + here string with a process substitution + redirection i.e. `done < <(head -20 filename.txt)` and adding a `-r` to the read in case any of the filenames contain escapes. Arguably it should be `while IFS= read -r i; do` if we assume that any leading whitespace is intentional. I guess we should wait for clarification from the OP.
Comment: I would use [`while IFS= read -r i`](https://unix.stackexchange.com/a/209184/201297)
Answer: Get first 20 words.
Using cut:
$ for i in $(cut -d ' ' -f1-20 a.txt); do touch $i.txt; done

(with mapfile):
$ mapfile -d ' ' -n 20 -t < a.txt; touch ${MAPFILE[@]/%/.txt}

(with awk):
$ awk '{for (i=1; i<=20; i++) {system("touch "$i".txt")}}' a.txt

(with shell parameter expansion):
$ a=($(<a.txt)); a=(${a[@]/%/.txt}); touch ${a[@]:0:19}

Answer: xargs command has --arg-file flag, which allows using arguments for a command you intend to run from file. Thus, you can do
xargs --arg-file=filenames.txt touch

If you want first 20 lines
head -n20 filenames.txt | xargs  touch

Substitute tail instead of head for last 20 lines from file
Comment: @bac0n  That's not been confirmed yet, but I'll edit my answer if that is in fact so
Comment: he wants 20 words.


How do I get a slack bot that is sending a message via Python to post @here and ping the channel?

Question: Currently my slack app / bot will post a message being sent via Python that has @here or @channel in the text but the @here or @channel won't be highlighted or actually ping the channel. Here is the code:
import slack
def slack_notif(slackchannel,message):
        client = slack.WebClient(token='xxxmytokenxxx')
        client.chat_postMessage(channel=slackchannel, text=message)
slack_notif(
        slackchannel = 'mychannel',
        message = '<@here> This is a test'
        )

Output = @here This is a test
Intended output:
Answer: To use @here & @channel as 'mentions',
they are marked as :
<!here>  &  <!channel>


$x^n = x$ implies commutativity, a universal algebraic proof?

Question: I read in an answer on MO that Nathan Jacobson had given a universal algebraic proof that a ring satisfying the equation $x^n=x$ is commutative.
The sketch given in the answer is very clear : wlog one may assume that $R$ is subdirectly irreducible, as a result of a general result in universal algebra (that is, it has a minimum nonzero ideal).
Then one proves that a subdirectly irreducible ring satisfying the equation is a finite (skew, a priori) field, and one concludes from Wedderburn's theorem that it's commutative.
But I'm having trouble with the interesting step, that is

A subdirectly irreducible ring satisfying the equation $x^n=x$ for some $n\geq 2$ is a finite division ring

I had the folliwing idea : since $R$ has no nilpotent elements it should be a subdirect product of integral domains satisfying the same equations - however I know this property for commutative rings, and it relies on the well-known fact that $\displaystyle\bigcap\{p, p\in \mathrm{Spec}R\} = \{x, x$ is nilpotent $\}$ - and I don't know whether this is true for noncommutative rings.
As a matter of fact I'm pretty much convinced that it's not true (in $M_n(K)$, $K$ a field, $n\geq 2$, the set of nilpotent elements isn't a bilateral ideal - indeed there are no nontrivial ones). So unless this idea can be saved by the specifics of the situation, I can't go any further with it.
What I also noticed (I don't know if that can help though) is that $I^2 = I$, if $I$ denotes the minimum nonzero ideal.
I can also sort of make a connection with Wedderburn's theorem by studying the case where $Z(R)$ (the center) is a field; and so $R$ is a $Z(R)$-vector space. Then, it's a finite field. I can't yet see why $Z(R)$ would be finite dimensional (this would probably help a lot).
Am I anywhere near the right direction ? Can anyone give some hints to solve this ? (If possible - I know sometimes it's not- I'd rather see some hints than a full solution; and also if someone has read the article in question and saw that the proof in question was longer than what an MS answer can suggest, I'd also like to know haha)
EDIT: Here's the MO question : https://mathoverflow.net/questions/30220/abstract-thought-vs-calculation The answer I'm mentioning should be recognizable
Comment: Could you link the MO question you mentioned?
Answer:
A subdirectly irreducible ring satisfying the
  equation $x^n=x$ for some $n\geq 2$ is a finite division ring

First let's consider the elementary part of this statement. Observe
Lemma.
If $R$ is a subdirectly irreducible ring with
no nonzero elements that square to zero, then
 $R$ has no nontrivial
  zero divisors.
Reasoning:
Assume not. Then $R$ has elements $a\neq 0\neq b$
such that $ab=0$. The set
$bRa$ consists of elements that square to zero, so $bRa=\{0\}$.
Then $(b)(a)=RbRaR=R\{0\}R=\{0\}=(0)$.
If $I$ is the least nonzero ideal of $R$, then
$I\subseteq (b)$ and $I\subseteq (a)$, so $I^2\subseteq (b)(a)=(0)$.
This shows that all elements of $I$ square to zero, a contradiction. \\\
Here is how the lemma applies.
No nonzero element $a\in R$ which squares
to zero can satisfy the equation $x^n=x$,
so the lemma implies that if $R$ is subdirectly
irreducible and satisfies $x^n=x$, then $R$
has no nontrivial zero divisors. Given any nonzero $a\in R$
we have $0=a^n-a = a(a^{n-1}-1)$. Since $a\neq 0$,
it must be that $a^{n-1}-1=0$.  Hence, any nonzero
$a\in R$ satisfies $a^{n-1}=1$, showing that
nonzero elements are units. Thus,
$R$ is a division ring.
The non-elementary part of the statement

A subdirectly irreducible ring satisfying the
  equation $x^n=x$ for some $n\geq 2$ is a finite division ring

is that a division $R$ whose nonzero elements satisfy $x^{n-1}=1$
must be finite. The idea for this is to first prove
that any maximal subfield of $R$ is finite (which is easy),
then to prove
that any finite maximal subfield of $R$ has finite index in $R$
(see Lam's A First Course in
Noncommutative Rings, Theorem 15.4).
Comment: For the last bit, can't just one do the same proof as for fields ? I.e. a polynomial has a finite number of roots ?
Comment: No. Polynomials need not have finitely many roots in a division ring. For example, $x^2+1=0$ has infinitely many roots in the quaternion algebra.
Comment: Damn me and my commutative mind ! Thank you for your help, I'll try to see why  maximal subfields have finite index
Answer:
I had the following idea: since $R$ has no nilpotent elements it should be a subdirect product of integral domains satisfying the same equations - however I know this property for commutative rings, and it relies on the well-known fact that $\displaystyle\bigcap\{p, p\in \mathrm{Spec}R\} = \{x, x \text{ is nilpotent}\}$ - and I don't know whether this is true for noncommutative rings.

That much is true for noncommutative rings.
The condition that $x^n = x$ for some $n$ implies $R$ is von Neumann regular, and it is well-known that a reduced VNR ring (which is called a strongly regular ring) is a subdirect product of division rings. Therefore a subdirectly irreducible ring with these properties is a division ring.
The thing working for us here is that in a strongly regular ring, quotients by prime ideals are division rings, so the prime ideals actually satisfy the commutative definition of "prime." As such, their intersection contains all nilpotent elements, and their intersection is zero. So, you can rely on a similar argument.
Comment: Isn't $M_n(K)$ a counterexample ? Indeed, the set of nilpotent elements can't be a bilateral ideal (there are no bilateral ideal except for $0$ and $M_n(K)$)...
Comment: Ok, I see one inclusion : the forward one, $\subset$, but the $\supset$ one doesn't seem true... except of course in a setting where prime $\implies$ completely prime. I'll try that out, thanks !
Comment: @max I thought we were working under the assumption $R$ is reduced, and $M_n(K)$ is not reduced. The condition that $x^n=x$ trivially implies the ring is reduced. If $x$ is nilpotent, just take any $k>n$ such that $x^k=0$ and $k$ is a power of $n$. Then $0=x^k=x$.
Comment: Ah alright ! Then yes I agree (the other inclusion is then trivial). I thought you meant the equality was true regardless of $R$
Comment: @Max I guess that is the point of confusion. I'm saying that any reduced ring satisfying $x^n=x$ for some $n$ is a subdirect product of division rings. I wasn't speaking to the proof about the intersection of primes, although I'm pretty sure it is true in this special case.
Comment: @Max Yeah, it's definitely not true in general. Rings for which the nilpotent elements form an ideal are called $2$-primal, and a nontrivial matrix ring is an example of a ring that isn't $2$-primal.
Comment: Anyway, thanks to you I've reduced the problem to showing the property you mention, i.e. if $P$ is prime then $R/P$ is a division ring; which must be a classical result (though I don't yet see how to do it ! I'm so used to the commutative setting where it's obvious)
Comment: @Max To summarize, in our case, $P$ prime (noncommutative definition) happens to mean $P$ is prime with the commutative definition. That means $R/P$ is a von Neumann regular domain, which is a division ring.   That is, if $axa=a$ for nonzero $a$, you cancel $a$ to get $xa=ax=1$, i.e. $a$ is invertible.
Comment: Yes, yes, I simply need to see why $R/P$ is a domain (i.e. why the two definitions agree here)
Comment: @Max I'm trying to think of a slicker proof, but right now I only see a plodding way. $R/P$ is strongly regular, meaning that for every element $a$ there exists $x$ such that $a^2x=a=axa$. You can show that idempotents are central, and $ax$ and $xa$ are idempotents. Then suppose $a,b$ are nonzero, and $axa=a$ so that $xa$ is central. We have that $xaRb=Rxab=0$, and since $\{0\}$ is prime in $R$ it implies $b=0$ or $ax=0$. This is a contradiction.
Comment: Sorry, last ax should be xa
Comment: Mhm I must not have the same definition of prime as you do ! (By the way there's no need to assume $a,b\neq 0$ in your proof, so it can be direct and without proof by contradiction)
Comment: Ok I get how you get this property of prime ideals ! Ok pfew I'm almost there, only need to prove that idempotents are central (I'll get it at some point)


Using jsdom and update at every POST Request Variable with elements, but doesnt work

Question: i have the problem, that my response function doesnt update the Variable, which takes an element out of an file:
Post Function:
app.post("/profile", function(req, res) {
var id = req.body.playerid;
request("https://statsroyale.com/profile/" + id).pipe(fs.createWriteStream('stats.html'));
var wins1 = document.getElementsByClassName('statistics__metricCounter ui__headerExtraSmall statistics__trophyMetric');
var wins = wins1[0].innerHTML;
res.render("profile", {person: id, wins: wins}); });

jsdom.env function(which sets the file onetime at the beginning):
jsdom.env({
file: 'stats.html',
done: function (err, window) {
    GLOBAL.window = window;
    GLOBAL.document = window.document;
}

});
But then, if i request an other id, it shows me the old element
SRC:
 var express = require("express");
var app = express();
var bodyParser = require('body-parser')
var request = require("request")
var fs = require("fs");
var $ = require("jquery");
var jsdom
try {
  jsdom = require("jsdom/lib/old-api.js"); // jsdom >= 10.x
  const { JSDOM } = jsdom;
} catch (e) {
  jsdom = require("jsdom"); // jsdom <= 9.x
  const { JSDOM } = jsdom;
}
app.use( bodyParser.json() );
app.use(bodyParser.urlencoded({
  extended: true
}));
app.set("view engine", "ejs");
app.get("/", function(req, res) {
    res.render("home");
});
app.post("/profile", function(req, res) {
    var id = req.body.playerid;
    jsdom.JSDOM.fromURL("https://statsroyale.com/profile/" + id).then(dom => {
      var wins1 = dom.window.document.getElementsByClassName('statistics__metricCounter ui__headerExtraSmall statistics__trophyMetric');
      var wins = wins1[0].innerHTML;
      res.render("profile", {person: id, wins: wins});
    });
});
app.get("/profile", function(req, res) {
    var id = req.query.playerid;
    res.render("profile", {person: id});
});
app.listen(3000);

Comment: Don't do that `try catch`. I don't know who told you to do that, but that prevents you from accessing the `fromURL` convenience method. Just do `var jsdom = require('jsdom');`
Comment: Nice works now!
Answer: Setting up your jsdom environment only occurs once. You'd need to use fs.watchFile() to keep track of any changes that occur to the file and re-initialize the environment each time that callback is invoked. In addition, you'll need to make sure that
var wins1 = document.getElementsByClassName('statistics__metricCounter ui__headerExtraSmall statistics__trophyMetric');
var wins = wins1[0].innerHTML;
res.render("profile", {person: id, wins: wins}); });

isn't invoked until after the asynchronous pipe completes and jsdom is re-initialized with the updated file.
Update
Even easier, instead of using a global dom initialized from the local HTML file, you can invoke jsdom directly from the URL:
jsdom.JSDOM.fromURL("https://statsroyale.com/profile/" + id, options).then(dom => {
  var wins1 = dom.window.document.getElementsByClassName('statistics__metricCounter ui__headerExtraSmall statistics__trophyMetric');
  var wins = wins1[0].innerHTML;
  res.render("profile", {person: id, wins: wins});
});

Comment: Nice one, Thank you !
Comment: But it shows, that there isnt any method like fromURL()... I dont know what to do
Comment: If i could ask one thing: Why does my server lag, if i want to split the string?
src:
https://jsfiddle.net/quy0w90v/
Comment: I would imagine your server is crashing, not lagging. You call `.substring(...)` on `dom.window.document.getElementsByClassName(...)`, which isn't a string.


How do I install a fan rated junction box and replace the existing one?

Question: I have a fan I was trying to install but when I removed the cover that was covering the junction box I realized it felt kind of flimsy, I proceed to unscrew the blue plastic box from the mounting points and see it is held on by a rather thin hangar and realize from looking at the spec sheet it is not fan rated.
Question: What is the best way to make this fan rated?
I am willing to go in the attic if I need to but the ceilings are vaulted so it is kind of cramped in there.
Is there a solution where I can just slip it in through the existing hole?
what kind of hanger/box do I need?
The current box, its the second one: https://www.mainelectricsupply.com/customer/docs/skudocs/ctxez20chg-spec-sheet.pdf
The fans I need to install are not small and light but not heavy. Another thing to note is that there is fiberglass insulation directly over this spot and presumably the others, when I removed the box I had to touch some of it to get it back on the hangar
Comment: OP stated that the original box was the 2nd on the list.  That one does NOT have the disclaimer making it non suitable for fan installation.
Comment: Interestingly the first and third boxes in your posted spec sheet show" not suitable for fan installation" under the spec. However the second , which is the one you say you have, does not have that disclaimer.  Perhaps you do have a fan rated box.
Comment: I thought that might be the case but I took the disclaimer to be for all of them since it felt very flimsy.
Comment: The boxes shown by the OP would require getting into the attic to install. Those are meant for new construction or when there is attic access. Also they might be for light fixtures only and not fan rated. If what you have is the first one nailed to the side of the joist, it is possible that you could just keep it in place if your fan has hardware to shift to the joist. I have installed new Hunter fans that way. What brand of fan do you have?
Comment: How did this work out? I have another idea on how to get the brace out if you are interested.
Comment: It ended up not working out yet, upon finding the box location in the attic it was completely unreachable due to being vaulted ceilings. I was able to remove one which was not in too deep and it was in fact screwed in to the joist so I have to figure out a way to remove the other ones that I'll have to do through the hole. Oddly enough the other harder ones have joist in a perfect location to side mount a box but for some reason they chose to use hangers anyways but that still leaves me with how to get the old hardware out. What's the idea?
Comment: You say the box is attached to a brace and is  located right next to a joist? In  removing the box from the brace, did you damage the box or the brace? Could that box be reattached to the brace? I ask because some fans (e.g., Hunter) have hardware that allows using the original box if it is attached to the side of the joist and MIGHT work on your box if it is right next to the joist. In this installation the fan is shifted maybe 2 inches and is hung from below the joist not below the box. The fan shroud is large enough to cover the box. What is the mfgr of your fan?
Answer: Go to your favorite DIY/home improvement store and purchase an "old work" fan box with mounting bracket.
These are designed to fit into the ceiling through the existing hole in the ceiling (therefore not requiring any attic access). They have a rod & braces that will extend to brace the bar against the joists to the side and have a strong box that will support your fan.
Of course, if you do have attic access, then you can get a regular fan-rated box and attach it to a 2x4 or 2x6 nailed into the ceiling joists on either side. TBH, the "old work" box is actually an easier install in probably 90% of the cases...
Comment: I purchased mine at Lowes, but it is quite similar. The legs sit on the drywall (in my case on the plaster & lath) of the ceiling while the barbs on the ends dig into the joists. All in all, yup, that's _exactly_ what these are designed to do!
Comment: Is the the current brace nailed to the sides of the joists that face the hole? If so,you may be able to cut the brace in the hole then work the braces back and forth and up and down to loosen the nails. Then you could reach in with a prybar between the brace and the joist and finish getting the brace out.
Comment: If you can cut/bash the old box apart/up, you should be able to use a saw to cut the bar, if it doesn't come loose on its own after bashing the box.
Comment: would something like this work? to my understanding I could just twist it until it is tight but would those little bits that poke into the wood really hold a fan? another thing that occurred is that if the current mounting is nailed in I might have to go up in the attic anyways
https://www.homedepot.com/p/Commercial-Electric-15-3-cu-in-Remodel-Construction-Ceiling-Fan-Brace-with-1-1-2-in-Box-CMB150-OB/205383178
Comment: What make and model of fan are you installing? Have you already purchased it? Some fans are designed to use a non-fan rated box if the box is nailed to the side of a wooden joist. Fans with that design are designed so that the fan bracket is installed off center of the box, supported by two special screws that screw into the edge of the joist. The fan shroud is large enough so that it covers the electrical box. Of course this means that the new fan would be displaced by 2 or 3 inches from where the center of the old fixture was. Often this is not observable, but sometimes it would be.
Comment: In the case above the existing electrical box is left in place, but does not bear the weight of the fan. I have installed new Hunter fans that way. The special wood screws come with the fan hardware. On the other hand some boxes supporting light fixtures have light metal braces to locate the fixture between two ceiling joists. In that case you would need to remove the light bracing and the original electrical box and replace it with an expandable fan rated brace which will fit the joist spacing of 16" to 24" on center. Putting the new brace in place can be done from below inside the house . .
Comment: . . . getting the old light weight bracing out might be a challenge for an inexperienced installer. Installing one of these fans is a challenge if you have never done it before, but can be done if you understand the instructions, have reasonable hand and arm strength,  and enough patience to work through it slowly.
Comment: it appears the old box hangar is held in with nails and won't come out, attic is the only way thank you for all the suggestions.
Answer: Installing the new fan rated bar and box is the best way to proceed.
To totally remove the old light-weight brace would probably require going into the attic, but you should be able to just cut the old brace in the middle and bend both ends up (and perhaps laterally) out of the way of the new fan brace. Before cutting the old bar remove the electrical box. A sawsall would be best but you could use a hacksaw.
The original brace might be fastened on the back and top sides of the joists. The new fan rated one fits inside and is tightened so that it digs into the inside faces of the joists.
If however the original brace is nailed to the insides of the joists you might have to remove it entirely. I woud cut it in the center, push the ends up and reach in with a small prybar to pull out the nails and free the ends. Or you could do this from the attic.
The new fan rated bar is inserted without the box attached and once the bar is tightened then the box is attched to the bar. I have two Hunters installed this way and they are very secure.
Comment: How did this work out?


Laravel 5 Swift_TransportException "550 5.7.1 Client does not have permissions to send as this sender "

Question: I am trying to send mail with relay mail server using smtp in laravel but I am getting this error:
Expected response code 250 but got code "550", with message "550 5.7.1 Client does not have permissions to send as this sender

"
I am using Centos server.When doing telnet like this:
Connected to relay.*****.
Escape character is '^]'.
220 MSEXCFE04.***** Microsoft ESMTP MAIL Service ready at Wed, 11 Jan 2017 14:11:25 +0300
mail from:test@***.com
503 5.5.2 Send hello first

After this doing HELO server sending mail.
But in laravel I am getting trouble with above error.
How can I fix this error?
Thanks
Comment: This could be helpful: https://stackoverflow.com/a/42752270/386579
Answer: Your email provider is checking your sendind information. So, if you are not part of the Apple company, you cannot send an email as being @apple.com, can you? This is known as forgery. So
 Client does not have permissions to send as this sender

Basically is saying that the domain you are trying to send to is not yours, or the server you are using to send it from, does not have rights to send emails for this particular domain.
This is probably being done by a SPF policy: https://en.wikipedia.org/wiki/Sender_Policy_Framework


How to force a specific .Net version (down to the minor/minor-minor version number) to be used when running an app

Question: I have installed different versions of the .Net framework on my machine and I wonder if it is possible to choose one specifically when running a .Net app.
I tried setting it in App.config like so:
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />

but when I check the version being actually used via RuntimeInformation.FrameworkDescription, the output is .NET Framework 4.8.4261.0, even though v4.6.1 is installed on my system.
How can one test a specific version, e.g. to see whether a bug shows on a particular .Net version?
Comment: The documentation states that it applies to .Net Framework 4.7.1 and up.
Comment: I would probably recommend using separate virtual machines for testing and isolating bugs. That lets you have full control over most environmental parameters.
Comment: @JonasH That would surely work, but I'd like to avoid having to set up a virtual machine. Also, what is the point of having mulitple versions installed, if they cannot actually be used. I'd like to believe there is some way to use one of the installed versions, rather than just the latest one.
Comment: Side note: since most of full framework updates are in-place (replacing the existing version) you may want to clarify what exactly you did for "I have installed different versions of the .Net framework on my machine".
Comment: @AlexeiLevenkov The installed version all list up in the "uninstall" section of the control panel, so it looks like they are installed side by side.
Answer: You could specify the .NET Version for your application by changing it in your application propreties, in Visual Studio right-click on your project and then propreties, under Application tab.
Then Visual Studio will update config files automatically.


Tabs vs Scroll in content heavy website

Question: I have a content heavy website. In a particular page there will be lot of data to be presented to the user.
There are two options.
Full Scroll
Just present the data grouped properly with proper heading and separation.
Pros

Higher visibilty
No data is hidden
User tend to scroll these days

Cons

Uncertainty - since the user doesn't know how much data is there.
Amount of data can be very large at times making scrolling boring and tiresome
Harder to find one particular data ( fix - separate sub navigation must be provided for this which is another overhead and takes up space )

Tabs
Present the grouped data in form of Tabs
Pros

Certainty - User will know how much data is there
No need to scroll , All the data can be accommodated inside two folds at most.
Proper grouping and hierarchy - with easiness to find one particular group of data

Cons

Contents may be hidden inside tabs ( User with no prior knowledge may skip the tabs )

Which is a better UX principle in case of in a data intense website ?
Are there any research done on this topic ? Any A/B test results ?
Any useful insights is appreciated.
Comment: But in my case all the data is related. I don't thin using more than one pages will be a good idea. Information will be regarding a single product , and all of them are related.
Comment: Okay. Hmm. Do you hae a sketch of what you want?
Comment: It isn't bad to use multiple pages for this, makes this a bit clearer for the user, also you can use breadcrumbs to make it even easier. People always think that data has to be shown on one page, but it's best to do it in seperate pages. Thought about that?
Answer: Which is a better UX principle in case of in a data intense website? It depends on a use case...
Tabs

The primary goal of the module tabs UI pattern is to permit users to view a group of related data one at a time, which in turn allows designers to modularize this group of information in a compacted manner, saving valuable screen real estate. In this section, we'll discuss the instances when module tabs are desirable. -From Smashing Magazine

Full Scroll

If content between sections is related and end-consumer needs to go back and forth and do cross referencing, then full scroll would be more desired.

Example: Features and Specs (for a car or a computer)
Answer: If you have so much data, why wouldn't you want to use both methods?
Facebook does this really well in their documentations.
You can click the link on the side to scroll to the content. This gives you the visibility and also the certainty you want.
Facebook example, as shown below:

Tabs vs Scroll in content heavy website


What does x[:,[0,1,2,2]](a kind of splicing) mean in numpy arrays in python? I was executing the following in anaconda

Question: In Numpy using numpy.ones, I got this
import numpy as np

x=np.ones((3,3))
print(x)
[[1. 1. 1.]
 [1. 1. 1.]
 [1. 1. 1.]]

x[:,[1,1,1,1]]
array([[1., 1., 1., 1.],
       [1., 1., 1., 1.],
       [1., 1., 1., 1.]])

Comment: If you want to analyze what `x[:,[1,1,1,1]]`, or some other operation does, the first thing you should probably do is to use better test data: If the input (and consequently, the output) is all ones, you have no hope whatsoever of making sense of what's happening.
Comment: It's [integer array indexing](https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#purely-integer-array-indexing)
Comment: You are getting four copies of the first column.
Answer: x[:, [0,1,2,2]] means you are taking (all the rows of) columns 0,1,2 and 2 and combining them.
Since you have all ones in your data, it is hard to visualize but the following example will help:
x = np.array([[1,2,3],[4,5,6],[7,8,9]])
x
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])

x[:, [0]]
array([[1],
       [4],
       [7]])

x[:, [1]]
array([[2],
       [5],
       [8]])

x[:, [2]]
array([[3],
       [6],
       [9]])

x[:, [0, 2, 1, 1]]
out: array([[1, 3, 2, 2],
            [4, 6, 5, 5],
            [7, 9, 8, 8]])


Logic to use COUNT() to return number of matching values

Question: I'm trying to do something with SQL, teaching it to myself, and I'm unsure what to do next with what I want.
I'm trying to write a query into my DB (using just an "employee info" DB) that returns their name, a job they've worked on, but most importantly I want each job to have a "completion code" that tells about how the job was completed, and an int that shows how many times they've done a job with that specific completion code.
Right now, I can return all the info, sorted by person, job, then code, but I do not know how to get the count of each individual completion code (per employee). Here's what I have:
SELECT crew.EMPLOYEE_NAME, o.WORK_TYPE, oc.COMPLETION_CODE, COUNT(oc.COMPLETION_CODE)
FROM   CREW_WORK_SCHEDULE crew, ORDERS o, ORDER_COMPLETION oc
WHERE  crew.CREW_ID = o.ASSIGNED_TO_USER_ID
AND    oc.ORDER_ID = o.ORDER_ID
ORDER BY (crew.EMPLOYEE_NAME, o.WORK_TYPE, oc.COMPLETION_CODE)

But that COUNT in the select statement would just return the total number of completion codes, not the one for each code of an employee's job type.
Sorry if it's not perfectly clear, but does anyone know?
Answer: Look into the group by statement,
Group By crew.EMPLOYEE_NAME, o.WORK_TYPE, oc.COMPLETION_CODE
Answer: SELECT crew.EMPLOYEE_NAME, o.WORK_TYPE, oc.COMPLETION_CODE, (SELECT COUNT(*) FROM ...)

And then replace your conditional with the ellipses. It is difficult for me to write it since I don't know your table structures.
Comment: No problem! That is known as a `subquery` btw
Comment: Not sure if you got the earlier comment asking a follow-up q, but I solved my issues, and got this working. Thanks!


APDEX - Is there any new approach so far?

Question: Apdex is the application performance index that takes user's response times and classify them as "satisfied", "tolerable" or "frustrated". It is a simple approach to evaluate the user experience for business applications. Here is described what the Apdex exactly is.
My question: Has anyone of you heard about a new approach how to measure an application's performance? I read on several websites that the Apdex is already outdated. Do you know of newer/better approaches to measure user expectations?
Answer: Newrelic is a monitoring tool for web applications. They are using apdex as one of the primary measures but they also use "throughput" and etc. It has a 1 month pro subscription trial where you can see all the measures. I am on a standard subscription currenty, maybe you can discover more measures in pro subscription trial. Worth checking out :)
Hope I understood your question.


How to install Ubuntu Server in an XFS file system?

Question: I'm unable to install Ubuntu Server 18.04 (fresh install, I use live version from USB install) to XFS partition. I selected manual partition, manually selected XFS as the filesystem type for / directory. The installer automatically create /boot/efi partition and I think it's fine. Also, there's no problem during installation. After installation however, the GRUB error happened.
How to do this correctly? Is there any tutorial for fresh install of Ubuntu Server to XFS?
Comment: well.. after some search on Google. XFS is impossible to install on live cd image. So I abandoning the XFS. https://ubuntuforums.org/showthread.php?t=1060323
Comment: https://tutorials.ubuntu.com/tutorial/tutorial-install-ubuntu-server#0
Comment: note: I don't think XFS has anything to do with your grub issue (*where I'd check your machine's bios settings first for that*), but your question was about tutorial for install with xfs (which is a default *fs* for certain conditions anyway)
Answer: Installing Ubuntu on XFS is possible,
but:

/boot/efi should be FAT (any of FAT8, FAT16, FAT32)¹
/ should be EXT4²
individual specific directories can be mounted on XFS where needed.³

However: putting everything on XFS doesn't make sense at the time of this writing. (Who knows what the future and grub3 will bring...)
Note 1: Source, Section 5
13.3
Note 2: Source, Section 1.1
Note 3: Source, Section "Use Cases"
Comment: Section 13.3 in Note 1
Comment: This needs some references.
Comment: @fkraiem See [edits](https://askubuntu.com/posts/1161476/revisions)
Comment: @mook765 Thanks!  Updated!!:  **:-)**
Comment: I don't understand this answer. So, you recommend to install Ubuntu on XFS but, you pointed out some posts that don't recommend. So, what is the good answer here.
Comment: https://wiki.ubuntu.com/XFS#Disadvantages:~:text=GRUB%2DSupport%20is%20in%20an%20early%20stage%2C%20therefore%20using%20xfs%20as%20boot%2Dfilesystem%20can%20be%20a%20bad%20idea might be a good citation for the "However" point. With mounting specific directories, probably no citation is needed, and the provided one is for ZFS anyway.


T9 synonyms in java implementation

Question: I am trying to implement t9 algorithms using Trie. Can someone please suggest how to calculate all the permutations of words(valid or invalid both) for a given numeric input.
For eg in T9 phone: 2 abc, 3 def, 4 ghi......9 wxyz
so if a user presses 234, 3^3 words that can be formed:
adg, aeh, afi, bdg, bei, cfh.....
I am trying to code this in java.
Answer: There is a trivial relationship between the solution for a set of n numbers and the solution for the set of n numbers + a new number.
However, I wonder if you really want to enumerate all the words, because the set of words will grow pretty fast: 3^n
In practice, people use the other way: they have a list of candidate words, and they see which ones are matching a given set of numbers.

T9 synonyms in java implementation


VScode C/C++ formatting failed

Question: I'm on windows 10, It used to work before i don't know why it stopped working, it gives the error message "Formatting failed. See the output window for details." refer to
I've looked for a solution online but what I've found is people saying to use a different extension rather than the default c/c++ formatter which i really don't want to do, why ? it changes my code theme
i just want this fixed i don't want a replacement
Answer: Fixed! just updated to the pre-release version of the c/c++ extension and it worked like a charm, you can update it back later :)

VScode C/C++ formatting failed


Is the Andromeda Initiative Stuck in the Heleus Cluster?

Question: In Mass Effect 1, 2, and 3, ships move around the galaxy using mass relays. They can accomplish "short"-range movement between "nearby" stars using FTL drives on the ships, but to get from one cluster of stars to another they need the relays.
I recall the codex in those games saying that although citadel-based galactic society is spread across the galaxy, it's largely confined to small pockets around mass relays.
In Andromeda, the Nexus and the Arks traveled from the Milky Way to the Andromeda Galaxy over the course of 600 years. I'm not sure if that speed is consistent with the short-range FTL, or if that would require the relays.
I have yet to see any mass relays in the Heleus cluster, which they would need to go to other clusters, suggesting they're stuck there for the time being.
So, do they have access to relays? If not, how did they get to the cluster and how can they leave?
Comment: On Ada, a historian near the docking bay asks you if it's true that the Initiative can never go back to the Milky Way, and Ryder answers yes. This has been implied in quite a few other conversations.
Comment: However, according to the SFF SE question about how they got there so fast, they ought to be able to fuel up and turn around.
Comment: My guess is that once they've had time to settle and build in Heleus they'll start trying to develop their own Mass Relays. An argument to back this up is that before they were wiped out, the Protheans were on the verge to discovering the secrets to the mass relays so its not hard to assume the milky way species' would also try. Plus i think that the ODSY Drives could handle the initial trips into the other clusters as it wouldn't take as long as the transit between galaxies.
Answer: The 600 year timeframe is consistent with the FTL speeds they used to move between stars within the same cluster in the previous three games. This is discussed at more length on SF&F SE here: How do they get to Andromeda so fast?
The innovations that lead to them being able to make such a long journey between the stars are the cryo pods, and the ODSY drive:

Standard ship drive cores build up static electricity, and require periodic discharge on a planet or at specialized facilities to prevent static from building to dangerous levels. With few such suitable discharge points in dark space, the ODSY drive core was developed for the arks long-haul journey to Andromeda.

I've finished the game and nearly every side quest, and never saw or heard anything that even vaguely implied that there might be mass relays in the Heleus cluster. On my first playthrough, during the opening scene, I saw something that I thought might have been a relay, but it was just the Hyperion ark ship seen out of context with no introduction.
Those facts, combined with ample dialogue indicating that the Initiative is stuck in the Heleus cluster for the foreseeable future, lead me to conclude that

there are no mass relays in Heleus,
they didn't use a mass relay to get to Heleus,
and that they would need to fuel up and go back into cryo in order to leave the cluster.
Comment: They may have used a relay to get to Heleus. Once brought up to speed, an object keeps moving. Aim the relay at Heleus and it does its job. The only assumption is that they can slow down on arrival using the ship's own mass effect generators; which is a reasonable assumption given that they could slow down gradually in the last X years even.
Answer: FTL travel would require Eezo which is listed as Ultra-rare in the codex.
They are running short on supplies, provisions. So much so that they are not waking up everyone from cryo-sleep.
So they are stuck for now.
EDIT

As far as mass relays are concerned, they are reaper tech and so far the reapers and their tech, according to the ME 1-2-3 games, are confined to the Milky Way galaxy.
IMO the first question would be how did they survey the so called golden worlds, since any light making it to the Milky Way would be 2 million years old. For that in game explanation is they happened across a Geth built FTL telescope which let them see a more current picture.
As for the speeds, I am yet to piece together an in-game explanation. I will update as I progress through the game.
However there is an interesting discussion regarding the same on Sci Fi SE site:
How do they get to Andromeda so fast?
Comment: In theory they can build new relays. The Protheans did it, and the Asari have discussed it (at least Liara's "father" mentions it in ME2). How long that would take, and whether or not the Heleus cluster even has the resources to accomplish such a feat is unknown.
Comment: Heleus has eezo, the main element needed for FTL travel; so it is reasonable that _eventually_ they can build relays. However, given the population size and the Heleus cluster's available space, it'll be quite some time before they need to expand, giving them time to delay the relays until the civilization is in full swing.
Answer: tl;dr: There are no relays in Andromeda and leaving Heleus is highly infeasible for the time being.

The Mass Relays are Reaper tech and the Reapers were located in the Milky Way (dormant in the nearby empty space). There are no relays in Andromeda or on the way so they had to use standard FTL transport, hence why it took 600 years to get there. This is confirmed throughout the game during Ryder's conversations.
They are low on fuel and resources so travelling to a different cluster inside Andromeda is not possible, hence they're stuck in Heleus for the time being. They could fuel up with the help of the Angara, go back in cryo and point themselves somewhere else but why would they do that? They surveyed the galaxy and the Heleus cluster was the most viable so they already are in the best place they know. Flying somewhere else would imply the same risks they took when flying to Heleus (such as hitting the scourge). Not to mention that they're still not sure what happened to the rest of the arks and leaving them behind would cause a lot of anger among the sleeping "relatives" of the people left behind, including those of the exiles left in Heleus.
They could also point themselves back to the Milky Way but then it would all be in vain. Thousands of people dead and the only achieved thing would be a jump 1200 years into the future. Not to mention that they were unable to communicate with them so many things could have happened in 1200 years and the Milky Way could be all but destroyed by war.
Therefore their best bet is making do with what they have in Heleus, get a foothold in there, get fuel and resources, build up their population, military and technology, try to communicate with the Milky Way and scan the rest of Andromeda. Another goal would definitely be to analyze the scourge and stop it from being a problem. They might even be able to work with the races of Heleus to research better travel technology (maybe even as good as the mass relays?) and make Andromeda as nice as the Milky Way.


PHP Issue with array not printing the first element of the array

Question: I have an issue I cannot seem to fix. I have a function that takes a file and converts it to an array using the first row as the keys:
function parseCSVToArray($filePath)
{
    $csvData = [];

    if (($handle = fopen($filePath, "r")) !== false) {
        $keys = fgetcsv($handle); // Get the first row as keys

        while (($data = fgetcsv($handle)) !== false) {
            $rowData = array();
            foreach ($keys as $index => $key) {
                $rowData[$key] = $data[$index] ?? ''; // Assign each value to its corresponding key
            }
            $csvData[] = $rowData;
        }

        fclose($handle);
    }
    return $csvData;
}

Everything works as normal and creates the array as expected:
$getTheRecords = parseCSVToArray('Data/records.csv');

// File contents
record,subdomain,hub_knows,domain,type,value,action,rationale
mail.sub.domain.com.,sub.domain.com,Hub knows about this,domain.com,CNAME,dispatch.domain.com.,DELETE,Dispatch links can go

Array
(
    [record] => mail.sub.domain.com
    [subdomain] => sub.domain.com
    [hub_knows] => Hub knows about this
    [domain] => domain.com
    [type] => CNAME
    [value] => dispatch.domain.com.
    [action] => DELETE
    [rationale] => Dispatch links can go
)

Now the issue is when I go to use or print the data. When I loop through the array using:
foreach($getTheRecords as $element)
{
    echo "
";
    echo($element['subdomain']); // This will print the subdomain as expected.
    echo "
";
}

If I change 'subdomain' to 'record' it prints nothing. However, every other 'key' prints the results just fine.
Thank you in advance for your help!
I have tried changing the name of the first key to 'mainrecord' or anything and it still will not print out.
Iside loop var_dmup():
array(8) {
  ["record"]=>
  string(31) "mail.0lemonade.starchapter.com."
  ["subdomain"]=>
  string(25) "0lemonade.starchapter.com"
  ["hub_knows"]=>
  string(20) "Hub knows about this"
  ["domain"]=>
  string(17) "scdomaintest3.com"
  ["type"]=>
  string(5) "CNAME"
  ["value"]=>
  string(22) "dispatch.scnetops.com."
  ["action"]=>
  string(6) "DELETE"
  ["rationale"]=>
  string(21) "Dispatch links can go"
}

Comment: It's most likely a set of BOM chars at the start of the file https://stackoverflow.com/questions/32184933/remove-bom-%C3%AF-from-imported-csv-file
Comment: If you `var_dump($element)` inside the loop where you're trying to print it, what do you see?
Comment: @droopsnoot Added var_dump() t the question.
Answer: Your file likely has a UTF8 Byte Order Mark [BOM] at the beginning which is throwing off the first key. While a BOM isn't necessary at all for UTF8, some programs still add it as a "hint" that the file is UTF8.
If you var_dump($keys[0], bin2hex($keys[0]) you'll likely see that the first key's is longer than what is visible, and the hex output will show it prefixed with EFBBBF which is the BOM.
Try replacing:
$keys = fgetcsv($handle);

With:
$keys = str_getcsv(preg_replace("/^\xef\xbb\xbf/", "", fgets($handle)));

Which will trim off the BOM, if it exists.
Edit: A bit more broadly-applicable code.
function stream_skip_bom($stream_handle) {
    if( ! stream_get_meta_data($stream_handle)['seekable'] ) {
        throw new \Exception('Specified stream is not seekable, and cannot be rewound.');
    }

    $pos = ftell($stream_handle);
    $test = fread($stream_handle, 3);

    if( $test !== "\xef\xbb\xbf" ) {
        fseek($stream_handle, $pos);
    }
}

so after opening $handle you would call simply:
stream_skip_bom($handle);

Comment: [The fundamental goal of closing duplicate questions is to help people find the right answer by getting all of those answers in one place.](https://stackoverflow.com/help/duplicates#:~:text=The%20fundamental%20goal%20of%20closing%20duplicate%20questions%20is%20to%20help%20people%20find%20the%20right%20answer%20by%20getting%20all%20of%20those%20answers%20in%20one%20place.)


Invalide hook call, Hooks can only be calle inside of the body of a function component

Question: i created a functionnal component
import React from 'react';
import { View, ScrollView, Text, SafeAreaView } from 'react-native';
import { useState, useEffect } from 'react';

const listFiliere = ({item}) => {
    const [show, setShow] = useState(false);

    return(
        <View style={{ height: 30, flex: 1, justifyContent: 'center', borderBottomWidth: 1, borderBottomColor: 'blue' }}>
            <Text>{ item.name }</Text>
        </View>
    );
}

export default listFiliere

I called this one inside class component for renderItem of flatlist; and it return error of invlide hook call; Is the class component which called it the cause or anything else?
Answer: it could be a few things. the code you posted is not a lot to go on. Take a look at this page. A few things you can check
Answer: If the problem is that you are calling useState in a class component, please reference this post.
Basically, you cannot use the useState hook in a class component. The class component equivalent would be:
export class ListFiliere extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      show: false
    };
  }

  render() {
    return(
        <View style={{ height: 30, flex: 1, justifyContent: 'center', borderBottomWidth: 1, borderBottomColor: 'blue' }}>
            <Text>{ item.name }</Text>
        </View>
    );
  }
}

Comment: so my function can't be called inside class component if it use hook?
Comment: No, you can't use hooks inside a class component.


iOS people picker get contact emails in array

Question: I'm trying to get emails from a contact in my people picker (iOS), but I'm encountering a little problem (since Swift 2.0, before it was working nice) : I want to get that emails in a string array, but when I print it, it looks like this :
["(\n    \"myEmail1.com\",\n    \"myEmail2.com\",\n    \"myEmail3\"\n)"]
Here is my code :
if ((ABRecordCopyValue(person, kABPersonEmailProperty)) != nil) {
        let email: ABMultiValueRef = ABRecordCopyValue(person, kABPersonEmailProperty).takeRetainedValue() as ABMultiValueRef
        self.contactSelectedEmails = [String(ABMultiValueCopyArrayOfAllValues(email).takeUnretainedValue())]
        print(self.contactSelectedEmails)
        prefs.setObject(self.contactSelectedEmails, forKey: self.contactSelectedName.stringByReplacingOccurrencesOfString(" ", withString: "").lowercaseString + "_emails")
}

When I print self.contactSelectedEmails[0], I can get my array but I can't store it in the var.
Thanks for your help
Answer: Have you tried using the CNContact stuff instead of the AB framework?
I recently converted all of my code to use CNContact and I haven't had any issues in Swift 2.
For reference, below is some code that grabs an email address and saves it into core data, but you could just as easily put it in an array. It wasn't as painful as I thought it'd be to convert to the CNContact framework, and it actually made my code a bit simpler.
func presentPicker() {
    let contactPicker = CNContactPickerViewController()
    contactPicker.delegate = self
    contactPicker.displayedPropertyKeys = [CNContactEmailAddressesKey]
    print("ContactPicker called")
    self.presentViewController(contactPicker, animated: true, completion: nil)
}
func contactPicker(picker: CNContactPickerViewController, didSelectContactProperty contactProperty: CNContactProperty) {
    let contact = contactProperty.contact
    let name = "\(contact.givenName) \(contact.familyName)"
    let email = contactProperty.value

    let aFetchedRequest = NSFetchRequest(entityName: "Recipients")

    let predicate = NSPredicate(format: "name == %@", contact)
    aFetchedRequest.predicate = predicate
    let recordCheck = managedObjectContext!.countForFetchRequest(aFetchedRequest, error: nil)

    if recordCheck > 0 {
        //if person is in MOC
        let thePerson = (try! managedObjectContext!.executeFetchRequest(aFetchedRequest)) as! [Recipients]
        thePerson[0].emailRecipient = "\(email!)"
        thePerson[0].name = name

        print("does exist name \(thePerson[0].name)")

    } else {
        //if person isn't in MOC
        let newRecipient = NSEntityDescription.insertNewObjectForEntityForName("Recipients", inManagedObjectContext: managedObjectContext!) as! Recipients

        newRecipient.emailRecipient = "\(email!)"
        newRecipient.name = name
        newRecipient.uniqueIdentifier = NSUUID().UUIDString
        print("didn't exist name: \(String(name))")
    }
    var error : NSError? = nil
    do {
        try managedObjectContext!.save()
    } catch let error1 as NSError {
        error = error1
        NSLog("Unresolved error \(error), \(error!.userInfo)")
        abort()
    }

    do {
        try managedObjectContext!.save()
    } catch _ {
    }
    getFetchResultsController()
    theTableView.reloadData()
    print("Stored number: = \(email!)")

}


C# open multiple images to array

Question: I'm new to C# and I'm trying to open multiple images to an array to later manipulate their pixels, this is my code so far:
private void button1_Click(object sender, EventArgs e)
    {

        openFileDialog1.Filter = "Image Files(*.jpg; *.jpeg; *.bmp)|*.jpg; *.jpeg; *.bmp";
        if (openFileDialog1.ShowDialog() == DialogResult.OK)
        {
            Bitmap[] images = new Bitmap(openFileDialog1.FileNames);
            MessageBox.Show(images.Length+" images loaded","",MessageBoxButtons.OK);

        }
    }

I'm getting problems with this line
Bitmap[] images = new Bitmap(openFileDialog1.FileNames);

Can you help me?
Answer: Use:
 images = openFileDialog1.FileNames.Select(fn=>new Bitmap(fn)).ToArray();

Because openFileDialog1.FileNames is array of strings and Bitmap constructor expects single image file name
Answer: Bitmap[] images = new Bitmap(openFileDialog1.FileNames);

Bitmap[] images // Is an array of Bitmap

new Bitmap(openFileDialog1.FileNames); // Returns a single (new) Bitmap

I suggest to use a List. And when you are new to C# it is much easier to use foreach than LinQ as Pavel Kymets suggested.
List<Bitmap> images = new List<Bitmap>();
foreach(string file in openFileDialog1.FileNames) {
    images.Add(new Bitmap(file));
}

Answer: Or, if you aren't ready for lambdas, something like
openFileDialog1.Filter = "Image Files(*.jpg; *.jpeg; *.bmp)|*.jpg; *.jpeg; *.bmp";
List<BitMap> images = new List<BitMaps>()
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
  foreach(string fileName in openFileDialog1.FileNames)
  {
     images.Add(new Bitmap(fileName));
  }
}
MessageBox.Show(String.Format("{0} images loaded",images.Count),"",MessageBoxButtons.OK);

C# open multiple images to array


Debian 12 Nestopia 1.52.0-1 has bugged default NES gamepad input

Question: I installed Nestopia through the official Debian repos (using Debian 12), i.e. sudo apt install nestopia. I also have one of those official Nintendo NES gamepads that have the Wii connector, and I have an adapter for PC for that.
I tried playing Mario 1, and noticed that the physical B button was bound to "turbo jump" while the physical A button was likely bound to "turbo run", i.e. very rapidly toggling between run and walk. This is despite me going into the configuration menu and attempting to correctly bind A and B to non-turbo.
Note that this is complicated by the fact that there is no obvious way to UNBIND a gamepad key, since if I just click the "turbo A" button, it will hang until I press a key on the gamepad, even if I mash Esc or any key on my keyboard.
apt show nestopia gives this:
Package: nestopia
Version: 1.52.0-1
Priority: optional
Section: games
Maintainer: Debian Games Team <firstname.lastname@example.com>

Answer: The described problem is certainly a bug and should probably be fixed by the Debian games team maintainer, but meanwhile here's a workaround.
Going to ~/.config/nestopia/input.cfg, we see this:
[gamepad1]
...
js_a=j0b3
js_b=j0b2
js_ta=j0b2
js_tb=j0b3
...
js_softreset=j0b99
js_hardreset=j0b99

I just set both js_ta and js_tb to j0b99, because I'm certain that I don't actually have that button on my NES gamepad, and after that everything worked correctly.
As an aside, I noticed that there's really bad input lag. Like maybe 1/5 of a second between pressing A and Mario jumping. In contrast, when I use the same gamepad on Windows 11 with Nestopia 1.40, it's absolutely perfect with no lag.
(Interestingly, I have the same input lag on FCEUX, which is also in the official debian repo, so I suspect this is a Linux thing, not the emulator's fault. A bit of googling suggests it's due to GNOME having compositor enabled by default.)


Searching files based on extension using os.path

Question: I was wondering how to search for files based on their extension. If you were to search for py or txt or some other extension, the user would input it and then it would search for it. I'm not allowed to use glob nor os.walk
This is the method I have. If necessary, I'll post the whole code.
The user first inputs a directory which is in another method after that, they would say
E txt or E .txt (both works) and it would return the files based on what extension you used. I'm not sure what's wrong with my code though.
Answer: In your code,
<code> for file in directory
</code>
is definitely wrong, as directory is a string with the path in it. it should be something like
<code>for file in os.listdir(directory):
</code>
to get a list of files in the directory
Comment: thank you! If I were to search for files based on their size would it be
        `for file in os.listdir(directory):

                        if os.path.getsize(directory) > interesting1[1]:
Comment: something like that, indeed. if you want to go down the directory trees though, you'll have to use recursion
Comment: The problem with that though is that the input accepts both integers and strings. When I run it, I get    `if os.path.getsize(directory) > interesting1[1]:
TypeError: unorderable types: int() > str() `
Comment: cast it to int, ie, `os.path.getsize(file) > int(interesting1[1])`
Comment: input only returns strings, you need to extract the number strings yourself (ie through splitting like you did) & cast them as needed
Comment: Oh. I see!. Thank you very much!


Django: Bad request syntax when redirected from Apache mod_rewrite

Question: I have Django running on port 8000, and Apache on 80. I configured the following rewrite rule in apache to redirect to django:
RewriteRule ^/?checkout/ http://%{HTTP_HOST}:8000/checkout/ [L,QSA]

If open a url in a browser, it works fine and redirects perfectly.
However, the external client (which works well when connecting to django directly without apache) always causes a Bad Request Syntax error on Django server. Heres' snippet from Django Log. It looks like Apache automatically appending those "Content-length" stuff to the query, why?
[05/Mar/2014 18:01:35] code 400, message Bad request syntax ('GET /checkout/wx_signature?signature=b226bb8f6e9ce2fdecb752c6808a979c62e235f7&echostr=5987526888415258224&timestamp=1394042480&nonce=1394079741Content-Length: 445Connection: closeContent-Type: text/html; charset=iso-8859-1 HTTP/1.0')

Comment: Are you trying to access to the URL trough HTTPS? If yes, this might be related: http://stackoverflow.com/questions/7929460/django-400-bad-request-syntax-what-does-this-message-mean but won't solve your problem...
Answer: tl;dr: This caused by a bug in your "external client". It is a badly designed HTTP client and should be avoided because not only does it cause this bug, it may open up avenues for security exploits.
In order to understand what's happening, you need to work backwards.

First, let's start with the line of log from the Django built-in server:
[05/Mar/2014 18:01:35] code 400, message Bad request syntax ('GET /checkout/wx_signature?signature=b226bb8f6e9ce2fdecb752c6808a979c62e235f7&echostr=5987526888415258224&timestamp=1394042480&nonce=1394079741Content-Length: 445Connection: closeContent-Type: text/html; charset=iso-8859-1 HTTP/1.0')

"code 400" refers to the HTTP status code 400. It  means the actual HTTP request is badly constructed and cannot be understood. Luckily, Django logs the erroneous input so we can analyze it.

Now that we understand the nature of the problem, we'll remove the irrelevant log fluff and the long signature to take a deeper look at the actual request:
GET /checkout/wx_signature?[SIGNATURE REMOVED]Content-Length: 445Connection: closeContent-Type: text/html; charset=iso-8859-1 HTTP/1.0

Here we see an invalid first line of an HTTP request.

From RFC2616 Section 5.1:

The Request-Line begins with a method token, followed by the Request-URI and the protocol version, and ending with CRLF. The elements are separated by SP characters. No CR or LF is allowed except in the final CRLF sequence.
   Request-Line   = Method SP Request-URI SP HTTP-Version CRLF

In the invalid request, we can identify that the HTTP verb GET is there and the version ending of HTTP/1.0 is there, so these are not the problem. The middle part, which is supposed to be the URL is as follows:
/checkout/wx_signature?[SIGNATURE REMOVED]Content-Length: 445Connection: closeContent-Type: text/html; charset=iso-8859-1

Spaces in the URL are normally replaced with + or %20 before being sent to the server. As you can see, this is not the case here and it is the cause of the invalid request. A good HTTP client would never have done this as it would automatically escape the URL. This is a red flag that the "external client" you are using is of poor quality.

Notice that the space appears there along side a number of strange looking fields.
If you look at RFC2616 Section 14.13, you'll see that Content-Length is actually the name of an HTTP 1.1 header. This is also the case for Connection, and Content-Type.
It obviously does not belong there and so why was it concatenated with the URL?
From here I can only make guesses since I don't have access to your code. However, I think I have a pretty good idea of what's happening.

Let's understand the nature of HTTP headers for a moment. We'll send a raw request to emulate what happens if we visit "http://google.com". This will trigger Google to redirect us to "http://www.google.com".
Raw Request:
GET / HTTP/1.1
Host: google.com

Raw Response:
HTTP/1.1 301 Moved Permanently
Location: http://www.google.com/
Content-Type: text/html; charset=UTF-8
Date: Thu, 15 May 2014 21:28:46 GMT
Expires: Sat, 14 Jun 2014 21:28:46 GMT
Cache-Control: public, max-age=2592000
Server: gws
Content-Length: 219
X-XSS-Protection: 1; mode=block
X-Frame-Options: SAMEORIGIN
Alternate-Protocol: 80:quic

[HTML content removed]

Whoa, Google returned a whole bunch of headers! We're only interested in the first few lines though:
HTTP/1.1 301 Moved Permanently
Location: http://www.google.com/
Content-Type: text/html; charset=UTF-8
...
Content-Length: 219

Here you can see that Content-Type, Content-Length, and other headers follow the Location header. The actual order doesn't matter normally since the HTTP client or server is smart enough to understand what each one means. However, what if you strip the line endings after the Location header?
You'll end up with something like this:
HTTP/1.1 301 Moved Permanently
Location: http://www.google.com/Content-Type: text/html; charset=UTF-8Content-Length: 219

Uh-oh... if you are a HTTP client, you'll think that I want to redirect you to http://www.google.com/Content-Type: text/html; charset=UTF-8Content-Length: 219.

This looks exactly like the symptom you have... but why does that happen?
It's very unlikely that Apache returned the header in this corrupted form (unless you custom coded a plugin or something to that effect).
It's also unlikely your "external client" purposely stripped the line endings in the header after receiving it.
A likely case is that the "external client" was coded to interpret everything before the content and after the Location: as the URL and somewhere afterwards strips the CRLF characters (commonly done for security reasons when dealing with HTTP headers, ironically done incorrectly in this case). The fact that the client tries to send the request with HTTP/1.0 instead of HTTP/1.1 supports this because HTTP/1.0 clients are usually very limited in terms of features and tends to make heavy assumptions based upon its obsolete knowledge.
It's also probable that your "external client" read the entire header after the request line into a string and the string handler automatically stripped the CRLFs.

I think it's pretty clear that the problem rests in the "external client", though there's not enough information to dig into it.
I suggest you use a different client or library to do the request.
Comment: +1ed I loved your methodical approach to the problem @ hand. I might add, when doing your raw-request to google.com example. I used another python lib [httpie](https://github.com/jakubroztocil/httpie) as telnet did not seem to work.
Answer: This message seems to appear when you are using HTTPS url with Django. You might need to configure also a HTTPS configuration in Apache2, inspired from this question for example: SSL based virtual host with django and mod_wsgi


How to tell if your locks are bump proof?

Question: I was reading about lock "bumping" where burglars buy 'bump' keys and can open locks very quickly. I was also reading that some locks are bump proof (double chamber perhaps?). My question is: how can I tell, by looking at the locks currently on my door, if they are bump proof or not?
I don't see any brand or manufacturer name on the locks but they were replaced 3 months ago when we bought the house.
If you are not familiar with bump keys or locks take a look at this video:
http://www.youtube.com/watch?v=hr23tpWX8lM
Comment: Sounds like security theatre to me. Have you heard of window "bumping?" A brick is an excellent tool for that.
Comment: @Matt - "Security theatre"? With your logic why have locks at all? Bump proof locks are a deterrent, like any security measure, meant to buy you time. http://www.consumerreports.org/cro/home-garden/home-improvement/home-security/door-locks/bump-keys-can-lead-to-home-break-ins-3-08/overview/bump-keys-ov.htm
Comment: @matt - I agree there is an curve somewhere between cost/benefit where added security measures add little actual overal security and therefor do indeed become theatre, but it also seems to me that doors that anyone can silently open for $20 are not theatre - that's a real problem I'd like to remedy. Most common burlars don't want to attract the attention of a brick through the window, especially with the neighbors I have
Comment: I'm saying that it only provides the illusion of security. [The illusion is sometimes enough of a deterrent.](http://en.wikipedia.org/wiki/Security_theater#Benefits). Think of it this way: it's silly to worry about having a fireproof, drill-proof, bombproof, apocalypse-proof vault door that's right next to a window into the vault. And if you're really concerned about your locks, use a keypad, or retina scanner, or...
Comment: Make it look less exciting to rob your house than the neighbor's...
Comment: Brick through the glass is the brute force method, scoring tool and duct-tape can be pretty noiseless.
Comment: You may be better just having an alarm as well as locks
Comment: Hey, it looks like @Rook's answer most directly answers the question you've asked. Consider accepting it?
Answer: If your lock is a just a simple pin tumbler  then its vulnerable to bumping.

There are some pin tumbler locks that say they protect against bumping,  but in practice it might be a little more difficult,  but still very vulnerable.   In fact the only deadbolt lock that I know of that isn't vulnerable to bumping, rakeing or other simple attacks.    Is the Shalge Primus or another Hybrid key type.   The pin tumbler on the primus is 100% vulnerable to bumping,  however,  the "side-bit milling"  isn't vulnerable.   Defense in depth security in layers.
Answer: I ordered a set of bump-keys and tried my doors.  It was $15 (with shipping).
What's particularly interesting (at least to me) is that the method of 'bumping' open a lock has been around since the 1930s.  It just wasn't well known by the general population until it was picked up by some TV shows/News stations in the 2000s.
Anyway - read the countermeasures section here:
http://en.wikipedia.org/wiki/Lock_bumping
Comment: If it's a traditional lock that isn't advertised as bump proof; it isn't.  If it is advertised as bump proof, it probably can still be bumped with additional hardware.  It's like a 'pick-proof' traditional lock....the nature of how it works means it can be 'picked'.
Comment: I guess that is one way - ordering the bump keys and trying it. But my question is more of "can I tell by looking at my new locks if they are bump proof?"
Comment: Thanks, sounds like trying it with bump keys is really the only way to know for sure but it also sounds like any traditional lock is susceptible so I guess that is my answer.
Comment: ordered some bump keys ($20 with shipping for me). Took all of 2 minutes - scary.
Comment: @themerlinproject, for $2 and 20 minutes you could have just made one. :)  BTW just because you cannot bump a lock doesn't mean it cant be done, it may just be your inexperience, or improper bumping method.
Comment: "ordering the bump keys and trying it" - Be sure to have your ID proving that you live at your home when the police come by and inquire what you're doing... :)
Answer: First look at your key, then your windows and finally your door frame. If your windows are made of glass or door frame of wood, then don't bother with extravagant locks. As a locksmith, I do appreciate selling high priced locks, but always inform my customers that forced entry is primary means of entry. (A chain is as strong as it's weakest link.) Most burglars are not picking locks. Yes, lock bumping has been around for a long time....my suspicion is that locksmiths brought it to light to sell more expensive locks.
A burglar doesn't have the knowledge to look at locks and say it's not pickable(generally).(they're more worried about it being kickable)
If a thief is looking at your place and has that knowledge of locks....then you have some fantastic and expensive stuff. They aren't coming after your flat screen tv.
High security locks are used more widely in Europe than US, either European criminals are more sophisticated, or Americans are more practical. There are steps that can be taken to strengthen a wood door and wood frame....but windows still need bars if you want any level of security.
We sell high security locks primarily as  a means of key control, with pick resistance as a secondary concern.
Answer: Basically, if your key looks regular (=standard) then it is likely that it is not a bump proof key.
The cheap advice if you want a "bump proof door", is to couple a security (=hard to bump) mechanic key with a magnetic lock (with a RFID card for instance).
However, you can find some really resistant keys. I guess the most well known in North America is the second generation Bilock key. Another star key is the anker magnetic key, almost impossible to copy, very difficult to lock pick.
To tell the truth, if you have an anker key, an armored door and a 12 points lock, most thieves will prefer destroy the wall next to the door to enter your house (I actually saw that at the office).
Answer: Test to see if your lock is bump-proof by putting your key in, give it turning pressure and push it all the way in. If the key jams, it's bump proof. If the key turns you need new locks. I am a former thief, but I'm now a lock smith. Look out for lock snapping on the useless PVC doors -- it's much more common than bumping. Lock snapping is what you need to protect yourself from.
Comment: Applying force to the lock so it breaks.
Comment: What is lock snapping?
Answer: Assume all types of pin tumbler cylinder lock (including dimple, cruciform, tubular) are bumpable, more or less easily. Withing the last few years, some bump-resistant cylinders have appeared, at higher prices. They are not bump-PROOF.
Lever key mechanisms, and disk detainer mechanisms, for example, are BUMP-PROOF. In the USA, burglars are unlikely to know either how to pick or drill lever locks. A lever lock bought from Britain conforming to British Standard BS3621, or a double-bit lever lock bought from eg Italy, (there are Internet suppliers) would be reliable security.
Answer: The simplest solution to bump-proof a door lock is to replace it with one that is bump-proof. Bump keys should be far less of a problem with these devices than they would be with a standard door lock. They aren't always 100 percent effective, but they are still your best bet.
Comment: This doesn't actually answer the question of "how to tell if the _existing_ lock is bump proof". Maybe the OPs locks already are, and you've just suggested wasting a lot of money replacing like for like.


Why Android emulator/layout editor is too slow in comparison to iOS simulator/storyboard?

Question: This is a conceptual question. It would be great if anyone could clarify the story behind.
I understand the difference between emulator and simulator.
emulator: mimics the device environment (hardware, network capability etc). More likely we will get a very close result in compare to device.
simulator: uses the running computer's capability. Less likely to get  close result to device, as the simulator is using computer's hardware performance.
Android platform is open for developers since 2009 AFIK. Why after all these years the emulator is still (practically) unusable in compare to iOS simulator? Developers have to use either Genymotion or real device even for a small test. Even after HAXM or Snapshot enabled, Android emulator and iOS simulator are not even close to compare.
Another closely related question is, why the layout editor of Android is too slow and not smooth at all in comparison to iOS Storyboard.
I believe you would agree that ADT (Eclipse Based) layout editor was simply unusable. Android Studio is doing a much better job, but not up to the mark in any ways. Quite often it gets stuck on my MacBook Pro 2012 model when I edit XML side by side with Preview window.
I understand the Android studio has just been released officially a few months back, but we are talking about only Android specific features. Its not a new IDE from scratch, it has the advantage of all the features of a successful product IntelliJIDEA.
There is no way an Android dev could possibly get away without editing XML by hand, whereas an iOS dev could and that's how the iOS ecosystem works. Now the iOS platform too has to deal with multiple sizes screen. So its not like Android platform is doing something substantially different, I guess.
Please pardon me for my poor English skill and beginner level knowledge. Just want to know the justifiable reasons/clarification, never meant to sound harsh or degrade Android ecosystem anyway.
(P.S: Primarily I am an Android app dev, recently started to learn iOS.)
Thanks in advance.
Answer: The iOS 8 Simulator is most of iOS 8 built for intel running with the OS X kernel.  There are a small handful of other system daemons involved (fseventsd, coreaudiod, configd, and powerd), and we use the host libsyscall, libpthreads, and libplatfom libraries to communicate with xnu (with a small interposition layer), but for the most part, you are running the entire OS natively.  It takes a few moments to boot the device (which consists of starting launchd and having it init the system just like on OS X or an iOS device), and after that, you've basically got a stripped down copy of iOS running natively on your system.  There is no emulator involved, no instruction translation, no bytecode interpreter, no extra abstractions or translations.  From the system's perspective, the simulator processes are just like any other OS X process except that they link against a different set of libraries and have a different bootstrap server.
Answer: Android Studio layout editor is really slow also, I think its design issue, and a lot of checks editor is doing and also some not fixed bugs on maybe related to OSX. Even App Code on OSX is really quick comparing to android studio what is same editor in core... Also build system gradle is terribly slow and this is also design issue... They choose slow technologies groovy I think, for build so now they will be searching for optimisations for rest of life... Well this is when somebody want to solve one problem just by blindly creating other... And emulator this is another story based on fundamental Android advantages and weaknesses also, I mean that android is based on java on open source libraries and also have to be available on multiple platforms, and also don't caring about this issues on start at all... It is possible to solve some of this problems emulator can be somehow made like java application if there will be will to develop it but I highly don't think anyone will do it , Genymotion is already decent in speed but incomparable to IOS emulator and x86 images runs quicker also but deployment of app still takes ages on based what I tested on OSX in android studio... I use Genymotion and Android Studio with all performance tuners available but have issue with performance and if you ever try to enable multidex support :)you will probably end like me that I had to remove some libraries and copy code from them to be able to build without multidex...
Answer: iOS : X-code having inbuilt iOS SDK and Simulator. It is inbuilt functions with x-code. So it is working very fast.
Android : In Eclipse, we are installing separate ADT, SDK and Emulator and all for Android Installation. It takes separate Memory in system.
Android 5.0.1 SDK takes 12GB installation memory in your system. So if you are working in layout, it takes time load layout from SDK. Every time Eclipse will load to get Android working tools from SDK.
So only Android taking too much to load, iOS is working very fast.