How to have my house inspected for mold?

Question: I recently did a Google search for mold inspection and felt a bit overwhelmed by the results and conflicting advice.
I am asking because I am chronically ill and have recently been diagnosed with severe mold allergies.  I just started a five year allergy immunotherapy program, but I'd like to know what I can do right now in order to reduce my exposure to environmental allergens.  Nasal sprays help enormously, but I'm constantly suffering with fatigue, malaise, and now I'm getting a flaring up of tinnitus on one side, too.
It may or may not be relevant to point out that I have lived in my home for four years, it was built in 1982, and the previous occupant of the home was an elderly man who only did work on the house if it was absolutely broken.
By my Google search, I found that there are two routes I can go.  One way is to get a home test kit.  The ones I've seen only test suspect surfaces.  Critics say that these kits are useless and I'm inclined to agree because I'm concerned about what I am actually breathing.  (I have a gut feeling that it likely has to do with the ventilation downwind from the air filter, which does get changed regularly)
The other way is to call for a professional mold inspector.  This is even more confusing, with advice about inspectors advertising questionable credentials and charging a huge range of prices for services.  I have no idea how to tell who is a credible professional or how much I should expect to pay.
I also have no idea what to do with any test results.
I don't know what to do, but I want to get some actionable information.
Answer: I don't like the self test kits either. Part of what you are hiring a testing agency for is 1) knowing what to test, 2) knowing how to take a "clean" test, 3) interpreting the test results, and 4) giving an estimate for abatement.
1) There are agencies that specialize in mold and some specialize in asbestos. If you suspect mold, I'd ask for their resume and then verify it. They will know where and what to test. Make sure they are bonded (ask the name and phone number of their bonding agency) and if they have worked for a local public agency like the school district, city, water board, county, etc. is a plus.
2) The containers must be "clean" and a sufficient amount of the sample suitable to test. The test samples are sent to an independent testing lab and will test for what the testing agency requests. BTW, it might not be your home. It could be furniture, clothing, car seats, etc.
3) The lab does not interpret the results. The agency will give a range of "acceptable" results. There is good and bad mold... not all mold needs to be removed.
4) Each test will cost about $25 - $35 each, where I live. The report (interpretation) will cost about $500 - $1800 depending on the number of "positive" results. The testing agency will be able to give an estimate of the cost of abatement based on quantity and location.
GET EVERYTHING IN WRITING. Make sure they give a start date and end date.
Oh, btw, if the report comes back positive and you don't have 100% removed, you must include it your disclosure statement when you go to sell.


Firefox extension auto installation

Question: I'm creating a Firefox extension and I have a folder with files of the extension. Every time I want to test in I have to zip it, change the extension to .xpi, drag&drop it to Firefox window, wait for 3 seconds, click install button and restart the browser.
I've made a batch file that zips the folder and changes the extension, but is it possible to reinstall it completely with the script, without drag&drop routine?
Answer: Edit (2017-06-25): As of Firefox 57, classic extensions (including Extension Auto-Installer mentioned below) will stop working. This means that your choices are now:

Go to about:debugging and load your extension as a temporary add-on. This will allow reloading it with a single click, whenever you make changes - either to a package or to an unpacked directory, both are possible.
Use the web-ext command line tool, it can install your extension as a temporary add-on from the command line. It can also watch extension files for changes and reload automatically.

Original answer for reference, will only work up to Firefox 56.
Actually, that's why I created Extension Auto-Installer a while ago. Install the extension in your test browser and add the following to your batch script:
wget --post-file=extension.xpi http://localhost:8888/

This will automatically install your extension in the browser and restart it if necessarily. If signing extensions is required, it will offer to install the extension as a temporary add-on, for the current browser session only.
As you seem to be using Windows, you will need Wget for Windows or a similar command line tool.
Comment: I had to go to `about:config` and change the value of `xpinstall.signatures.required` to `false` before this solution could work. Another option was to sign the xpi using the [jpm sign](https://developer.mozilla.org/en-US/Add-ons/SDK/Tools/jpm#jpm_sign) command.
Answer: I know this question already has an accepted answer, but:
You don't necessarily have to do that.

Open up Help menu.
Select Troubleshooting Information
Find Profile Folder and click on Show Folder button next to it. This will open your Firefox profile folder.
In the extensions folder, create a new folder with your extension ID or name. (Like this: {8956a28d-xxxx-xxxx-xxxx-xxxxxxxxxxxx})
Just edit your extension files, and restart the browser. Changes will take effect in no time!

Note: First time you run Firefox after this implicit installation, you'll be asked to allow this installation; just allow it.
P.S. It's a good idea to have the Extension Developer add-on; it'll make things easy (For instance, restarting Firefox with one click).
Comment: Yes, you don't need to reinstall - but you still have to restart the browser, something that is normally unnecessary with a restartless extension. And you will be fighting various browser caches. And you will get pretty inconsistent results if you edit the files while the browser is still running. I used that approach myself but got pretty annoyed by the issues and created Extension Auto-Installer.
Comment: Restarting Firefox all the time gets pretty tiresome very soon if you are working on a restartless extension.
Comment: @WladimirPalant: Instead, you don't have to reinstall the component at all! I've used this method and it was pretty cool! (with *Extension Developer* it was even better)

Firefox extension auto installation


Need RegEx to remove all alphabets from string

Question: I need a regex to move all alphabets from string (A-Z) and (a-z)..everything including any kind of special character should remain intact. I tried @"[^\d]" but it only returns numbers in string.
String : asd!@# $%dfdf4545D jasjkd #(*)jdjd56

desired output : !@# $%4545 #(*)56

Answer: Just replace all undesired characters with an empty string sequence:
string filtered = Regex.Replace(input, "[A-Za-z]", "");

Answer: Try the following regular expression:
[^a-zA-Z]

This will match all non-english letters.


Windows Service how to slow down infinite loop

Question: The way I was told to make windows services is as followed:
Thread serviceThread = new Thread(new Thread(runProc())
Boolean isRunning = true;

if (_isRunning)
   {
      serviceThread.Start();
   }else
      close and log service

void runProc()
{
   while(_isRunning)
   {
      //Service tasks
   }

   _isRunning = false;
}

This has worked fine for me so far but now I need to make a service that has big breaks in it, up to 2 hours at a time. Also I have started using timers so nothing is being done in the infinite loop other than stopping runProc() running over and over again which I can imagine is bad because threads are being made and remade a lot.
My question is, I have read that it is bad practice to put Thread.Sleep(big number) in that while(_isRunning) infinite loop, is this true? If this is the case, how do I get around the loop running constantly and using loads of resource? There is literally nothing being done in the loop right now, it is all handled in the tickevent of my timer,  the only reason I have a loop is to stop runProc ending.
Thanks a lot an sorry if I explain myself badly
Comment: Is that `runProc` only method to set `_isRunning` to false? If yes this is infinite loop
Comment: Where to you see indications that Thread.Sleep(big number) in that loop is bad practice?
Comment: Hey BlueMonk, something about it causing different things to stop and also it not being accurate?
Answer: Thread.Sleep is bad because it cannot be (easily) interrupted1.
I generally prefer to use a ManualResetEvent or similar:
class abc {
  Thread serviceThread = new Thread(new Thread(runProc())
  ManualResetEvent abort = new ManualResetEvent(false);

  void Start(){
      serviceThread.Start();
  }
  void Stop(){
     abort.Set();
     serviceThread.Join();
  }
  void runProc()
  {
     while(!abort.WaitOne(delay))
     {
      //Service tasks
     }
  }
}

Hopefully you get the gist, not a great code sample.
The delay can be as large or small as you want (and can be arbitrarily recomputed during each loop). The WaitOne call will either delay the progress of this thread for delay milliseconds or, if Stop is called, will cause the loop to exit immediately.

1To summarize my position from the comments below - it can only be interrupted by blunt tools like Thread.Abort or Thread.Interrupt which both share the failing (to a greater or lesser extent) that they can also introduce their associated exceptions at various other places in your code. If you can guarantee that the thread is actually inside the Thread.Sleep call then the latter may be okay - but if you can make such a guarantee, you can also usually arrange to use a less blunt inter-thread communication mechanism - such as the one I've suggested in this answer.
Comment: I've never had problems waking threads with an ``Interrupt()`` call. The interrupted thread just needs to catch the appropriate exception and exit its main loop.
Comment: @acfrancis - it's less dangerous than `Thread.Abort`, but not by much in my view - note that you've got no idea *what* specifically has caused the thread to enter the **WaitSleepJoin** state - among other things, it may be waiting for a lock - well, you better have architected your code to grab *all* locks before it perturbs any shared state or you may have issues.
Comment: I have a feeling we write very different code in our services. If one of my threads gets interrupted, it'll either quit (if the service's stopping) or catch the exception, log it and iterate the loop again to perform the next unit of work available. That's always worked well for me.
Comment: @acfrancis - my issue is that `Thread.Sleep` isn't the *only* place where the `ThreadInterruptedException` might suddenly get thrown - I'd rather use a reliable form of inter-thread communication where I indicate "at *this* piece of code, I'll respond to a *specific* signal (or set of signals)"
Answer: I've always written services with a main infinite loop, not timers. Inside the loop, I check to see if there's any work to do, if so I do the work, if not I call Thread.Sleep(). That means that as long as there's work to be done, the loop will keep iterating, running as fast as it can. When the queue of work "dries up", it sleeps a little (a few seconds or minutes) while more work becomes available.
That's always worked really well for back-end jobs on a server where there's a constant stream of new work to be done throughout the day (and night). If you have big periods with no work the service will wake many times to check and then go back to sleep. You might like that or not. As long as the check is quick, it shouldn't be an issue. An alternative is to use a scheduled task (or database job) so that you know that work will be completed at specific times throughout the day. That's a better approach in some cases.
Comment: This is how I have designed all my previous services but it just seems like an overkill for a service that I know only has to check every 1h45m. I am currently looking into scheduled tasks, so thanks for that!
Comment: Agreed, I would consider a scheduled task in that case. But, of course, the devil is in the details.


Is it possible to allow didSet to be called during initialization in Swift?

Question:  Question
Apple's docs specify that:

willSet and didSet observers are not called when a property is first initialized. They are only called when the property's value is set outside of an initialization context.

Is it possible to force these to be called during initialization?
Why?
Let's say I have this class
class SomeClass {
    var someProperty: AnyObject {
        didSet {
            doStuff()
        }
    }

    init(someProperty: AnyObject) {
        self.someProperty = someProperty
        doStuff()
    }

    func doStuff() {
        // do stuff now that someProperty is set
    }
}

I created the method doStuff, to make the processing calls more concise, but I'd rather just process the property within the didSet function.  Is there a way to force this to call during initialization?
 Update
I decided to just remove the convenience intializer for my class and force you to set the property after initialization.  This allows me to know didSet will always be called.  I haven't decided if this is better overall, but it suits my situation well.
Comment: If you want to use the convenience initializer, you can combine it with `defer`:
`convenience init(someProperty: AnyObject) {
  self.init()
  defer {
    self.someProperty = someProperty
  }
`
Comment: it is honestly best just to "accept this is how swift works".  if you put an inline initialization value on the var statement, of course that does not call "didSet".  that's why the "init()" situation must also not call "didSet".  it all makes sense.
Comment: @Logan The question itself answered my question ;) thanks!
Answer: If you use defer inside of an initializer, for updating any optional properties or further updating non-optional properties that you've already initialized and after you've called any super.init() methods, then your willSet, didSet, etc. will be called.  I find this to be more convenient than implementing separate methods that you have to keep track of calling in the right places.
For example:
public class MyNewType: NSObject {

    public var myRequiredField:Int

    public var myOptionalField:Float? {
        willSet {
            if let newValue = newValue {
                print("I'm going to change to \(newValue)")
            }
        }
        didSet {
            if let myOptionalField = self.myOptionalField {
                print("Now I'm \(myOptionalField)")
            }
        }
    }

    override public init() {
        self.myRequiredField = 1

        super.init()

        // Non-defered
        self.myOptionalField = 6.28

        // Defered
        defer {
            self.myOptionalField = 3.14
        }
    }
}

Will yield:
I'm going to change to 3.14
Now I'm 3.14

Comment: Cheeky little trick, I like it... weird quirk of Swift though.
Comment: Great. You found another useful case of using `defer`. Thanks.
Comment: very interesting.. I've never seen defer used like this before. It's eloquent and works.
Comment: Great use of defer! Wish I could give you more than one upvote.
Comment: But you set myOptionalField twice which isn't great from performance perspective. What if heavy calculations takes place?
Comment: @YakivKovalsky agreed that there's a small amount of extra overhead with this design.  But, I think you'll just have to use some judgement there on the performance impact for your specific use case.  I would almost always use this on an optional field where the initial assignment is nil and requires no calculation.  So, there should, at least, not be wasted calculation.
Comment: JUST AMAZING, THANKS
Comment: can't argue with that!  nice!
Comment: This only works for classes, not structs.
Answer: Create an own set-Method and use it within your init-Method:
class SomeClass {
    var someProperty: AnyObject! {
        didSet {
            //do some Stuff
        }
    }

    init(someProperty: AnyObject) {
        setSomeProperty(someProperty)
    }

    func setSomeProperty(newValue:AnyObject) {
        self.someProperty = newValue
    }
}

By declaring someProperty as type: AnyObject! (an implicitly
  unwrapped optional), you allow self to fully initialize without
  someProperty being set. When you call
  setSomeProperty(someProperty) you're calling an equivalent of
  self.setSomeProperty(someProperty). Normally you wouldn't be able to
  do this because self hasn't been fully initialized. Since
  someProperty doesn't require initialization and you are calling a
  method dependent on self, Swift leaves the initialization context and
  didSet will run.
Comment: I think I know what's happening here. By declaring `someProperty` as type: `AnyObject!` (an implicitly unwrapped optional), you allow `self` to fully initialize without `someProperty` being set.  When you call `setSomeProperty(someProperty)` you're calling an equivalent of `self.setSomeProperty(someProperty)`.  Normally you wouldn't be able to do this because `self` hasn't been fully initialized.  Since `someProperty` doesn't require initialization and you are calling a method dependent on `self`, Swift leaves the initialization context and `didSet` will run.
Comment: @Mark seriously, trying to apply common sense or  logic to Swift is just absurd. But you can trust the upvotes or try it yourself. I just did and it works. And yes, it makes no sense at all.
Comment: Why would this differ from self.someProperty = newValue in the init? Have you got a working test case?
Comment: It looks like anything that is set outside of the actual init() DOES get didSet called. Literally anything that is not set `init() { *HERE* }` will have didSet called. Great for this question but using a secondary function to set some values leads to didSet being called. Not great if you want to reuse that setter function.
Comment: Don't know why it works -- but it does. Directly setting the new value within the init()-Method doesn't call didSet() -- but using the given Method setSomeProperty() does.
Comment: This isn't horrible.  Since the `setSomeProperty()` method is only used as a work-around for what can't be done in `init()`, you could just as well name it `lateInit()` or `start()` or `begin()` or `ignition()` and just use that for any post-member-value-initialization stuff you want to run when the object is created.
Comment: @Logan is correct. You can test out his theory for yourself by trying to set a non-optional property after calling the method. It won't work since you need to initialize all properties before you can use self.
Comment: @Logan Your observation is *almost* correct. Whenever you have `var x : String?` then automatically `x` **is** set to `nil` (same **isn't** true if you used `let` instead of `var`). Same is true for `var x : String!`. The only difference is this time if you access *when* it's `nil` you will crash. If you don't access it, it doesn't mean that it's value isn't set. It means it's `nil` but you're not messing with it to create an error. For more see [here](https://stackoverflow.com/questions/27797351/class-has-no-initializers-swift/40769917#40769917). Make sure you see the links at the end.
Comment: @Logan You can always 'initialize' a class with implicitly unwrapped optionals. What you can't do is access them safely. You can only access them after it's value is changed from `nil` to a non-nil value. FWIW it having a value of `nil` doesn't mean it's not set. It **is** set, but set to `nil`.
Comment: This doesn't seem to work in latest version of Xcode and Swift
Answer: As a variation of Oliver's answer, you could wrap the lines in a closure. Eg:
class Classy {

    var foo: Int! { didSet { doStuff() } }

    init( foo: Int ) {
        // closure invokes didSet
        ({ self.foo = foo })()
    }

}

Edit: Brian Westphal's answer is nicer imho. The nice thing about his is that it hints at the intent.
Comment: Clever answer! One note: if your class is a subclass of something else, you will need to call super.init() before ({ self.foo = foo })()
Comment: That's clever and does not pollute the class with redundant methods.
Comment: @Hlung, I don't get a feeling it's more likely to break in future than anything else, but there is still the problem that without commenting the code it's not very clear what it does. At least Brian's "defer" answer gives the reader a hint that we want to perform the code after initialization.
Comment: Great answer, thanks! Worth noting that in Swift 2.2 you need to wrap the closure in parentheses always.
Comment: @Max Cheers, the sample include parens now
Answer: I had the same problem and this works for me
class SomeClass {
    var someProperty: AnyObject {
        didSet {
            doStuff()
        }
    }

    init(someProperty: AnyObject) {
        defer { self.someProperty = someProperty }
    }

    func doStuff() {
        // do stuff now that someProperty is set
    }
}

Comment: This approach no longer works. The compiler throws two errors:
– 'self' used in method call '$defer' before all stored properties are initialized
– Return from initializer without initializing all stored properties
Comment: You're right but there's a workaround. You only need to declare someProperty as implicit unwrapped or optional and supply it will a default value with nil coalescing  to avoid failures.

tldr; someProperty must be an optional type
Comment: where did you get it?
Answer: This works if you do this in a subclass
class Base {

  var someProperty: AnyObject {
    didSet {
      doStuff()
    }
  }

  required init() {
    someProperty = "hello"
  }

  func doStuff() {
    print(someProperty)
  }
}

class SomeClass: Base {

  required init() {
    super.init()

    someProperty = "hello"
  }
}

let a = Base()
let b = SomeClass()

In a example, didSet is not triggered. But in b example, didSet is triggered, because it is in the subclass. It has to do something with what initialization context really means, in this case the superclass did care about that
Comment: Hi @onmyway133
swift being a type safe language always fully initialized a type else not.
When you initialized someClass. Base class being fully initialized and then in SomeClass you are setting someProperty = "hello".
Hence didSet being called
Answer: While this isn't a solution, an alternative way of going about it would be using a class constructor:
class SomeClass {
    var someProperty: AnyObject {
        didSet {
            // do stuff
        }
    }

    class func createInstance(someProperty: AnyObject) -> SomeClass {
        let instance = SomeClass()
        instance.someProperty = someProperty
        return instance
    }
}

Comment: This solution would require you to change the optionality of `someProperty` since it won't have given it a value during initialization.
Answer: In the particular case where you want to invoke willSet or didSet inside init for a property available in your superclass, you can simply assign your super property directly:
override init(frame: CGRect) {
    super.init(frame: frame)
    // this will call `willSet` and `didSet`
    someProperty = super.someProperty
}

Note that Charlesism solution with a closure would always work too in that case. So my solution is just an alternative.
Answer: unfortunately, didSet observers aren't called when a root class is initialized.
If your class isn't a subclass, you have to use getters and setters to achieve the functionality you want:
class SomeClass {
    private var _test: Int = 0
    var test: Int {
        get { _test }
        set { _test = newValue }
    }

    init(test: Int) { self.test = test }
}

alternatively, if your class is a subclass, you can use didSet and do:
override init(test: int) {
    super.init()
    self.test = test
}

The didSet SHOULD get called after super.init() is called.
One thing I have not tried but MIGHT also work:
init(test: int) {
    defer { self.test = test }
}

NOTE: you will need to make your properties nullable, or set a default value for them, or unwrap the class properties.
Answer: You can solve it in obj-с way:
class SomeClass {
    private var _someProperty: AnyObject!
    var someProperty: AnyObject{
        get{
            return _someProperty
        }
        set{
            _someProperty = newValue
            doStuff()
        }
    }
    init(someProperty: AnyObject) {
        self.someProperty = someProperty
        doStuff()
    }

    func doStuff() {
        // do stuff now that someProperty is set
    }
}

Comment: Hi @yshilov, I don't think this really solves the problem I was hoping to since technically, when you call `self.someProperty` you're leaving initialization scope.  I believe the same thing could be accomplished by doing `var someProperty: AnyObject! = nil { didSet { ... } }`.  Still, some might appreciate it as a work around, thanks for the addition
Comment: @Logan nope, that will not work. didSet will be completely ignored in init().


Sum of even in Scheme

Question: This is my first experience with Scheme. I have a list with integers and I wanna get the sum of all even number in list.
<code> ; sum_even
(define (sum_even l)
  (if (null? l) l
  (cond ((even? (car l)) 0)
        ((not(even? (car l))) (car l)))
  (+ (sum_even (car l) (sum_even(cdr l))))))
(sum_even '(2 3 4))
</code>
Comment: So what exactly do you want to do? Get the sum of all even numbers in the list or get the sum of all even indices?
Comment: the sum of the even numbers. (sum_even '(2 3 4 6)) = 12
Answer: <code>(define (sum_even l)
    (cond ((null? l) 0)
          ((even? (car l)) (+ (car l) (sum_even (cdr l))))
          (else (sum_even (cdr l)))))
</code>
Not tested
Answer: You're not exactly asking a question. Are you checking if your solution is correct or looking for an alternate solution?
You can also implement it as follows via
<code>(apply + (filter even? lst))
</code>
edit: If, as you mentioned, you can't use filter, this solution will work and is tail-recursive:
<code>(define (sum-even lst)
    (let loop ((only-evens lst) (sum 0))
        (cond
            ((null? only-evens) sum)
            ((even? (car only-evens))
             (loop (cdr only-evens) (+ (car only-evens) sum)))
            (else (loop (cdr only-evens) sum)))))
</code>
Comment: thank you for the answer, but I should solve this problem without filter function
Comment: Thank you again. I prefer simple solutions. Lambda and let expression make me nervous, especially for simple tasks. Wish you all the best ; )
Answer: <code>(define (sum-even xs)
  (foldl (lambda (e acc)
           (if (even? e)
               (+ e acc)
               acc))
         0
         xs))
</code>
Example:
<code>> (sum-even (list 1 2 3 4 5 6 6))
18
</code>
Answer: Here is another one with higher order functions and no explicit recursion:
<code>(use srfi-1)

(define (sum-even ls) (fold + 0 (filter even? ls)))
</code>
Comment: O(2n) ist still O(n). Yes there is a intermediate list created. But this list could be eliminated by the compiler: http://en.wikipedia.org/wiki/Deforestation_(computer_science) . I do not know if any compiler for scheme does this automatically. Another version without intermediate lists looks like: (define (sum-list ls) (fold (lambda(x a) (if (even? x) (+ x a) x)) 0 ls))
Comment: I think that is slower than just `foldl`, because you create a new list with `filter`, then fold it, reading every element once again.
Answer: Consider using the built-in filter function. For example:
<code>(filter even? l)
</code>
will return a list of even numbers in the list l. There are lots of ways to sum numbers in a list (example taken from http://groups.engin.umd.umich.edu/CIS/course.des/cis400/scheme/listsum.htm):
<code>;
; List Sum
; By Jerry Smith
;
(define (list-sum lst)
   (cond
     ((null? lst)
       0)
     ((pair? (car lst))
      (+(list-sum (car lst)) (list-sum (cdr lst))))
     (else
       (+ (car lst) (list-sum (cdr lst))))))
</code>
Comment: Yes, this should be atom sum? Thank you for solution!

Sum of even in Scheme


What is the purpose of these small unaligned studs for building a precut chest of drawers?

Question: I was working on building this drawer by FOTOSOK I had ordered from amazon.
and in the instruction booklet on page 11 step 12 there is a mysterious step which I don't understand the purpose of. I have attached a photo below:

Basically it involves adding 4 small plastic studs (photo below) to the back of the drawer.

The instructions don't appear to indicate any clear lines/landmarks to align the studs to. And they never get mentioned later in the manual after insertion. It seems I can skip this step without affecting any other steps so I want to know what exactly is the purpose of this. Is it just some kind of reinforcement? Is there some obvious alignment of the pegs that I have missed?
Edit, the image (1) is the "back" of the entire built dresser. The studs are inserted into a flat panel that is the back of the dresser. The studs don't have a name in the parts list.
Comment: Given the direction of the screws on the drawing (parallel to the back panel), they're 100% meant to attach to the *frame*, not the panel.
Comment: So there is a flimsy panel, and these studs are attached to that flimsy panel. the more I think about it, it seems likely they make it difficult for the flimsy panel to bend more than a few mm before the studs ram into wall that the dresser would be placed along.
Comment: Maybe these prevent you from pushing the drawers out the back? Or if there is a solid panel (but flimsy, as is often the case) added on the back later, maybe this keeps the drawers from bumping into it.
Comment: Is there a parts list at the beginning of the instructions?  If so it might include a name for those pieces, which might be helpful in understanding their purpose.
Comment: Yes there is but it doesn't have a name. Just an image of a stud and 12 + 1 underneath indicating 12 copies + 1 extra
Comment: I'll attach images once near a computer since they need to be compressed under 2.5mb to be attached to posts
Answer: These are clips that prevent the thin material that is slid into the groove from coming out and provides more support for the panel and to prevent racking.
The thin plastic goes in the groove behind the panel and screws into place. Press the piece into the general area depicted and then screw it into the wood sides/top/bottom (NOT the panel).
After some searching, the proper name seems to be "45 Degrees Angle Wedge Bracket Retaining Clip"
Comment: It might not be clear that the screw that goes through this part then goes into the carcass at 45 degrees, rather than perpendicular.
Comment: The purpose is to clamp the back panel in place and stop it from moving.  With these clips clamping the back panel, it prevents the dresser from racking/twisting.  These are quite important for the structure of the cabinet.
Comment: @JPhi1618 I hadn't considered it for racking prevention, but that totally makes sense. The 45 degree screw goes through the edge of the panel an into the wood to lock it together.
Comment: Odd... Usually the back panel (often just heavy card stock) is nailed to the back. These clips and screws must cost quite a bit more than the handful of nails usually provided.
Comment: @FreeMan The nail on panels are difficult to install and error prone (nails not straight), and with IKEA's return policy for people near their stores, that could be an high cost for them.  IKEA is cheap, but they really do make an effort for their furniture to be easy to assemble and as durable as possible considering the materials.
Comment: They give you a little plastic clip to hold the nail, @JPhi1618, how hard can it be? Oh, wait, never mind... :(


submit form and store data in database using tapestry

Question: I have been praticing tapestry for form submission and submitting data into database using hibernate.
I am referring below two links for it.
https://tapestry.apache.org/using-beaneditform-to-create-user-forms.html
https://tapestry.apache.org/using-tapestry-with-hibernate.html

But making form in these links is given using beaneditform component.
But I don't want  to use beaneditform and just make a normal html/tml submit form and store data to database. How can I do it? Please help.
Answer: Main reference page for Tapestry Forms & Validation can be found here: https://tapestry.apache.org/forms-and-validation.html
Use t:Form, t:TextField, and other form components if you need finer control of your form elements & layout.
BeanEditForm is a helper component that allows quickly generate form for a given JavaBean. This component is just a mix of t:Form + t:BeanEditor.
You can also try one of the Jumpstart examples, i.e.:
http://jumpstart.doublenegative.com.au/jumpstart/examples/input/forms1
explanations for the above example are here:
http://jumpstart.doublenegative.com.au/jumpstart/examples/input/formsexplained1


How can I get data from XML [2 identical children and I want only 1 of them]?

Question: I have got XML file. This is his structure:
<data>
 <pos1>
 </pos1>
 <pos2>
 </pos2>
 .
 .
 .
 <pos3>
   <pos1>
   </pos1>
 </pos3>
</data>

I want only first data from <pos1>. If I use $xml->getElementsByTagName('pos1') I received all data.
Is it better way than get all elements from data and then search pos1?
Comment: One of them is in `data`, other one is nested in ``.
Comment: I can do this, but I have got hundreds of XML files and not always `` is on first place.
Comment: Then how you choose between the two if it isn't by position? What's the criteria?
Answer: You can try using DOMXPath::query() :
$xpath = new DOMXPath($yourDomDocument);
$nodes = $xpath->query('//data/pos1');

Above xpath query only return <pos1> that is child of <data>.


From barycentric to cartesian

Question: I have the following function to convert a point on the same plane as a triangle into a barycentric point.
<code>// p0, p1 and p2  and the points that make up this triangle
Vector3d Tri::barycentric(Vector3d p) {
    double triArea = (p1 - p0).cross(p2 - p0).norm() * 0.5;
    double u = ((p1 - p).cross(p2 - p).norm() * 0.5) / triArea;
    double v = ((p0 - p).cross(p2 - p).norm() * 0.5) / triArea;
    double w = ((p0 - p).cross(p1 - p).norm() * 0.5) / triArea;
    return Vector3d(u,v,w);
}
</code>
How can I write the inverse of this operation? I would like to write a function that takes a barycentric coord and returns the cartesian point.
Answer: The cartesian coordinates of a point can be calculated as a linear combination with barycentric coordinates as coefficients:
<code>Vector3d Tri::cartesian(const Vector3d& barycentric) const
{
      return barycentric.x * p0 + barycentric.y * p1 + barycentric.z * p2;
}
</code>

From barycentric to cartesian


Powershell: how to stream, paginate text from very large files?

Question: I've got some huge log files that I need to view. I don't want to attempt to open them up in an editor, and I'd like to be able to scroll through them in a paginated manner. It seems as if there is an alias for more in powershell but piping to it doesn't do anything and get-help yields only "more."
This seems to me like a totally silly question, but I haven't figured it out yet--how can I get something similar to the unix more command?
Answer: Try the Out-Host cmdlet:
Get-Content file.txt | Out-Host -Paging

Answer: This is one way:
get-content file | out-host -Paging


How to bind booleans in JTable with JGoodies

Question: I have seven boolean values in a column of a JTable that I want to bind to my bean.
How do I bind them?
All the JTable binding examples out there focus on binding the table selection, but I only care about what the values of those booleans are.
Comment: don't quite understand - those booleans are on different beans (aka: rows)? If so, bind to the bean/s directly ...
Comment: do you mean seven different boolean values in a row or in a column. If its in a row, you can define a bean with seven boolean attribute and bind each attribute to each column.If its column, i am not sure what it means. Basic thing is each row would represent a bean. So seven different boolean values on column means seven different beans  .
Comment: JTables store values as Object so, regardless of being boolean values you can bind them the same way you bind any other value type
Answer: You need to implement your own data model. I give you simplified example that shows idea of usage. Take a look at getColumnClass method.
Usage: table.setModel(new DataModel(myData));
class DataModel extends AbstractTableModel
{

    public DataModel(Object yourData){
         //some code here
    }

    @Override
    public int getRowCount() {
        return yourData.rows;
    }

    @Override
    public int getColumnCount() {
        return yourData.colums;
    }

    @Override
    public Class<?> getColumnClass(int col) {
        if (col == myBooleanColumn) {
            return Boolean.class;
        } else {
            return null;
        }
    }

    @Override
    public boolean isCellEditable(int row, int col)
    {
        return col >= 0;
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {

        return yourData.get(rowIndex,columnIndex);
    }

    @Override
    public void setValueAt(Object aValue, int row, int col) {

    yourData.set(aValue,row,col)

        this.fireTableCellUpdated(row, col);
    }
}

Hope this helps.


Replace GFCI in bathroom

Question: When I opened up the old one, there are 3 cables with the normal 2 black, 2 white, and ground.  However, there are 2 whites and black capped together to a load screw and another white on the other load screw, and on the line side, there are 2 blacks attached to 1 screw, and 1 black to the other.  The GFCI won't reset.  Can I piggyback the 2 blacks that are attached to 1 screw?  I've never seen anything like that before.  Electricity is not my forte, but I have replaced outlets before.
Comment: Can you attach a picture?
Comment: Are you describing the wiring on the old receptacle, or how you have wired it?
Comment: black and white connected together is a flag usually (there are exceptions though)
Comment: 2 black in the same assembly? That's not really "normal". There's usually a different color (red) or if there's duplicate colors they're distinguishable.
Answer: A white wire connected to a hot can be seen on switched hots. A good electrician will often add a piece of black tape to indicate this, but that often doesn't happen.
When connecting wires to screws on outlets, you only want one wire per screw. If you need to attach multiple wires and don't have enough locations to screw them on, then pig tail them together with a short piece of wire, secure and cover with a wire nut, and connect the short piece of wire to the outlet.
To resolve the GFCI not resetting, disconnect everything except the line connections. Verify the GFCI is working properly. Then connect each load one at a time until you locate the fault. You'll need to trace these lines or identify what isn't working when disconnected and inspect every junction to locate the problem with that line. If you don't feel comfortable with this, then I recommend hiring a professional electrician. As always with electrical, do not work on live wires and use a voltage tester, preferably non-contact, to check all wiring before you touch it.
Answer: It is definitely abnormal for a white and black to be connected. I wonder if what you mean is that the two whites are connected with a wire nut to a black pigtail connected to the load side, which while improper, makes sense. We need a picture. In any event, don't connect multiple wires to one screw -- use a wire nut.

Replace GFCI in bathroom


debug/optimize java application

Question: Is there any optimized and debug mode for a java code? Using GCC, it is possible to add debug symbols via -g -ggdb to the binary for debugging purposes and remove them by adding -O option to maximize the speed.
What about Java? I am using Maven (pom.xml). I can not find such option for Java
Comment: I don't understand the question. Java code can be debugged through any java debugging tool. And the JVM handles optimizations and whatnot. You'll have to elaborate.
Answer: Java compiler options can be specified in the Maven Compiler Plugin.
Example: excluding debug information, enabling optimization:
  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>2.4</version>
    <configuration>
      <debug>false</debug>
      <debuglevel>none</debuglevel>
      <optimize>true</optimize>
    </configuration>
  </plugin>

A complete list of configuration options can be found here.
Comment: OK I see `false` and `true`.
Comment: The -o option in gcc enables compile-time optimizations (http://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html). For Maven, this corresponds to the  option. Java has less optimization options at compile time (such as inlining), but can optimize itself at runtime (Just-in-time compiler).
Comment: In each folder, there is a pom.xml file. Should I add `false` in all of them or just the root folder?

debug/optimize java application


vb net button do two things

Question: i want my button to color the other buttons And different color the other buttons when it is clicked again(2nd time).... I am trying this code. Please Help me....
Private Sub Button1_MouseClick(sender As Object, e As MouseEventArgs) Handles Button1.MouseClick
    Dim visit As Integer = e.Clicks
    visit = 0
    If (visit = 1) Then
        Button2.BackColor = Color.BlueViolet
        Button3.BackColor = Color.Aqua
    ElseIf (visit > 1) Then
        Button2.BackColor = Color.Brown
        Button3.BackColor = Color.Bisque
    End If
    visit += 1
End Sub

Comment: Pull `Dim visit As Integer` outside to the class and you will be fine. Don't use `e.Clicks`
Comment: Why are you using MouseClick rather than ButtonClick?  If want White, use White, not those other colors.  And learn about variable Scope
Comment: try using boolean values, (instead of 1 and 0). it will also allow 'toggling' if required.
Answer: e.Clicks doesn't do what you think it does.  It's not tracking the total clicks over the lifetime of the form, just for that one event.  And since visit is re-initialized in the scope of the event handler as well, it's always going to re-start for every event.
Track the total clicks outside of that scope.  Something like this:
Dim visit as Integer = 0;

Private Sub Button1_MouseClick(sender As Object, e As MouseEventArgs) Handles Button1.MouseClick

    visit += 1

    If (visit = 1) Then
        Button2.BackColor = Color.BlueViolet
        Button3.BackColor = Color.Aqua
    ElseIf (visit > 1) Then
        Button2.BackColor = Color.Brown
        Button3.BackColor = Color.Bisque
    End If

End Sub

As long as the class remains in scope, visit will continue to increment with each event.  If the class itself is also falling out of scope (such as on a web form) then you'd need to persist visit in an even higher scope, potentially even outside the application state itself.
It's also not entirely clear the logic you're trying to express here.  After the first click, that ElseIf condition will always be true.  Are you just looking to toggle between true/false values instead of incrementing an integer?  Something like this?:
Dim visit as Boolean = False;

Private Sub Button1_MouseClick(sender As Object, e As MouseEventArgs) Handles Button1.MouseClick

    visit = Not visit

    If (visit = True) Then
        Button2.BackColor = Color.BlueViolet
        Button3.BackColor = Color.Aqua
    Else
        Button2.BackColor = Color.Brown
        Button3.BackColor = Color.Bisque
    End If

End Sub

Comment: Thanx my dear its realy working...
Answer: An other option is to set your variable as Static. This will keep it's value in memory in between method call.
Private Sub Button1_MouseClick(sender As Object, e As MouseEventArgs) Handles Button1.MouseClick
    Static visit As Integer = 0

    visit += 1

    If (visit = 1) Then
        Button2.BackColor = Color.BlueViolet
        Button3.BackColor = Color.Aqua
    ElseIf (visit > 1) Then
        Button2.BackColor = Color.Brown
        Button3.BackColor = Color.Bisque
    End If

End Sub

Comment: Thanx my dear its realy working...
Answer:  Dim visit As Integer = 0;
 Private Sub Button1_MouseClick(sender As Object, e As MouseEventArgs) Handles Button1.MouseClick

    If (visit = 0) Then
       Button2.BackColor = Color.BlueViolet
       Button3.BackColor = Color.Aqua
       visit = 1
    ElseIf (visit = 1) Then
       Button2.BackColor = Color.Brown
       Button3.BackColor = Color.Bisque
       visit = 0
    End If

 End Sub

Comment: Thanx my dear its realy working...
Answer: This will alternate the colour of button2 based on a boolean flag
Dim PrevClicked As Boolean = False
Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
    If PrevClicked = False Then
        Button2.BackColor = Color.Black
        PrevClicked = True
    Else
        Button2.BackColor = Color.White
        PrevClicked = False
    End If
End Sub

Comment: Thanx my dear its realy working...

vb net button do two things


Text Replacement in MS Word

Question: In my MS-Word template, my client sends template with an error in the header section, as below,
VERMONT, ROBIN S.       Date:  10/21/2017
File No:  312335        DOB:  05/02/1967Claim#:   RE155B53452
DOI:   06/21/2017
The error being the 'Claim#' coming up right next to the DOB value, while it should come on the next line, as below:
VERMONT, ROBIN S.       Date:  10/21/2017
File No:  312335        DOB:  05/02/1967
Claim#:   RE155B53452       DOI:   06/21/2017
Also, this error comes up occasionally in some files and not all, so to solve it, I created a word macro, as below:
Sub ShiftClaimNumber2NextLine()

  Dim rngStory As Word.Range
  Dim lngJunk As Long
  'Fix the skipped blank Header/Footer problem as provided by Peter Hewett
  lngJunk = ActiveDocument.Sections(1).Headers(1).Range.StoryType
  'Iterate through all story types in the current document
  For Each rngStory In ActiveDocument.StoryRanges
    'Iterate through all linked stories
    Do
      With rngStory.Find
        .text = "Claim#:"
        .Replacement.text = "^pClaim#:"
        .Wrap = wdFindContinue
        .Execute Replace:=wdReplaceAll
      End With
      'Get next linked story (if any)
      Set rngStory = rngStory.NextStoryRange
    Loop Until rngStory Is Nothing
  Next

End Sub

And I run the above macro through a Group Macro, as below:
Sub ProcessAllDocumentsInFolder()

Dim file
Dim path As String

' Path to folder
path = "D:\Test\"
file = Dir(path & "*.doc")
Do While file <> ""
Documents.Open FileName:=path & file

' Call the macro to run on each file in the folder
Call ShiftClaimNumber2NextLine

' Saves the file
ActiveDocument.Save
ActiveDocument.Close

' set file to next in Dir
file = Dir()
Loop

End Sub

When I run the macro ProcessAllDocumentsInFolder(), for all files with such an error, it shifts the 'Claim#' to the next line.
However, the problem is, it also does so for files that do not have such a problem, thereby adding one enter line below the DOB, as below (as depicted by the yellow line):

What changes should I make to my macro ShiftClaimNumber2NextLine() , so that it does not make any change to files which DO NOT HAVE the 'Claim#' problem ?
Answer: This is a situation best suited to regular expressions see below link for similar issue, refer vba solution
https://superuser.com/questions/846646/is-there-a-way-to-search-for-a-pattern-in-a-ms-word-document
Sub RegexReplace()

    Dim RegEx As Object
    Set RegEx = CreateObject("VBScript.RegExp")
    On Error Resume Next

    RegEx.Global = True
    RegEx.Pattern = "[0-9]Claim#:"
    ActiveDocument.Range = _
     RegEx.Replace(ActiveDocument.Range, "\rClaim#:")

End Sub

Text Replacement in MS Word


Error While Debugging

Question: I have one web application. while i debug the solution the rendering makes too slow and if i close the browser page i got one error like this
WebDev.WebServer.exe has encountered a problem and needs to close.  We are sorry for the inconvenience.
I got one information from attched proess is that this .exe file related to asp.net development server- port(port number).
How it can be resolved? please help me..
Answer: You cannot close the browser that opens when you are running debug for an ASP.NET program.
It renders slower because you are debugging it. This means the compiler has injected a lot of extra code need to make the application work with the debugger. There is no getting around this.

Error While Debugging


Boundary of the boundary of a manifold is empty

Question: As mentioned in the title, it's well know that boundary of the boundary of a manifold is empty. That is, if $M$ is the boundary of a manifold $N$, i.e. $M=\partial N$, then $M$ is a manifold without boundary, i.e. $\partial M=\varnothing$. For example, the sphere $S^n$ has no boundary because $S^n=\partial B^{n+1}$ where $B^{n+1}$ is the closed unit ball in $\mathbb{R}^{n+1}$. What I would like to ask is that: is there an easy proof or a short proof for this statement?
Comment: Of course I know that. However, since you have asked me "What definition of "boundary of a manifold" are you using?", I just quoted the definition which is available from wiki.
Comment: You should probably get a better reference... that blurb in Wikipedia is not exactly a piece of great exposition!
Comment: What definition of "boundary of a manifold" are you using?
Comment: Are there several definitions of "boundary of a manifold"? I didn't know that. But the one I am using is this: http://en.wikipedia.org/wiki/Manifold#Manifold_with_boundary
Answer: Let us define a (topological) $n$-manifold with boundary to be a (Hausdorff, second-countable) topological space $M$ locally homeomorphic to the closed half space $H$ in $\mathbb R^n$, and the boundary $\partial M$ of $M$ to be the subset of $M$ of points which do not have a neighborhood homeomorphic to an open set in $\mathbb R^n$.
Then:

show that the claim that $\partial\partial M=\emptyset$ follows from the observation that $\partial\partial H=\emptyset$;
show that $\partial\partial H=\emptyset$.
Comment: Yes, really. But I think it is better if *you* do it.
Comment: Oh really? Ok. Let's have a deal then. If you can write down the proof with all the details with less than, say 15 lines, I will accept your answer as what I required to be a short proof.
Comment: @Mariano: Can you give a hint as to how to proceed further?
Comment: I am afraid that's what I need. I know how to prove the statement by using definition as you have said. But it's not short if you  prove it rigorously by writting down all the details.
Comment: *What* is not short?
Comment: What you have given is just the idea of the proof. If you try to write down all the details of the proof, the proof is not short.
Comment: The first of my two bullets is almost immediate; the second one is a fast computation: first, that $\partial H$ is homeomorphic to $\mathbb R^{n-1}$, and that $\partial \mathbb R^{n-1}$ is empty.
Comment: (What is not trivial is that a point is *either* an interior point *or* a boundary point)


Hydronic boiler sharing 20A circuit

Question: I would like to connect my hydronic boiler to a 20A circuit already loaded by a microwave and a range hood. The label on the boiler says it draws LESS THAN 12A.

Does this run a risk of overloading the circuit?
Comment: Depending on size of microwave would say yes.  Microwave, boiler and range hood together will probably be enough over 20 amps to trip on same circuit.  Less than 12 amps sounds more like max you can use, compared to uses.
Comment: The risk is very high.   "Less than 12 amps" presumably means it might sometimes use up to 12 amps.  A typical microwave uses 8 or 9 amps.  A range hood uses more than zero.  If you have a very small microwave and range hood, there is a small chance you *won't* overload the circuit.   Also, I think your boiler is required to have a dedicated circuit, but I'll let others confirm that.
Answer: Can't do that.

NEC 422.12 – Central heating equipment other than fixed electric space-heating equipment shall be supplied by an individual branch
circuit.

Exception No. 1:  Auxiliary equipment, such as a pump, valve, humidifier, or electrostatic air cleaner directly associated with the heating equipment, shall be permitted to be connected to the same branch circuit.
Exception No. 2:  Permanently connected air-conditioning equipment
shall be permitted to be connected to the same branch circuit.

You need a dedicated circuit.
Depending on your LAHJ, you may also not be legally permited to install a boiler, period, unless you are licensed for that trade. Boiler mishaps are expensive in terms of dollars and lives, leading to considerable legislation applying to their installation.
Comment: okay, I have 2 15A circuits running through a JB nearby that I think I can integrate in one (lights and outlets only) and use one for the boiler
Answer: I'll stick my neck out here and provide another reason not to do what you want.
The other answers note correctly that your boiler must be on a dedicated circuit, and that 12 + anything is a lot.
But.
Why would a gas boiler use 12A?  Makes no sense.  I propose it doesn't.  The power consumption of a gas hot water boiler is mainly in the circulator, usually about 1 amp, and indicated on the circulator's name plate, not the boiler's.  If there are other accessories like a flue damper, zone valves, etc that are permitted to be on the same circuit, you need to add up their power requirements.
The actual power consumption of the boiler is probably, if it is anything like mine, closer to 0.07 amps and that includes two smart thermostats and the leakage from several 24V transformers.
I believe what is meant by "Input less then 12 Amps" is that the dedicated circuit that this boiler MUST be on, for practical purposes needs to have a 10A breaker on it and not a 15A one.
So if you put it on a shared 20A circuit with a microwave and a range hood, and perhaps a 1 amp circulator, the answer to your question is probably that you will not overload the circuit, but you will violate code in two ways: 1) the one indicated in the other answers, and 2) putting the boiler on a 20A breaker when it needs a 10A (or anything less than 12, which means 10) one.
That requirement may also be a good reason (other than compliance) not to use a power cord and plug.  You could then plug it into a 15A or 20A circuit, and fail to protect it internally however it needs to be protected by a 10A breaker.
Comment: `Why would a gas boiler use 12A?` -- exactly, the only power it uses is for the pump to recirc water through the radiators
Comment: The boiler's *usage* does not include the circulator's.  The 12A is something else.  I'm not sure my interpretation of "less than" is correct.  Can you post a picture of the entire nameplate including the make and model?
Comment: @amphibient the whole point of a nameplate is to be an authoritative source for how much current you must provison.  You can't really argue around the nameplate.
Comment: @Harper but what does "less than" mean?  Does it mean it consumes less than 12A?  Or that it needs a breaker less than 12A ?   Or something else?  Unclear to me.  My answer is a bit of a guess.
Answer: Well, would you say 12A is a small part of 20A, or would you say it's most of 20A?  Anytime you see a math problem like this, convert it into a money problem: if we earned $20 on a job, is $12/$8 a fair split?
Anyway you may have fallen into a fallacy of logic.  Being eager to do it this way, you optimistically hope a microwave and range hood draw less than 8A together.  You could find out for sure, but then, you'd have to face facts :)
But aside from that, there are three deal-killers in NEC.

The microwave uses a cord and plug into a receptacle.  It's in the kitchen.  Kitchen receptacle circuits (like the microwave/hood) can't power anything outside the kitchen area.
Furnaces must be hard-wired. If a hardwired load uses >50% of the circuit ampacity (12A is 60% of 20A) then no receptacles can be on that circuit at all.
Furnaces require a dedicated circuit regardless (as Ecnerwall covers).

You don't just want a separate circuit. You want a separate panel.
Or to be more precise, you want to see if you can get a sensibly priced generator interlock for your main panel.  If you can't, then you want to install a subpanel near it, and install a generator interlock there.
The reason is: power loss is inevitable. With the increasing popularity of generators, and the ballistically increasing popularity of non-generator things that act like generators such as electric vehicles with AC sockets, you will probably want to be able to power this furnace (and a few other things) during a power outage.  The easy way to do that is a $40 sub panel (Siemens 12-space; better a $70 24-space) and a $25 generator interlock (Siemens ECSBPK01).  And Square D and Eaton have comparable things.
The sooner you "get going on this" the better.  Nobody is in "we don't have power outages around here" territory anymore.  Not with Seattle and Texas getting freezes, the dry southwest getting transmission line shutdowns during windy wildfire conditions, and solar/wind taking an outsize part of generating capacity which can no longer be time-shifted using pumped storage, as the dams are out of water.

Hydronic boiler sharing 20A circuit


Excluding items from a list by object property

Question: I'm trying to build a list of items based on their presence in a list.

itemsAll contains all products
itemsNew contains only new products
I'd like itemsOld to contain only old products (i.e. itemsAll -
itemsNew)

This was my approach, which doesn't return the correct number of items.
var itemsAll = objProductStagingRepository.AllImports(fileId, cid).ToList();

var itemsNew = objProductStagingRepository.DetectNonPresentProductNames(fileId, cid).ToList();

var itemsOld = from t1 in itemsAll where !(from o in itemsNew select o.Id).Contains(t1.Id)
                                        select t1; // this does not work

Does anybody have any suggestions as to how I shuold be approacing this?  I have tried itemsAll.Except(itemsNew) which also doesn't yield the correct results!
Answer: I think you probably could use the Except method, but you would need to provide an equality comparer for the method to know when two items are equal.
http://msdn.microsoft.com/en-us/library/bb336390.aspx
In your question it looks like you're not using your own comparer, so it's comparing the items to see if they are the same object in memory (most likely), which is not what you're trying to do.
You want to compare the objects by database identity, which means you need to provide you're own comparer.
Example:
public class Item
{
    public int Id { get; set; }
}

class ItemComparer : IEqualityComparer<Item>
{
    public bool Equals(Item x, Item y)
    {
        if (Object.ReferenceEquals(x, y)) return true;

        if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
            return false;

        return x.Id == y.Id;
    }

    public int GetHashCode(Item value)
    {
        if (Object.ReferenceEquals(value, null)) return 0;

        int hash = value.Id.GetHashCode();

        return hash;
    }

}

Answer: itemsOld.AddRange(itemsAll.Where(p => !itemsNew.Any(a => a.Id == p.Id)));

Answer: I prefer the fluent syntax so:
var itemsOld = itemsAll.Where(x => !itemsNew.Any(y => y.Id == x.Id));

or
var itemsOld = itemsAll.Where(x => !itemsNew.Exists(y => y.Id == x.Id));

Answer: This might work
var itemsOld = from a in itemsAll
               join n in itemsNew on a.Id equals n.Id into ng
               where !ng.Any()
               select a;


Implications of $\inf_{\left\|x\right\|,\left\|y\right\|\le c}\sup_{\gamma\text{ coupling of }δ_xκ,δ_yκ}\gamma\left(\{\rho<δ\}\right)>0$

Question: Let $E$ be a $\mathbb R$-Banach space, $d$ be a complete separable metric on $E$, $\delta$ denote the Dirac kernel on $(E,\mathcal B(E))$ and $\kappa$ be a Markov kernel on $(E,\mathcal B(E))$. Assume $$a:=\inf_{\substack{(x,\:y)\:\in\:E^2\\\left\|x\right\|_E,\:\left\|y\right\|_E\:\le\:c}}\sup_{\substack{\gamma\\\gamma\text{ is a coupling of }\delta_x\kappa\text{ and }\delta_y\kappa}}\gamma\left(\left\{\rho<\delta\right\}\right)>0\tag1$$ for all $c,\delta>0$.

Let $c,\delta>0$. How can we conclude that for all $(x,y)\in E^2$ with $\left\|x\right\|_E,\left\|y\right\|_E\le c$, there is a coupling $\gamma$ of $\delta_x\kappa$ and $\delta_y\kappa$ with $$\gamma\left(\left\{\rho\le\frac\delta2\right\}\right)>a?\tag2$$

Let $(x,y)\in E^2$ and $\varepsilon>0$. Then, clearly, there is a coupling $\gamma$ of $\delta_x\kappa$ and $\delta_y\kappa$ with $$\gamma\left(\left\{\rho<\delta\right\}\right)>a-\varepsilon.\tag3$$ Maybe $\delta$ should be replaced by $\delta/2$ in $(3)$ and clearly $$\gamma\left(\left\{\rho<\delta\right\}\right)=\gamma\left(\left\{\rho\le\frac\delta2\right\}\right)+\gamma\left(\left\{\rho\in\left(\frac\delta2,\delta\right)\right\}\right),\tag4$$ but I'm not able to obtain $(2)$ from that.
Comment: The set of couplings between two probability measures should be compact for the weak topology under some appropriate conditions on $E$ ($E$ Polish I believe) so that the supremum will be attained.
Comment: @Michh Can you elaborate (and maybe giving some references) why compactness wrt weak topology (which weak topology are we talking about?) implies that the supremum is attained?
Answer: Assume that $E$ is Polish so that the set of couplings between any two probability measures on $E$ is compact w.r.t. the weak topology. Here weak topology refers to the topology of weak convergence for measures, that is $\gamma_n \to \gamma$ if $\int_E f d\gamma_n \to \int_E fd\gamma$ for every continuous bounded $f \colon E \to \mathbb{R}$.
Let $x,y \in E$ and set $F = \{\rho \leq \delta \}$ (the argument requires a closed set). Since
$$\sup_{\gamma \text{ coupling of } \delta_x \kappa \text{ and } \delta_y \kappa} \gamma(F) \geq a,$$
for every $n$ there exists a coupling $\gamma_n$ such that $\gamma_n(F) \geq a-\frac{1}{n}$. By compactness we may assume that $\gamma_n$ converges weakly to some coupling $\gamma$. Then by the Portmanteau theorem we get
$$\gamma(F) \geq \limsup_n \gamma_n(F) \geq a.$$

For the compactness of the set of couplings, check out lemma $0.13$ and Corollary $0.14$ here. The proof relies on the Prokhorov theorem.
Comment: Do you have a reference for the "set of couplings is compact" claim?
Comment: @0xbadf00d see the edit
Comment: (a) Please note that I've mistakenly defined $E$ to be a metric space, while the infimum in $(1)$ was taken over the closed ball around $0$ in $E^2$. So, I've intended to let $E$ be a Banach space and $d$ be any complete separable metric on $E$. Now we should need to be careful. In order for your argument to work, we should require that the Borel $\sigma$-algebra $\mathcal B(E)$ on $E$ induced by the norm on $E$ coincides with the Borel $\sigma$-algebra induced by the topology $\tau_\rho$ generated by $\rho$, right? This should be equivalent to requiring that $\tau_\rho$ coincides
Comment: with the topology generated by the norm on $E$. The next thing is that we need that $\{\rho\le\delta\}$ is $\tau_\rho$-closed; but isn't this true for any metric $\rho$? (b) Did I get you right that the result generally holds for every complete separable metric space $(E,\rho)$, Markov kernel on $(E,\mathcal B(E))$ (here $\mathcal B(E)$ denotes the Borel $\sigma$-algebra generated by the topology induced by $\rho$), $x,y\in E$ and closed $B\subseteq E^2$ satisfying $a:=\sup_\gamma\gamma[B]>0$? And all we use is that the set of those couplings is sequentially compact, right?
Comment: @0xbadf00d (a) You are right, I was a bit careless there. If you assume that $\rho$ induces the same topology as the norm topology then everything works fine indeed. And the closed ball is always closed in any metric space. (b) Absolutely right, and only *sequential* compactness is needed.
Comment: I quickly correct myself: if $E$ is Polish then the space of probability measures $\mathcal{P}(E)$ endowed with the weak topology is metrizable (and Polish), so no difference between compactness and sequential compactness.
Comment: So, the point of the conclusion in (b) is that $\gamma(B)=a$ (since you've showed $\gamma(B)\ge a$ and it $\gamma(B)\le a$ is trivial from the definition, right?
Comment: BTW: You've written "the closed ball is always closed in any metric space", which is clearly correct, but $\{\rho\le\delta\}$ is not a closed ball in a metric space or am I missing something?
Comment: @0xbadf00d Oops you're obviously right! But it is still closed, for instance this is the set of points at distance at most $\delta$ from the diagonal $D= \{(x,x): \, x\in E\}\subset E^2$ where the "distance" on $E^2$ is $d((x,y),(x',y')) = \rho(x,x') + \rho(y,y')$. Maybe there is an easier way of seeing this though
Comment: Sorry for replying to this post again, but I just figured out that in my application the topology $\tau_\rho$ induced by $\rho$ is *not* equal to the topology $\tau_E$ induced by $\left\;\cdot\;\right\|_E$. However, $\tau_\rho$ is coarser than $\tau_E$. So, $\rho$ is separable (and complete? Should be trivial, but I'm unsure at the moment). Note that $\mathcal B(E,\tau_\rho)\subseteq\mathcal B(E)$. Is this a problem at some point? Do we need to take $F$ to be $\tau_\rho$-closed or $\tau_E$-closed?


Mamp won't start apache (Windows 10)

Question: I've installed MAMP Pro on my Windows 10 Computer this week, and it worked fine until today. I've restarted my computer and immediately started MAMP Pro - this caused the MySQL server to start, but not Apache. Then, I restarted MAMP and no server was running, I've checked if any other Services were running on the MAMP port but there were none. I also changed the Ports in MAMP but it wasn't working either.
Why might this be happening?
Here are the Apache logs:
[Sat Oct 21 04:46:43 2017] [warn] pid file C:/MAMP/bin/apache/logs/httpd.pid overwritten -- Unclean shutdown of previous Apache run?

[Sat Oct 21 04:46:43 2017] [notice] Digest: generating secret for digest authentication ...

[Sat Oct 21 04:46:43 2017] [notice] Digest: done

[Sat Oct 21 04:46:44 2017] [notice] Apache/2.2.31 (Win32) DAV/2 mod_ssl/2.2.31 OpenSSL/1.0.2e mod_fcgid/2.3.9 mod_wsgi/3.4 Python/2.7.6 PHP/7.1.5

mod_perl/2.0.8 Perl/v5.16.3 configured -- resuming normal operations

[Sat Oct 21 04:46:44 2017] [notice] Server built: May  6 2016 10:19:53

[Sat Oct 21 04:46:44 2017] [notice] Parent: Created child process 5348

[Sat Oct 21 04:46:45 2017] [notice] Digest: generating secret for digest authentication ...

[Sat Oct 21 04:46:45 2017] [notice] Digest: done

[Sat Oct 21 04:46:46 2017] [notice] Child 5348: Child process is running

[Sat Oct 21 04:46:46 2017] [notice] Child 5348: Acquired the start mutex.

[Sat Oct 21 04:46:46 2017] [notice] Child 5348: Starting 64 worker threads.

[Sat Oct 21 04:46:46 2017] [notice] Child 5348: Starting thread to listen on port 443.

[Sat Oct 21 04:46:46 2017] [notice] Child 5348: Starting thread to listen on port 443.

[Sat Oct 21 04:46:46 2017] [notice] Child 5348: Starting thread to listen on port 80.

Answer: Do the following:
MAMP -> Preferences -> PHP. Change Standard Version 7.3.7 to 7.2.14. Start the servers.
After success, you can return to Standard Version 7.3.7.
Comment: This indeed works, thanks! But when I return to version 7.3.7 after it successfully started apache..same thing happens, it won't start the apache server again. :(
Answer: I had this same problem, and the only thing that worked for me to get the Apache server started again was to change the PHP version to 7.2.14 in the Preferences area of MAMP:
MAMP > Preferences... > PHP > Standard Version > 7.2.14
Note: After I was able to get the Apache server started again, I tried to change the PHP version back to 7.3.7, but this broke the Apache server startup process again. The green dot would wink on, and then off. So I am leaving MAMP with PHP version 7.2.14 for now (since the version of PHP doesn't matter to me as long as it is 7.x and not 5.6.x).
Answer: A problem might be that the port apache uses is blocked by something else I can't remember that port but you can easily look that up.
I think
world wide publishing
Usually uses that same port as apache so unrun that and see if it works.
I know you said you checked the ports but world wide publishing is always running by default. So I'd check that.

Mamp won't start apache (Windows 10)


Embedded google maps into a circle div in google chrome

Question: I have problem with google maps.
As you can see on this link: http://fenixreklama.cz/kontakt.html
In Firefox is no problem, embedded map is in black circle, but in Google Chrome the map is rectangle above black circle.
How can this be solved?
Comment: Can you please post the code here or better - in a jsfiddle? (jsfiddle.net)
Comment: Sorry, here is jsfiddle link: http://jsfiddle.net/xixaom/qtL4t0j2/1/
Answer: The solution is to put iframe with map into div with radius border and set overflow to hidden, of course.


android.media.MediaPlayer crashes without exception

Question: The MediaPlayer makes my app freeze without throwing an exception when I pass corrupted audio files to it. Here's my code:
<code>try
{
    if (this.mediaPlayer.isPlaying())
    {
        this.mediaPlayer.reset();
    }

    this.mediaPlayer.setDataSource(this.currentSong.getFile() /* path string */);
    this.mediaPlayer.prepare();
    this.mediaPlayer.start();
}
catch (Exception e)
{
    Log.v("Oh snap", "MediaPlayer exception: " + e.toString());
}
</code>
What can I do about this? I need an exception to handle corrupted files properly. The test device is a Samsung Galaxy S2 running Android 2.3.6 and I'm targeting API level 8.
I'm not sure what's wrong with the corrupted flac files that I'm passing to the MediaPlayer. All I know is that they crash my app and the stock music player too, which shouldn't happen.
Comment: Yes, no exceptions or warnings.
Answer: If it's a native crash there's very little you can do just from the Java layer. Check this answer for a slightly scary guide to the frightful hacking you'd need to do.


What Is the "character" in string's definition?

Question: C11 defines a "string" as:

A string is a contiguous sequence of characters terminated by and
  including the first null character.   §7.1.1 1

It earlier defines a "character" as:

3.7  character
  〈abstract〉 member of a set of elements used for the organization, control, or representation of data
3.7.1
  character
  single-byte character
  〈C〉 bit representation that fits in a byte
3.7.2
  multibyte character
  sequence of one or more bytes representing a member of the extended character set ...
3.7.3
  wide character
  value representable by an object of type wchar_t, capable of representing any character
  in the current locale

Question: What definition of "character" is being used in the definition of "string":
"character" in 3.7,
"character" in 3.7.1,
or something else?
Comment: All of the above.
Comment: Aside: Reading 3.7.3, a wide character string cannot use UTF-16.
Comment: @Deduplicator: Right.  16 bit `wchar_t` UCS-2 is a possibility, if the "current locale" includes only the BMP.
Comment: Maybe helpful reading [Representation of Strings](http://www.gnu.org/software/libc/manual/html_node/Representation-of-Strings.html)
Answer: A string is a contiguous sequence of data of type char.
The word "character" is used in two senses, abstract and practical.
From the abstract point of view, we first would have to define the concept "set of characters", in order to, later, go to 3.7 and say "a member of a set of elements for...".
This definition of "character" fits another standard: ISO/IEC 2382-1.
See ISO/IEC 2382-1(character)
There, you can analyze a big list of terms related to "Information Representation".
MY SHORT ANSWER: "character" in the definition of "string" corresponds to c188.8.131.52.
The explanation is as follows:
CHARACTER IN THE ABSTRACT
A symbol is an intellectual convention of human beings.
So, the abstract symbol for "A" is a convention which we use to recognize different "graphs" like A, A, A, as being all "the same" thing (a piece of information, say).
The information is represented, then, by ordered and finite sequences of a set of (abstract) characters.
Next, you need to codify this abstract symbols to make possible their representation in information systems (computers).
This is done, in general, by defining a one-to-one correspondence between integer numbers (called code-points) and their correspondant characters in a given set.
An encoding schema is a way in that a set of characters is associated to certain numbers (code-points).
This encoding can change from one system to another ("A" has not the same encoding in EBCDIC as in ASCII).
Finally, we associate a "graph" to each character+code-point, that is, a written representation, which can be eventually printed or shown on screen.
The shape of the graph can change according to a font design, so it is not a good starting point to define the term "character".
CHARACTER IN C
In 3.7.1. it seems that C11 refers to another meaning of "character", intended to be a brief form to say "single-byte character". It is talking about code-points (that is, integer numbers associated to "abstract characters of a given set") that fit in exactly 1 byte.
In this case, we need the definition of Byte.
In C, a byte is an information storage unit, consisting of an ordered sequence of n bits, where n is an integer number greater than or equal to 8 (in general is 8, of course), whose value you can found by checking the constant CHAR_BIT, in <limits.h>.
There are data types whose size is exactly 1 byte: char, unsigned char, signed char.
The range of values of unsigned char is exactly 0...2^n - 1, where n is CHAR_BIT.
The range of values of char coincides with signed char or unsgined char, but C11 doesn't say which of them corresponds to char.
Moreover, in any case, the type char must be considered different from signed char and unsigned char.
A string is, now, a sequence of objects of type char.
WHY CHAR?
The standard defines the representation of characters in terms of char:
(22.214.171.124)

An object declared as type char is large enough to store any member of the basic
  execution character set. If a member of the basic execution character set is stored in a
  char object, its value is guaranteed to be nonnegative. If any other character is stored in
  a char object, the resulting value is implementation-defined but shall be within the range
  of values that can be represented in that type.

STRING
Now, a string in C is a contiguous sequence of (single-byte) characters terminated by the null character, which in C is always 0.
This definition can be understood again in an abstract way, however in 188.8.131.52 the text talks about the address of the string, so it must be understood that a "string" is an object in memory.
A "string" object is, then, a contiguous sequence of "bytes", each one holding the code-point of a character.
This is derived from the fact that a "character" is intended to fit exactly in 1 byte.
It is represented in C by an array of type char, whose last element is 0.
MULTIBYTE CHARACTER
The definition of "multibyte" is complicated.
It is referred to some special encoding schemas that uses a variable number of bytes to represent an (abstract) character.
You need information about the execution character sets in order to properly handle multibyte character sets.
However, even if you have a multibyte character, it is still represented in memory as a sequence of bytes.
That means that you will represent a multibyte string again as an array of char.
The way in that the execution system interprets these bytes is a different issue.
WIDE CHARACTER
A wide character is an element of another set of (abstract) characters, different to those represented in the type char.
It is intended that the set of "wide characters" be larger than the set of "single-byte characters".
But this is not necessarily the case.
The relevant facts of the "wide characters" are the following:

The set of "wide characters", whichever they are, can be represented by the range of values of the type wchar_t.
These characters can be different from those represented in the type char.
A "wide character" can use more than 1 byte storage.
A "wide string" is a null-terminated contiguous sequence of "wide characters".

Thus, a "wide string" is a different object than a "string".
CONCLUSION
A string has nothing to do with "wide" characters, but only "single-byte characters".
A string is a null-terminated contiguous sequence of "bytes", which, in turn, means, objects of some the char types: char, signed char, unsigned char, corresponding to code-points of an abstract character set that fits in 1 byte.
Comment: I have a few problems with the precision of this phrase: "terminated by and including the first null character" So, concat functions drop characters? String length functions are off-by-one? String-end pointers are not one-beyond? The character set has to have a null character? What if it encodes its null character as something other than 0? What if it doesn't have any character encoded as 0? I think the terminator is not part of the string and not a _character in the character set;_ It is simply 0 and if the character set does have a character encoded as 0, it can't be represented in a string.
Comment: @TomBlodget Too many questions... I cannot properly answer all of them inside this comments.
Comment: @Tom Blodget I'll try one: "String length functions are off-by-one?".  The `strlen()` returns the number of characters that precede the `'\0'` - by definition.  So even with the definition of string including the `'\0'`, the definition of `strlen()` is, as you suggest "off by-one", in that it does not return the number of `char` in the string.  Instead `strlen()` is _defined_ to be affected by, but does not include, the `'\0'` in its return value.  `sizeof("1234")` does return 5.
Comment: My previous rhetorical questions were off-topic. The standard does require the execution character set to have a null character and to encode it as 0. So the terminator issue has no bearing on the question asked or @pablo1977's excellent answer.


What do I do with this legacy weapon unlock?

Question: So, 1.2 is here and suddenly all those legacy levels mean something. Somehow in the deluge of info, I missed the part where they told me what to with the legacy main hand weapon parts they mailed me.  So... anybody want to post that up here, so I can make this weapon?
Answer: At capital worlds (coruscant/Dromund Kaas) there are 4 new legacy vendors (Senate Tower square/ Kaas City Square), You can exchange this kit you got for one mainhand weapon 14-16 lvl.
Comment: oh so basically it's some thing I'll use for about three hours... best reward ever!


Computing Factor Group step-by-step manually

Question: I am reading Fraleigh's Abstract Algebra $\S$15 on factor group, Example #15.11:

Compute factor group $(\mathbb Z_4 \times \mathbb Z_6) / \langle (2, 3)\rangle.$

The text gives a solution that is only a shortcut and I think it's applicable only to this problem. I would like to do it in manually, dumbly, in step-by-step fashion such that I can internalize the concept better; admittedly factor group is a hard concept for beginners.
I did the following tediously:
$$\begin{align}
\mathbb Z_4 \times \mathbb Z_6 = \{ &(0, 0), (0,1), (0,2), (0, 3),(0, 4), (0,5),\\
&(1, 0), (1,1), (1,2), (1, 3),(1, 4), (1,5),\\
&(2, 0), (2,1), (2,2), (2, 3),(2, 4), (2,5),\\
&(3, 0), (3,1), (3,2), (3, 3), (3, 4), (3,5)\}
\end{align}$$
Questions: (1) Is it possible to manually solve the problem like this?
(2) If it is, how do I mode out each of them with $\langle (2, 3) \rangle$? Just give me a few examples.
The text says the factor group is isomorphic to either $\mathbb Z_{12}$ or $\mathbb Z_4 \times \mathbb Z_3$. Thank you for yoru time and effort.

Post Script: I must admit that there is a possible duplicate here which I found out belated only after I posted mine. But keep in mind that my question is about how to solve it manually to enforce my understanding. Thank you.
Answer: I'll show you how to compute it manually.
The elements of the factor (or quotient) group are the cosets of the subgroup $H=\langle (2,3)\rangle$, which is normal in $\Bbb Z_4 \times \Bbb Z_6$ because $\Bbb Z_4 \times \Bbb Z_6$ is abelian.
To find all the cosets, we take each element $(h,k) \in \Bbb Z_4 \times \Bbb Z_6$ and  compute $$(h,k)+H =\{ (h,k)+(0,0), (h,k)+(2,3)\} = \{(h,k), (h+2,k+3)\}.$$ Doing this, we get the following:
$$
H = \{(0,0), (2,3)\}\\
(0,1)+H=\{(0,1),(2,4)\}\\
(0,2)+H=\{(0,2), (2,5)\}\\
(0,3)+H=\{(0,3), (2,0)\}\\
(0,4)+H = \{(0,4), (2,1)\}\\
(0,5)+H = \{(0,5), (2,2)\}\\
(1,0)+H = \{(1,0), (3,3)\}\\
(1,1)+H = \{(1,1), (3,4)\}\\
(1,2)+H = \{(1,2), (3,5)\}\\
(1,3)+H = \{(1,3), (3,0)\}\\
(1,4)+H = \{(1,4), (3,1)\}\\
(1,5)+H = \{(1,5), (3,2)\}
$$
We know that we're done once we have a partition of $\Bbb Z_4 \times \Bbb Z_6$. To check this, just check that every element of $\Bbb Z_4 \times \Bbb Z_6$ is in one of the cosets.
(This idea of the cosets being the equivalence classes of the equivalence relation $a \sim b \iff a-b \in H$ is used in the proof of Langrange's theorem, and it also explains why two cosets are either disjoint or equal; it's a property of equivalence classes.)
We could also argue that we've found all the cosets by using Lagrange's theorem, which tells us that the  factor (or quotient) group should have 12 elements: $$[\Bbb Z_4 \times \Bbb Z_6 : \langle (2,3)\rangle] = \frac{|\Bbb Z_4 \times \Bbb Z_6|}{|\langle (2,3)\rangle|} = \frac {24}{2}=12.$$

Now, to prove this group is isomorphic to $Z_{12}$, you could, as A.P. did, use the fundamental theorem of finitely generated abelian groups, or you could show directly that the group is cyclic (because all cyclic groups of a given order are isomorphic):
To show $G= \Bbb Z_4 \times Z_6 / \langle(2,3)\rangle$ is cyclic, we will show that the element $(1,1)+H$ has order 12:
We know its order must divide $|G|=12$, so it can be $1,2,3,4, 6,$ or $12$.
Its order is not 1 because $(1,1)+H \neq H$, the identity of $G$.
Its order is not $2,3,$ or $6$, because $6((1,1)+H)= (6,6)+H=(2,0)+H \neq H$
Its order is not $4$ because $4((1,1)+H)=(4,4)+H = (0,4)+H \neq H$.
Thus, its order is 12, meaning  $\Bbb Z_4 \times Z_6 / \langle(2,3)\rangle = \langle (1,1)+H \rangle$ is cyclic, so $$\Bbb Z_4 \times Z_6 / \langle(2,3)\rangle \cong \Bbb Z_{12} \cong \Bbb Z_3 \times \Bbb Z_4$$.
Comment: Eek, I'll let someone else do that. I'll edit something else in for that part.
Comment: @DavidWheeler yes, but the fact that $6(1,1)+H\neq H$ implies that the order of $(1,1)+H$ does not divide 6, so it cannot be $2$ or $3$.
Comment: Indeed, it's more efficient to rule out maximal divisors ($6$ and $4$) of $12$ first.
Comment: +1 And now for the boring part: writing out the addition table for those classes and figuring out which group we have. :)
Comment: Note that $(1,1) + H \neq H$, and $2((1,1) + H) = (2,2) + H \neq H$, and that $3((1,1) + H) = (3,3) + H \neq H$, and also $4((1,1) + H) = (0,4) + H \neq H$, and finally: $6((1,1) + H) = (2,0) + H \neq H$, which shows that $(1,1) + H$ does not have additive order $1,2,3,4$ or $6$, and therefore must have order $12$ (the only divisor of $12$ left), and thus generates $(\Bbb Z_4 \times \Bbb Z_6)/\langle(2,3)\rangle$, which is therefore cyclic, of order $12$.
Comment: @coldnumber : Thank you. You have earned my upvote and green check mark.
Answer: We can definitely compute quotients of finite groups by inspecting each element, but one almost never does, because it is a tedious and error prone process.
In this case, note that
$$
(2,3) + (2,3) = (4,6) \equiv (0,0)
$$
so $(2,3)$ has order $2$, i.e. that $\langle (2,3) \rangle = \{(0,0),(2,3)\}$. This means that the quotient group has cardinality $24/2 = 12$, so by the fundamental theorem of finitely generated abelian groups the quotient is either $\Bbb{Z}_{12} \simeq \Bbb{Z}_4 \times \Bbb{Z}_3$ (the isomorphism is due to the Chinese Remainder Theorem) or $\Bbb{Z}_2 \times \Bbb{Z}_2 \times \Bbb{Z}_3$.
We can easily distinguish between those two cases, because the latter doesn't have any elements of order $4$. Indeed, observe that, say
$$
(1,0),(2,0),(3,0) \notin \langle (2,3) \rangle
$$
which means that the class of $(1,0)$ has order $4$ in the quotient. Thus $(\Bbb{Z}_4 \times \Bbb{Z}_6) / \langle (2,3) \rangle \simeq \Bbb{Z}_{12}$.
Comment: Thanks. I pretty much understand your explanation, up to the 3rd. paragraph when you said "We can easily distinguish between..." Here are my two questions: (1) Why do you choose element of order 4 to distinguish between $\mathbb Z_{12}$ and $\mathbb Z_2 \times \mathbb Z_2 \times \mathbb Z_3$ in the first place? What is the significance of order 4 in this quest here? (I will ask the second question on the next comment space.) Thanks again.
Comment: And here is my second question: (2) I understand when you said that $(1,0),(2,0),(3,0) \notin \langle (2,3) \rangle.$ But I did not see the relationship to your next assertion that "... which means that the class of $(0, 1)$ has order 4 in the quotient. Thanks again and again for your time and effort.
Comment: @A.Magnus for (1): $\Bbb Z_2 \times \Bbb Z_2$ has no element of order 4 because every nonidentity element has order 2 (so  $\Bbb Z_2 \times \Bbb Z_2\times \Bbb Z_3$ has only elements of orders 1, 2, 3, and 6), whereas in $\Bbb Z_4\times \Bbb Z_3$, the element (1,0,0) has order 4. The existence of an element of order four in $\Bbb Z_4$ is the easiest way to show that it is not isomorphic to $\Bbb Z_2 \times \Bbb Z_2$.
Comment: I refer you to coldnumber's explanation for (1). As for (2), recall that the order of an element $x$ of a group $G$ (in additive notation) is the smallest positive integer $n$ such that $nx = 0$ (if it exists). Now, if $H$ is a subgroup of $G$, then we know that $n(x + H) = nx + H$ and that the class of $x$ in $G/H$ is $0$ if and only if $x \in H$. Since $(1,0)$ has order $4$ in $\Bbb{Z}_4 \times \Bbb{Z}_6$, it is enough to check that $n(1,0) \notin \langle (2,3) \rangle$ for $1 \leq n \leq 3$.
Comment: Actually, checking $n \in \{1,2\}$ is enough because one can show that, for every $x \in G$, the order of the class of $x$ in $G/H$ divides the order of $x$ in $G$.
Comment: @coldnumber : Many thanks to Coldnumber and A.P. Give me some times to digest yours. In the meantime, is there anyone out there willing to compute the factor group manually as I originally asked. I know it is tedious, as A.P. has pointed out, but I would like to see the making of a factor group in action. Thank you again.


Ceiling lights (fluorescent) takes too long to light

Question: My kitchen fluorescent ceiling light does not come on and another (smaller) fluorescent over sink is dim. Both come on later. Now my dishwasher won't come on. When the lights came on, the dishwasher lights came on for a few seconds. I checked the breakers, and I turned them on and off. They seems to be okay. What gives???
Comment: Since there are multiple issues I would be looking for a wiring problem with a broken or loose wire feeding these it could be on the hot or neutral. I would guess that they are all fed by the same breaker.
Answer: First, a little bit of a slow start is a good thing -- that is a better-quality ballast "soft-starting" the bulbs.  They light up pre-heaters in the ends of the bulb before striking the arc.  The best programmed-start ballasts actually measure performance, so they know to give the bulbs longer to start.  But this is not that.   To troubleshoot this:

Change the bulbs, unless you have tested the bulb good in another fixture.
look around for a "starter" and change the starter if it has one.
Replace the ballast with a modern electronic ballast.  In this case, if there's a starter, it will be bypassed.  You can leave it in place to avoid an ugly hole.

Far better to get an LED "tube" which fits in the fixture you have.  I recommend getting "direct wire" LED tubes, in which you rewire your fixture to bypass the ballast.  (Don't use "ballast ready" or "drop in" types, because they require you to keep the ballast in the fixture, and it must be working, and it must be a very particular type 0 which is more trouble than it's worth.)
Answer: If it were just the light then I would replace the ballast.  Not sure about the dishwasher.  Hopefully someone else will jump in on this.  Best of luck.
Answer: Fluorescent light tubes have a limited lifetime. There are a couple of effects of ageing

They get dimmer. A smoky black mark develops at one end of the tube.
They get harder to start - usually there's a period where they blink on and off a few times before starting.

Unless these tubes are less than a year old, I'd replace them.
I have an office with 64 fluorescent light tubes. Several have lasted more than 15 years, one lasted only 1 year. Most last around 7 years but there is very considerable variation. I wouldn't assume an individual fluorescent tube has a well-defined lifetime.

Unlike traditional incandescent tungsten-filament light bulbs, fluorescent light tubes need electronic gear to make them work. There are several generations of this and the oldest used a "starter" that needed replacing periodically.
If your light fittings are old and have starters, I would try replacing them. Starters are rated by power (Watts) - you need a starter that has a higher rating than your tube.
After that, I would consider changing the rest of the electrical gear, usually called a ballast, and available in several forms - magnetic or electronic.
If it comes to this, you might consider replacing the light fittings with a LED based alternative.

None of this should affect your dishwasher. Problems with this may be coincidental or indicative of a more serious problem with the circuit.
Comment: The difference in performance in those bulbs in your office could be explained by ballasts. One of the failure modes of ballasts, particularly old heavy magnetic ones, is to prematurely age bulbs.


TypeScript fails to infer type correctly when type alias used

Question: In the code below I have two instances of a Record<string, string[]>: one that declares itself directly as the Record, and one that uses a type alias referring to the exact same Record type. When passing these into a function, along with an empty array (which I expect TypeScript to infer as being an empty string array), TypeScript compiles the first, but not the second. So it looks like the type alias is causing it to have a problem. Is there a way around this? Is this a bug in TypeScript that should be reported?
function foo<T>(record: Record<string, T>, entity: T) {
}

type StringArrayRecord = Record<string, string[]>;

function test() {
    const working: Record<string, string[]> = {};
    foo(working, []); // Compiles

    const broken: StringArrayRecord = {};
    foo(broken, []); // Does not compile
}

The error is:
Argument of type 'StringArrayRecord' is not assignable to parameter of type 'Record<string, never[]>'.
  'string' index signatures are incompatible.
    Type 'string[]' is not assignable to type 'never[]'.
      Type 'string' is not assignable to type 'never'.

If I try a different type instead of string[] as the second type parameter in the record, I get the same problem as soon as there is any ambiguity in the type (e.g. if it's a union type), e.g.
type StringOrNumberRecord = Record<string, string | number>;

function test() {
    const working: Record<string, string | number> = {};
    foo(working, "string"); // Compiles

    const broken: StringOrNumberRecord = {};
    foo(broken, "string"); // Does not compile
}

(Am getting this both with TypeScript 4.8 and with 5.)
(One possible solution is to explicitly tell the compiler the type of the second parameter when calling foo, e.g. foo(broken, "string" as string | number);. Another is specify the generic type parameter when calling foo, e.g. foo<string | number>(broken, "string"). But both of these seem like they should not be necessary.)
Comment: This seems like an unfortunate interaction in the generic inference algorithm; one wouldn't think that using a type alias would lower the priority of an inference site, but I guess it does.  I couldn't find an obviously relevant issue in GitHub about this.  Someone might want to file one and then report back here with an official answer once it gets triaged.
Comment: Thanks @jcalz. Have now logged this as an issue: https://github.com/microsoft/TypeScript/issues/54000.
Comment: What is your tsconfig.json config as I try to compile it and it does not fail?
Comment: Just the default when using `npx tsc --init`
Comment: Okay, that got triaged. Do you want to write up your own answer here or shall I do it?
Comment: I feel you have a much greater understanding of the compiler so could explain it much better than I could :-) So why don't you write it up (assuming you're happy to?) and I'll then mark it as the correct answer.
Comment: you can do `function foo>(record: T, entity: T[string]) {}` and coerce TS to determine `T` from the `Record` and match the arrays type against that. Not determine `T` from the (empty) array and try to match the Records values against that type.
Answer: This is apparently working as intended, according to microsoft/TypeScript#54000 although it's definitely strange when a type alias has such a large effect on inference.
The reason for the difference is that when TypeScript compares two types, it often has to recursively match up pieces of each one before deciding if they are the same, or different, or if one can be used to infer pieces of the other.
But if they both types are written in terms of an identical generic type with known variance in its type parameter (see Difference between Variance, Covariance, Contravariance, Bivariance and Invariance in TypeScript ), then the compiler can take a shortcut by just comparing the type arguments.  For example, if the compiler is comparing F<string> to F<unknown> for the following F<T> type
type F<T> = {
  prop: T;
  otherProp: string;
  anotherProp: number;
  // ... lots more stuff, none of which depend on T
}

which it has already analyzed as being covariant in its type parameter, then it can immediately say that F<string> is a subtype of F<unknown> because string is a subtype of unknown, without needing to actually evaluate F<string> or F<unknown> and compare them directly.
This shortcut is, to a first approximation, just a faster way of getting the same result it would have gotten the long slow way.

On the other hand, if the compiler is comparing F<string> to G for the following G type
type G = F<unknown>

then it would need to start evaluating the types before it could compare them.  If it does so by plugging string into F and then evaluating G, it would be too late to notice that they are both in terms of F and therefore it needs to start comparing all the properties of both.
This will eventually determine that F<string> is a subtype of G.  But it does so through a different path.
(And you can substitute Record<string, T> for F<T> and Record<string, string[]> for G if you want here.)

Even though these have basically the same result, there are observable differences, for better or worse.  And one is that it can affect generic type argument inference.
When inferring Record<string, T> from a value of type Record<string, string[]> at the same time as inferring T from a value of type never[] (which is the default type of an empty array), the compiler can immediately use the variance marker on Record's second type parameter to see that as the same as inferring T from string[] and T from never[].  These two inference candidates are given equal priority and the compiler decides that string[] is the right choice because never[] is assignable to string[].
On the other hand when inferring Record<string, T> from a value of type StringOrNumberRecord at the same time as inferring T from a value of type never[], the compiler cannot take the shortcut of variance markings.  It needs to evaluate StringOrNumberRecord to do that, and therefore the inference candidate of never[] has a higher priority because it's more direct.  And then when it does finally evaluate StringOrNumberRecord it fails because it's not assignable to Record<string, never[]>.
It's an unfortunate inconsistency in behavior, but neither way is "incorrect" per se.  And according to the TS team dev lead, the more consistent fix would be to lower the variance marker priority and have both calls fail, which probably wouldn't make anyone happier.  So it is what it is, at least for now.
Answer: The main issue is that you didn't specify the type of T in foo when you call it:
// Here T is a generic type
function foo<T>(record: Record<string, T>, entity: T) {
}

// broken is of type Record<string, string[]>
const broken: StringArrayRecord = {};

foo(broken, []); // Does not compile since the type of [] is uknown[]

See the issue there? You have  value of the second parameter passed as [] which for Typescript its an empty untyped array so it resolves into uknown[] thus the mismatch.
If you put an empty string there like:
foo(broken, [""]);

Now the compiler can infer the parameters as string[] which is valid and resolved without issues.
Comment: Thanks, but I don't think this really answers the question. The suggestion you provide is similar to what I list as possible solutions at the bottom of my question. But the question is: why do I need to do these workarounds _only if using the type alias_? (Also, FYI, I can't use `[""]` as that's not an empty array: I'd need to do, for example, `[] as string[]`, or `foo(broken, [])`.)
Comment: Because you are not specifying the type of `T` when you pass `foo(broken, []);` since
`[]` resolves into `unknown[]` which makes sense. You could have added anything there in the list so the compiler needs to have more information about the type you are using for `T`.

Hense when using `[] as string[]` or `foo(broken, [])` the compiler can infer the type  of `T` as `string[]`.
Comment: I totally get what you're saying, but that's not my question. My question is: why is it only necessary to specify `T` when using the type alias? Why does this work: `foo(working, []);`, but this doesn't: `foo(broken, []);`? Both are exactly the same, it's just that the latter uses a type alias for the `Record`.