Compare String in flex

Question: I want to check whether string is empty or not
when i create object=Shared.getLocal("abc");
it assigns undefinded to the object at the first time
 if(object.data.name=="undefnied") {
         // is this correct
 }

Answer: undefined is a value, not a string to compare to. You want:
if (object.data.name == undefined) {
    //This property on your SharedObject was/is not defined.
}

Note that setting a property on a SharedObject to null does not delete it, it must be deleted with "delete".
Answer: Use the hasOwnProperty function to test if the variable exists. For example:

    if ( object.data.hasOwnProperty("name") ){
        // Ok. object.data.name exists...
        var value_of_name : String = String(object.data["name"]);

        // Check for non-null, non-empty
        if ( value_of_name ){
             // Ok. It is a non-null, non-empty string
             // ...
        }
     }
Answer: I am not sure with flex, but it should be undefined or null without quotes, I think.
Answer: To answer your exact question (if is empty), I'd do this:
var name : String = object.data.name;
if(name != null && name.length > 0) {
    //also, a common actionScript technique is to say if(name && name.length...)
    //same difference.
}

Compare String in flex


MVC 3 Wizard via JavaScript unsafe?

Question: I stepped over the following tutorial:
http://afana.me/post/create-wizard-in-aspnet-mvc-3.aspx
Since it looks pretty nice, I'm asking myself if making the complete wizard in JavaScript just like that is a good/safe idea?
Answer: I don't see anything wrong in that as long as you are using POST HTTP methods for save/delete data operations. But i would always make the app to work in a non-javascript version and once it is done, add the javascript fancy version like the ajaxified wizard.
Comment: I would have prefered the non-javascript way but since I'm having trouble with it I gave it up for now and thought this example is pretty good explained which would be perfect, I just had some doubts about security stuff. Thanks for your answer, I guess it's just fine then. :)

MVC 3 Wizard via JavaScript unsafe?


How to deal with League of Legends sound volume

Question: Everytime there is an update, Windows resets the volume level (in game and for the client).
Is there a way to fix it ?
Comment: I don't encounter this problem, so I can't give you the solution but I think there is one...
Answer: One way i am aware you can do this is by using LSI(League Summoner Information) which was one of the reasons i started using it actually, you can control at which volume LoL stays even after updates.
There might be other ways, but this is the one i use.
Answer: In your config folder there is a file called persistedsettings.json that is getting recreated on launch. This is a new addition to their file system and I think the settings are in here.
Try moving this file out of the directory and replacing it with a config.ini file, which is used to load in game settings. I haven't had this problem since doing this.


MySQL/PHP Only Returning One Result

Question: I have seen a few topics like this so i would like to say sorry first but none of the solutions given in those topics fixed my issue.
I am trying to make a dynamic navigation menu using php and mysql, i have multiple inputs in the database as dummy text but for some reason it only wants to show one result..
Here is my code:
<?php
require_once("../includes/connect.php");
include("../includes/header.php");
include("../includes/functions.php");
?>

                        <?php
                            $result = mysql_query("SELECT * FROM information LIMIT 10", $connection);

                            while ($row = mysql_fetch_assoc($result)){
                                echo "
{$row["menu"]}
";
                            $result = mysql_query("SELECT * FROM pages WHERE information_id ={$row["id"]} LIMIT 10", $connection);
                                echo "
";
                            while ($row = mysql_fetch_assoc($result)){
                                echo "
{$row["menu"]}
";
                            }
                                echo "
";
                            }
                        ?>

Main Content

    <?php
    include("../includes/footer.php");
    ?>

Dont hate because there are tables in here lol, its not for public use and i will be converting it to grids when i get it all set up and functioning. I am not a 'pro' php programmer so be nice!
Comment: you might want to name your fetch/result/row variables differently for the while loop iteration.
Comment: Oh my, i am so dumb. I worked out the issue, i used the variable $result for both queries. I changed the second $result to $res and its working fine now... sorry! thanks!
Answer: I guess the problem is here..
your are pushing datas to the same variables twice....
make first query and push to $result. again make another query and push datas to same var $result.
try pushing it to seperate variable
 $result1 = mysql_query("SELECT * FROM pages WHERE information_id ={$row['id']} LIMIT 10", $connection);
                            echo "
";
                        while ($row1 = mysql_fetch_assoc($result)){
                            echo "
{$row1["menu"]}
";
                        }

Comment: Haha yeah, i just saw that! Thanks! Why does it seem weird?
Comment: weird as in like i think you can use join instead of two loops.. anyways since i have no idea how your table structure is so i assume your are doing it right... removed the weird part..:).. anyways glad it helped.. happy coding... CHEERS!!! :)
Comment: Haha oh right ok lol. Well like i said, im not a pro and im working on improvements :) - Im sure i will end up recoding it to what you just stated in the near future when i boost my skills up :D

MySQL/PHP Only Returning One Result


How do i make use of groupingby in java

Question: I have a movie list from a web service that i need to group using genres attribute from the data. My question is very similar to this groupby ngFor angular2 but in java instead.
movie list from the web service looks like this
[
    {
        "title": "AAAAAAAA",
        "genres": [
          "Comedy"
        ]
    },
    {
        "title": "BBBBBBBBBBBB",
        "genres": [
          "Action", "Adventure"
        ]
    },
    {
        "title": "CCCCCCCCCCCCC",
        "genres": [
          "Action"
        ]
    },
    {
        "title": "DDDDDDDDDDDD",
        "genres": [
          "Comedy", "Adventure"
        ]
    },
    {
        "title": "EEEEEEEEEEEEEEEEEEE",
        "genres": [
          "Horror"
        ]
    }
]

here is what i'm trying to achieve but i cant seems to get it right
[
    {
        "Action": [
            {
                "title": "BBBBBBBBBBBB",
                "genres": [
                  "Action", "Adventure"
                ]
            },
            {
                "title": "CCCCCCCCCCCCC",
                "genres": [
                  "Action"
                ]
            }
        ],
        "Adventure": [
            {
                "title": "BBBBBBBBBBBB",
                "genres": [
                  "Action", "Adventure"
                ]
            },
            {
                "title": "DDDDDDDDDDDD",
                "genres": [
                  "Comedy", "Adventure"
                ]
            }
        ],
        "Comedy": [
            {
                "title": "AAAAAAAA",
                "genres": [
                  "Comedy"
                ]
            },
            {
                "title": "DDDDDDDDDDDD",
                "genres": [
                  "Comedy", "Adventure"
                ]
            }
        ],
        "Horror": [
            {
                "title": "EEEEEEEEEEEEEEEEEEE",
                "genres": [
                  "Horror"
                ]
            }
        ]
    }
]

i've tried replicating the javascript solution from the answer in
groupby ngFor angular2 but I'm stucked
    ItemArray.stream().reduce((identity, accumulator) -> {
        accumulator.getGenres().forEach((k) -> {});
        return identity;
    });

Comment: Try doing it with a standard for-loop first. Whenever I'm struggling with how to construct a stream, having the imperative version helps a lot
Answer: I think it would be easier not to use streams:
Map<String, List<Item>> itemsByGenre = new HashMap<>();
for (Item item : items) {
  for (String genre : item.genres()) {
    itemsByGenre.computeIfAbsent(genre, g -> new ArrayList<>()).add(item);
  }
}

The key point here is that you need to explode by genre, because each item can be in multiple genres. So, you could do something like this:
Map<String, List<Item>> itemsByGentre = items.stream()
    // Make a stream of map entries where the key is the genre, and the value is the item.
    .flatMap(i -> i.genres().stream().map(g -> new AbstractMap.SimpleEntry<>(g, i))
    .collect(
        // Now, group by key (genre)...
        Collectors.groupingBy(
            Map.Entry::getKey,
            // and map the entry to just the value (the item),
            // and collect the items into a list.
            Collectors.mapping(Map.Entry::getValue, Collectors.toList())));

How do i make use of groupingby in java


Should I use conduit for a less than 10' run of 6/3 THHN in my garage

Question: My electrical panel is in a cabinet attached to my garage but accessible from the outside so the utility has access. I'm installing a 14-50R receptacle using 6/3 THHN in my garage and it will be directly adjacent to my service panel but on the other side of the cabinet wall so it's in the garage for EV charging. We're talking less than 10' run, probably closer to 4 or 5 feet. I believe code states that conduit isn't required since the cable is protected by the wall of the utility cabinet but considering the cabinet has a dirt floor and is accessible outside I suppose rodents could be an issue? Do I need to worry about rodents chewing wire here? I've never seen evidence of them there, nor could I imagine why they'd want to be in that cabinet, but maybe it's better to be safe than sorry? Or is the additional heat that the conduit would create more of an issue?
Comment: Are you using individual conductors, or a cable?  A 10' length of schedule 80 PVC conduit is about $4.00, so I'm confused as to why you seem to want to avoid using conduit.
Comment: Keep in mind that *code*, is a **minimum** safety standard. There's almost never a problem building above minimum standards.
Comment: I've got a cable, if I went with conduit I'm told I should remove the outer jacket and just pull the conductors through... Just wondering if it's worth the extra effort or if code somehow necessitates it and I'm missing something. Not really a cost thing guess I'm just curious what's considered best practice in this scenario
Comment: Is this cabinet only used to house electrical equipment?
Comment: No, the cabinet is a combination utility closet it's got the phone and cable drops and the gas main in there also. The sense I'm getting here is that for such a small run I should just put it in conduit and be done with it right? Any reason not to?
Comment: It sounds to me like the cabinet is not used for storage, or livable space.  So I'd say any cable in there is already protected from physical damage. Since it's a cable, and it's in a "protected" area, I wouldn't think conduit would be necessary.
Comment: Correct. No storage and I certainly wouldn't want to live in there. ;)
Comment: Use 1" EMT (room for 7 #6 wires, so spacious for 3-4) and it will probably cool BETTER than NM cable...
Answer: If you have evidence of rodent damage to other wires in that location then maybe it's worth doing something more. But otherwise if using conduit is the more difficult method, I don't think I'd bother. If your garage is open framing and you can run from point A to point B in an approved NM fashion, that's the way to go. Nail a plastic 2 gang box to a 2 by and run the #6-3 NM. BTW I think #8-3 NM would've been OK for that circuit.
Comment: Given it's a short run, and any potential (which has been described) of rodents, I'd choose conduit, as cheap fire insurance. Rodents can and do chew on wires, and they can and do burn buildings down as a result. I'm a bit amazed at whatever code @Pooch is living under having the electric and gas main in the same closet, rather than separated by at least 10 feet as most places do, but codes do vary wildly, and places where the gas and electric company are the same company often have less caution than other places.
Comment: I thought it a bit strange myself, but to supposedly mitigate putting the gas and electric together a shelf with Sheetrock exists between the gas main closer to the ground and the electrical panel about 4 feet up. By no means are the compartments air tight so any leaking gas could still certainly find its way up, but I suppose it's better than nothing.


Generate time sequence with step 7 seconds

Question: How would you generate the following sequence of strings in Python?
00:00:00
00:00:07
00:00:14
00:00:21
...
00:00:49
00:00:56
00:01:03

The step is 7 seconds. The end is about 03:30:+/-
I would come with solution that uses modular arithmetic (first 1200 to have hours, than 60 to have minutes and the remainder are seconds and the numbers should be converted to strings and "one-place" strings should be prefixed by "0").
Is there some smarter (pythonic) solution with using some helper generators in standard library or list comprehension?
Comment: Have a look at [this SO question](http://stackoverflow.com/questions/100210/python-easy-way-to-add-n-seconds-to-a-datetime-time)
Comment: Possible duplicate of [Python generate dates series](https://stackoverflow.com/questions/4479800/python-generate-dates-series)
Answer: def yield_times():
    from datetime import date, time, datetime, timedelta
    start = datetime.combine(date.today(), time(0, 0))
    yield start.strftime("%H:%M:%S")
    while True:
        start += timedelta(seconds=7)
        yield start.strftime("%H:%M:%S")

>>> gen = yield_times()
>>> for ii in range(5):
...     print gen.next()
...
00:00:00
00:00:07
00:00:14
00:00:21
00:00:28

Answer: Try this one
from datetime import datetime, timedelta

now = datetime(2000, 1, 1, 0, 0, 0)
last = datetime(2000, 1, 1, 3, 30, 0)
delta = timedelta(seconds=7)

times = []
while now < last:
    times.append(now.strftime('%H:%M:%S'))
    now += delta

Answer: I think you're over complicating things by looking at generators and list comprehension. The Python datetime module will do this easily.
from datetime import datetime, timedelta

t = datetime(2012, 1, 1, 0, 0, 0)

while t < datetime(2012, 1, 1, 3, 30, 0):
    print t.time()

    t = t + timedelta(seconds=7)

Answer: This generates times for every 5 minutes between 9:00AM and 2.00PM==14:00.
In [1]: from datetime import datetime

In [2]: [str(datetime(2012, 1, 1, hr, min, 0).time()) for hr in range(9,14) for min in range(0,60,5)]
Out[2]:
['09:00:00',
 '09:05:00',
 '09:10:00',
 '09:15:00',
 '09:20:00',
 '09:25:00',
 '09:30:00',
 '09:35:00',
 '09:40:00',
 '09:45:00',
 '09:50:00',
 '09:55:00',
 '10:00:00',
 '10:05:00',
 '10:10:00',
 '10:15:00',
 '10:20:00',
 '10:25:00',
 '10:30:00',
 '10:35:00',
 '10:40:00',
 '10:45:00',
 '10:50:00',
 '10:55:00',
 '11:00:00',
 '11:05:00',
 '11:10:00',
 '11:15:00',
 '11:20:00',
 '11:25:00',
 '11:30:00',
 '11:35:00',
 '11:40:00',
 '11:45:00',
 '11:50:00',
 '11:55:00',
 '12:00:00',
 '12:05:00',
 '12:10:00',
 '12:15:00',
 '12:20:00',
 '12:25:00',
 '12:30:00',
 '12:35:00',
 '12:40:00',
 '12:45:00',
 '12:50:00',
 '12:55:00',
 '13:00:00',
 '13:05:00',
 '13:10:00',
 '13:15:00',
 '13:20:00',
 '13:25:00',
 '13:30:00',
 '13:35:00',
 '13:40:00',
 '13:45:00',
 '13:50:00',
 '13:55:00']

In [3]:


Node.JS - Watching AND getting changes made to a file

Question: How can I watch and get changes made to a file in Node.JS? I've heard that fs.watch and fs.watchFile are pretty buggy and that they should be avoided, but libraries such as node-watch and chokidar don't output the oldFile/newFile (If I'm mistaken, please let me know). So what's a way to watch and output the changes of a file?
Answer: You will have to manage oldFile yourself.
Store the file data somewhere initially. When the file changes, compare it's data with the stored old data and use the diff for your application. The overwrite your stored data with the new file data and wait for the next change.
If the file is small or changes often, you can store the file data in a variable. Otherwise it might be more memory efficient to copy the file on the file system each time.
Comment: Yes, that shouldn't be a problem.
Comment: would this also be efficient if I stored it in a database? the file should be no more that 10,000 characters and changes fairly rarely.


DefaultAppPool suffered a fatal communication error with WWW Publishing service

Question: Recently changes were made on the .net version on the server, post which all IIS applications are failing with the following exception.
A process serving the DefaultAppPool suffered a fatal communication error with the WWW publishing service.
Data field error no : 8007006d
Using Debug Diag tool i have generated the dump file and the analysis is as below.

In w3wp__DefaultAppPool__PID__3932__Date__08_06_2019__Time_01_42_15PM__731__Second_Chance_Exception_C0000005.dmp
  the assembly instruction at aspnet_isapi!AttachHandleToThreadPool+10
  in \?\C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\aspnet_isapi.dll
  from Microsoft Corporation has caused an access violation exception
  (0xC0000005) when trying to read from memory location 0x00000000 on
  thread 9

Thread 9 - System ID 1480
Entry point   w3tp+1d70
Create time   06/08/2019 13:41:53
Time spent in user mode   0 Days 0:0:0.0
Time spent in kernel mode   0 Days 0:0:0.0
Full Call Stack
Function     Arg 1     Arg 2     Arg 3     Arg 4   Source
aspnet_isapi!AttachHandleToThreadPool+10     01b61e90     01b621fa     00000238     77e63d9a
aspnet_isapi!CloseVersionedPerfData+1714     00000000     79e79ff5     00000000     79e7660d
aspnet_isapi!CloseVersionedPerfData+1607     0000021c     01211fec     00000000     0109556c
w3isapi!ProcessIsapiRequest+532     000c5030     0108fe20     0000021c     01211fec
w3isapi!ProcessIsapiRequest+39     01095af8     0109556c     0108fe50     01095518
w3core+690f     00000000     00000000     010948c8     01095480
w3core+67f0     0108fee8     010948c8     00000000     00000001
w3core+6774     010948c8     00000000     0108fec4     5a3966be
w3core+6704     010948d0     010948c8     00000001     010948c8
w3core+66be     00000001     0108fee8     002aaff8     010948c8
w3core+6658     00000000     00000000     00000000     01093e00
w3core+2274     00000000     00000000     00000000     00000001
w3core+65fa     01093e00     01093e00     5a361680     002a4710
w3dt!UlAtqAllocateMemory+16f     00000470     00000000     01093e04     0108ff8c
w3dt!UlAtqAllocateMemory+19a     00000000     00000470     01093e04     002a4718
w3tp!THREAD_POOL::PostCompletion+c9     00000000     002a8ab0     5a300000     0108ffb8
w3tp!THREAD_POOL::~THREAD_POOL+153     002a4710     00000000     00000000     002a8ab0
w3tp+1da9     002a8ab0     00000000     00000000     002a8ab0
kernel32!GetModuleHandleA+df     5a301d70     002a8ab0     00000000     000000c8

Exception Information
ASPNET_ISAPI!ATTACHHANDLETOTHREADPOOL+10WARNING - DebugDiag was not able to locate debug symbols for aspnet_isapi.dll, so the information below may be incomplete.

In w3wp__DefaultAppPool__PID__3932__Date__08_06_2019__Time_01_42_15PM__731__Second_Chance_Exception_C0000005.dmp
  the assembly instruction at aspnet_isapi!AttachHandleToThreadPool+10
  in \?\C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\aspnet_isapi.dll
  from Microsoft Corporation has caused an access violation exception
  (0xC0000005) when trying to read from memory location 0x00000000 on
  thread 9

Module Information  Image Name: \?\C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\aspnet_isapi.dll
  Symbol Type:  Export  Base address: 0x00905a4d                             Time Stamp:
  Thu Feb 19 20:10:03 2015   Checksum: 0x00000000                                   Comments:
  Microsoft .NET Framework build environement is Retail. SafeSync
  counter=0  COM DLL: False Company Name:  Microsoft Corporation
  ISAPIExtension: True                                   File Description:  aspnet_isapi.lib
  ISAPIFilter: False                                    File Version:  1.1.4322.2515  Managed
  DLL: False                                    Internal Name:  aspnet_isapi.lib  VB DLL: False
                                   Loaded Image Name:  aspnet_isapi.dll                             Mapped Image Name:                                     Original filename:  aspnet_isapi.lib  Module name:
  aspnet_isapi                              Private Build:    Single Threaded:  False
                            Product Name:  Microsoft (R) .NET Framework  Module Size:  264.00 KBytes                             Product Version:  1.1.4322.2515  Symbol File Name:  aspnet_isapi.dll                          Special Build:  &
Comment: I don't have a certain answer, but have you tried re-registering the dot net version with iis via: 'ASPNET_REGIIS'? In the past, re-running this has resolved some random issues for me.
Comment: Which version of IIS?
Comment: IIS 6.0, yes I have registered the dot net version using aspnet_regiis -i command.
Comment: Eek. Sort of clutching, here, but could try creating a new, empty dot net application / site in IIS. Maybe nothing but a web.config and an aspx file and see if it will run. It looks at first glance like a fundamental IIS issue, and not something with your application versus the version of dot net, but would be good to eliminate that. If that's the case, then even an empty dot net site should fail..
Answer: To fix errors related to.DLL file you need to download aspnet_isapi.dll and copy it to the installation folder of the application, or copy it into the Windows system folder and it should fix the error.
You could also follow the below steps to Reset ASP.NET settings:
1) register dll file by running below command(run command prompt as administrator)
regsvr32 "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\aspnet_isapi.dll"

2)Run the following command line to view the NS Web applications associated with .NET 1.1.4322:
 C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\aspnet_regiis.exe -lk

3)Run the following command line to remove all associations to .NET 1.1.4322:
 C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\aspnet_regiis.exe -k W3SVC/

4)Run the following command line to add the NS Web applications back to .NET 1.1.4322:
 C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\aspnet_regiis.exe -i

5)reset the iis:
 iisreset

after doing these things check the below things:
open iis manager. select the default site and right-click and select Properties. Click on the ASP.NET tab and, in the "ASP.NET version," select the 1.1.4322 version from the drop list. Click OK.
In the IIS Manager, go to Web Server Extensions and make sure that at least ASP.NET v1.1.4322 is allowed. If allowed, then it should not be a problem.
Comment: Hi Jalpa, I have followed all the steps starting from 1, but still the same exception appears when the application is accessed. As soon as a web request hits, the same error is occurring. Does this have to do with identity service accounts used on the machine? maybe access related issue?
Comment: which permission assigned to C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\aspnet_regiis.exe file?you could try to check the event viewer for more deail.
Comment: do you have any other. net version installed on your machine?
Comment: No, this is the only .net version installed v1.1.4322. From the event viewer we are getting "A process serving the DefaultAppPool suffered a fatal communication error with the WWW publishing service." Data field error no : 8007006d


How do i check, if two Circles are intersecting in Processing?

Question: So I'm currently learning Java, and i struggle a lot to get my Code working.
I made a "Fun" Code in which some circles are popping up and it calculates how many of them are on the Upper Side of the Screen. (I know, some silly code.)
I'm coding it in the "Processing" Environment, Language is Java.
Here's my main File:
Circle[] circles = new Circle[50];

int index = 0;
boolean finished = false;

void setup() {
  size(900, 900);
  background(0);

  for(int i = 0; i < circles.length; i++) {
    circles[i] = new Circle();
  }

  if(finished = true) {
  }
}

void draw() {
  if(index < circles.length) {
    circles[index].show(circles);
    index++;
  } else {
    finished = true;
  }
}

void count(Circle[] arr) {
  int n = 0;
  for(Circle c : arr) {
    if(c.getY() > height / 2) {
      n++;
    }
  }
  println(n);
}

And here's the "Problem" Circle class:
class Circle {
  private int x, y;
  private float r = random(10, 25);

  Circle() {
    this.x = Math.round(random(0 + r, width - r));
    this.y = Math.round(random(0 + r, height - r));
  }

  public int getX() {
    return this.x;
  }

  public int getY() {
    return this.y;
  }

  public void show(Circle[] arr) {
    if(isColliding(arr)) {
      this.x = Math.round(random(0 + r, width - r));
      this.y = Math.round(random(0 + r, height - r));
    } else {
      ellipse(this.x, this.y, r * 2, r * 2);
      stroke(255);
      fill(255);
    }
  }

  public boolean isColliding(Circle[] arr) {
    boolean result = false;
    if(arr == null) {
      result = false;
    } else {
      for(Circle c : arr) {
      float d = dist(c.getX(), c.getY(), this.x, this.y);
        if(d < r * 2) {
          result = true;
          println("Collision at: " + c.getX() + " " + c.getY());
          break;
        }
      }
    }
    return result;
  }
}

As you can see, i already have a isColliding Method, and the Outputs in the Console seem to be right, however it won't work in the show() Method, the Circles won't stop intersecting each other.
So how can i make it work, that the Position is re-calculated when it is colliding?
Comment: Your code has some uninitialized variables like width and heigh and methods like random that are missing from your example.
Comment: Oh, I'm sorry. Maybe i should add that it's in Java. The random Method is already implemented and variables like height and width are in the Processing Environment implemented as i put a size in the box. For a better saying, the code works just fine, but the isColliding Method,
Answer: Are you sure your collision method works? Unless I'm missing something, it should ALWAYS return true as you're passing in an array that includes itself.
That aside, I'd start looking at how your show() logic is laid out. You are checking for overlap, and then assigning a new random position if it finds any. This new position could very likely be on a circle that has already been drawn and in a good position.
Put your re-positioning in a loop so that it checks to make sure that it didn't just place itself onto an existing circle.
public void show(Circle[] arr)
{
    /*
      You could potentially get into a situation where you will NEVER find an empty spot.
      Add an escape method for the loop.
    */
    int failLimit = 500;
    while(failLimit-- > 0 && isColliding(arr))
    {
        this.x = Math.round(random(0 + r, width - r));
        this.y = Math.round(random(0 + r, height - r));
    }
    ellipse(this.x, this.y, r * 2, r * 2);
    stroke(255);
    fill(255);
}

You could simplify this and make it a bit more efficient by spawning in circles one at a time, checking to make sure their positions are good then.
Comment: Well, that's actually it. I didn't think of the fact the the Array already includes the new Circle, which would explain why it doesn't draw show anything if i used a while Loop. Thank's a lot! I'm going to put an extra ArrayList in my Code and add every Circle after the show() Method.!!


Detecting Words mistakes in String Input

Question: I am trying to make a code that can detect mistakes in the user input with respect to String array stored in program.
Lets say Program contains "The quick brown fox jumps over the lazy dog"
if the user enters "The quick brown is name over Jumps the lazy"
The program tells the user that you have made 5 Mistakes. But my code is not working correctly for the above mentioned user input. What is my code lacking to detect such mistakes. Here is the code:
public void checkTextCompleted()
{
    String input= text.getText();
    int temp=array[0],mistakes=0;

    if(input.length()==data.length()) {
        text.setEditable(false);
        text.setFocusable(false);

        for(int j=0;j<dataWords;j++) {
            int x = input.indexOf(data.substring(array[j]-temp, array[j]-1));

            System.out.println(x);
            if(x != -1) {
                String subs = input.substring(x, input.length());

                if(data.contains(subs)) {
                    break;
                } else {
                    mistakes++;
                    if(j!=0)
                        temp=array[j-1];
                    else
                        temp=array[j];
                }
            }
            else
                mistakes++;
        }
        JOptionPane.showMessageDialog(null,"You have made "+mistakes+" mistakes" , "Typing Test Completed", JOptionPane.OK_OPTION);
    }
}

The array[] contains the positions at which the space is detected in Program builtin String(data) and dataWords contains the number of words in program builtin String(data). User input is stored in "input"
What is my code lacking to detect the above mentioned problem?
Note:
if one word is wrong and the remaining string after it is correct, mistake will be 1 other wise, next mistake will be detected on the same principal.

Regards
Comment: When is something 1 mistake? What are your requirements? E.g. 'a b' instead of ' ba', is this 1 or 2 mistakes? 'abc' instead of 'cba'; 1 or 3 mistakes?
Comment: What are you actually trying to ask ?
Comment: 1 mistake occurs when the user inputs "The QUick brown fox jumps over the lazy dog" or "The qui brown fox jumps over the lazy dog". Similarly 2 mistakes occur when input is "The QUik brown fox jmps over the lazy dog". In nut shall before declaring a mistake, my program checks the substring after the word, whose index is find currently
Comment: so you will have at most one mistake per word?
Comment: yes but rest of the input string after the mistaken word should match with the Builtin string.
Answer: Cant you shrink your code by this simple logic ?
String[] expectedSentenceA = "The quick brown fox jumps over the lazy dog".split(" ");
String[] inputStringA = inputString.split(" ");
int diff=  expectedSentenceA.length-inputStringA.length;
if(diff>0) {
    System.out.println("You have missed " + diff + " word(s)..!!!");
} else if (diff < 0) {
    System.out.println("Found " + diff + " excess word(s)..!!!");
}else {
   ArrayList<String> mistakeWords= new ArrayList();
   for(int i=0;i<expectedSentenceA.length;i++) {
    if(!expectedSentenceA[i].equals(inputStringA[i])){
        mistakeWords.add(inputStringA[i]);
    }
   }
   JOptionPane.showMessageDialog(null,"Total Mistakes ["+mistakeWords.size()+"] are " + mistakeWords);
}

Comment: Must check size of inputStringA before compare
Comment: Thanks you showed me a new way to work with string. Thanks alot for your help
Comment: Good experiment. Try more. Here is a game example which I did using swing [Java Swing Shuffle Game](http://javabeginner.com/java-swing/java-swing-shuffle-game)
Comment: what if the length of the input string is less then builtin string? I am thinking to set a condition if input string length is less than builtin string lenght, then checking loop will run until the length of input string. Is there any other better way?
Answer: I don't understand all of your code, but what's wrong with a solution like this:
String[] expectedWords = "The quick brown fox".split(" ");
String[] inputWords = inputText.split(" ");
int mistakes = 0;
if (expectedWords.length != inputWords.length) {
    return;
}
for (int i = 0; i < expectedWords.length; i++) {
    if (!expectedWords[i].equals(inputWords[i])) {
        mistakes++;
    }
}
// Show number of mistakes.

Comment: you are checking the Strings character by character which may declare wrong number of mistakes.
Comment: Not character by character, word by word!
Comment: Or I don't understand your question. Entering `The FOO brown fox jumps over the lazy dog` would result in 1 error, if the array elements were one word each.
Comment: actually you are considering String as char array. Your code checks whether the input string array is equal to Builtin String array.
Comment: Should this `The FOO brown fox jumps over the lazy dog` result in 1 mistake? - Than my code is correct. Otherwise I do not understand your requirements.
Comment: yes. I mentioned the principal on which mistake counter is incremented in my question


I get an "Outdated Client" message when I try to play with my friends

Question: When I try to go to my friends world, a message comes up and says "could not connect outdated client", and when I try to invite my friends over to my world it won't let them come to my world.
What can I do to fix it?
Comment: You provided NO details on any errors or anything. No one cann solve your problem if ye don't describe it fully
Comment: Have you tried updating your Minecraft? Check what version you are using, and what version they are using.
Comment: @Ben You should post that as an answer
Answer: This message refers to a mismatch between the Client version, and the Host version Minecraft. If you are running two different versions of the game, they will not be able to connect.
In the launcher, you can choose which version of Minecraft you wish to play. Make sure you and your friends are choosing the same version, and you will be able to play together.


Trying to run ColdFusion 10 on Ubuntu 14 with apache2?

Question: I have been using ColdFusion 10 with IIS7, and recently decided to move to Ubuntu. I have installed CF to run as a self-contained server.
I am trying to use wsconfig with to configure CF to work with apache2. I use the following command:
sudo /opt/coldfusion10/cfusion/runtime/bin/wsconfig -ws Apache -dir /etc/apache2/ -v

And I get the following error:
[bash4.3:apache2] sudo /opt/coldfusion10/cfusion/runtime/bin/wsconfig -ws Apache -dir /etc/apache2/ -v
command line: -ws Apache -dir /etc/apache2/ -v
Could not find file /etc/bin/httpd
Using Apache binary /usr/sbin/httpd
Server version: Apache/2.4.7 (Ubuntu)
/etc/apache2 is not a valid configuration directory for Apache

I am getting the above error message all the time. Checked CF doc on Adobe and it was no help.
Answer: ColdFusion 10 doesn't work with Apache 2.4.x so I had to upgrade to ColdFusion 11 and that solved the problem.
Answer: You can change /usr/sbin/httpd to /usr/sbin/apache2
Answer: I got this error for a couple reasons. As @Kunal noted, older versions of ColdFusion don't work with Apache 2.4, so my solution was to downgrade to Apache 2.2. I also continued to have this error when I was trying to use Debian, but it was fixed when I moved to Ubuntu.


CakePhP 1.3 multiple and or conditions in find

Question: I'm trying to retrieve the latest images uploaded to my site but not when they're in a private gallery, event or if the user is deleted. I need to do these checks on a 0 or a null as well.
I've looked around and found a fair few ways of doing multiple and's and multiple or's but not together. It seems to look correct but doesn't work at all.
<code>$conditions = array(
            'AND' => array(
                array(
                    'OR' => array(
                        'Event.private'     => null,
                        'Event.private'     => 0
                    )
                ),
                array(
                    'OR' => array(
                        'Gallery.private'   => null,
                        'Gallery.private'   => 0
                    )
                ),
                array(
                    'OR' => array(
                        'User.deleted'      => null,
                        'User.deleted'      => 0
                    )
                )
            )
        );

        $images = $this->Image->find('all',array(
                        'order'=>array('Image.id'=>'desc'),
                        'limit'=>$limit,
                        'group'=>'Image.id',
                        'offset'=>$offset,
                        'conditions'=>$conditions)
                    );
</code>
Comment: Never use a key twice in an array (a key 'Event.private' would overwrite the first one in the same array!).
Comment: "doesnt work at all"? any details? maybe you can post your sql query that cake generates and runs here.
Comment: Well it only loads 11 entries out of a few hundred possible entries. It also crashes the hell out of the javascript that renders out the images. I don't have access to the view so can only test it with debugging.

If i however add a condition to only get images from a private gallery, that part works. so the only part that seems to not be working is my and or tree, and as i cant find an example of the correct syntax the only thing I can think of being wrong is that somehow.
Comment: Allways switch on debug SQL for check query
Answer: The OR statements should probably be also in an array.
Try following conditions:
<code>$conditions = array(
    'AND' => array(
        array(
            'OR' => array(
                array('Event.private' => null),
                array('Event.private' => 0)
            )
        ),
        array(
            'OR' => array(
                array('Gallery.private' => null),
                array('Gallery.private' => 0)
            )
        ),
        array(
            'OR' => array(
                array('User.deleted' => null),
                array('User.deleted' => 0)
            )
        )
    )
);
</code>
Comment: Thank you, that worked a treat. I remember reading about having multiple or's and them needing to be in an array due to over writing each other. Never considered the same for multiple sections in an or :)


UISearchBar with UISearchDisplayController animates outside screen

Question: I have standard iPad view controller which has a custom navigation bar at the top. In the xib-file I've added a UISearchBar aligned to the right edge of the view. The search bar is 320px in width. I init a searchdisplaycontroller like this:
// Search display controller
self.mySearchDisplayController = [[UISearchDisplayController alloc] initWithSearchBar:_searchBar
                                                                                contentsController:self];
_mySearchDisplayController.delegate = self;
_mySearchDisplayController.searchResultsDataSource = self;
_mySearchDisplayController.searchResultsDelegate = self;

The problem is that when I press the search bar, the bar resizes to be the full width of the entire view, but keeps its x-position. This means that it stretches far outside the screen. I'm guessing it has something to do with the "Cancel" button that slides in next to a search bar. If I place the search bar to the far left in the screen, it animates to the full width of the screen and the cancel button is visible.
Anyone has a solution for this?
Answer: You can animate the frame of your UISearchBar in the searchDisplayControllerWillBeginSearch method to correct its position like this:
- (void)searchDisplayControllerWillBeginSearch:(UISearchDisplayController *)controller
{
    // animate the search bar to the left ie. x=0
    [UIView animateWithDuration:0.25f animations:^{
        CGRect frame = controller.searchBar.frame;
        frame.origin.x = 0;
        controller.searchBar.frame = frame;
    }];
    // remove all toolbar items if you need to
    [self.toolbar setItems:nil animated:YES];
}

and the animate it back again when finished searching:
- (void)searchDisplayControllerDidEndSearch:(UISearchDisplayController *)controller
{
    // animate search bar back to its previous position and size
    // in my case it was x=55, y=1
    // and reduce its width by the amount moved, again 55px
    [UIView animateWithDuration:0.25f
                          delay:0.0f
                    // the UIViewAnimationOptionLayoutSubviews is IMPORTANT,
                    // otherwise you get no animation
                    // but some kind of snap-back movement
                        options:UIViewAnimationOptionLayoutSubviews
                     animations:^{
                         CGRect frame = self.toolbar.frame;
                         frame.origin.y = 1;
                         frame.origin.x = 55;
                         frame.size.width -= 55;
                         controller.searchBar.frame = frame;
                     }
                     completion:^(BOOL finished){
                         // when finished, insert any tool bar items you had
                         [self.toolbar setItems:[NSArray arrayWithObjects: /* put your bar button items here */] animated:YES];
                     }];
}

I have answered a similar question, you can check it here, I've put some images too.
The only thing you have to do is to adapt the code for the iPad.


How do I get a value from another page and output it to a selectlist? JAVASCRIPT

Question: I have several input elements in which I enter the name of the book author and the book title. This data should appear in a selectlist that is on a different page. I have to pass values from one page to another, but I don't know how to do it in JavaScript. Could you show me how to do it?
HTML

          <input id="item" type="text" placeholder="Add book" required>
          <input id="item2" type="text" placeholder="Add author" required>

          <select id="mySelect" class="block">
            <option>JS Part 1</option>
            <option>JS Part 2</option>
            <option>HTML + CSS book</option>
            <option>Bootstrap</option>

          </select>
          <select id="mySelect2" class="block">
              <option>Author 1</option>
              <option>Author 2</option>
              <option>Author 3</option>
              <option>Author 4</option>

            </select>
          <input type="submit" id="send" class="block">

JS
    var inp = document.getElementById("item");
    inp.value = "Book Title";
    var inp2 = document.getElementById("item2");
    inp2.value = "Author name";
    var itemsArray = localStorage.getItem('items') ?
    JSON.parse(localStorage.getItem('items')) : [];

    send.onclick = function (e) {
    e.preventDefault();
    let name = {
      obj: "ID: ",
      obj2: " Book: ",
      obj3: " Author: "
    }

    var li = document.getElementsByClassName("me");
    var count = li.length;
    console.log(count);

    var sel = document.getElementById('mySelect').selectedIndex;
    var options = document.getElementById('mySelect').options;
    var sel2 = document.getElementById('mySelect2').selectedIndex;
    var options2 = document.getElementById('mySelect2').options;
    var string = name.obj + (count + 1) + " | " + name.obj2 + inp.value + " | " + name.obj3 + inp2.value;

    itemsArray.push(string);
    localStorage.setItem('items', JSON.stringify(itemsArray));
}

Comment: Please show your code (your attempt). I'm 99.9% sure that if you don't, you will get downvoted and leave without an answer.
Comment: Have you written your code? If yes please show your code...
Comment: You can use ajax or url parameters for sending data to second page.
Comment: I have edit my post, please open my question
Comment: if you added it in the localstorage then access it on next page whats the matter
Answer: on submit add data in localstorage
var itemsArray = localStorage.getItem('items') ?
JSON.parse(localStorage.getItem('items')) : {authors:[],books:[]};
itemsArray.authors.push(inp);
itemsArray.books.push(inp2);

then on next page you can do is
document.addEventListener("DOMContentLoaded", function(event)
{
console.log("DOM fully loaded ");
let data=JSON.parse(localstorage.getItem('items'))
let select1="";
data.authors.map(author=>{
  select1+="<option>"+author+"</option>"
})
//populate in input fields accordingly
 document.getElementById("slect1").innerHTML=select1 //same way you can do this for book also
}


loop scanf until user types nothing (hits enter twice) using while loop

Question: I've tried using NULL but it doesn't work. Any ideas?
while (index != NULL) { //what expression must be passed here?
printf("Enter a number\n");
scanf ("%d", &index);
//do some work
}

Answer: The decimal value for NULL in ASCII is 0, so if you enter this in your program now it will end. This is not the same as a newline character (10 in decimal).
In any case, scanf() will continue until you enter a value, so you will need to use some sort of sentinel value for the loop condition eg. if you are using only positive numbers - use a negative; if you have an upper limit, an arbitrary value beyond this. Otherwise you will have to do it some other way eg. input a string and convert to an int if it's not your exit character/string.
Comment: I'm sorry @Neil, what exactly are you referring to - could you be more specific?
Comment: Entering a 0 will end the loop, because that is the decimal equivalent of NULL.
Comment: Sorry I misunderstood you, I thought you meant entering the NUL character.
Answer: If you think about it, I bet you have never seen  a real world program that prompts you for input like this. Why? Because it's almost impossible to write them correctly, and even more impossible to use correctly. The way real world programs work is to either use a GUI or to read input from a file/stream without prompting. Given this fact, I've never understood why so many newbie programmers want to prompt the user for input.
Having said that, there may be no value that you can enter in your code to terminate the loop. Are all integer values valid input for your program? If so, you need some other way of terminating, such as typing the end-of-file character.
Comment: No you're right, I've never seen any real world programs. I'll try the EOF way.


Floating comparision in linux kernel gives linking error

Question: In linux kernel module i have below code.
float temp
temp = some_function();
if(temp < 0.0f) {
printk("error");
}

i am cross compiling it for arm platform using arm-none-linux-gnueabi- tool-chain
i got below error on   this line   if(temp < 0.0f) {

undefined reference to `__aeabi_fcmplt

I am not getting why this happening. Does am i missing any linking in makefile?
Comment: Probably because GCC has to emulate floating point operations for that platform, and those emulation functions are in the GCC runtime library which is not linked when building a kernel?
Comment: i have not added/linked any lib in makefile
Answer: Last I checked floating point was not allowed in the Linux kernel. Since the cpu arch and ABI you're building for does not support hardware floating point, GCC is generating calls to soft-float functions which are not available in the kernel.
Comment: i also searched stuff and find out that its not possible directly in linux kernel. but still some drivers in kernel use float using some other complex methods. but i dont want to go with that so just updated logic part in my module


SQL Get rows based on 3 column values

Question: sorry for the title not sure how to summarize my needs. I have a dataset with the following rows
Select ID,User,[Row#],[Row2#],Types,Date from MyTable

ID
User
Row#
Row2#
Types
Date

65930969
000080A8C8
1
1
TYPE 1
9/18/2019

65948916
000080A8C8
2
1
TYPE 1
10/3/2019

66074230
000080A8C8
3
2
TYPE 2
11/12/2019

59544865
0001116BE4
1
1
TYPE 1
10/30/2017

59736459
0001116BE4
2
2
TYPE 2
12/11/2017

68676655
0001116BE4
3
1
TYPE 1
9/17/2020

68794822
0001116BE4
4
2
TYPE 2
10/20/2020

69067248
0001116BE4
5
3
TYPE 2
11/30/2020

69722764
0001116BE4
6
4
TYPE 2
1/28/2021

69902103
0001116BE4
7
5
TYPE 2
2/24/2021

62646449
0014E0F7C1
1
1
TYPE 1
10/1/2018

62646463
0014E0F7C1
2
2
TYPE 1
10/1/2018

66279347
0027C08119
1
1
TYPE 1
10/29/2019

66333035
 0027C08119
2
2
TYPE 2
12/5/2019

66640349
0027C08119
3
3
TYPE 2
1/9/2020

66990998
0027C08119
4
4
TYPE 2
1/21/2020

67020294
0027C08119
5
5
TYPE 2
2/20/2020

69673544
0027C08119
6
6
TYPE 1
1/19/2021

My goal is to get All Types = "Type 1" And the following Types = "Type 2" with the Higher Date (or Row2#) whatever is easier. This table shows the result needed.

ID
User
Row#
Row2#
Types
Date

65930969
000080A8C8
1
1
TYPE 1
9/18/2019

65948916
000080A8C8
2
1
TYPE 1
10/3/2019

66074230
000080A8C8
3
2
TYPE 2
11/12/2019

59544865
0001116BE4
1
1
TYPE 1
10/30/2017

59736459
0001116BE4
2
2
TYPE 2
12/11/2017

68676655
0001116BE4
3
1
TYPE 1
9/17/2020

69902103
0001116BE4
7
5
TYPE 2
2/24/2021

62646449
0014E0F7C1
1
1
TYPE 1
10/1/2018

62646463
0014E0F7C1
2
2
TYPE 1
10/1/2018

66279347
0027C08119
1
1
TYPE 1
10/29/2019

67020294
0027C08119
5
5
TYPE 2
2/20/2020

69673544
0027C08119
6
6
TYPE 1
1/19/2021
Comment: your results don't align with your logic, eg user *0001116BE4* has TYPE 2 twice, which is not the TYPE 2 with the higher date.
Comment: can you just be Lil more clear about your required results?
Comment: While asking a question, you need to provide a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example):
(1) DDL and sample data population, i.e. CREATE table(s) plus INSERT T-SQL statements.
(2) What you need to do, i.e. logic and your code attempt implementation of it in T-SQL.
(3) Desired output, based on the sample data in #1 above.
(4) Your SQL Server version (SELECT @@version;).
Comment: Maybe using `ORDER BY` clause might help you out to get your required output if it's just about sorting.
Answer: Try below query
select ID,[User],Row#,Row2#,[Types],[date] from Mytable where [Types]='Type1'
Union All
select ID,[User],Row#,Row2#,[Types],[date] from
(
select ID,[User],Row#,Row2#,[Types],[date]
ROW_NUMBER() over (partition By [Types],[User] Order by Row2# desc) Serial
from Mytable where [Types]='Type2'
) a where Serial=1

SQL Get rows based on 3 column values


How to make a reusable modifier for view lifecycle events (onAppear, onDisappear)?

Question: I have a common fadeIn and fadeOut animation that I use for when views appear and disappear:
struct ActiveView: View {
    @State var showCode: Bool = false
    @State var opacity = 0.0
    var body: some View {

    if self.showCode {
        Color.black.opacity(0.7)
            .onAppear{
                let animation = Animation.easeIn(duration: 0.5)
                    return withAnimation(animation) {
                        self.opacity = 1
                    }
            }
            .onDisappear{
                let animation = Animation.easeOut(duration: 0.5)
                    return withAnimation(animation) {
                        self.opacity = 0
                    }
            }
    }
    }
}

However, I want to use these same animations on other views, so I want it to be simple and reusable, like this:
if self.showCode {
    Color.black.opacity(0.7)
        .fadeAnimation()
}

How can I achieve this?
EDIT:
Trying to implement a View extension:
extension View {
    func fadeAnimation(opacity: Binding<Double>) -> some View {
        self.onAppear{
            let animation = Animation.easeIn(duration: 0.5)
                return withAnimation(animation) {
                    opacity = 1
                }
        }
        .onDisappear{
            let animation = Animation.easeOut(duration: 0.5)
                return withAnimation(animation) {
                    opacity = 0
                }
        }
    }
}

Comment: You can use a view extension to achieve the same functionality as well as reusable for each view.
Answer: What you try to do is already present and named opacity transition, which is written in one modifier.
Here is a demo:

struct ActiveView: View {
    @State var showCode: Bool = false
    var body: some View {
        ZStack {
            if self.showCode {
                Color.black.opacity(0.7)
                    .transition(AnyTransition.opacity.animation(.default))
            }
            Button("Demo") { self.showCode.toggle() }
        }.frame(maxWidth: .infinity, maxHeight: .infinity)
    }
}

Answer: The functionality that you are trying to implement is already part of the Animation and Transition modifiers from SwiftUI.
Therefore, you can add .transition modifier to any of your Views and it will animate its insertion and removal.
if self.showCode {
    Color.black.opacity(0.7)
        .transition(AnyTransition.opacity.animation(.easeInOut(duration: 0.5)))
}

You can use a multitude of different transitions like .slide, .scale, .offset, etc. More information about transitions here.
You can even create custom transitions with different actions for insertion and removal. In your case, different animation curves.
extension AnyTransition {
    static var fadeTransition: AnyTransition {
        .asymmetric(
            insertion: AnyTransition.opacity.animation(.easeIn(duration: 0.5)),
            removal: AnyTransition.opacity.animation(.easeOut(duration: 0.5))
        )
    }
}

And use it like this:
if self.showCode {
    Color.black.opacity(0.7)
        .transition(.fadeTransition)
}

Hope this helps !


What should I do about the floor for a outside metal shed / ventilation

Question: I put together one of those 1 million fastener sheds from lowes.  I didn't do a lot of ground prep but tried to make it as flat as possible.  There were initially some areas under the perimeter wall that were too low so I added dirt under those sections.  The exterior walls then all sat flat but due to time constraints I didn't try to completely level the inside dirt area.  I then put some 6mil poly down on the flat ground and then put the shed on top.
A season later and I have some water puddles in the low spots.  I am not sure if the water came in from the change in season and humidity - over the winter there were certainly times where the metal ceiling of the shed was sweating with condensation and dripping.
Do I put a hole in the poly at the low spots to allow the water to drain?  Should I put a layer of sand on top of the poly?  Anyone add a vent to these things to allow more air flow?  The shed is in a really tight spot so I can move it maybe a few feet in one direction but it is pinned in by a tree, a garage, and two sides with fence.
I suppose I could cut the poly, add soil to level and tuck tape in new poly.  Really I guess the water and ventilation are the main issue.  There is a probably a liter of water sitting on the floor and that seems like a lot for condensation from season change but I am pretty sure that the grade all around the exterior slopes away so maybe there is some kind of small leak in the roof.  In the pacific north west we have enough rain that if there was any sizable leak the thing would be saturated.
With two people I can lift the shed vertically.  Ideas?  Thank you in advance.
Answer: The plastic is good to prevent growth from taking over the shed floor. You're now paying the price for not taking the time to do proper ground prep. This is going to be some additional work, but think about adding more sand to the top of the plastic, level it and put down some of those 16" x 16" concrete pavers. Those are easy to keep level and any water dripping down for any reason would fall into the cracks of the pavers and be absorbed by the sand. Just a thought.
Answer: Two years ago I built a 6'x 3' kit type shed in my backyard and dealt with similar drainage issues.

I would move the shed off the base and get rid of the plastic. Since the grade slopes away from the shed I would use metal landscape edging to set a perimeter to hold pavers. Level out the sand and use 12" x 12" pavers to build a base. You'll want the base to extend out past the shed by at least 6" around the sides and back and at least 12 to 18" for an apron in the front.
This will allow water to drain down and away from the shed. Depending on your situation you might also want to improvise vents for air circulation between the shed base and the pavers - on the floor perimeter.
Answer: The water is likely from condensation and possibly dripping down the side of the exterior walls. Plastic is used in the crawlspaces of houses to keep moisture down that originates from the soil, and as you noted you don't have for your shed, there is also foundation ventilation so that any air that is moist will vent to the exterior and be replaced with drier air.
For your shed, the plastic isn't necessary. I would suggest making a cut in the lower areas so that the standing water will drain away.


A Non-Compact Topology on $\mathbb{N}$, the Natural Numbers

Question: I am given the following set $\mathcal{T}$ which is a topology on the natural numbers:
$$\mathcal{T}:=\{\emptyset,\{1\},\{1,2\},\{1,2,3\},\{1,2,3,4\},\ldots,\mathbb{N}\}$$
I want to show that $(\mathbb{N}, \mathcal{T})$ is non-compact. To show that a topological space is not compact, I know that I have the following tools to do so:

I can show that there does not exist a finite subcover of an open cover of $(\mathbb{N}, \mathcal{T})$.
I can show that there is a collection of closed sets $\mathcal{C}$ in the topological space that does not have the finite intersection property (i.e., the intersection of all the elements of $\mathcal{C}$ is empty).

I am not sure if #2 would be helpful here, and I am not sure how to apply #1 given the topology that I have. How would I go about crafting an open cover (and then showing that such an open cover has no finite subcover)?
Comment: A cover worth looking at in more detail is given by $\mathcal{T} \setminus \{ \mathbb{N} \}$...
Comment: Think about the cover of $\mathbb{N}$ of all the elements of the topology except $\mathbb{N}$ itself.
Comment: If $\mathbb{N} \in \mathcal{O}$ then $\mathcal{O}$ has the finite subcover $\{\mathbb{N}\}$. Can you describe an open cover that does not include $\mathbb{N}$?
Answer: You already have excellent hints in the comments for how to use $1.$ If you want to use $2.$, you can consider the following decreasing sequence of closed sets:
$$(\mathbb{N} \setminus \{1,\ldots,n\})_{n \in \mathbb{N}}.$$
What is $\bigcap\limits_{n \in \mathbb{N}} (\mathbb{N} \setminus \{1,\ldots,n\})$?


How to prevent chrome devtools from stopping on `debugger` keyword?

Question: Is there a way to prevent chrome from stopping on debugger statements while the devtools window is open, and at the same time allow stopping on manually set breakpoints?
The deactivate breakpoints button (⌘/ctrl + F8) disables both the debugger statements and the user breakpoints so it's not really a solution. It would be good to somehow be able to control separately 'code' breakpoints and 'devtools' breakpoints.
Answer: You can use "Never Pause Here" feature. but you need to do it for every line.
Answer: How about two scripts to launch your app , where one script can comment out all the debugger statements and then launch the app ?
If it's that important to you right now.
Comment: See if this helps.  [answer](https://stackoverflow.com/questions/26569955/disable-the-debugger-statement-through-the-browser)
Comment: That would be an answer to a different question. But let's assume that you are loading an external library that you cannot modify.
Comment: well no one puts debugger; in production builds
Comment: I only said *let's assume*, didn't say it's a production build.
Comment: Thanks, yes, it lists among others the answer provided by @m.hassaballah.


Best way to use the same HTML on static web-pages

Question: If you use dynamic pages like JSP or asp.net, you can have your page template included, and then content added. But what if you have no server-side component and all pages are just HTML/JS? You can of course create a template then copy it for each page, but then if you want to change something you risk having to modify every page, even if you put most styling in CSS properly.
Are there any non-awful ways to do this? I could see that an iframe could be used to load the content into the central page but that sounds nasty. Does HTML provide any way to include a base file and add to it?
Comment: possible duplicate of [How is this problem usually solved without using sever-side scripting?](http://stackoverflow.com/questions/2898741/how-is-this-problem-usually-solved-without-using-sever-side-scripting)
Answer: You can use Server Side Includes to include other files on the server. It's similar to scripting languages like ASP or php, but SSI is usually supported by the server directly, so it's available on many servers, even if there is scripting language available.
Comment: This seems the best approach. I don't have time/inclination to do a proper Java/ASP.net site and my host doesn't support them. The other option is PHP but I don't know it or want to learn it. SSI seem to be included on every host and require virtually no knowledge to stitch a file together.
Answer: The answer is still templates. Just process them offline instead of on the server. I like to use ttree for this.
Answer: You can create the pages offline and render into HTML, and deploy those to the site.
One option might be: https://github.com/thewml but it does feel ... "too much". I also saw asciidoc for creating sites ( https://asciidoc.org/ ) and I also used several times doxygen for that ( http://www.doxygen.nl/ ).
I also saw CMS that create static HTML files, but hey are no longer maintained.
Comment: makefiles + cat? Updated answer


Static constructor BEFORE reflection

Question: If I load an assembly, and get a static readonly field of a given type, and I expect that field to be initialized on static constructor, and I call GetValue on that field, will it have a value (since I'm accessing a field on a type, so it needs to be typeinitialized)?
(No, I'm not planning on calling the static constructor from reflection...)
Comment: Seems like this would be pretty easy to test...
Comment: Come on TDaver - you know enough to verify this on your own!
Comment: yeah I figured out I overcomplicated my test case :) Sorry for wasting your time :)
Comment: Are you not able to call GetValue and get the value back?
Answer: Looks like a yes to me.
<code>// In SomeAssembly.dll
public class TestClass
{
    public static readonly int Field;

    static TestClass()
    {
        Field = 5;
    }
}

// In its own assembly
public class Program
{
    public static void Main()
    {
        BindingFlags bindingFlags = BindingFlags.Static | BindingFlags.Public;

        Assembly someAssembly = Assembly.LoadFile(@"Path\To\SomeAssembly.dll");

        object field = someAssembly.GetType("TestClass")
                                   .GetField("Field", bindingFlags)
                                   .GetValue(null);

        Console.WriteLine(field);
    }
}
</code>
Output:

5
Comment: @Richard: I actually did try it, and yes, it works in that case too... I'll update the answer.
Comment: He states 'Load an assembly', does this work even if the assembly with the static field is loaded at runtime (which i presume he means)? cant see why it wouldnt but im far too lazy to try it myself..
Comment: Thanks again for testing it! My code kept throwing exceptions and it took me a while that it had nothing to do with the static field :)

Static constructor BEFORE reflection


How to calibrate continuous water Gas Heater?

Question: i have installed a gas continuous water gas heater, it is around 30 mts of pipe away. my shower has a mixer valve (one unique lever for both the hot and cold water). The problem is, whenever I am taking a shower, and after aproximately 5 mins, the gas heater turns off and i start to get cold water, forcing me to shut down the water, and turn it all hot again, and wait for the hot water to come again, so i can resume my shower, it keeps happening again and again. I have tried different sets of configurations for the heater (moving the minimum water, and gas level) nothing solved the problem.
Answer: Obviously, there is some threshold or setting that needs to be adjusted, as when you go back to full hot it kicks back on. You need to adjust it so that full hot is not required to keep it on. All this you already know. Not being familiar with your particular unit, I don't know exactly what adjustments are available.
As I understand it, when you are on full hot, the water flow through the unit is greater, and the water does not get as hot (maybe, because the flow is greater), but you get more of it. The incoming water supply is cold, and it supplies both the heater and the cold water line, so when you start using both, the flow through the heater decreases. This would be the case even if you still had the shower set for all hot, but the cold water was turned on at the sink (try this - does the heater turn off, as it has before, mid shower?).
Then when you start mixing the hot and cold in the shower to get a pleasant temperature the flow through the heater is reduced again, because you are requiring less hot water. This may result in the heater turning off because the flow is less, or maybe it is turning off because the water is getting too hot. So either there is a low-flow sensor that needs to be adjusted to a much lower setting, or maybe there is an overheating cut off switch that is faulty or needs to be set higher.
You might try your shower again, as normal, but with the hot water on at the sink. Does this make your hot water stay on, as you want it? (Of course this is not a solution, but it might help you find the source of the problem).
Hope this helps.


Link to apps page on FB

Question: Link to my apps page on FB is like this http://www.facebook.com/apps/application.php?id=112233445566778899.
But for some apps i saw that link to their pages are like this http://www.facebook.com/AppName. For example: to go to page of app MafiaWars we can use www.facebook.com/MafiaWars...
How can i do like this for my app?? is there any config or what??
Answer: There is a setting on Facebook Page called as "username" which will set the link to your FB page as facebook.com/UserName
it can be found under the settings:
<code>Edit Profile >> Basic Information >> Username
</code>

Link to apps page on FB


Show that $V(I \cap J)=V(I) \cup V(J)$.

Question: Let $I$, $J$ ideals of $K[x_1, x_2, \dots , x_n]$.
I want to show that $$V(I \cap J)=V(I) \cup V(J)$$
I tried the following:
$$\subseteq: $$
Let $x \in V(I \cap J)$.
From the definition of $V$:
$V(S)=\{ (a_1,a_2, \dots, a_n) \in K^n| f_a(a_1,a_2, \dots, a_n)=0 \forall a \in A\}$
we have that $f(x)=0, \forall f \in I \cap J$.
So, $f(x)=0, \forall f \in I \text{ AND } f \in J$.
So, $f(x)=0, \forall f \in I \text{ AND } f(x)=0, \forall f \in J$.
So, $x \in V(I) \text{ AND } x \in V(J)$.
So, $x \in V(I) \cap V(J)$.
But... I have to show that $x \in V(I) \cup V(J)$.
What have I done wrong?
Comment: The mistake is in the second line that begins with "So". The AND cannot be split like that.
Comment: @Arthur How could I write it then?
Answer: Assume $x$ is neither in $V(I)$ nor $V(J)$ (i.e. $x \notin V(I)\cup V(J)$). That means that there is an $f\in I$ and a $g\in J$ such that $f(x) \neq 0$ and $g(x) \neq 0$.
We have $fg \in I\cap J$, but $fg(x) \neq 0$, and therefore $x \notin V(I\cap J)$.
This shows that $x \notin V(I)\cup V(J)$ implies $x \notin V(I\cap J)$, which is the contrapositive of what you want to show.
As for the direct approach, how about something along these lines?
$$
x \in V(I\cap J) \implies\\
\forall f\in I\cap J: f(x) = 0 \implies\\
\forall f \in I, g\in J: fg (x) = 0\implies\\
\forall f \in I, g\in J: f(x) = 0 \text{ OR } g(x) = 0 \implies\\
x \in V(I) \text{ OR } x\in V(J)\implies\\
x \in V(I)\cup V(J)
$$
Comment: Because if $f \in I$ and $g \in J$, then $fg \in I\cap J$.
Comment: Why do we conclude from $$\forall f \in I \cap J: f(x)=0 $$ that $$\forall f \in I, g \in J: fg(x)=0$$ ?
Comment: How do we conclude that if $f \in I$ and $g \in J$, that $f \cdot g \in I \cap J$ ? :/
Comment: By the definition of an ideal, since $f \in I$, we must have $fg \in I$. In exactly the same way, since $g \in J$, we must have $fg \in J$. But then we have $fg \in I$ and $fg \in J$, which gives $fg \in I\cap J$.
Comment: That way is easier. Let $x\in V(I)\cup V(J)$. Then it's either the case that $\forall f\in I: f(x) =0$ or it is the case that $\forall g\in J: g(x)=0$. Now, if a function $h$ is in $I\cap J$, then no matter which of the above applies to our $x$, we have $h(x) =0$, since $h$ is in both ideals.
Comment: Arthur Could you explain me why after saying that $\forall f \in I \cap J:f(x)=0$, we take a $f \in I$ and a $g \in J$, such that $fg(x)=0$?
Comment: We want to show that either $x$ is in the zero set of $I$, or it's in the zero set of $J$. So we take a random function $f$ from $I$ and a random function $g$ function from $J$. By my last comment, we know that $fg \in I\cap J$, which means that $fg(x) = 0$. But then we must have either $f(x) = 0$ or $g(x) = 0$, and we're done. Note that the $f$ in one line has a slightly different meaning than the $f$ in the other line. I could've written $\forall g \in I, h \in J: gh(x)=0$ instead, without changing the meaning of anything.
Comment: Arthur Could we prove $\supseteq$ like that?
$$\text{Let } x \in V(I) \cup V(J)$$
$$\Rightarrow x \in V(I) \text{ OR } x \in V(J)$$
$$\Rightarrow \forall f \in I: f(x)=0 \text{ OR } \forall g \in J: g(x)=0$$
$$\Rightarrow \forall f,g \in I \cap J: f(x)g(x)=0$$

$$\Rightarrow \forall \phi(x) \in I \cap J: \phi(x)=0$$
$$\Rightarrow x \in V(I \cap J)$$
Comment: So, $V(I \cap J) \supseteq V(I) \cup V(J)$
Comment: Therefore, $V(I \cap J)=V(I) \cup V(J)$.
Comment: What do you mean with " no matter which of the above applies to our x"?
Comment: @evinda I mean that for any single $x\in V(I)\cup V(J)$, it's either the case that $x\in V(I)$, and therefore $\forall f\in I: f(x) =0$, _or_ it's the case that $x\in V(J)$, which means that $\forall g\in J:g(x)=0$ (might also be both, mind you). No matter which one it is, though, whenever we have an $f\in I$ and $g\in J$, at least one of $f(x)$ and $g(x)$ is guaranteed to be equal to $0$. Another way to write that is $$\forall f,g: f\in I \text{ AND } g\in J \implies fg(x)=0$$
Comment: Arthur Could you explain me why $x \notin V(I) \cup V(J)$ means that  there is an $f \in I$ and a $g \in J$ such that $f(x) \neq 0$ and $g(x) \neq 0$ ? Can it be that there are $f,g$ such that $f(x)=0$ and $g(x)=0$ ? :/
Answer: Let $x \in V(I \cap J) \Rightarrow f(x) = 0, \forall f \in I \cap J.$ Suppose there exists $h \in I$ such that $h(x) \neq 0.$ The for any $g \in J, g(x) = 0,$ because $hg \in I \cap J.$
Comment: Not necessarily. First of all, it can be that $IJ \subsetneq I \cap J,$ and even if $IJ = I \cap J,$ not all the elements of $I \cap J$ is of the form $hg$ for some $h \in I, g \in J.$ But it is always true that $V(IJ) = V(I \cap J).$
Comment: Does $f(x)=0, \forall f \in I \cap J$ mean that there exists $h \in I$ and $g \in J$ such that $f=hg$ ? If so, why is it like that?

Show that $V(I \cap J)=V(I) \cup V(J)$.


Power tool for scraping paint off windows

Question: I need to scrape paint off of a bunch of windows where the painters painted over the glass. I know I can use a razor, but that takes a long time.
Are there any power tools that I could use to make the process faster?
Comment: Power tools on glass?  Let us know how THAT works out !
Comment: How much of the glass is painted?  Is it just like a  1/8th of an inch or slopped on?
Comment: Get one of those old time vibrators that straps to your hand and hold the razor tool and let the vibrations do the work.
Answer: No no no, you really don't want to do that
As Alaska Man says... "power tools near glass, what could go wrong?"
I strip a lot of paint off a lot of windows because I hate masking.  And it's not super-easy latex paint either - it's alkyds or LPUs (which are a fight) or worse, 2-pack epoxy primer, which has an uncanny bite on glass (how??)    Or silicone sealants.
Just go to town with a bottle of Windex and a stack of sharp razor blades.  It's really fast work, and I don't see how a power tool could help. Keep the area wet with Windex.  If you don't want to waste Windex that way, dilute any lliquid soap; the purpose is to lubricate the razor blade to keep it from scratching and extend its life.  Let a good rain take the soap away and windex it at the end.  Do Not Do This Dry.
If it's slow going, you're doing it dry, or using dull razor blades (change those lickity split, they are your enemy as they will scratch the glass!  Also, there are no medals/awards for conserving razor blades, and they recycle 100% because the landfill shreds your trash and runs a magnet over it to pick up ferrous waste).


Offline package installation

Question: I want to install some packages without internet connection.
Please suggest the ways to copy already installed packages on "System1" to "System2" (System2 without internet connection).
Answer: Copying files
Take a look at <code>/var/cache/apt/archives</code>. You could copy them to System2 using a USB disk or via ssh (if it has local network access).
This might not work if your don't repeat this each time you update System1, because you might miss dependencies which were installed in  the meantime. So: Not recommended.
Local network mirror
Also, you could setup a local network apt mirror, which is possibly the best solution.
Create a CD or USB-Disk
For this, try APTonCD, reprepro or AptMedium. All do more or less the same - choose your flavour.
Comment: A network mirror will work only if it System2 is networked, which I think is not the case. APTonCD is obsolete(last development activity for the project was in the year 2007). For apt-medium there has been no development since 2009, other than a spelling correction.
Comment: @daltonfury42 Objection. He says, System2 is without internet connection. That's not the same as "without network connection". Please read the question more carefully.

Even though the mentioned projects are obsolete, it doesn't mean they won't work. In fact, they do just fine.
Comment: Have you tested them yourselves?
Comment: Some of them, about 1.5 years ago. Sadly I don't remember which one.
I do remember using http://wiki.ubuntuusers.de/Lokale_Paketquellen/apt-cacher and https://wiki.ubuntuusers.de/ubumirror, and there are also https://wiki.ubuntuusers.de/Ubuntu-Mirror and  https://wiki.ubuntuusers.de/apt-mirror.
German ubuntu community has usefull articles, if you can read german.
Comment: Giving it another thought, apt-cacher might be the best solution for small environments.

Offline package installation


How to convert in kotlin view model factory to property delegation?

Question: I have this base class for view model factory :
class BaseViewModelFactory<T>(val creator: () -> T) : ViewModelProvider.Factory {
    override fun <T : ViewModel> create(modelClass: Class<T>): T {
        return creator() as T
    }
}

I want to convert it to delegation property something like this..
inline fun <reified T : ViewModel> ViewModel.lazyWithParams(noinline provider: () -> T): ReadOnlyProperty<ViewModel, T> {
    return ...
}

If not possible maybe as extension function example...
Thanks!
Answer: Here's a way to do that:
class LazyViewModelDelegate<T: ViewModel>(
    private val viewModelClass: Class<T>,
    private val viewModelProducer: () -> T) {

    lateinit var provider: ViewModelProvider

    operator fun getValue(owner: ViewModelStoreOwner, property: KProperty<*>): T {
        if(!::provider.isInitialized) {
            provider = ViewModelProvider(owner, object : ViewModelProvider.Factory {
                //Unchecked cast because we only request a ViewModel of type T from this provider
                @Suppress("UNCHECKED_CAST")
                override fun <T : ViewModel> create(modelClass: Class<T>): T {
                    return viewModelProducer.invoke() as T
                }
            })
        }

        return provider.get(viewModelClass)
    }
}

inline fun <reified T: ViewModel> ViewModelStoreOwner.viewModelFactory(noinline factory: () -> T) =
    LazyViewModelDelegate(T::class.java, factory)

To use, put in your activity e.g.
private val viewModel by viewModelFactory {
    LoginActivityViewModel()
}

Though perhaps not the cleanest approach, it's possible to add parameters to the constructor of the viewmodel, the viewModel will be instantiated lazily when you first access it.


how to run python in gedit?

Question: I wrote python code in gedit.
As we know there is an internal python console in gedit, how can I run my python code there instead of running it in terminal.
Answer: This can be achieved by following these steps:

Go to the menu and select the Preferences option.

Go to Plugins tab, check the External Tools plugin and close the Preferences dialog.

Go back to the menu and select the Manage External Tools... option.

Add a tool and name it Run (or anything else you prefer)

Insert following code in the right side top section:

    #!/usr/bin/env python3

    import sys

    exec(sys.stdin.read())

Set following options in the right side bottom section:

Shortcut key: Ctrl+R (or any other shortcut you prefer)
Save: Nothing (or any of the options you prefer)
Input: Current document
Output: Display in bottom pane
Applicability: All documents All languages

Close the Manage External Tools... dialog.

Now you can write any Python code in an open document and press the shortcut key (you set in step 6) to run the code. The code will run whether the document is untitled or saved (whether with .py or any other extension).

You might want to set the document type to Python to see proper code highlighting for an unsaved document or a file with extension other than .py. For a .py file this option will be set automatically.
Comment: Amazing answer. Exactly what I wanted. Adding a few extra steps I took to make things look & feel even better.
Comment: Amazing, didn't know gedit can do that. I usually use Visual Studio Code for Python development, it works quite well.
Answer:
Activate the plugin: Preferences/Plugins and check Python command line (or something similar, this is my translation)
Under View, check Bottom panel.
Comment: I did same, but my problem is how can I execute my python code in the bottom view rather than switching to terminal.
Comment: Unfortunately this doesn't run anything that you've written in gedit.
Answer: I couldn't make the file run on python without saving and closing it, at first. Then it would run python only after I opened it with ex gedit filename.py
Tks again for your tutorial
Comment: Please don't add "thank you" as an answer. Once you have sufficient [reputation](https://askubuntu.com/help/whats-reputation), you will be able to [vote up questions and answers](https://askubuntu.com/help/privileges/vote-up) that you found helpful. - [From Review](/review/late-answers/1291213)

how to run python in gedit?


Why does my purified Pokémon need to be healed?

Question: I was purifying a few of my Shadow Pokémon when I suddenly noticed the Zubat  I had purified apparently had taken 1 damage somewhere. I had literally just purified it, I was still in the Pokemon screen; I didn't use it in battle or anything.
I also noticed many other purified Pokémon (Rattata, Bulbasaur, Golbat) with very little damage, but still hurt. I tried purifying a fainted (0 HP) Shadow Squirtle, and it came out at full HP. I can't trade them if they're damaged, and I don't have infinite potions to heal.
Where is the random damage coming from?
Answer: This is a bug that's been in the game since day one actually. You see what happens is the Pokemon's level is increased to 25 (or higher), given full health like in evolution, but then its IVs are increased. Usually +2 Stamina IVs will be enough to increase HP by 1, the game doesn't heal this health so it will be 1-2 health down.


How can I loop through Exception getCause() to find root cause with detail message

Question: I am trying to call saveOrUpdate() in hibernate to save data. Since columns have unique index, so its throws ConstraintViolationException when I look through via Eclipse debugger.
Since root cause could be different for different exception while inserting data to table.
I wanted to know, how can I loop / traverse through getCause() to check what is the root cause of exception and its message.
Update:
Thanks everyone for your kind response, thing is I want output like in below image:

I need to access  detailMessage field.
(I am really sorry If could not make my question more clear.)
Thanks.
Comment: Well, catch JDBCException then, or HibernateException. You should never catch `Exception` to begin with.
Comment: What do you call the "root cause" exactly? The DB-specific exception?
Comment: @fge, Yes its DB specific exception and question is updated.
Comment: Maybe `.getSQLException().getMessage()` then?
Comment: @fge, thing is I do not know what kind of exception will be thrown, hence I used parent class `Exception` to catch any possible exception. so `.getSQLException()...` wont work I guess.
Comment: See also https://stackoverflow.com/a/65442410/548473 in case you have Spring dependency
Answer: The Apache ExceptionUtils provide the following method:
Throwable getRootCause(Throwable throwable)

as well as
String getRootCauseMessage(Throwable th)

Comment: You can find something similar in Guava's [Throwables](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/base/Throwables.html): `getRootCause(Throwable)` and `getStackTraceAsString(Throwable)`
Comment: However Guava has an [issue](https://github.com/google/guava/issues/1173) regarding db style exception, thus creating infinite loops.
Comment: Yes but this requires using Guava or Apache Commons, if your project is small enough it doesn't make sense, have a look at my anwser bellow I provide a 3 line util function.
Comment: Mehdi, your solution doesn't seem to handle possible infinite loops.
Comment: Unfortunately, Apache's solution will return the same exception if it is equal to the root cause. Sometimes that's not the intend. I would say to use Legna's.
Comment: See also https://stackoverflow.com/a/65442410/548473 in case you have Spring dependency (`NestedExceptionUtils.getRootCause`)
Answer: I normally use the implementation below instead of Apache's one.
Besides its complexity, Apache's implementation returns null when no cause is found, which force me to perform an additional check for null.
Normally when looking for an exception's root/cause I already have a non-null exception to start with, which is for all intended proposes is the cause of the failure at hand, if a deeper cause can't be found.
Throwable getCause(Throwable e) {
    Throwable cause = null;
    Throwable result = e;

    while(null != (cause = result.getCause())  && (result != cause) ) {
        result = cause;
    }
    return result;
}

Comment: I believe such answers should be prefered by the questioner and the community as opposed to the answers with only a tool or lib recommendation.
Comment: The implementation I provided above is guards you from cyclically chained exceptions  of just one step in depth, meaning when the exception chains to itself e = e.getCause() (the most common and only situation I have met).

Nevertheless apache's implementation will really guard your code from cyclic exception chains of any depth e = e.getCause().getCause()... etc .. .getCause();
Comment: Indeed its helpful ! :) Thanks !
Comment: -1: *Apache's implementation returns null when no cause is found, which force me to perform an additional check for null.*: er? `ExceptionUtils.getRootCause(new Exception())` returns the input Exception, so I think the whole benefit argument provided in the answer is misguided.  In fact, the implementation in the answer produces the exact same result as `ExceptionUtils.getRootCause()`, but unlike Apache's, has only marginal handling for cyclic causes so can go into an infinite loop.
Comment: in which cases (result != cause) will help?
Comment: @KulbhushanSingh '(result != cause)' will help every single time 'result' has a non null cause.

the condition/expression on the while statement evaluates in the following order:
1.- assign cause = result.getCause()
2.- evaluates the result of the assignment above for null. null != cause
3.- if cause == null the whole expression evaluates to false, otherwise it proceeds to
4.- evaluate (result != cause) and that's your result
Comment: No additional libraries or frameworks, simple and doable logic, thanks for this answer!
Comment: would there be any concern with using such code in production?
Answer: Using java 8 Stream API, this can be achieved by:
Optional<Throwable> rootCause = Stream.iterate(exception, Throwable::getCause)
                                      .filter(element -> element.getCause() == null)
                                      .findFirst();

Note that this code is not immune to exception cause loops and therefore should be avoided in production.
Comment: I like this code, but failed to understand why it should be avoided in production, is there an example?
Comment: @A.S.Ranjan I think you should post a question of its own on SO and ask what a exeption cause loop is and why this can be dangerous in production to encounter.
Answer: Are you asking for something like this?
Throwable cause = originalException;
while(cause.getCause() != null && cause.getCause() != cause) {
    cause = cause.getCause();
}

or am I missing something?
Comment: Exception is basically of DB type exceptions. so above while loop goes in indefinite loop.
Comment: It can be N causes deep....  cause.getCause().getCause().getCause().. hence the need for something like  Apache ExceptionUtils.getRootCause()
Answer: Guava's Throwables provides the following methods:
Throwable getRootCause(Throwable throwable)

as well as
String getStackTraceAsString(Throwable throwable)

Answer: In APACHE; the implementation is like below.
The highlight is list.contains(throwable) == false
public static Throwable getRootCause(final Throwable throwable) {
    final List<Throwable> list = getThrowableList(throwable);
    return list.size() < 2 ? null : (Throwable)list.get(list.size() - 1);
}

public static List<Throwable> getThrowableList(Throwable throwable) {
    final List<Throwable> list = new ArrayList<Throwable>();
    while (throwable != null && list.contains(throwable) == false) {
        list.add(throwable);
        throwable = ExceptionUtils.getCause(throwable);
    }
    return list;
}

Answer: } catch (Exception ex) {
    while (ex.getCause() != null)
        ex = ex.getCause();
    System.out.println("Root cause is " + ex.getMessage());
}

Were you expecting something more complicated?
Comment: This is not immune to loops - the case where an exception cause points to exception itself.
Comment: actually I am getting database regarding exception, so in that case above logic is not working. anyway thanks for your response. :)
Comment: @agpt why the above logic does not work with the database in relation to exclusion?
Answer: Try this, you can put this function in a kind of Util class:
public static Throwable getRootException(Throwable exception){
 Throwable rootException=exception;
 while(rootException.getCause()!=null){
  rootException = rootException.getCause();
 }
 return rootException;
}

Example of usage :
catch(MyException e){
  System.out.println(getRootException(e).getLocalizedMessage());
}

Source : How to get the root exception of any exception
Answer: Recursively:
public static Throwable getRootCause(Throwable e) {
    if (e.getCause() == null) return e;
    return getRootCause(e.getCause());
}

Comment: Might want to replace `if (e.getCause() == null)` with `if (e == null)` else you'll lose one level information.


Bathroom Tile over old thinset

Question: Is it possible to use self leveling concrete over old thin set? I do not believe breaking it all up is an option as it was placed over existing asbestos tile. If the floor was cleaned properly and any loose pieces were removed could this work?
Comment: I see no reason why not, as long you count for increase in total hight
Comment: And scrape and/or vacuum any loose material before you do your new tile.  (Careful not to disturb the asbestos.)
Answer: The self-leveling underlayment products I've used specifically allowed for this. Materials and methods are listed in the instructions. Make sure to follow them carefully and completely.
Answer: I see no reason why it will not work.
As long you make sure the old layer is solid.
And as long you keep in mind the increase in total hight alignment to next room.

Bathroom Tile over old thinset


If I leave the Overflow queue, can I rejoin it?

Question: So I'm in Lion's Arch Overflow doing a jumping puzzle, and suddenly the popup to leave Overflow and join the main instance of Lion's Arch for my server;

Since I'm in the middle of doing a jumping puzzle and do not wish to restart or be interrupted again until I finish, I click 'Leave Queue'.
If I leave the queue to join the proper instance of a zone I'm in from the Overflow instance, is it possible to rejoin the queue for the proper instance of the zone without leaving the zone and re-entering it?
Answer: Nope. Once you hit "Leave Queue", you'll stay in that Overflow until you change zones or log out.
...but why are you worried about switching to an overflow in the middle of a jumping puzzle? Your character remains in the same position both before and after the swap from the overflow. I've switched in the middle of one of the LA jumping puzzles before, and had no issue continuing on once in my "Home" Lion's Arch.
Comment: Oh, I had read somewhere that joining the main instance moved you to a specific point of the map, and that you shouldn't transfer between the two when you're doing things like jumping puzzles...
Comment: @pixel It used to, I believe they fixed that.
Comment: Ah ok, so no longer a problem and I shouldn't worry about switching from overflow at all.


Promises function in Typescript "type void is not assignable ..."

Question: I have just started using Typescript.  One problem I can't seem to solve without cheating the Typescript system and using any type is the following:
I have a function that returns a promise:
  saveExpirableToken(tokenField: string, tokenExpiresField: string, tokenExpiresAt: Date) {
    return new Promise<UserDocument>((resolve, reject) => {
      this.generateResetToken((err: Error, resetToken: string) => {
        if (err) { reject(err) }

        this[tokenField] = resetToken
        this[tokenExpiresField] = tokenExpiresAt
        resolve(this.save())
      })
    })
  },

I call elsewhere the following
    let winningUser: UserDocument = await randomUser.saveExpirableToken(
      'wonEverythingToken',
      'wonEverythingTokenExpires',
      moment().add(1, 'year').toDate() // add one year as expiration to claiming prize
    )

The Typescript error I get is: Type 'void' is not assignable to type 'UserDocument'
What am I missing with my function declaration?  And how do I handle Promises with Typescript such that I can tell Typescript that winningUser will in fact be of type UserDocument
** Edit **
  generateResetToken(callback: (err: Error | null, token?: string) => Promise<UserDocument>) {
    const byteSize = 16
    crypto.randomBytes(byteSize, (err, resetToken) => {
      if (err) { callback(err) }

      callback(null, resetToken.toString('hex'))
    })
  },

Answer: Please check out the type definition of this.save() method, it seems like it does not return UserDocument but instead returning void.
I've created a playground link and it shows that your other type definitions is working just fine: Link
Comment: This seems right.  They should call `this.save()` (and wait for it if it's `async`) and then resolve with `this`.
Comment: I'm specifically using MongoDB and Mongoose.  Based on these docs `document.save()` should return a promise that resolves to the document that was saved:  https://mongoosejs.com/docs/documents.html#updating-using-save .
Comment: I believe my issue here is with how `generateResetToken` is working as well.

I've tried to add typescript (see edit) to the function to say it will receive a callback that is a function that will return a promise to the user document.
Comment: Looks like the error coming from the type definition of the `generateResetToken`. The `callback` should return nothing so you may want to change the return type of `generateResetToken` to `void`. Just to make sure again, which line is the error pointing to?
Comment: What is the type of `randomUser`? Could you also provide the code of `save` method? `this.save()` means calling `save` method of your object (which I guess will eventually call `save` provided by Mongoose)
Comment: This ended up being the simplest and silly mistake on my part where though I had everything right in the above, my interface definition was never changed to `Promise`


Filtering out rows according to the result of a function of variables

Question: I am looking for a faster way to filter out data.frame rows where, say, any three of the first 5 variables have values in a given vector. The command I used (which is very slow - the data.frame has more that 20M rows) is like that:
x %>%
  rowwise %>%
  filter(sum(!is.na(match(c(V1,V2,V3,V4,V5),c(9,11,33,43,44))))==3 & V6!=13)

It seems that rowwise is not the best way to go. (When I tried purrr::by_row, it ate up all memory causing my machine to become unresponsive)
A reproducible example:
library(tidyverse)

n <- choose(45,5)
n1 <- 20*n
d <- rep(NA,n1)
y <- tibble(V1=d,V2=d,V3=d,V4=d,V5=d,V6=rep(1:20,each=n))

x1 <- t(combn(45,5))

for(i in 1:20){
  y[((i-1)*n+1):(i*n),1:5] <- x1
}

k <- sample.int(n1,21854909,replace = TRUE)
x <- y[k,]

Comment: can you perhaps minimze your example, i don't think we need a 20m row dataframe to illustrate your question.
Answer: rowwise is slow, you should avoid using it if you can. The operation you are doing can be vectorized:
v <- c(9,11,33,43,44)
x1 <- x %>%
           mutate_at(1:5, funs(. %in% v)) %>%
           filter(rowSums(select(., 1:5)) == 3 & V6 != 13)

It's pretty fast even with the large data set you are providing:
system.time(x1 <- x %>% mutate_at(1:5, funs(. %in% v)) %>% filter(rowSums(select(., 1:5)) == 3 & V6 != 13))

#   user  system elapsed
#  3.561   0.807   4.465

Comment: You can create new variables instead of replacing the original ones by providing a suffix inside `mutate_at..funs`, and later on select based on the suffix of the columns. such as `x %>% mutate_at(1:5, funs(bool = . %in% v)) %>% filter(rowSums(select(., ends_with("bool"))) == 3 & V6 != 13)`
Comment: Thank you very much. Is there a way to also keep the original data in filtered data.frame?
Answer: We can use data.table as well to make it faster
library(data.table)
v <- c(9,11,33,43,44)
setDT(x)[x[, Reduce(`+`, lapply(.SD, function(x) x %in% v))==3 & V6 != 13, .SDcols = 1:5]]

Benchmarks
library(fastmatch)
system.time(setDT(x)[x[, Reduce(`+`, lapply(.SD, function(x) !is.na(fmatch(x, v))))==3
         & V6 != 13, .SDcols = 1:5]])
#   user  system elapsed
#   3.75    0.92    4.68


Date.js parsing an ISO 8601 UTC date incorrectly

Question: Using the javascript library Date.js I am finding that when i pass into the Date.parse() function an ISO 8601 formatted UTC 0 date I am getting an object that is representative of the same date but with the local time zone added.
For example,

Given the date: 2012-08-27T14:57:00Z (in ISO 8601 format), which is showing a time of 14:57 UTC, why would this be parsed as 14:57 GMT-400 as opposed to 10:57 GMT-400?

I have created a fiddle to show it in action.
Please let me know if there is in fact an error or if my understanding of the parsing result is incorrect.
Answer: Yep, it's a bug - even a reported one.
Might I recommend using Moment.js library instead? For example, this:
console.log(moment('2012-08-27T14:57:00Z').toString());
... will correctly recognize that UTC time is given.
Comment: After further review, it turns out developers should no longer be using Date.js (see this link https://plus.google.com/113127438179392830442/posts/htwWUqxHmUY). Good note to direct people to moment.
Comment: Why have I not come across Moment.js before, excellent library, good call @raina77ow :)
Answer: This seems like an error with Date.js.  Using new Date('2012-08-27T14:57:00Z') returns the correct date.
Comment: It turns out yes, it is a bug in Date.js. I do not see any new development since 2008, so I am assuming its never going to be fixed. Thanks for noting that it works with new Date(...), as that will be the fix I will use for the time being.
Answer: It's caused by a buggy implementation of DateJS's rather otherwise awesome grammar parser.
Basically the old version just checked to see if it could use the built in parser, the new version tries to use grammar parsing but forgets to try that original step first and the grammar parser fails to use the timezone (which is a bug, but a different one).
Replace the parse function with this one:
$D.parse = function (s) {
    var date, time, r = null;
    if (!s) {
        return null;
    }
    if (s instanceof Date) {
        return s;
    }

    date = new Date(Date._parse(s));
    time = date.getTime();
    // The following will be FALSE if time is NaN which happens if date is an Invalid Date
    // (yes, invalid dates are still date objects. Go figure.)
    if (time === time) {
        return date;
    } else {
        // try our grammar parser
        try {
            r = $D.Grammar.start.call({}, s.replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1"));
        } catch (e) {
            return null;
        }
        return ((r[1].length === 0) ? r[0] : null);
    }
};

Updated version of the core code (and will be fixing open bugs in the future) available here:
https://github.com/abritinthebay/datejs/


Image is not shown in the Xamarin XAML Designers Preview

Question: I'm in Xamarin Studio 6.1.1 on a Mac an try to design something with XAML in the Designer and wonder why labels are shown in the preview, but images are not.
If I run the project in the iOS-Simulator the image is shown.
This is my code:
<code><Image Source="images/bla_wifi.png" HorizontalOptions="LayoutOptions.FillAndExpand" VerticalOptions="LayoutOptions.FillAndExpand" Margin="70,70,70,0"/>
<Label HorizontalOptions="Center" XAlign="Center">
    <Label.Text>
Are you connected to the
WiFi?
    </Label.Text>
</Label>
</code>
Any idea what I can do to see the image in the preview?
Answer: I am having the same problem but with Visual Studio. So far the only suggestion I can give is to re-build the solution (it helps sometimes) and also mentally keep treating the Forms Viewer as experimental.