TCPDF generated PDF does not conform to PDF/A standart

Question: I have the task to create a PHP tool using TCPDF/FPDI  that takes existing PDFs and converts them to PDF/A standard while adding a certificate.
Unfortunately all the generated PDFs did not conform to the PDF/A standard. I also tried to generate a random test document as shown here https://tcpdf.org/examples/example_065/ but that document did not conform either.
This is my code:
<code>public static function convertPdf($path)
{
    $pdf = new \FPDI(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false, true);

    $pagecount = $pdf->setSourceFile(ROOT . $path);

    for ($i = 1; $i <= $pagecount; $i++) {
        $tpl  = $pdf->importPage($i);
        $size = $pdf->getTemplateSize($tpl);
        $orientation = $size['h'] > $size['w'] ? 'P':'L';
        $pdf->AddPage($orientation);
        $pdf->useTemplate($tpl, null, null, $size['w'], $size['h'], true);
    }

    $pdf->SetCreator("Creator");
    $pdf->SetAuthor('Nicola Asuni');
    $pdf->SetTitle('My PDFA example');
    $pdf->SetSubject('TCPDF Tutorial');

    $certificatePath = 'file://' . ROOT . '/libs/TCPDF-master/examples/data/cert/tcpdf.crt';
    // set additional information
    $info = array(
        'Name' => 'TCPDF',
        'Location' => 'Office',
        'Reason' => 'Testing TCPDF',
        'ContactInfo' => 'http://www.tcpdf.org',
    );

    $pdf->setSignature($certificatePath, $certificatePath, 'tcpdfdemo', '', 2, $info);
    $pdf->addEmptySignatureAppearance(0, 0, 0, 0);

    $pdf->Output('example_065.pdf', 'I');
}
</code>
I used this https://www.pdf-online.com/osa/validate.aspx to validate my PDF. It generates this output:

Compliance    pdfa-1b Result  Document does not conform to PDF/A. Details
  Validating file "testerrrrrr.pdf" for conformance level pdfa-1b There
  is data after the EOF marker. pdfaExtension:schemas/[0] :: Missing
  required field 'property' in value type 'Schema'.
  pdfaExtension:schemas/[0] :: Missing required field 'valueType' in
  value type 'Schema'. pdfaExtension:schemas/[1] :: Missing required
  field 'valueType' in value type 'Schema'. pdfaExtension:schemas/[2]
  :: Missing required field 'valueType' in value type 'Schema'. The
  appearance dictionary doesn't contain an entry. The key S has a value
  Transparency which is prohibited. The document does not conform to the
  requested standard. The file format (header, trailer, objects, xref,
  streams) is corrupted. The document contains transparency. The
  document contains annotations or form fields with ambigous or without
  appropriate appearances. The document's meta data is either missing or
  inconsistent or corrupt. Done.
Comment: What validator says it's not valid and what does it complain about?
Answer: In my case (TCPDF v. 6.2.26), the problem was located in tcpdf.php file at line 9583:
<code>$xmp .= "\t\t\t\t\t\t".'<pdfaSchema:schema>Adobe PDF Schema</pdfaSchema:schema>'."\n";
$xmp .= "\t\t\t\t\t".'</rdf:li>'."\n";
$xmp .= "\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
</code>
After "Adobe PDF schema", the declaration of the property was missing. I solved adding the following code between pdfaSchema declaration and li closure tag:
<code>$xmp .= "\t\t\t\t\t\t".'<pdfaSchema:property>'."\n";
$xmp .= "\t\t\t\t\t\t\t".'<rdf:Seq>'."\n";
$xmp .= "\t\t\t\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
$xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:category>internal</pdfaProperty:category>'."\n";
$xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:description>A name object indicating whether the document has been modified to include trapping information</pdfaProperty:description>'."\n";
$xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:name>Trapped</pdfaProperty:name>'."\n";
$xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:valueType>Text</pdfaProperty:valueType>'."\n";
$xmp .= "\t\t\t\t\t\t\t\t".'</rdf:li>'."\n";
$xmp .= "\t\t\t\t\t\t\t".'</rdf:Seq>'."\n";
$xmp .= "\t\t\t\t\t\t".'</pdfaSchema:property>'."\n";
</code>
Answer: Generally: If the document that is imported via FPDI is not PDF/A conform (comes e.g. with transparency), the result will never be validated successfully. Just by setting some PDF/A flags through TCPDF doesn't make the imported pages PDF/A conform.
TCPDF fakes the signature appearance because the appearance is written to the pages content stream while the real appearance is empty (in view to "The appearance dictionary doesn't contain an entry.").
The missing attributes should be added in the TCPDF code (other "validators" do not complain about them).
Comment: Thank you for your reply. What attributes are missing and should be added in TCPDFs code?
Comment: Mmmhh... maybe the validation is wrong, too. Because the missing fields are there (and for the first view not all mentioned are required). The fields are e.g. documented [here](http://www.pdfa.org/wp-content/uploads/2011/09/tn0009_xmp_extension_schemas_in_pdfa-1_2008-03-20.pdf) (page 9 and follows).


How can i move all files and folders from multiple directories?

Question: So i am writing this bash script to do all sorts of things but the last step is to move the contents of four different directories into one spot so i can run a shred command or remove or something like that (not sure what yet). this is what i have so far
for dir in $dir1 $dir2 $dir3 $dir4; do
     mv -vi ./* $CYCL
done

would this loop remove all files and folders from those directories at once? or would i have to change it?
edit: changed code . there was a function in there that i replaced with the original code
Comment: Also, if your directories or files have spaces, you will have problems. You need to quote your variables.
Comment: I think `mv $dir/* $CYCL`, but you do not really need a loop, `mv $dir1/* $dir2/* $dir3/* $dir4/* $CYCL` and you really should use the full path in scripts, ./* is ambiguous can will yield unpredictable results. I would trust $dir1 and $CYCL are full paths to some location.
Comment: You set variable `dir` but then not use it?
Comment: And if you decide that `shred` should be used, if your previous `mv` was from a separate partition, there may still be remnants.
Answer:
The concise way:
mv -vi {$dir1,$dir2,$dir3,$dir4}/* $CYCL

I don't know why you're using the -i option for files you want to delete anyway. You don't care if anything is overwritten, you're just adding more manual steps.
Using your loop:
for dir in $dir1 $dir2 $dir3 $dir4; do
   mv -vi $dir/* $CYCL
done

The for var in list; do ; done syntax will sequentially assign the value of each element in the list to the variable X and then run whatever is in the do block. If you don't mention the variable you used nothing is done to it. For example, this will simply print "hello" 3 times:
for i in Tom Dick Harry; do echo hello; done
hello
hello
hello

If you want to actually do something to the elements of your list, you will need to refer to the variable you assigned them to:
$ for i in Tom Dick Harry; do echo hello $i; done
hello Tom
hello Dick
hello Harry

So, your loop was running mv ./* $CYCL which would have moved the contents of your current directory into whatever is the value of $CYCL. It would not have touched the contents of dirs 1-4 in any way.
Comment: ok. i thought the the loop would cycle through the directories so that the current directory would change each time. Didn't know that i had to use the variable


Can Endermen pick up TNT then set it off?

Question:
Possible Duplicate:
What blocks can the Enderman pick up and what blocks can't they pick up?

Can an Endermen pick up a TNT block then place it beside a redstone torch or something and make it explode? If so then please leave a picture or a video!
Comment: Stop with the spam, and do your damn research.  Test it out.  It's not that hard.
Comment: Also, is it just me, or have the last few questions coming from this guy shown little to no research whatsoever?
Comment: I'm sorry but I'm practically grounded of of everything but the iPod I'm playing on, so it's kind of hard to do research! So I'm sorry.
Comment: more like definite duplicate
Comment: The answer is also on minecraft wiki. do some research before asking questions.
Answer: The short answer: Yes.
Take a look at this thread to see what an Enderman can and cannot pickup.
Seeing as an Enderman can pick up TNT, it can place it next to a red stone torch, triggering an explosion.  Try the Bukkit Mod to spawn mobs and TNT to test this.


Ubuntu 13.04 speakers making no sound after booting?

Question: I get this weird issue when you boot a certain time into 13.04, the sound doesn't work. Restarting the computer fixes the sound and nothing seems to be wrong after that. Would this be considered a bug? When that one time the booting causes the no sound problem, you can see a field of codes and text something you would see in the terminal. I'm assuming that might be kernel or am I wrong?
Comment: I'm currently having the same problem and I'm trying to find the reason for it. Could you clarify some simple things real quick? - Are you using a desktop or laptop? If it's a laptop, what kind. - Does your headphone jack still work when this happens? - If possible could you check if your microphone works when this happens? - Is your computer just ubuntu or is it dual with windows or other? My laptop also freezes when I attempt to shutdown or restart when the problem occurs. I force it off and when it I restart the sound works again. Have you had this problem at all?
Comment: @bmp You are rite I'm experiencing the same thing you listed... No sound tried to restart but got hung. Force restart and it works. I use a Lenevo Thinkpad with 13.04
Comment: My fix for this problem was upgrading the kernel and booting since then has improved.
Comment: @MichaelScott I have this version now and the sound from my laptop is working but when i plugin speakers jack then no ouput "Linux rsz 3.9.0-030900-generic #201304291257 SMP Mon Apr 29 16:58:15 UTC 2013 x86_64 x86_64 x86_64 GNU/Linux"
Answer: Entering
sudo alsa force-reload
in the terminal is the only solution I've found
Comment: This might help. http://linuxg.net/how-to-install-3-9-kernel-on-ubuntu-13-04-12-10-12-04-and-linux-mint-15-14-13/
Answer: The best solution if above not work is:
Open the terminal and edit speech-dispatcher file by using the following command:
sudo gedit /etc/default/speech-dispatcher

In here, change RUN=yes to RUN=no
Reboot and enjoy sound.
Via http://itsfoss.com/fix-sound-ubuntu-1304-quick-tip


mysql search by title in last 100 records

Question: My case is, when someone is posting to my news web data with 600k records,
they can create the same title which someone just posted in the last few hours with same subject.
data: sid|title|desc|timestamp|userid

Usually I use:
select sid from ".$prefix."_stories WHERE title = '".$subject."' limit 0,1

It searches all data for $subject then notice poster if have they have the same title.
I need a query which searches in the last 100 records.
I tried the following, but this did not work:
select sid from ".$prefix."_stories WHERE title = '".$subject."' and sid > MAX(sid)-100 limit 0,1

Answer: You can do this with a subquery that returns the last 100 sid. Note, I have omitted the PHP concatenations for brevity here.
SELECT
  last100.sid
FROM
  (
    SELECT
      sid,
      title
    FROM $prefix._stories
    ORDER BY sid DESC LIMIT 100
  ) last100
WHERE
  last100.title = '$subject'

Comment: Thanks! I tested this query but it not work, no result found :)
Comment: thanks! i did test with this query before but the result not acurated .. for eg: data has 120 records: the record sid = 50 with title "aaa" then record sid = 120 with same title="aaa" now i test to search with your query it only show the record with id=50 so the last record with id=120 do not found .. ! so bad .. any ideal ?
Comment: sorry i did not corect some typo in query.. actualy it work very good
Comment: @BinhNguyen I thought it would. Welcome to Stack Overflow. Please mark an answer as accepted by clicking the checkmark beside it.
Answer: Assuming that you have a primary key, incrementing by 1 with every record (which will put newest at the bottom), just do this:
SELECT sid, title
FROM ".$prefix."_stories
ORDER BY sid DESC
LIMIT 100

This will select the last 100 records
Good point by Michael in my comments... Edit to code and further comment:
Removing the where clause, this will select the last 100 records... Run a loop to check to see if the title or summary already exists:
while ($row = $result) {
   if $subject = $row['title'] {
      $duplicate = TRUE;
      endwhile;
   }
}

Just compare the resulting data.  Thanks Michael
Comment: This will return up to 100 matching titles, not search the most recently added 100 records for `$subject`.
Comment: As I know.. this still collect all sid wich have same title in all records then show the last 100 records..  IN-fact i need it search only on last 100 records only.. thanks anyway!
Comment: @BinhNguyen No, without the `WHERE`, and assuming that `sid` is your primary key, this will collect the last 100 records entered into the database.  If `sid` is not your primary key, then in the `SELECT` also enter your primary key in front of `sid, title`, change the `ORDER BY` from `sid` to the primary key and it will collect the last (newest) 100 records in the database.
Answer: Sort by sid (descending, so newest entries come first) and limit results to 100:
$sql = "select t.sid from (select sid, title from ".$prefix."_stories ORDER BY sid DESC LIMIT 0,100) t WHERE title = '".$subject."';"

Be sure to chek $subject to avoid SQL Injection (better: Use prepared statements / PDO).
Comment: This is the same as I originally had my answer.  As Michael noted in my comments, this will collect up to 100 records containing the `title` with `$subject` rather than search the last 100 records.


WP8 TextBlock text has color layers for certain characters

Question: I need to prevent the TextBlock from changing the color of special characters, it looks like the WP TextBlock recognizes some shapes as emojis and colors them but it seems there is no way to control it like in Windows 8 like this article says:
http://blogs.windows.com/windows/b/appbuilder/archive/2013/11/11/xaml-text-improvements-in-windows-8-1.aspx
http://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.xaml.controls.textbox.iscolorfontenabled.aspx
There is no IsColorFontEnabled in WP, anyone knows how to override this behavior?
The problem is with the heart character ♥, and I would not want to use a list of heart shape paths
EDIT: I have used the ❤ character but has different spacing and coloring than the normal one, I think the only way is to use a list of paths with this shape :(
Thanks
Comment: I should read the question more thoroughly,  I posted an answer on how to make the text colored, not remove the colors.
Answer: You can make the RichTextBox act like the TextBlock by setting the IsReadOnly property to true.  It looks similar to the TextBlock, while the TextBox doesn't.
I'm not sure if you can control the emoji problem with this idea, you'd have to test,  but it does allow you have full control over the color of text.
XAML
<code><StackPanel x:Name="ContentPanel"
          Grid.Row="1"
          Margin="12,0,12,0">
<!-- One Color-->
  <RichTextBox Foreground='White'>
    <Paragraph>Text with ☻</Paragraph>
  </RichTextBox>

  <!-- Multi color -->
  <RichTextBox IsReadOnly='True'>
    <Paragraph>
      <Run>Mixed Colors.</Run>
      <Run Foreground='Red'
           FontWeight='Bold'>☺</Run>
      <Run Foreground='Yellow'>☻</Run>
      <Run Foreground='LightGreen'>♫</Run>

    </Paragraph>
  </RichTextBox>
    </StackPanel>
</code>
Output
Comment: Hi, thanks but unfortunately didn't work with a richtextbox set as readonly, still shows the emoji colored
Comment: Good to know, too bad it doesn't solve your problem.


What is the initial state of an application called?

Question: Typically this would be the state in which a user would see hints or be prompted to take a tour. What's the correct UX terminology for this? Something along the lines of pristine/dirty as in forms?
Comment: NUX (New User Experience) is a term that I have heard being used multiple times. Some references: https://engineering.pinterest.com/blog/rebuilding-nux-experience-framework, https://help.optimizely.com/hc/en-us/articles/203430454-Mobile-optimization-ideas-Onboarding-flow-and-new-user-experience
Answer: I think you're talking about two things:

Default state: Everything is set up according to the initial "install".
User on-boarding: The mechanisms designed into the software to help the user develop their proficiency without "reading the manual" or contacting support.
Answer: I often refer to this state as the "First Run" state of an application. First Run means that the user has been onramped via some invitation and has arrived at the app and is about to have their first experience.
I refer the experience itself of moving through the first run state the "Welcome Experience".  The Welcome Experience can, as you note, include hints or prompts to get the user initiated and off to a good start with the app.
Answer: I have encountered it being called 'Zero State', 'Empty State', 'New User' or 'Zero Data'.
Here's a good article that provides a summary on different states that might be educational and added knowledge on this topic as well.

Nothing
  What happens before your component does anything? Maybe it's the first time a user sees it. Maybe it's not activated yet. Essentially, the component exists but hasn't started.
Loading
  The dreaded state. In a perfect world, no one would ever see this; Alas, here we find ourselves. There are plenty of ways to keep your loading state subtle and unobtrusive. Facebook does a pretty good job of this:
None
  Your component has initialized, but it's empty. No data. No Items. Now may be a good time to get the user to act ("Do this thing!"), or to reward them ("Good job, everything is taken care of").
One
  You have some data. On an input, this may be after the first keystroke. In a list, it might be when you have one item (or one left).
Some
  This is usually what you think of first. What is the ideal state for this component? Your data is loaded, you have input, and the user is familiar with it.
Too many
  Woah there! The user has overdone it in some way. Too many results (maybe you paginate them now), too many characters (maybe ellipses?), and so on.
Incorrect
  Something is not right about the component. An error has occurred.
Correct
  Good to go! This item has had its needs satisfied.
Done
  The user's correct input has been received by the application. They don't have to worry about it anymore.


How to peacefully remove space station

Question: My borders recently expanded and I managed to take control of the system of another empire. I need to build an observation station on a planet but the other empire already built one.
I can disband a mining station, but the option is not available for an observation post.
How can I remove the current space station and build my own?
Comment: Is the system in a sector?
Comment: @RavenDreamer it is in a sector owned by me
Answer: That's because the observation post actually still belongs to the other empire. Ownership of these is not transferred when system control changes. No idea, whether it's a bug or intentional.
The only option is to go to war again and destroy the observation post.
Comment: Not sure when it changed, but this seems to have shifted in a subsequent patch. Observation posts now change hands, I think (and, interestingly, you inherit the old owner's policy - I aquired an ob post and almost immediately afterwards had it complete technological enlightenment... a bit of a surprise!)
Comment: Well that seems like a serious problem. That observation post can take control of the planet, giving the system back to the original owner.
Comment: Yes, this behavior seemed to have changed at some point in the last 2.5 years because I just inherited an observation outpost when I took a bunch of nearby systems.

How to peacefully remove space station


Out of sector combat in X3: how can I tell my ships to evade enemies?

Question: As noted in a related question, out of sector combat can be a source of heartache and hassle.  In building my budding mercantile empire, I don't want to lose ships if I can avoid it.  I am aware of the MK3 Blacklist Manager and the emergency jump command but that's not exactly what I'm looking for:

Blacklisting a sector is great for telling the ships "don't go into this war sector."  It's less useful in areas that are super useful / profitable but where maybe sometimes there's going to be a Xenon raid.
Emergency jump is great as a last-ditch getaway but is too late if the enemy overwhelms you on the first salvo.

What I'd really like is to be able to tell a freighter "If an enemy M6 closes to within 10 KM, evade / change course / jump away."  I'd settle for "If you pick up a Big Bad at long range, jump away immediately."
Is this even possible within the existing suite of commands?  If not, is there a close-to-official mod that will give me a similar command set?
Comment: I think it should be possible to do with additional commands (same command type as mosquito missile defense), but I haven't seen any such scripts. My solution: use Springblossoms with cargo space cheated to 100k as traders. Those babies only ever get blown up in war sectors.
Comment: @kotekzot, thanks but I'm trying to play straight as much as possible.  I know about several interesting cheats but that's not what I'm trying to accomplish with this playthrough.
Answer: One good approach is to make sure there's no Fight Command software on the ship, then it'll run away at the first sign of trouble because it has no other option.
Comment: That doesn't really fulfill the goal of "evade on detection."  Instead, your ships change course after being engaged.


Printing Bitwise NOT operator with hexadecimal format specifier

Question: If i'm using m instead of ~m then the code gives me the expected hexadecimal value of 32 but here it's giving ffffffdf as output.
EDIT
I know how bitwise ~ NOT operator works. But i'm not understanding this.Could somebody explain this...??
#include<stdio.h>

int main()
{
    unsigned int m = 32;
    printf("%x\n", ~m); //ffffffdf is printed as output

    return 0;
}

Comment: Do you know what is `~` in C? You are saying you do. So what is the question?
Comment: if you know how ~ works, then why are you asking this? You took an int, notted it, and asking why it's different...
Comment: @claj Integers are *what* ? Many things are not clear to everyone, but it doesn't mean they all make a valid SO question.
Comment: What is your expected result?
Comment: I'm voting to close this question as off-topic because it shows no research effort.
Comment: @EugeneSh. ~32 will give me answer -33 using %d as a format specifier but here the format specifier is hexadecimal so i don't get it...
Comment: possible duplicate of [The tilde operator in C](http://stackoverflow.com/questions/7207391/the-tilde-operator-in-c)
Comment: @VivekMahto Google "two's complement"
Comment: @VivekMahto that's because if you print with a `%d` specifier, `0xffffffdf` is  hex for -33 as a **signed** integer. `%x` prints the hexadecimal representation of an integer, which is **unsigned**. There's no signed hexadecimal in programming because that wouldn't make any sense
Comment: Go Google and study "twos complement"
Comment: @AlexYan: That is actually not quite correct. Hex constants for instance are [promoted](http://port70.net/~nsz/c/c11/n1570.html#126.96.36.199p5) like positive integer values (but not like decimal constants). The hexadecimal _representation_, however is unsigned.
Comment: I think it's a fair question. It's not clear to everyone that integers are registers in C, rather than natural numbers represented with as many bits as nescessary.
Comment: @Olaf Yes representation and interpretation is what I meant if that wasn't clear enough in my previous comment. `ffffffdf` interpreted as a signed integer is -33, but is `ffffffdf` if it's interpreted as hex. So if you set the print specifier to `%d`, it'll be interpreted as a signed integer, and be printed as -33 etc
Comment: @claj: Well, I learned about integer numbers in the very first years of school. I think they are pretty much "natural". (Not clear what you mean by "registers"). About the question: Accepting any simple question about something you will find in the very early chapters of any book about programming or Wikipedia would flood this site with mostly "random" noise and would render it almost useless.
Comment: But, @Olaf, as you already know then, the "natural" integers aren't of specific bit width. A ~ on a natural numbers "natural representation" would never render a higher value than the natural number itself. You probably didn't learn about computer number registers in your first schoolyears.
Comment: @claj: Well, that is the point with modulo-arithmetic, isn't it? And - as I already stated, it is handled very well in any book, Wikipedia and even in the standard for [fprintf](http://port70.net/~nsz/c/c11/n1570.html#188.8.131.52p8). Note, that `unsigned int` does not even have a signed representation (surprise, surprise), so the question is actually even nonsense for `%d` (as that takes `signed int`).
Comment: @claj Your answer is right and pretty good. But your comments are not making any sense, sorry.
Comment: @Olaf, well, I meant https://en.wikipedia.org/wiki/Processor_register, sorry if that was unclear.
Comment: @EugeneSh. Sorry, but neither does yours. Thanks. EOF
Comment: @claj: What have integer data types to do with processor registers? Prove me wrong, but the _abstract macine_ does not even state about an actual processor, nor does it require a CPU with registers actually.
Answer: Every hexadecimal digit is four bits. Since you got 8 hexadecimal digits your integers seems to be 8*4=32 bit.
The NOT of 32 = 000000000000000000000000000010000 would be something like 11111111111111111111111111101111 which would be the hexadecimal digits above.
Comment: `000000000000000000000000000010000` hex? That would be `F...FEFFFF`.
Comment: @EugeneSh.: Ehm.. didn't he talk about hex? Sorry; if that is binary, he should have stated. Switching bases without clear statement is confusing.
Answer: In C, ~ is the bitwise-not operator. You said you understand how this operator works, but your question indicates that you do not. So let's go through this example:
First, you declare m to be an unsigned int, which happens to be 32 bits wide on your platform. You assign it the decimal value 32. The variable m is 0x00000020.
Then, you print it out. When you print it out normally, the expected output appears. But when you print it out with the ~ operator, you get something completely different.
The ~ (bitwise-not) operator does exactly what it says on the tin: It negates (flips) every bit, so 1s become 0s and 0s become 1s. Let's see what that would do to your number:
 m = 0b00000000000000000000000000100000 = 0x00000020
~m = 0b11111111111111111111111111011111 = 0xffffffdf

As you can see, the result exactly matches what is being output, which is good -- it means both your compiler and CPU are working as expected!


How to query array in vue store using Getters?

Question: I'm trying to pass an argument inside getters that should return the ID of the permissions but for some reason it is not returning anything.
////STATE
state: {
  permissions: [
    {id: 1, name: 'Create User'},
    {id: 2, name: 'Delete User'},
    {id: 3, name: 'UpdateUser'}
   ]
  }
//// GETTERS
getters: {
  getPermissionById: state => id => {
    return state.permissions.find(p => p.id=== id) // I tried with "=="
  }
}

And it is returning getPermissionById:ƒ (id) as result. I'm not quite sure what I'm missing here.
In component
computed: {

...mapGetters('permissionStore', ['getPermissionById'])
}

I'm using vue devtool to check the state.
Comment: Can you show how you are calling `getPermissionById`?
Comment: @rcbgalido, I have update my code. I'm using vue devtool to check the data for now. Other  argument like filter is working fine.
Answer: Try this:
computed: {
  ...mapGetters('permissionStore', ['getPermissionById']),
  permission() {
    return this.getPermissionById(this.id)
  }
},

Comment: `permission:undefined`
Comment: Did you set a value for `id`?
Comment: How can I pass a value to id dynamically?
Comment: You can call the `getPermissionById` function anywhere in your code with an `id` parameter e.g. `getPermissionById(3)` and the function will return the object. For the code above, you can set the value of `id` and the computed property `permission` will be automatically updated (`this.id = `).
Answer: This sort of thing was discussed here with some input from Linus Borg
Why not just use a getPermissions getter to return the permissions array from state as-is? In your component's computed "permission" method, you could then use
return this.getPermissions.find(x => x.id === this.id)
  ? this.getPermissions.find(x => x.id === this.id).id
  : someFallback

// or if you're using optional chaining...

return this.getPermissions.find(x => x.id === this.id)?.id || someFallback

If you need getPermissionsById to be a shared function, why not create a vuex action for that which accesses the state via the getter?


Letting a ComboBox blink in WPF

Question: I have a simple ComboBox inside a MVVM app.
The important things inside the ComboBox look like this:
    <ComboBox Name="EmployeesComboBox"
              ItemsSource="{Binding EmployeeEntries}"
              SelectedValuePath="Id"
              SelectedValue="{Binding Id}"
              Width="192" FontFamily="Arial" FontSize="12">
        <ComboBox.Resources>
            <Storyboard x:Key="BlinkingStoryboard">
                <ColorAnimation Storyboard.TargetProperty="Background.Color" Duration="0:0:2"
                        From="White" To="Yellow" RepeatBehavior="Forever" AutoReverse="True" />
            </Storyboard>
        </ComboBox.Resources>
    </ComboBox>

I changed even the style of the XAML of the ToggleButton(inside the ComboBox Style definitions) like follows:

(I took most of the definition out of the original style and only changed the Background="{StaticResource ComboBox.Static.Background}" to the Background="{TemplateBinding Background}".
After that I could use the Background property inside the XAML to change the color of the ComboBox as intended, but I need to fire the StoryBoard, so that I can make the ComboBox 'blink' by programmatically means.
As soon as I start the Storyboard the app crashes (timer dont work anymore, and so on) wihtout error messages.
Anyone an idea what I am missing?
Answer: You need to get a reference to the storyboard in code so you can start it. See Call a storyboard declared in xaml from c# (of course yours is defined in the combobox's resources so you'd need to get it from there).
Edit: to get more information about failures, enable trace settings for WPF in visual studio's settings - debugging/output window, then look in the output window for any warnings/errors.
Comment: You'll need to get more information then; off the top of my head, enable trace settings for WPF in visual studio's settings - debugging/output window (or if already enabled, look in the output window for any warnings/errors).
Comment: From the code behind I call the Storyboard and it is found, but it doesn't work. I use a simple `Storyboard animationStoryboard = (Storyboard) EmployeesComboBox.FindResource("BlinkingStoryboard");` and then `animationStoryboard.Begin();`
Comment: Ok, now I got the exception that there was no target for the animation. I set it with Storyboard.TargetName="ExployeesComboBox" and now it works fine. Thanks. Please change your text of your answer to that of your comment and I can call it a solution ;)

Letting a ComboBox blink in WPF


Wordpress Dynamically Inserting Post Name as Link Text

Question: I am using the following code in my template file to display an audio player with Download Button (download button handled by the audio player plugin)
I need the Post Name To be inserted into the code so that the resulting downloaded filename will match the post name.
example - Post Name = "Really Cool Audio" would = Really Cool Audio.mp3 when Downloaded
It also appears that spaces are being removed even though spaces in .mp3 files are "ok" and preferred.
<?php $customField = get_post_custom_values("audio");
if (isset($customField[0])) {
echo '
Need Post Name Here
';
} ?>
Answer: If you're in The Loop (and it sounds like you are), the following should work. "Need Post Name Here" has been replaced by .get_the_title().
<?php
  $customField = get_post_custom_values("audio");
  if (isset($customField[0])) {
    echo '
'.get_the_title().'
';
  }
?>

Comment: I replaced Need Post Name Here with `.get_the_title();';
} ?>`  Sorry for not understanding.  Where do I use `.get_the_title();.` ?
Comment: You need to wrap .get_the_title() in single quotes - '.get_the_title().'
Comment: Sweet!  This works!!  It removed the spaces Would it be possible to keep spaces?
Comment: It's usually better not to have spaces in file names.  The get_the_title() function includes spaces but the audio plugin probably strips them out.
Comment: I would like to leave spaces and dashes as you would see when you buy a track from iTunes  I have started another thread here - [link](http://stackoverflow.com/questions/13821989/wordpress-filename-same-as-post-name-keep-spaces-and-dashes)


How do I know if an async method call changes the caller's context?

Question: Consider this example:
async Task Foo()
{
    button.Text = "This is the UI context!";

    await BarA();

    button.Text = "This is still the UI context!";

    await BarB();

    button.Text = "Oh no!"; // exception (?)
}

async Task BarA()
{
    await Calculations();
}

async Task BarB()
{
    await Calculations().ConfigureAwait(false);
}

How do I know if calling await BarB() changes the context without reading the body of the async Task BarB() function? Do I really need to know exactly whether an async function calls ConfigureAwait(false) at any point? Or maybe the example is wrong and there's no exception?
Comment: "maybe the example is wrong and there's no exception?" - maybe you could compile and run the code and find out? Showing us an example and not even knowing whether it exhibits a behaviour you're wanting to ask about make for a *bad* question.
Answer: What BarB() does is largely irrelevant, unless BarB() needs to talk to the UI. The important part here is the await in the line:
await BarB();

it is that await which captures context (too) - and negotiates getting back onto the correct context if it finds itself continuing from the wrong context. So; unless you write:
await BarB().ConfigureAwait(false);

you should be fine here.
The ConfigureAwait(false) in BarB() looks normal and is probably correct, if we assume that BarB() doesn't need to directly update the UI or perform any other context-bound operation.
Answer: To supplement Marc's answer - bear in mind that async is an implementation detail of a method. How or why a method creates a Task that it hands back to you are largely transparent (and that's why async isn't part of the signature, not allowed in interface definitions, etc)
Whilst it's true that your method shares it's "current context" with methods it calls, that's only to the extent that those methods, if they want to know the current context, will call SynchronizationContext.Current. They'll then use methods on that context to get "back on it" if necessary. Any "changes" to the context will usually actually be performed by switching continuations onto a suitable thread that already has the right context set.
What these methods won't normally do is call SetSynchronizationContext. It's only if a method does call that that you have to worry about changes to "your" context. (Some infrastructure code may call that method if their synchronization context is free-threaded but requires other ambient resources. They'll get a thread pool thread, call SetSynchronizationContext, execute the continuation and then unset the synchronization context again).


What is the install terminal and how to remove it from VS Code terminal window?

Question: This started showing up a few months back in my VS Code setup. It wasn't bothering so much, so I kept ignoring it. I am not sure what it's called, but searching around with "install window" or other combinations for VS Code gives some unexpected results. I am using remote-ssh extension for development and believe that it has something to do with a remote extension setting. If I try to close this window, my ssh connection breaks and VS Code opens up another of these to recreate the ssh connection.

I have tried checking and unchecking various remote-ssh extensions but to no avail. Even reinstalling VS Code didn't do any good. I don't see the same behavior on other machines that I have VS Code installed.
I would really appreciate if someone could help me get rid of this terminal. My VS Code is running on macos and ssh server is Ubuntu if this helps.
Comment: It is very annoying.  I don't want to see all that junk.  Couldn't it just show some kind of status in the bottom bar?  Also, it has gotten worse in latest version.  You can't even kill the window anymore.  It just comes back, cluttering up my terminal list.  BTW, how should I create an issue for this in github?  It isn't a bug or feature request.
Comment: I went to github but it sent me here to ask this question. I was hoping some VS Code maintainer would read this and answer.
Answer: Remove "remote.SSH.showLoginTerminal": true from your User settings JSON file, then exit VSCode and re-launch the workspace. If that doesn't work set the setting to false instead.
Comment: OMG! You are an angel! Thanks, I have gone through some many of the remote ssh settings but nothing had worked! That was such an eyesore for last one year for me!


Add, don't replace, icon to mouse cursor

Question: I want to add an icon to mouse when they hover html element, so that I could hint to the user, that they can right click.
I don't want to replace the default cursor, because they differ on platform and don't really need to replace the default mouse icon itself.
Comment: Have a look here. https://www.w3schools.com/cssref/tryit.asp?filename=trycss_cursor
Comment: @Dula all those replace the the cursor. I'm interested in ADDing to the cursor. :)
Answer: You can add a mousemove event listener on the element which you want to show the custom cursor over that gets the relative x and y coordinates of the mouse to the element and applies them to the top and left style properties of the cursor:

element.addEventListener('mousemove', function(e){
  const rect = element.getBoundingClientRect();
  const [x, y] = [e.pageX - rect.left, e.pageY - Math.abs(rect.top) + window.scrollY]
  cursor.style.display = "block";
  cursor.style.left = x + "px";
  cursor.style.top = y + "px";
})

element.addEventListener('mouseleave', function(e){
  cursor.style.display = "none"; //hide the custom cursor when they leave the element
})
#element{
  height:1200px;
  width:600px;
  background-color:black;
  position:relative;
}

#cursor{
  position:absolute;
  display:none;
  color:white;
}

right click!

Keep in mind this solution requires the container element to be relatively positioned, since the cursor is absolutely positioned.
Comment: Omg. Learned something additionally new from this example. `id='cursor'` is accessible without explicitly creating the element! :D
Comment: @MihkelL. BTW, the previous version of my answer did not support scrolling (e.g, after the user scrolled, it would break). It should work now


How to combine multiple condition

Question: Dears
im trying to modify below queries to have this result as the table attached , if someone can help me

i need to use case statement or if statement i think

thanks in advance,
Comment: please add your content as text see https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-on-so-when-asking-a-question  and also include the original data
Answer: With conditional aggregation:
select date(created_utc),
  count(case when isMnp = 0 and isEsim = 0 then 1 end) SIM,
  count(case when isMnp = 1 and isEsim = 0 then 1 end) MNP,
  count(case when isMnp = 0 and isEsim = 1 then 1 end) eSIM,
  count(case when isMnp = 1 and isEsim = 1 then 1 end) "eSIM-MNP"
from "Order"
where status = 'completed' and date(created_utc) >= '2020-04-25'
group by date(created_utc)

If the columns isMnp and isEsim are boolean then use this:
select date(created_utc),
  count(case when not isMnp and isEsim then 1 end) SIM,
  count(case when isMnp and not isEsim then 1 end) MNP,
  count(case when not isMnp and isEsim then 1 end) eSIM,
  count(case when isMnp and isEsim then 1 end) "eSIM-MNP"
from "Order"
where status = 'completed' and date(created_utc) >= '2020-04-25'
group by date(created_utc)

Comment: Many thanks i really appreciate your help but when i tried to run it i faced this error SQL Error [42883]: ERROR: operator does not exist: boolean = integer
  Hint: No operator matches the given name and argument types. You might need to add explicit type casts.
  Position: 58
Comment: Which column is boolean?
Comment: Check my 2nd query.
Comment: I add single quotation to the 0 and 1 in column isMnp and isEsim and its worked.
Comment: but how about if i want the date interval is the previous 4 days from now ?
Comment: `where date(created_utc) >= current_date - interval '4 day'`

How to combine multiple condition


barchart "grouped by" option doesnt distinct categories properly

Question: I have a barchart to display the number of action on a keyboard for a time interval of 10 seconds. Without using "group by" function, I have the expected result:
http://postimg.org/image/by1vzottr/
However, I wanted to improve it by using group by function. Therefore, I categorized my Y value. EG: if Y < 10, cat = 0; if Y < 20, cat = 1 etc. But when using "Group by" option, I have this result:
http://postimg.org/image/fcx8e8j4x/
My goal is to have the first graph display, but with the colour corresponding to the categories.
Comment: Can you post your code please, so we can see what you are doing wrong.
Comment: Hi, I am directly building the chart in plot.ly. My initial plot.ly sheet looks like this: http://postimg.org/image/j7wztunfb/
Answer: this is Étienne from plotly.
In brief, plotly doesn't understand that your x-axis values are in fact times, not mere categories.
Currently, the plotly grid understands datetime formats listed here.
Once in one of the supported formats, a grid like https://plot.ly/~etpinard/2603 turns into a plot like https://plot.ly/~etpinard/2607/_0-1-2/ .
I hope this helps.


A question about derivation in oblique view frustum

Question: Problem Description:

Reference:
Oblique View Frustum Depth Projection and Clipping
"Mathematics for 3D Game Programming and Computer Graphics" 3rd edition, chapter 5.6.
M is the original projection matrix.
Plane C is the modified near plane, and C'=transpose(inverse(M))*C is the projected plane by M.
Why in NDC the corner Q' of the view frustum lying opposite the plane C' is given by Q'=(Cx, Cy, 1, 1)?
Answer: check this link
quotations :
"The points (+/-1, +/-1, 1, 1) are the four corners of the view frustum on the far plane in clip space."
this should be the point Q' which equals (sgn(Cx), sgn(Cy), 1, 1)


Simple compression in c++

Question: we have a C++ MFC application and C# Web Service. They are communicating over HTTP, but as they are exchanging text data, compression will help a lot. But for some reasons, we  can't use an external library.
We basically need to compress a byte array on one side and decompress it on the other side.
What should we use to compress our data? The best scenario would be if there is something in MFC/win32 api. Or is there some simplistic code with at most LGPL license that we could integrate into our project?
Answer: Can't you just switch on HTTP compression? http://en.wikipedia.org/wiki/HTTP_compression
Answer: As has already been said, the zlib is probably what you are looking for.
There are several algorithms within:

The deflate and inflate pair
zlib itself
lzo

The simpler is probably lzo (I advise to pass the uncompressed size on the side), but zlib isn't very complicated either and the compression rate can be parameterized (speed / size trade off) which can be a plus depending on your constraints.
For XML data (since you were speaking of web services), LZO gave me a ~4x compression factor.
Answer: zlib has a very liberal license.

Simple compression in c++


How do I stay undetected while pickpocketing?

Question: When I'm pickpocketing, sometimes it seems like I have a 90% chance to steal, but after a few items, I get detected. I thought I saw a loading screen about this, but it went by too fast and I didn't get a chance to read it.
How do I make sure I don't get detected while pickpocketing?
Answer: Spells like Muffle and Invisibility seem to help me remain undetected, or at least escape after detection.  Also, pickpocketing while detected by anyone in the area seems to aggro guards most swiftly.
When I really want something that's dangerous to get--pickpocketing a staff of fireballs off an enemy warlock for example--I often save before the attempt.  It feels a little like cheating, but becoming a crispy critter somehow didn't make my character's bucket list.
--You probably saw the tip that describes how looking at someone's pockets isn't a crime, but taking anything is.
Answer: I find it's easier to pickpocket at night when people are in bed.  Pick their door lock, sneak into their house and pickpocket them without them knowing.
At the beginning of your skill they will often awake but your skill will get better.
I even pickpocketed the Jarl's main assistant!
Comment: there is also a perk that pickpocketing sleeping person is 25% easier
Answer: The calm spell can open up new pickpocketing opportunities.  I've used it on bandits with great success.
Since they are calm, they don't wander around to make sure they see you.  It's very easy to stay hidden (just don't move).


Drawing a colorbar aside a line plot, using Matplotlib

Question: I'm trying to add a color bar in a graph, but I don't understand how it works. The problem is that I make my own colorcode by:
x = np.arange(11)

ys = [i+x+(i*x)**2 for i in range(11)]

colors = cm.rainbow(np.linspace(0, 1, len(ys)))

and colors[i] will give me a new color. Then I use (homemade) functions to select the relevant data and plot them accordingly. This would look something like this:
function(x,y,concentration,temperature,1,37,colors[0])
function(x,y,concentration,temperature,2,37,colors[1])
# etc

Now I want to add the colors in a color bar, with labels I can change. How do I do this?
I have seen several examples where you plot all the data as one array, with automated color bars, but here I plot the data one by one (by using functions to select the relevant data).
EDIT:
function(x,y,concentration,temperature,1,37,colors[0]) looks like this (simplified):
def function(x,y,c,T,condition1,condition2,colors):

  import matplotlib.pyplot as plt

  i=0

  for element in c:
   if element == condition1:
      if T[i]==condition2:
          plt.plot(x,y,color=colors,linewidth=2)

  i=i+1

return

Comment: I am assuming `function` will eventually call a "plotting" function or similar. There you will need to pass your colour. Can you post the content of `function`?
Comment: Couldn't you remove references to `ys` in the question?  or does `ys` in the first box become `y` in the second one?
Comment: My understanding of your Q: (1) you plot repeatedly a curve whose shape and color depend on a parameter, that is monotonically varying; (2) afterwards, you want to give an hint at parameter value for the different curves using a pl.colorbar.  If I'm correct, it's difficult to do, because colorbars are designed to play nice with pl.imshow and pl.countourf rather than with pl.plot.  That said, you should be able to use two subplots, in the first one your plot and in the second a colorbar drawn on its own, as it is explained/exemplified in http://matplotlib.org/examples/api/colorbar_only.html
Comment: Thanks for the link, only I don't understand how that example works. I have seen the example before posting this, but I couldn't get it to work for my purpose. What is 'cmap' in this example? What does it contain? And what is 'norm'?
Comment: @KayJansen It's a complex task, you either find on SO a good-hearted `matplotlib` specialist (that I am not, sorry) or you're mostly on your own. Besides, I'm a bit astonished by the fact that you didn't mention your previous research in your question, but this is your 1st Q in SO... if you intend to hang about you'd better read something about _asking good questions_. Ciao
Comment: @KayJansen ps: try to add a matplotlib tag to your question, or ask anew the question using the  'python' and 'matplotlib' tags.  For your info the tag 'colorbar' has exactly 0 followers.
Comment: @KayJansen Never mind, I edited your Q myself: I tried to give a more meaningful title and added the matplotlib tag.  Let's see if these edits are approved.
Answer: Drawing a colorbar aside a line plot
Please map my solution (I used simply 11 sines of different amplitudes) to your problem (as I told you, it is difficult to understand from what you wrote in your Q).
import matplotlib
import numpy as np
from matplotlib import pyplot as plt

# an array of parameters, each of our curves depend on a specific
# value of parameters
parameters = np.linspace(0,10,11)

# norm is a class which, when called, can normalize data into the
# [0.0, 1.0] interval.
norm = matplotlib.colors.Normalize(
    vmin=np.min(parameters),
    vmax=np.max(parameters))

# choose a colormap
c_m = matplotlib.cm.cool

# create a ScalarMappable and initialize a data structure
s_m = matplotlib.cm.ScalarMappable(cmap=c_m, norm=norm)
s_m.set_array([])

# plotting 11 sines of varying amplitudes, the colors are chosen
# calling the ScalarMappable that was initialised with c_m and norm
x = np.linspace(0,np.pi,31)
for parameter in parameters:
    plt.plot(x,
             parameter*np.sin(x),
             color=s_m.to_rgba(parameter))

# having plotted the 11 curves we plot the colorbar, using again our
# ScalarMappable
plt.colorbar(s_m)

# That's all, folks
plt.show()

Example

Acknowledgements
A similar problem, about a scatter plot
Update — April 14, 2021

With recent versions of Matplotlib, the statement s_m.set_array([]) is not required any more.  On the other hand, it does no harm.
When plotting, in place of color=s_m.to_rgba(parameter) one may want to use the (slightly) more obvious color=c_m(norm(parameter)).
Comment: Perfect answer!


Registration of chrooted environment on Landscape not working with Virtual license

Question: Despite having several remaining registrations on Landscape, it doesn't let me register chrooted environments:
'There are no licenses available for $accountname. $hostname was not accepted.'
License type: Virtual
Seats free: 12
How should I add those chrooted environments to Landscape?
Comment: A chrooted environment is not a virtual environment as there is no isolation; the environment shares the same devices, address space, uids/gids, network configuration. For all practical purpose, a chroot IS the same physical machine. If you're looking for lightweight virtualization, LXD/LXC is probably what you're looking for as it does just enough isolation to make the container distinct from the host system.
Comment: Right, thanks. The chroot are running, I guess it's more an issue with the license type then.
Comment: Those chrooted environments (precise) are running on VMs (xenial) that have not been added to landscape. I'm trying to get Ubuntu ESM for the chroot envs. Is someone able to tell the licenses I'd need?
Comment: Hi Benoit -- Ubuntu ESM is a commercial product offered by Canonical, for help using it, please file a support request with Canonical.  FYI, Canonical does not support landscape running in a chroot.  Only a system container, VM or physical system.
Answer: Ubuntu ESM is a commercial product offered by Canonical, for help using it, please file a support request with Canonical.
FYI, Canonical does not support landscape running in a chroot. Only a system container, VM or physical system.


disappearing files on desktop

Question: I have upgraded my Ubuntu desktop from 14.04 to 14.10.After that,my files on my desktop disappearing but they are present in desktop folder.
I solved this problem by disabling wallpaper in compiz (CCSM).
Answer: In Ubuntu Gnome 14.10, in the Tweak Tool enable 'Icons on Desktop' under Desktop
In Ubuntu 14.10, use dconf-editor and change the setting of Org->Gnome->Desktop->Background->Show-Desktop-Icons

disappearing files on desktop


Adding a shelf in a laundry closet that can support a 150lb clothes dryer

Question: I'm considering adding a shelf in our laundry closet to hold our 150 pound clothes dryer, as an alternative to the massive hassle (e.g. here and here) of moving a 300+ pound vertical washer+dryer stack whenever I need to service the washer.
Here's the layout today, not exactly to scale. The red lines are the edges of the "dryer shelf" that I'm considering.

Is a "dryer shelf" a good idea? If yes, I've got questions:

What's a good material for a shelf that needs to span 43.5 inches and support a heavy, vibrating load? Let's be safe and assume 250lbs in case I upgrade later.
How should I support the shelf on either side? At first I thought of a big triangular buttress like many shelves use, but that would impinge on the washer below. So I'm wondering if some other structural support would be better, e.g. two 2x4s screwed into the studs on either side, and a thick shelf board mounted on top of those 2x4s?
How much clearance should I leave between the top of the washer underneath and the bottom of the shelf on top? I don't want too much clearance because it'll make the dryer hard to get to for my (shorter) family members, but I don't want too little that it'll make it impossible to upgrade the washer later to a slightly-taller model.
Should I build a lip on the front and/or back of the shelf to prevent the dryer from vibrating itself off the shelf?  Or is this a non-issue because dryers' vibrations are minimal relative to their massive weight?
What are gotchas (other than remembering to disconnect and reconnect everything!) that I should watch out for?
Are there code requirements (in California) for supporting a dryer that I should be aware of?

For actually doing the work, I have a crazy idea described below. Is this a good way to do it? If not, what's better?

Temporarily screw a few heavy-duty hooks (at joists, of course!) to the 11-foot ceiling.
Thread some rope or straps under the dryer
Hoist the dryer up an inch or two
Move the washer out of the way so I can have access underneath and in back
Disconnect the lint hose, gas hose, power, etc.
Hoist the dryer up 3-4 feet (high ceilings FTW!) to give me room to work
Mount the shelf
Reverse steps 6-2

BTW, what's prompting this now is that our washer (a 7.4 ft3 Whirlpool Duet Steam) has a busted sensor or some other problem that's causing it to think it needs to drain for many minutes after the tub is fully drained, and which often causes various delays and errors on the console. If I need to go through the trouble of repairing it anyways, then I figured that it's a good time to consider a longer-term investment in easier future repairs.
BTW, here's what the closet looks like today.
Comment: Why do you not want to install a dryer hanger bracket?
Comment: Your dynamic forces are going to be more than 250lbs on front-loader with 150lbs static. I wouldn't want to transfer waves, noise, and oscillations into my walls either, unless I rented. Consider a box-like structure with 4 or 5 sides that will communicate the vibes to the floor.
Comment: @FreeMan - I've had to repair this washer at least annually for the last 5 years, while the dryer has never needed any repairs at all. But your question gave me an idea: I don't really need a shelf all the time, only when I need to pull out the washer to repair it. So if I can set up a way to hoist the dryer up in the air temporarily (which is what I need to do to install a shelf anyways), that should be good enough. No need to build a shelf at all. Should have thought of that sooner! Thanks for prompting me to think more deeply about what's really needed here.
Comment: @Jasen - I had no idea that there was such a thing as a "dryer hanger bracket". I'll take a look. Thanks for the pointer!
Comment: Frame challenge: Just because your washer is giving you problems _now_, what's the _last time_ you had to service your washer? Are you sure you're not creating issues (damage to the walls from the weight and vibration, possible collapse dropping the dryer on the washer) to avoid a 1x per decade maintenance/service "problem"? I've lived in my house for 30 years and have to replace a washer, but never service one. They dryer, I've had to service 2 or 3 times, and I'd think your idea would make the drier service more difficult.
Comment: Not only that, they probably make one for that dryer.   But TLDR answer: 3-4 spans of Unistrut.
Answer: Your width is quite tight.
Build two ledgers, by mounting a 1x6 against the suds to the left and right of the dryer.
On top of the ledger place 2x6 on flat, one in front and one in the back, bearing on the ledger. Measure the length of the 2x6 for a tight fit and fasten to ledger with construction glue and construction screws.
If there is not enough room for a ledger use angle iron instead, - it can also be used inverted.
Use structural framing screws to fasten the ledger or angle iron to the studs, as they have higher tensile strength. The drywall is effectively a 1/2in spacer and will increase the bending force applied to the screw.
For screw length budget 3/4in for the ledger, 1/2in for the drywall, and 1in penetration in studs. For each ledger apply 2 screws per stud.
For an upgrade use a 1x8 ledger and 3 screws per stud.
Ideally confirm the location of the stud by pre-drilling a 1.5-in wide hole to remove just that much drywall over the stud. This ensures you properly centre the screw in the stud. It is not uncommon to have a stud finder mis-identify or mis-locate a stud edge.
Should the ledger in your opinion not suffice due to poor stud positioning, support the ledger with vertical 1x6 reaching to the floor, attached to the studs to hold it in place.
Due to load and vibrations do not rely whatsoever on the drywall. Assume it will brittle away over time.
Your question was about carpentry. Alternatively it could be about appliances, in which case this could also work in your case:

Ref homedepot.ca
Comment: If there is not enough room for a lledger  use angle iron instead, - it can also be used inverted
Comment: good point @Jasen, edited
Comment: Good fix. I would cut a neoprene mousepad into thin strips to line the interface between the bracket and floor. Or at least a bead of silicone or low-temp hotglue, anything slightly squishy that would isolate vibrations.
Comment: I wouldn't trust 1x material (3/4" actual thickness and usually the worst of worst woods at my local stores) to support the dryer. Even with 2 or 3 structural screws per stud, that's simply not much bearing surface for the 2x shelf material to sit on. I would use a 2x8, minimum, ledger with at least 3 screws into each stud it passes. Angle iron at a minimum of 2x2x1/4" thick, probably thicker would likely be better.


How many points in a line segment?

Question: My teacher said that in the circumference of circle there are infinite points. When I was learning more about circle, I came to this picture:

My question is: When we unroll the circle, then the length of the circle and line segment are the same. For this reason, I think that the unrolled line segment should also have infinite points! But there are only two end points. Can anyone explain to me where am I going wrong?
Answer: You are conflating end points and points.

The circumference of a circle does not have any end points but infinitely many points.
The line segment has two end points and still infinitely many points.

Sidenote: The length of the segment is not as important as you may think. We cannot distinguish the number of points on a line segment of length $π$ from those on a line segment of length $2π$.
Comment: Adding to this, the idea that there are infinitely many points on a line segment is a consequence of the idea that the line segment has a length while a point does not. If you start at one end point and move halfway to the other, you arrive at a third point on the line segment. If you again move halfway from where you are to the second end point, you arrive at a fourth point on the line segment. As long as you stay between the end points, you can never move to any position that is not a point on the line segment.
Comment: @user20879: I am sorry, but I fail to understand what you are saying.
Comment: Oh so infinite points are limited in a finite length? How can it possible?
Comment: @Moderator: For the same reason that there are infinitely many rational (or real) numbers between 0 and 1. If you have a question about this, you better ask it separately as this is a fundamental insight and it's impossible to satisfyingly answer this without you elaborating what you understood so far and where your problem is.
Comment: @Wrzlprmft http://math.stackexchange.com/questions/1915081/how-many-points-need-to-make-a-linesegment
Comment: @Moderator: That's not the same question you asked me (at least in my understanding). Also, you really need to elaborate what you understood so far, so we can start explaining from there.
Answer: Both the circumference and the segment have infinitely many points, but that's not the point (heh, heh).
What matters is their length. The picture presumably is trying to show the ratio between the diameter and the circumference, which turns up to be $\pi$, or 3 and then something.
Answer: There are more than two points on a line segment. In fact, there are infinitely many points on the line segment. For example, there is a point between the two endpoints that is also in the line.
And a point between the middle point and the start.
And one between the middle and the end.
And one at a distance of $\frac{\pi^2}{4}$ from the start and on and on and on...
Comment: Oh so infinite points are limited in a finite length? How can it possible?
Answer: In the case of the circle, you take a polygon and say that it approximates a circle, but it is not precise.  As you increase the number of points on the polygon, it approximates a circle more and more, but never quite reaches it.  It is said that as the limit of points on the polygon approaches infinity, you have yourself a circle, which is why one interpretation of a circle is a polygon of infinite points.
In the second case, a line may have infinite points between its endpoints, however it is not a defining feature of the point.  In other words, it doesn't become more "line"-like with increased points on the same line.  However your assumption is not wrong!  You could think of the line rolled out from a circle as having infinite points!  Most people just tend to prefer to define a line in terms of its start and end points.
Answer: Another Pointless Discsussion!  :-)
On to a tangential question...
It is all relative to the scale that is being examined.   But points are dimensionless.  So I take issue with the precise idea that a tangent can be determined by two points that are in close proximity. "Leibniz defined it as the line through a pair of infinitely close points on the curve." Wikipedia.   The problem is, no matter how close two points are, there are an infinite number of points between two inifnitely close points.  A better definition is to think in terms of tuples.  A curve consists of an infinite set of tuples.  For each tuple in that curved line, there only one tuple at a time can be concurrent with a tuple in an intersecting  straight line. When that straight line intersects precisely that one point tuple in the curved line, then the straight line is a tangent.  Now, practically (why differentian and integration was invented), there had to be a way to call "Close Enough" and converge to an answer.  That works when the measurements needed to find that precise tuple, are below the level of accuracy possible for the scale you are working with.
So it matters that points are dimensionless and infinte in all mathematical applications.  But to be practical, and make sense of a problem, points have to be defined in a way that is useful to the scale that the problem exists in.  For example, if you zoom into a circle far enough, geometrically, the segment you are examining will appear to be a straight line, because the remaining curve falls below measurability.  Practically, it becomes a straight line.  Mathematically, the infinite set of tuples representing the curved line, is still curved.
Answer: Any legitimate question depends on whether the terminology is understood correctly. The problem is, the definition of a "point" is not understood correctly. Your teacher believes a point has no size because most, if not all, of the geometry books, old and new, say so. It is an error of immense proportions, wasting people's time and even warping their thinking. Geometry is supposed to help us understand the physical world around us. If a point has no size, then it has zero size. Basic math tells us that no matter how many times you add zero, it will always equal zero.
The correct definition of a POINT is "the smallest possible size". From there, everything will make sense mathematically, and logically. Both a circle, and a line segment, have an "indefinite" amount of points, but surely finite.
Comment: wrong conclusion, see https://math.stackexchange.com/a/1173406/34603

How many points in a line segment?


Notifications in db

Question: I want to perform notifications on my web site. I'll for them on client side with an ajax request every 300 seconds, then I want a response from my server. I can do all of this things, but I don't know how to save the notifications. I'm thinking to save every notifications in a table in my db, then I perform a query with PHP every time i have a request from the clients. There are other ways to do this?
Comment: First of all, how are you planning to achieve something 'real-time' if you only poll every 300 seconds.
Also, why do you want to save the notifications, what do you need them for? What is the context of your project?
Comment: Well, there are other ways to perform the notifications, such as using web sockets.  But it sounds like you're not asking about the notifications themselves, but rather how to persist data on the server?  Generally a database is the way to go for that, yes.
Comment: "Real time notifications", "Request every 300 seconds" ... Thats surely not real time. Use something like websockets or learn the observer pattern in PHP.
Comment: Sorry, i wasn't clear. I can use also real time notifications, but i think that using a request every 300 seconds (or something like that) can be enough for my project. I don't know if there are other ways to perform this kind of notifications. Then I want to know if storing all the notifications in one table is too much for the db.
Comment: Can you be more clear on what kind of notifications you are talking about, i.e. give us an example of the payload of such a notification. Also, can you be more clear on the context of your project with the purpose of giving us a more intuitive idea of what you want/
Comment: An example of notification is: "Carl published red.txt". Carl is an user and red.txt a file. So, Carl is a row of the table Users, Red.txt is a row of table Files. I'm thinking to create a table Notifications where i put the IDs of users and files, the Ts and a text value.
Answer: I resolved my problem. I'm using ajax request every 300 seconds and all my notifications are in my db. It works fine and it seems to be a good solution.

Notifications in db


Formatting USB stick with 11.10 is unreadable with Windows 7

Question: If I format a USB stick (any) on my Ubuntu 11.10 system, they are unreadable with my Windows 7 system.
I have tried both NTFS & FAT but Windows refuses to see the drive as having been formatted (it reports it as RAW in Disk Management Console).
This has been done with Disk Utility, gParted, & mkfs (mkfs.vfat / mkfs.ntfs) but nothing seems to work.
If I do this the other way (i.e. format on Windows) I can copy files to it through Ubuntu and then see them with Win7.
I'm fairly new to Ubuntu....
Comment: Does the USB stick work in Ubuntu after formatting in Ubuntu (including after unplugging and re-plugging it)?
Comment: It does. All files copied to it are intact....
Comment: Did you try formatting using another Ubuntu/linux version?  (You should be able to do that from any live-CD if you want.)
Answer: Open up Disk Utility, insert your USB stick. It should list under Peripheral Devices (left side). Click on it.
On right side click unmount volume and then Format Volume (not Format Drive). If only format drive appears and Format Volume does not appear read till last.
A window pops up. In type select FAT, give a name and then hit format. It asks for confirmation, press format.
After formatting press Mount Volume again.
Go to home using the File Explorer (gui, nautilus, home button), or select the drive using unity lauch bar. See if you can create new file or directory. Right click on a blank area inside file explorer (file manager) inside your drive and select properties.
If Filesystem type: says msdos. It is perfect (FAT32), it should work on windows or linux (unless you are trying to copy a file larger than 4G). 4G being limit for FAT. In Disk Utility if you don't see Partition Type: w9 FAT32 and options like Unmount Voulme or if not mounted Mount Volume, Format volume, Check Filesystem, Edit Partition, Delete Partition read on. These options should be shown in lower half below Volumes(thick black above your driver partition gui).
If you only see buttons above Volumes like Format, Safe Removal and Benchmark you have only Formatted the Drive but not created a Volume. You have to create a filesystem in a drive before you can use it.
These all steps seems lame, but if you have missed anything, it might help, if not your USB stick is damaged, get a new one.
Warning: Don't just vaguely format drives under Local Storage (you might have no os to boot into).
Comment: Thanks, will try this when I'm next with my Ubuntu box. USB Stick certainly not damaged as formatting in Win7 works fine on both. Will let you know how it goes!
Answer: @neildeadman - when you format the USB stick in Ubuntu as a device, let's presume you are doing this through a single tool like perhaps gparted for ease of discussion's sake. One the device has been formatted, how do you remove the device from the system prior to readying it for use within a Windows 7 system?
If you simply unplug the device, it may appear as RAW, because it has not been properly unmounted from the Ubuntu system. Would suggest unmounting the USB stick from Ubuntu prior to attempting to unplug, then remove from the Ubuntu system and then plug into the Windows 7 system and determine if the formatting remains.
The act of not unmounting the USB stick could be the potential cause for your error.
HTH. Have a nice day. :)
Comment: I usually either click 'Safely Remove Device' if in Device Utility or I run 'sync' and then 'eject \dev\sdc' from the command line.
Comment: That is odd indeed. Never seen that issue before; do you have the ntfs-3g package installed? That might help.
Comment: Not sure ntfs-3g would help as I have also tried as a FAT32 type too :S
Comment: Just a generic USB device? Have you tried using gnome-format with the device? You will probably have to add the package using apt-get (sudo apt-get  install gnome-format) if it is in the Oneiric distribution (sorry working on Natty @ the office, Oneiric @ home - headed there later). It will offer to format in either FAT or EXT2, but should be able to format for compatibility with all devices. If that works, then pick a tool and try to format with that again and determine if the tool creates issues again. Might need to gather /var/log/syslog output to see if errors are reported.
Answer: when you format the usb stick, change the file format to FAT or FAT32
When formating make sure that the "take the ownership of file system" is selected
Comment: He tried that, 'I have tried both NTFS & FAT...' from the second sentence.


What type of plastic is best for outdoor usage?

Question: What type of plastic is best for outdoor usage? Like resistant to constant sunlight and water exposure and strong enough. It will be used to encolse part of (small size bird) aviary. Also please specify how much thickness will be enough for it.
Comment: What are you using the plastic for?
Comment: It will be used to encolsed part of an aviary.
Comment: Updated the question. please see.
Answer: Corrugated roofing panels, either clear polycarbonate or fiberglass skylight panels, should do the job. I'd put more trust in the light/weather resistance of fiberglass than polycarbonate, but both are readily available.
Comment: I want to enclose side of aviary too. How much thick it need to be? and what type?
Comment: Roofing material should be thick enough for walls hung on a supporting frame. The fibreglass stuff is strong enough to walk on. It won't have any value as insulation, or stand up to typhoon winds, but it ought to keep your birds in without trouble.


How to quick switch between Jack the drone's support abilities in Gears 5?

Question: A tooltip popped up but I couldn't read it in time.
Going through the game menus doesn't show any control for the same? All the websites online talk about controllers - I want the mouse/kb button for the same
Answer: Figured it out, You have to press Shift and then a mini menu pops up that you can press 2 or 4 on to quick switch.
Gears 5 conditions you not to press Shift key for anything so didn't think of pressing it.


For $z\in\mathbb{C}$, prove $\lim_{n\to\infty}n$Log$(1+z/n) = z$.

Question: Here Log is the principal complex logarithm, Log$z = \log|z| + i$Arg$z$.
I have tried multiple approaches none of which look even remotely promising. I know that Log is discontinuous along the negative real axis and this was a cause of some minor problems.
As a follow up I'm supposed to show that $\lim_{n\to\infty}(1+z/n)^n = e^z$ which I have done assuming the result in the title.
Can someone give me hints or an outline of what I can try?
Comment: Is there a missing power of $n$ in your title?
Comment: @nobody oops, yes, its suppose to be $n$Log$(1+z/n)$
Comment: Do you know the Taylor series for $\log$ about the point $1$?
Comment: Yes, $\log(x+1) = x-\frac{x^2}{2}+\frac{x^3}{3}-\frac{x^4}{4}+\cdots,$
Comment: Then for $n$ large enough note that the taylor series is convergent at $z/n$. Try plugging in the taylor series and see what you get.
Comment: Is this using the real result for Taylor series or the complex one? I have not yet seen the complex result
Comment: I meant the complex one. Sorry for the confusion. Can you give us an idea of the kind of thing you have seen?
Comment: Cauchy Riemann equations, and then we defined $e$ and Log
Comment: Do you know that your Log function is analytic?
Comment: Except on the negative real axis right?
Answer: You have that
$$\text{Log}\left(1+\frac{z}n\right) = \log\left(\left|1+\frac{z}n\right|\right) + i\,\text{Arg}\left(1+\frac{z}n\right)$$
Now, let $z=a+bi$.
Then
$$\text{Arg}\left(1+\frac{z}n\right) = \arctan\left(\frac{\frac{b}n}{1+\frac{a}n}\right)=\arctan\left(\frac{b}{n+a}\right)$$
From real analysis we know that
$$\arctan(x) = \sum_{k \geq 0}\frac{(-1)^k}{2k+1}\,x^{2k+1}=x-\frac{x^3}3+\frac{x^5}5-\dots$$
Hence,
\begin{align}
n\cdot\arctan\left(\frac{b}{n+a}\right)
&= n\,\frac{b}{n+a} - \frac{n}3\,\left(\frac{b}{n+a}\right)^3 + \frac{n}5\,\left(\frac{b}{n+a}\right)^5 - \dots\\
&\stackrel{n\to\infty}{\longrightarrow}\,\,b,
\end{align}
which shows that $\Im(z)=\Im\left(\lim_{n\to\infty}n\,\text{Log}\left(1+\frac{z}n\right)\right)$.
For the real part, observe that
\begin{align}
\left|1+\frac{z}n\right|
&= \sqrt{{\left(1+\frac{a}n\right)}^2+{\left(\frac{b}n\right)}^2}\\
&= \sqrt{1+\left(\frac{2a}{n}+\frac{a^2+b^2}{n^2}\right)}
\end{align}
Hence, $\log\left(\left|1+\frac{z}n\right|\right) = \frac12\,\log\left(1+\left(\frac{2a}{n}+\frac{a^2+b^2}{n^2}\right)\right)$.
We know from real analysis that for $|x|<1$
$$\log(1+x) = \sum_{k\geq 1}\frac{(-1)^{k+1}}{k}\,x^k=x-\frac{x^2}2+\frac{x^3}3-\dots$$
Since $\frac{2a}{n}+\frac{a^2+b^2}{n^2} \to 0$ as $n\to\infty$, we have that for $n$ large enough:
\begin{align}n\cdot \log\left(\left|1+\frac{z}n\right|\right)
&=\frac{1}2\,\left[n\,{\left(\frac{2a}{n}+\frac{a^2+b^2}{n^2}\right)}
-\frac{n}2\,{\left(\frac{2a}{n}+\frac{a^2+b^2}{n^2}\right)}^2
+\frac{n}3\,\,{\left(\frac{2a}{n}+\frac{a^2+b^2}{n^2}\right)}^3
-\dots\right]\\
&\stackrel{n\to\infty}{\longrightarrow}\,\,\frac12\,[2a]=a.
\end{align}
This shows that $\Re(z)=\Re\left(\lim_{n\to\infty}n\,\text{Log}\left(1+\frac{z}n\right)\right)$
and completes the proof. $\square$
Comment: For $x>0$, it is true that $\text{Arg}(x+iy) = \arctan(y/x)$. For large $n$, we have that $\Re(1+\frac{z}n)>0$. It follows that for large $n$ we indeed have $\text{Arg}\left(1+\frac{z}n\right) = \arctan\big(\Im(z)/\Re(z)\big)$.
Comment: Why can you express $\text{Arg}$ in terms of $\arctan$ in that way, should there not be multiple cases to consider?
Comment: Well, how do you define $\text{Arg}$?
Comment: Principal Argument, which is between $(-\pi,\pi]$. If you write $\text{Arg}(x+iy) = \arctan(y/x)$, then the points $1+i$ and $-1-i$ have the same argument despite been in different quadrants.


How to change accent colour in Ubuntu 22 via terminal

Question: Ubuntu 22 added a new feature to Settings that allows the "accent colour" (orange by default) to be changed.
I'm wondering where this setting is stored and how I might be able to set it via the terminal.
Answer: This changes to a different Yaru icon theme and corresponding gtk theme by changing the settings org.gnome.desktop.interface icon-theme and org.gnome.desktop.interface gtk-theme.
With the command line, e.g.:
gsettings set org.gnome.desktop.interface gtk-theme 'Yaru-bark'
gsettings set org.gnome.desktop.interface icon-theme 'Yaru-bark'

The Yaru themes and icons are installed in /usr/share/themes and /usr/share/icons, and you can see the names by looking at the contents of these folders:
ls /usr/share/themes/ | grep Yaru

Comment: I don't understand the answer. He was asking about accent color, and you answered about icon theme.
Comment: @nonhocapito "This changes to a different Yaru icon theme and corresponding gtk theme" so the way to change accent color through the terminal is to change theme


Configure webpack to write to file and watch for changes

Question: I have this webpack configuration:
module.exports = {

  entry: ['babel-polyfill', './lib/index.js'],

  output: {
    path: path.resolve(__dirname + '/dist'),
    filename: 'suman.js'
  },

  module: {
    loaders: [
      {
        test: /\.js$/,
        loader: 'babel-loader',
        exclude: /node_modules/,
        options: {
          presets: ['latest'],
          plugins: ['transform-runtime']
        }
      },
      {
        test: /(\/lib\/init\/|cli.js$)/,
        loader: 'ignore-loader'
      }
    ]
  },

  resolve: {
    alias: {
      fs: require.resolve('suman-browser-polyfills/modules/fs'),
      // assert: require.resolve('suman-browser-polyfills/modules/assert'),
      process: require.resolve('suman-browser-polyfills/modules/process'),
    },
    extensions: ['.js']
  }
};

as you can see Webpack is configured to write to a file, denoted by the "output" property in the configuration.
However, when I use webpack-dev-server, it will create a build, but it won't write it to the "output" file, it seems to just serve it to the browser.
What I am looking to do is have Webpack do incremental builds, but write to the file upon changes.
Comment: So to make it clear -  when running `webpack` it will write to the suman.js file, but when running `webpack-dev-server`, it won't write to the file.
Comment: Possible duplicate of [Webpack: How to compile, write on disk and serve static content (js/css) using webpack-dev-server](https://stackoverflow.com/questions/41928358/webpack-how-to-compile-write-on-disk-and-serve-static-content-js-css-using-w)
Answer: I believe the answer is simply to use webpack --watch, there is no need for me to use webpack-dev-server for my use case.


Where is ConcurrentQueue TryDequeue implementation

Question: Where can I see the actual code that performs the heavy lifting on TryDequeue?  I tried F12 (Go To Definition) but just the method name and parameters.
lock (this)
{
    T overflow;
    while (q.Count > Limit && q.TryDequeue(out overflow)) ;
}

Comment: This is not how you are supposed to use `ConcurrentQueue`. Don't lock and don't check its count. Just dequeue and use the value if `TryDeque` returns `true`
Comment: If I don't check the count then in every iteration an item is added and then removed for a net zero items. I did remove the count but not no items build up.
Answer: You can view the reference source. Highly recommend not locking around a ConcurrentQueue, it defeats the purpose. A Queue will be much faster in that case.
Answer: ConcurrentQueue is a class of the .NET framework. As such, it is available on your system as a binary in the global assembly cache. That means it comes without source code. In the title of your tab you will see the remark [from metadata], which means it is auto-generated source.
You can check the reference source online, which is provided by Microsoft. You can also use a decompiler like ILSpy or reflector.


CAGradientLayer diagonal gradient

Question:
I use the following CAGradientLayer:
let layer = CAGradientLayer()
layer.colors = [
    UIColor.redColor().CGColor,
    UIColor.greenColor().CGColor,
    UIColor.blueColor().CGColor
]
layer.startPoint = CGPointMake(0, 1)
layer.endPoint = CGPointMake(1, 0)
layer.locations = [0.0, 0.6, 1.0]

But when I set bounds property for the layer, it just stretches a square gradient. I need a result like in Sketch 3 app image (see above).
How can I achieve this?
Comment: Share the frame size also
Comment: It doesn't matter actually, but 320x60 is a good example.
Answer: Update: Use context.drawLinearGradient() instead of CAGradientLayer in a manner similar to the following. It will draw gradients that are consistent with Sketch/Photoshop.
If you absolutely must use CAGradientLayer, then here is the math you'll need to use...

It took some time to figure out, but from careful observation, I found out that Apple's implementation of gradients in CAGradientLayer is pretty odd:

First it converts the view to a square.
Then it applies the gradient using start/end points.
The middle gradient will indeed form a 90 degree angle in this resolution.
Finally, it squishes the view down to the original size.

This means that the middle gradient will no longer form a 90 degree angle in the new size. This contradicts the behavior of virtually every other paint application: Sketch, Photoshop, etc.
If you want to implement start/end points as it works in Sketch, you'll need to translate the start/end points to account for the fact that Apple is going to squish the view.

Steps to perform (Diagrams)

Code
import UIKit

/// Last updated 4/3/17.
/// See https://stackoverflow.com/a/43176174 for more information.
public enum LinearGradientFixer {
  public static func fixPoints(start: CGPoint, end: CGPoint, bounds: CGSize) -> (CGPoint, CGPoint) {
    // Naming convention:
    // - a: point a
    // - ab: line segment from a to b
    // - abLine: line that passes through a and b
    // - lineAB: line that passes through A and B
    // - lineSegmentAB: line segment that passes from A to B

    if start.x == end.x || start.y == end.y {
      // Apple's implementation of horizontal and vertical gradients works just fine
      return (start, end)
    }

    // 1. Convert to absolute coordinates
    let startEnd = LineSegment(start, end)
    let ab = startEnd.multiplied(multipliers: (x: bounds.width, y: bounds.height))
    let a = ab.p1
    let b = ab.p2

    // 2. Calculate perpendicular bisector
    let cd = ab.perpendicularBisector

    // 3. Scale to square coordinates
    let multipliers = calculateMultipliers(bounds: bounds)
    let lineSegmentCD = cd.multiplied(multipliers: multipliers)

    // 4. Create scaled perpendicular bisector
    let lineSegmentEF = lineSegmentCD.perpendicularBisector

    // 5. Unscale back to rectangle
    let ef = lineSegmentEF.divided(divisors: multipliers)

    // 6. Extend line
    let efLine = ef.line

    // 7. Extend two lines from a and b parallel to cd
    let aParallelLine = Line(m: cd.slope, p: a)
    let bParallelLine = Line(m: cd.slope, p: b)

    // 8. Find the intersection of these lines
    let g = efLine.intersection(with: aParallelLine)
    let h = efLine.intersection(with: bParallelLine)

    if let g = g, let h = h {
      // 9. Convert to relative coordinates
      let gh = LineSegment(g, h)
      let result = gh.divided(divisors: (x: bounds.width, y: bounds.height))
      return (result.p1, result.p2)
    }
    return (start, end)
  }

  private static func unitTest() {
    let w = 320.0
    let h = 60.0
    let bounds = CGSize(width: w, height: h)
    let a = CGPoint(x: 138.5, y: 11.5)
    let b = CGPoint(x: 151.5, y: 53.5)
    let ab = LineSegment(a, b)
    let startEnd = ab.divided(divisors: (x: bounds.width, y: bounds.height))
    let start = startEnd.p1
    let end = startEnd.p2

    let points = fixPoints(start: start, end: end, bounds: bounds)

    let pointsSegment = LineSegment(points.0, points.1)
    let result = pointsSegment.multiplied(multipliers: (x: bounds.width, y: bounds.height))

    print(result.p1) // expected: (90.6119039567129, 26.3225059181603)
    print(result.p2) // expected: (199.388096043287, 38.6774940818397)
  }
}

private func calculateMultipliers(bounds: CGSize) -> (x: CGFloat, y: CGFloat) {
  if bounds.height <= bounds.width {
    return (x: 1, y: bounds.width/bounds.height)
  } else {
    return (x: bounds.height/bounds.width, y: 1)
  }
}

private struct LineSegment {
  let p1: CGPoint
  let p2: CGPoint

  init(_ p1: CGPoint, _ p2: CGPoint) {
    self.p1 = p1
    self.p2 = p2
  }

  init(p1: CGPoint, m: CGFloat, distance: CGFloat) {
    self.p1 = p1

    let line = Line(m: m, p: p1)
    let measuringPoint = line.point(x: p1.x + 1)
    let measuringDeltaH = LineSegment(p1, measuringPoint).distance

    let deltaX = distance/measuringDeltaH
    self.p2 = line.point(x: p1.x + deltaX)
  }

  var length: CGFloat {
    let dx = p2.x - p1.x
    let dy = p2.y - p1.y
    return sqrt(dx * dx + dy * dy)
  }
  var distance: CGFloat {
    return p1.x <= p2.x ? length : -length
  }
  var midpoint: CGPoint {
    return CGPoint(x: (p1.x + p2.x)/2, y: (p1.y + p2.y)/2)
  }
  var slope: CGFloat {
    return (p2.y-p1.y)/(p2.x-p1.x)
  }
  var perpendicularSlope: CGFloat {
    return -1/slope
  }
  var line: Line {
    return Line(p1, p2)
  }
  var perpendicularBisector: LineSegment {
    let p1 = LineSegment(p1: midpoint, m: perpendicularSlope, distance: -distance/2).p2
    let p2 = LineSegment(p1: midpoint, m: perpendicularSlope, distance: distance/2).p2
    return LineSegment(p1, p2)
  }

  func multiplied(multipliers: (x: CGFloat, y: CGFloat)) -> LineSegment {
    return LineSegment(
      CGPoint(x: p1.x * multipliers.x, y: p1.y * multipliers.y),
      CGPoint(x: p2.x * multipliers.x, y: p2.y * multipliers.y))
  }
  func divided(divisors: (x: CGFloat, y: CGFloat)) -> LineSegment {
    return multiplied(multipliers: (x: 1/divisors.x, y: 1/divisors.y))
  }
}

private struct Line {
  let m: CGFloat
  let b: CGFloat

  /// y = mx+b
  init(m: CGFloat, b: CGFloat) {
    self.m = m
    self.b = b
  }

  /// y-y1 = m(x-x1)
  init(m: CGFloat, p: CGPoint) {
    // y = m(x-x1) + y1
    // y = mx-mx1 + y1
    // y = mx + (y1 - mx1)
    // b = y1 - mx1
    self.m = m
    self.b = p.y - m*p.x
  }

  init(_ p1: CGPoint, _ p2: CGPoint) {
    self.init(m: LineSegment(p1, p2).slope, p: p1)
  }

  func y(x: CGFloat) -> CGFloat {
    return m*x + b
  }

  func point(x: CGFloat) -> CGPoint {
    return CGPoint(x: x, y: y(x: x))
  }

  func intersection(with line: Line) -> CGPoint? {
    // Line 1: y = mx + b
    // Line 2: y = nx + c
    // mx+b = nx+c
    // mx-nx = c-b
    // x(m-n) = c-b
    // x = (c-b)/(m-n)
    let n = line.m
    let c = line.b
    if m-n == 0 {
      // lines are parallel
      return nil
    }
    let x = (c-b)/(m-n)
    return point(x: x)
  }
}

Proof it works regardless of rectangle size
I tried this with a view size=320x60, gradient=[red@0,firstname.lastname@example.com,blue@1], startPoint = (0,1), and endPoint = (1,0).
Sketch 3:

Actual generated iOS screenshot using the code above:

Note that the angle of the green line looks 100% accurate. The difference lies in how the red and blue are blended. I can't tell if that's because I'm calculating the start/end points incorrectly, or if it's just a difference in how Apple blends gradients vs. how Sketch blends gradients.
Comment: Very nice answer, but I think your thoughts about "conversion to square" are not exact. Since `startPoint` and `endPoint` are in unit coordinates (from 0 to 1), I think they also _interpolate_ them in unit coordinates when drawing the gradient. This creates the effect of stretched or resized bitmap, but I'm pretty sure no intermediate steps are taken to achieve this result.
Answer: Here's the math to fix the endPoint
let width = bounds.width
let height = bounds.height
let dx = endPoint.x - startPoint.x
let dy = endPoint.y - startPoint.y
if width == 0 || height == 0 || width == height || dx == 0 || dy == 0 {
  return
}
let ux = dx * width / height
let uy = dy * height / width
let coef = (dx * ux + dy * uy) / (ux * ux + uy * uy)
endPoint = CGPoint(x: startPoint.x + coef * ux, y: startPoint.y + coef * uy)

Answer: Full code of layoutSubviews method is
override func layoutSubviews() {
    super.layoutSubviews()

    let gradientOffset = self.bounds.height / self.bounds.width / 2

    self.gradientLayer.startPoint = CGPointMake(0, 0.5 + gradientOffset)
    self.gradientLayer.endPoint = CGPointMake(1, 0.5 - gradientOffset)
    self.gradientLayer.frame = self.bounds
}

Comment: The actual formula that works with any rectangle size seems to require a lot more math than that. Check out [this answer](http://stackoverflow.com/a/43176174/35690) for my solution.
Comment: That's closer, but still far off from what Sketch gives you.

CAGradientLayer diagonal gradient


How to add Backgroung Image to Tablelayout in Android?

Question: I have TableLayout in my project which contains 6 TableRow layouts. Each TableRow layout has 7 TextViews in it. I want to set a background image to this TableLayout which is currently displaying 42 TextViews. I also had set some background color to each TextView. I tried this
mDateSelectionBar.setBackgroundResource(resid);

But it is not showing up my Image. However, If I do this for my 42 TextViews..
TextView.setBackgroundResource(0);

Then my Image is visible. But I want to display TableLayout background Image as well as background color of each TextView. How can I do this? Please Help! Thanks :D
Answer: The issue is that the background of the individual cells in a table layout is drawn over the overall layout background. If you remove the background of the cell, then the overall background is visible. If you need to display the background of the table as well as some colouring of the cells, consider setting the alpha channel of the cell background colour to less than 100%, e.g. 0.8 or something.
When you set the colour for your cells, use #ARGB syntax, e.g.
setBackgroundColour(Color.argb(192, 255, 0, 0));


R Squared missing from output of coxph

Question: I'm new to R and am doing an online course. I'm running a cox model, but not getting an r squared value in the output. Anyone know why?
<code>cox2 <- coxph(Surv(fu_time,death) ~ age_cat)
> summary(cox2)
Call:
coxph(formula = Surv(fu_time, death) ~ age_cat)

  n= 1000, number of events= 492

                   coef exp(coef) se(coef)      z Pr(>|z|)
age_catUnder 65 -1.4264    0.2402   0.2402 -5.938 2.88e-09 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

                exp(coef) exp(-coef) lower .95 upper .95
age_catUnder 65    0.2402      4.164      0.15    0.3846

Concordance= 0.549  (se = 0.007 )
Likelihood ratio test= 56.34  on 1 df,   p=6e-14
Wald test            = 35.26  on 1 df,   p=3e-09
Score (logrank) test = 41.66  on 1 df,   p=1e-10
</code>
Answer: R packages are "live", they change with time. Form version 2.44 of the package "survival", summary.coxph does not report R2 anymore.
You can read the reason for this in the "Changes in version 2.44":

The Nagelkirke R^2 has been removed from summary.coxph. The
  shortcomings of this measure are well known, concordance is a better
  measure.

R Squared missing from output of coxph


Minecraft LAN world fails to load Player 2 without freezing him

Question: I was in a 1.13.2 LAN world with my friend, and while joking around, I teleported him to something on the order of [~, 2e24, ~] and It froze him and kicked him from the world. He kept trying to rejoin but it didn't work. I tried using command blocks to change his spawn, but nothing worked.
I've seen posts on here that explain how to fix this issue: (I teleported too far away and now the game crashes on world load)
But the solution involved MCedit, which wasn't working for me (I presume because of MC being in 1.13.2)
The other posts' solution mentioned going into the saves folder and deleting player data, but In my saves folder, the player data is unassigned to each player, ad I don't want to accidentally delete the wrong one, making the world un-joinable for all players.I do think /tp is slightly OP, and I also think it should have limits based on proximity.
Any consideration would be much appreciated!
Comment: You can look at the "date modified" for the player data. Player 2 logs out, wait 5 minutes, and then you should be able to identify which file belongs to which player.
Comment: This is weird. Teleporting to 2e24 should just fail with an error message. Or teleport you to 3e7, the maximum.
Answer: You can download Mcedit and move the player with the tool, this tool can be usefull for creating world or moving entity like player.
don't tp you friend to far, there is a limit in the minecraft world, behond this "wall" his game may do wierd stuff like crash or being unable to play.
there is a trick if you want, prepare the tp commande and as soon he connect tp him. If it don't work try with Mcedit.


Ruby - Why use a Block as a parameter?

Question: I'm having trouble understanding Blocks vs Procs in ruby. I get the basic idea that a proc is a method saved as an object that you can call repeatedly without having to continue writing the same lines of code over and over.
My trouble lies with accepting blocks as parameters in methods.
The homework problem is super simple.
Write a method that accepts a block as a parameter and reverses all the words in a string.
Below is the answer they're looking for.
def reverser(&prc)
  sentence = prc.call
  words = sentence.split(" ")
  words.map { |word| word.reverse }.join(" ")
end

I have two questions -
1 How do you call this method because if I put
print reverser("Hello")

I get an error "wrong number of arguments (given 1, expected 0)"
Second, why not just write the following method? What's the benefit of writing a method that takes a block?
def reverser(string)
  string.split.map{|x| x.reverse}.join(" ")
end

Comment: "The homework problem is super simple." – The homework problem is super stupid, in that it in no way demonstrates the usefulness of blocks.
Comment: "How do you call this method": `reverser { "Hello" }`
Comment: @JörgWMittag do you have a good example that would be useful? Any help would be appreciated as the past 6 months I've been completely teaching myself.
Comment: Well, you actually already used a block in your implementation of `reverser`, and the `Enumerable` methods (most of which take a block) are all good examples.
Answer:
You'd call it like this:
print reverser { "Hello" }

Or if your block is several lines long then like this:
print reverser do
  "Hello"
end

Blocks are close to what anonymous functions are in other languages.

Map is a good example.
What map does is it takes an array and maps (transforms) every element according to whatever rules you need.
These mapping rules must be a code. That means, it can't be a string or number or something, it has to be a function. Block is used here as function which you can write using minimal code.
So in your example you have this:
words.map { |word| word.reverse }.join(" ")

If you couldn't pass block to map then you'd have to define that function and pass it somewhere - and name that function. That is just not efficient.
Lets change this block to work so that it reverses word only if it starts with capital letter.
words.map do |word|
  if word[0] =~ /[A-Z]/
    word.reverse
  else
    word
end.join(" ")

Without blocks you'd need to define that function, which you do not need in any other places and call that. That's just not efficient.
This is what it would look like
def reverse_if_starts_with_capital_letter(word)
  if word[0] =~ /[A-Z]/
    word.reverse
  else
    word
  end
end

# not sure if this syntax would work, just demonstrates idea
words.map(&reverse_if_starts_with_capital_letter)

Comment: This just blew my mind. I've been stuck for two days trying to grasp what was going on, this made me understand the concept a lot better.

Ruby - Why use a Block as a parameter?


What C is PS using to Determine Process Info Programmatically

Question: In both linux and macos we can get PID info, start time by using bash: ps -p PID_HERE -o lstart=.
I was going to use lstat and plan on it. But just out of curiosity:
Programatically ps has to be using C right? And in my use using the C functions is much faster, as I don't have to use popen to open and read.
In MacOSX/Darwin apparently they use something called proc_pidinfo and a topic on SO tells us how to do it here: Determine Process Info Programmatically in Darwin/OSX
But what about in Linux? I couldn't find a such thing as proc_pidinfo for us.
Thanks!
Answer: According to multiple answers on stackoverflow, ps uses the proc file system through libproc to gather process information. It appears that this is the preferred way to do it, so I would think lstat(2) is the right way™ to find out the start time of a process.
Comment: Perfect thank you so much! Just wanted to make sure :)