Using Inner classes in C#

Question: What are the best practices regarding the use and structure of inner classes in C#.
For instance if I have a very large base class and two large inner classes should I split them up into separate (partial class) codefiles or leave them as one very large unwieldy codefile?
Also is it bad practice to have an abstract class, with a public inherited inner class?
Answer: Typically I reserve inner-classes for one of two purposes:

Public classes which derive from their parent class where the parent class is an abstract base implementation with one or more abstract methods and each subclass is an implementation which serves a specific implementation. after reading Framework Design and Guidelines I see that this is marked as "Avoid", however I use it in scenarios similar to enums--althogh that's probably giving a bad impression as well
The inner classes are private and are units of business logic or otherwise tightly coupled to their parent class in a manner in which they are fundamentally broken when consumed or used by any other class.

For all other cases I try to keep them in the same namespace and the same accessibility level as their consumer/logical parent--often with names that are a little less friendly than the "main" class.
On big projects you'd be surprised how often you may find yourself initially building a strongly-coupled component just because it's first or primary purpose makes it seem logical--however unless you have a very good or technical reason to lock it down and hide it from sight then there is little harm in exposing the class so that other components can consume it.
Edit Keep in mind that even though we're talking about sub-classes they should be more-or-less well designed and loosely coupled components.  Even if they are private and invisible to the outside world keeping a minimal "surface area" between classes will greatly ease the maintainability of your code for future expansion or alteration.
Comment: This: "fundamentally broken when consumed or used by any other class."
Answer: I don't have the book to hand, but the Framework Design Guidelines suggests using public inner classes as long as clients don't have to refer to the class name. private inner classes are fine: nobody's going to notice these.
Bad: ListView.ListViewItemCollection collection = new ListView.ListViewItemCollection();
Good: listView.Items.Add(...);
Regarding your large class: it's generally worthwhile splitting something like this into smaller classes, each with one specific piece of functionality. It's difficult to break it up initially, but I predict it'll make your life easier later on...
Comment: Some points from the book (pg 102)... nested types should be used sparingly; nested types are best suited for modeling implementation deatils of their parent types; the end user should rarely have to declare a nested type, and almost never instantiate one; do not use nested types for grouping--use namespaces; AVOID PUBLIC NESTED TYPES
Answer: Generally inner classes should be private and usable only by the class that contains them. If the inner classes are very large that would suggest they should be their own classes.
Usually when you've got a big inner class it's because the inner class is tightly coupled to it's containing class and needs access to its private methods.
Answer: I think this is rather subjective, but I would probably split them up in separate code files by making the "host" class partial.
By doing like this, you can get even more overview by editing the project file to make the files group just like designer classes in Windows Forms. I think I've seen a Visual Studio addin that does this automagically for you, but I don't remember where.
EDIT:
After some looking I found the Visual Studio add-in for doing this called VSCommands
Comment: Don't they do this automatically in Visual Studio if you name them MyClass.cs, MyClass.subportion.cs, MyClass.anotherbit.cs, MyClass.lastoneipromise.cs, etc?
Comment: I just tested, and Visual Studio don't do this automatically.
Comment: I haven't done this personally, but perhaps they've implemented it in Visual Studio 2008?
Comment: if you do public partial class pclass {} in one file (e.g. pclass.cs) and public partial class pclass { class subclass {} } in another file (e.g. sclass.cs), Visual Studio 2010 understands they are the same class (and in MSIL they are compiled like they were in the same file). I understand VS2010 was released after this post, though.
Answer: Regarding only how to structure such a beast ...
You can use partial classes to split the main class and the nested classes. When you do so, you're advised to name files appropriately so it's obvious what is going on.
// main class in file Outer.cs
namespace Demo
{
  public partial class Outer
  {
     // Outer class
  }
}

// nested class in file Outer.Nested1.cs
namespace Demo
{
  public partial class Outer
  {
    private class Nested1
    {
      // Nested1 details
    }
  }
}

In much the same way, you often see (explicit) interfaces in their own file. e.g. Outer.ISomeInterface.cs rather than the editor default of #regioning them.
Your projects file structure then starts to look like

   /Project/Demo/ISomeInterface.cs
   /Project/Demo/Outer.cs
   /Project/Demo/Outer.Nested1.cs
   /Project/Demo/Outer.ISomeInterface.cs

Typically when we're doing this it's for a variation of the Builder pattern.
Answer: I personally like to have one class per file, and the inner classes as part of that file.  I believe inner classes should typically (nearly always) be private, and are an implementation detail of the class.  Having them in a separate file confuses things, IMO.
Using code regions to wrap around the inner classes and hide their details works well for me, in this case, and keeps the file from being difficult to work with.  The code regions keep the inner class "hidden", and since it's a private implementation detail, that's fine with me.
Answer: I personally use inner classes to encapsulate some of concepts and operations used only internally within a class. This way I don't pollute that class' non-public api and keep the api clean and compact.
You can take advantage of partial classes to move the definition of these inner classes into a different file for better orgnanization. VS does not automatically group partial class files for you except for some of the templatized items such as ASP.NET, WinForm forms, etc. You will need to edit the project file and make some changes in there. You can look at one of the existing grouping in there to see how it is done. I believe there are some macros that allow you to group partial class files for you in the solution explorer.
Answer: In my opinion inner classes, if needed at all, should be kept small and used internally by that class only. If you use Relfector on the .NET framework you'll see them used a lot just for that purpose.
If your inner classes are getting too big I would definitely move them out into separate classes/codefiles somehow if only for maintainability. I have to support some existing code where someone thought it was a great idea to use inner classes within inner classes. It resulted in an inner class hierarchy running 4 - 5 levels deep. Needless to say the code is impenetrable and takes ages to understand what you are looking at.
Answer: Here see a practical example of a nested class that could give you an idea of their use (added  some unit test)
namespace CoreLib.Helpers
{
    using System;
    using System.Security.Cryptography;

    public static class Rnd
    {
        private static readonly Random _random = new Random();

        public static Random Generator { get { return _random; } }

        static Rnd()
        {
        }

        public static class Crypto
        {
            private static readonly RandomNumberGenerator _highRandom = RandomNumberGenerator.Create();

            public static RandomNumberGenerator Generator { get { return _highRandom; } }

            static Crypto()
            {
            }

        }

        public static UInt32 Next(this RandomNumberGenerator value)
        {
            var bytes = new byte[4];
            value.GetBytes(bytes);

            return BitConverter.ToUInt32(bytes, 0);
        }
    }
}

[TestMethod]
public void Rnd_OnGenerator_UniqueRandomSequence()
{
    var rdn1 = Rnd.Generator;
    var rdn2 = Rnd.Generator;
    var list = new List<Int32>();
    var tasks = new Task[10];
    for (var i = 0; i < 10; i++)
    {
        tasks[i] = Task.Factory.StartNew((() =>
        {
            for (var k = 0; k < 1000; k++)
            {
                lock (list)
                {
                    list.Add(Rnd.Generator.Next(Int32.MinValue, Int32.MaxValue));
                }
            }
        }));
    }
    Task.WaitAll(tasks);
    var distinct = list.Distinct().ToList();
    Assert.AreSame(rdn1, rdn2);
    Assert.AreEqual(10000, list.Count);
    Assert.AreEqual(list.Count, distinct.Count);
}

[TestMethod]
public void Rnd_OnCryptoGenerator_UniqueRandomSequence()
{
    var rdn1 = Rnd.Crypto.Generator;
    var rdn2 = Rnd.Crypto.Generator;
    var list = new ConcurrentQueue<UInt32>();
    var tasks = new Task[10];
    for (var i = 0; i < 10; i++)
    {
        tasks[i] = Task.Factory.StartNew((() =>
        {
            for (var k = 0; k < 1000; k++)
            {
                    list.Enqueue(Rnd.Crypto.Generator.Next());
            }
        }));
    }
    Task.WaitAll(tasks);
    var distinct = list.Distinct().ToList();
    Assert.AreSame(rdn1, rdn2);
    Assert.AreEqual(10000, list.Count);
    Assert.AreEqual(list.Count, distinct.Count);
}

Using Inner classes in C#


Invalid JSON RPC response: undefined, when running web3.eth.accounts (Node)

Question: I'm very new Ethereum and trying to follow this tutorial:
https://medium.com/@mvmurthy/full-stack-hello-world-voting-ethereum-dapp-tutorial-part-1-40d2d0d807c2
But when I run:
web3.eth.accounts

I get an error:
Error: Invalid JSON RPC response: undefined
    at Object.InvalidResponse (/Users/me/Ethereum/hello_world_voting/node_modules/web3/lib/web3/errors.js:38:16)
    at HttpProvider.send (/Users/me/Ethereum/hello_world_voting/node_modules/web3/lib/web3/httpprovider.js:95:18)
    at RequestManager.send (/Users/me/Ethereum/hello_world_voting/node_modules/web3/lib/web3/requestmanager.js:58:32)
    at Eth.get [as accounts] (/Users/me/Ethereum/hello_world_voting/node_modules/web3/lib/web3/property.js:107:62)
    at repl:1:9
    at ContextifyScript.Script.runInThisContext (vm.js:44:33)
    at REPLServer.defaultEval (repl.js:239:29)
    at bound (domain.js:301:14)
    at REPLServer.runBound [as eval] (domain.js:314:12)
    at REPLServer.onLine (repl.js:433:10)

Everything up until this worked.
Looks like an associated question here, but I don't have enough background to understand and follow it.
Error: Invalid JSON RPC response: undefined from node web3.js app
Can anyone point me in the right direction?
Comment: As per your link, you are running the testrpc. Try to check if testrpc is running or not.
Comment: Thanks Abhishek! I didn't realize I needed `testrpc` to be running in another terminal window. That solved it for me.
Comment: do you execute command 'geth --datadir=./dev/data0 --networkid 1 --rpc 8545 console' on terminal? and then execute 'geth --networkid 1 --datadir=./dev/data0 --dev attach ipc:./dev/data0/geth.ipc' on other terminal
Comment: Hi @tim_xyz - could you add an answer to your own question explaining in a bit more detail what you needed to do to solve this? It might help others in future, and it'll stop this question from going stale and unanswered :-)
Answer: I had the same issue, and just found the solution. This response happens when testrpc is not running, as stated by @Abhishek in the comments.
To solve it, the trick is to run testrpc in another terminal window:
Install web3 and testrpc packages: npm install ethereumjs-testrpc firstname.lastname@example.com
In the same terminal window, run testrpc: node_modules/.bin/testrpc
Open a NEW terminal window (with the first one still open and running), and run node :
mahesh@projectblockchain:~/hello_world_voting$ node
> Web3 = require('web3')
> web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));

Finally, you can run: > web3.eth.accounts
You will get the list of accounts.
Comment: To clarify, testrpc is just a mocked test node right? If you're running a real node and want to debug an issue with the real node, you should not be using testrpc right?
Comment: @marcvander TestRPC is for test network.. What if i want to transfer real coin on tokens on main network programmatically ? what is the command for running main network instead of TestRPC?? Please Help
Comment: I get error after following all the commands you mentioned

`Error: Invalid JSON RPC response: undefined at Object.InvalidResponse`
Comment: I did that but dont get any response. No failures either, it just freezes
Comment: In windows to start RPC from your application root it should be node_modules\.bin\testrpc
Comment: @obesechicken13 yes TestRPC is just a mocked test node
Comment: @veereshkumbar TestRPC is not event for test network, it is just running on your computer. The second part of the tutorial written by Mahesh Murthy explains how to deploy your contract to the public test network, so everyone can see it: https://medium.com/@mvmurthy/full-stack-hello-world-voting-ethereum-dapp-tutorial-part-2-30b3d335aa1f
Answer: I had the same issue, but i solved this problem as:
before run web3.eth.accounts, you need to open new terminal, go to your folder project and run command testrpc, after that you can run web3.eth.accounts without error
Answer: I had this problem but for a different reason.  I was trying to access Ganache (which is now also TestRPC) using an HTTPS URL instead of an HTTP URL:
Wrong:
https://127.0.0.1:8545

Right:
http://127.0.0.1:8545

Assuming you have Ganache listening on port 8545.
TIP: Grab the URL right from the Ganache GUI.  You'll see it at the top of the screen.  If you are using the Ganache CLI version, grab it from the startup messages you should see in the command window you launched it from.  Then just paste it into your web3 object initialization line when you create that object in your Javascript code:
let web3 = new Web3(new Web3.providers.HttpProvider("http://127.0.0.1:8545"));

Comment: My case with **infura** url was vice versa. Infura forces `https`, my connection url was based on `http` and it cause an hour of headache.
Answer: To make access to web3 and use it to retrieve a list of accounts that can be automatically created for you as part of the local ganache network.
You start out by defining a beforeEach() statement where you can add an arrow syntax and add some comments that can guide you in completing these tasks.
So how do you gain access to web3 to gain access to all unlocked accounts?
Inside your beforeEach() you access your web3 module which can be used with many different types of cryptocurrencies. In this case you are looking for ethereum currency so it will look like this: web3.eth.
Then you will want to access the getAccounts() function. web3 is asynchronous in nature, which means it will always be returning a promise and you want it to return a promise with a list of accounts that you care about. So you have to implement async/await like so below:
const assert = require('assert');
const ganache = require('ganache-cli');
const Web3 = require('web3');

const provider = ganache.provider();
const web3 = new Web3(provider);

let accounts;

beforeEach(async () => {
  // Get a list of accounts
  accounts = await web3.eth.getAccounts();

Answer: I had the same issue. Ganache was running on http://127.0.0.1:7545
I replaced this line
const web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:7545"))

with this one:
const web3 = new Web3(new Web3.providers.HttpProvider("http://127.0.0.1:7545"))

And it worked
Answer: Go to settings in Ganache Desktop app and change hostname in server settings.
Settings -> server -> hostname

set [All Interfaces] then try,
running your js file with node following.
const Web3 = require("web3");

var web3 = new Web3(new Web3.providers.HttpProvider("http://0.0.0.0:7545"));
try {
  console.log(web3.eth.accounts);
} catch (e) {
  console.log(e.message);
}


BGE How to make text appear when winning or losing a game?

Question: I'm creating a game in the BGE. I want to make a message appear when the player reaches an object which is supposed to be the winning way out of the game.
I also want to make another message pop up when the player reaches a plane I've created and loses the game. Should I should use the collision sensor and then the Message actuator? But how do I make the message pop up on the screen?
Answer: The Message Actuator works with the Message Sensor to send messages between objects in the game, not to send messages to the player. To show text to the player you need to show a text object or an object that has text as part of it's material, you can also use a scene as an overlay to present the text as part of a HUD.
You could use the messaging system to have an exit sign object become visible by having it change it's visibility when it recieves a message.


How to unit test assemblies targeted at different platforms (64bit and 32bit) in visual studio

Question: I have a visual studio C# project targeted at different platforms (64bit and 32 bit). I also have an extensive unit test covering this project. The nature of the project is such that , the assemblies it generates differs depending on the platform(not the fully qualified assembly name, assembly names are same regardless of the targeted platform). I now want to unit test these assemblies. What is the best approach to do this? Also note that I have to run test report (code coverage and unit test) on hudson. The current implementation have two different projects for two different platforms so that test run folder (the one with in /out directories) does not mess up with assemblies of different image format.  Please note that I am NOT expecting an answer for "how to unit test, perform code code coverage on Visual Studio" . My question is "What is the best and easiest way to unit test assemblies targeted at different platforms in visual studio".
Answer: I would actually make the assemblies Any-CPU, if possible (of-course you may some 32/64 interop that means you have set the CPU target, but otherwise let them be CPU agnostic), and have the executing process decide on the architecture i.e 32/64 bit. That will rapidly cut down on the number of assemblies you have to test.
MSTest (VS2010) should be able to handle both 32 and 64 as it farms this work out to QTAgent(32).exe as appropriate. NUnit has 2 console types one set at any-cpu for running on 32 and 64 and one fixed at 32 bit for testing 32 bit assemblies on 64 bit platforms. Other testing tools may have their own approach or use one of the two I have described.
Coverage tools you could use in hudson:

NCover - a commercial tool (handles 32 and 64)
OpenCover - an open source tool (handles 32 and 64)

There are others that may be appropriate but I haven't used them so I can't comment on their suitability for use via hudson i.e. perhaps the one in visual studio can be command-line driven.
Answer:
What is the best and easiest way to unit test assemblies targetted at
  different platforms in Visual Studio.

Have you simply tried running your unit tests on a x86 and a x64 operating system?  Although I should point out except for a small minority of things, the behavior of your code will behave exactly the same, two important exceptions are working with the registry and dealing with say unsafe code ( i.e. Handles ) which are platform specfic.
Honestly..You seem to already know what you need to do.


About choosing the right point to be the cutoff frequency

Question: If there are multiple points across 0dB in the open loop transfer function bode plot, which one should I take as the cutoff frequency to calculate the phase margin?
In Matlab, it seems that the last point that crosses 0dB from top to bottom is taken as the cutoff frequency to calculate the phase margin.

Any answer is a great help to me, thank you!
Comment: Matlab is correct in selecting this point. However, how did you obtain this compensated transfer function? It looks like that of a buck converter operated in voltage-mode control? If this is the case, then the crossover frequency is not selected far enough from the resonating peak. It should be at least 3-5 times this value. It looks to me that you have placed zeroes in the low-frequency part and it can explain why you have the multiple crossover points. By shifting crossover to higher values, the zeroes will go up and should let the magnitude curve fly well above the 0-dB axis before \$f_c\$.
Comment: Thanks for your answer! !In fact, I'm trying to design a compensation loop for boost in voltage-mode control, and I can't set the cutoff frequency too high because of the inherent right-half-plane zero of boost. It is mentioned in some literature that the cutoff frequency should be set to within 1/3 of the right half plane zero to ensure sufficient stability margin . The open-loop gain obtained after the design is the one above. Could you please explain in detail why the phase margin is not calculated by taking the first point passing through 0dB? Looking forward to your answer!
Comment: I see, in this case, if you are stuck with the RHP zero of the boost, then increase the output capacitance to shift the resonance at a lower value - this will not affect the RHP zero - and you should be able to place the zeroes differently, usually at the resonance or so. Reduce \$f_c\$ to 20% of the lowest RHPZ as 30% can lead to marginal results. What matter is a loop gain with a magnitude of 1 so the point where the margin is critical in your example is after the peak as it is very large before. If time permits, I will try to write an answer tonight.
Comment: Thank you! I will try to improve my compensator design by changing the resonant frequency by changing the value of the output capacitor as you suggested. Thanks again for your selfless help!
Answer: What you see on this Bode plot is the effect of a crossover frequency \$f_c\$ that is selected too close to the resonating peak. You should normally select a crossover value that is at least 3-5 times beyond the resonance. This is to make sure the system has gain at resonance and can effectively reject oscillations.
In the below circuit, I have simulated a voltage-mode-controlled boost converter featuring a 100-µF output capacitance. The RHPZ is evaluated at 14.5 kHz in worst-case which suggests a maximum crossover of 20% of this value, i.e. 2.9 kHz:

If you run the simulation in this mode, compensating the converter for a 2-kHz crossover, you see below the multiple crossover points occurring as in your plot:

This is because of the zeroes placed before crossover which affect the loop gain in the 200-400-Hz region. To improve the situation and respect the 3-5 times relationship between the peak and crossover, the easiest way is to move the peak to a lower frequency. Increasing the inductance value is a bad option as it will affect the RHPZ and bring it even lower. The fastest and simplest way - if cost and size permit of course - is to increase the output capacitance. In the below example, increasing the capacitance to 680 µF while resizing the compensator does the job with a single crossover point around 2 kHz:

These examples can be downloaded from my webpage and are part of the free 60+ ready-made simulation templates working with the demo version of SIMPLIS that I recently released.
Comment: Thanks!Learn a lot!Maybe I should read your book carefully before asking questions. I have bought your Designing Control Loops for Linear and Switching Power Supplies: a Tutorial Guide. Ashamed that I started trying to design the circuit before I even started watching the book.
Comment: You now have some material to study and I wish you luck with your design!


Can smartphones, like iPhone 12 Pro, replace entry-level DSLR cameras?

Question: I am new to this photography. I was planning on buying an entry-level DSLR like Canon Rebel SL3 with a few lenses (18-55 mm, 70-300 mm, and 50 mm prime lens), but after the iPhone 12 pro release I started wondering if this DSLR is any good compared to the phone? Can I just buy the new iPhone instead?
Comment: if this was [for the iPhone 11](https://www.youtube.com/watch?v=1qMkvhCX2pk), imagine with the new lens system  - as a Professional, the DSLR will provide you with all you want as gives full manual control, while the mobile will be semi-auto... you can change things, but it will always have to "say" something about it, meaning, it will always try to override some of your inputs for a "better" image.
Comment: This is like asking if a new model pickup truck can replace an entry level bulldozer? It all depends upon the job one wants to do with it.
Comment: @balexandre Your comment would work great as an answer. [Please put your answers in the answers section, even if they're short.](https://photo.meta.stackexchange.com/questions/4655/please-put-your-answers-in-the-answers-section-even-if-theyre-short)
Comment: A DSLR can zoom in hardware.  No phone can simulate what a 300 mm can do.
Comment: Here is a relevant discussion https://photo.stackexchange.com/questions/108530/can-an-old-dslr-be-upgraded-to-match-modern-smartphone-image-quality
Answer: There is no clear answer: That depends on your type of photography.
If you want the camera just to take the usual this and that photos, you are probably not missing out very much. The computational support in the phone has come quite a way and is improving with astonishing speed.
You will notice some limitations: Due to the small sensor, the performance in low light is limited. The phone's image enhancement will do its best, and is now (year 2022) able to negate a lot of the effects by computational de-noising.
Things you can do with the phone, you probably cannot do that easily with the entry level dslr

Filming without knowing what you do, including slow motion
Carry it around you ALL the time
Photos in very wet environments
Automated panorama

Things that are hard or impossible with a phone

low light photography (depends of post processing capabilities)
anything that needs long time exposures or filters for artistic effect (like ND filters for landscape)
Anything that needs a flash (you will have to use continuous light for any elaborate lighting, but then you cannot easily freeze action with continuous light)
Zoom lenses. The best phones have a 5x optical zoom lens, equivalent to ~130mm. With a DSLR you can get a 400mm-equivalent lens cheaply (250mm lens on a crop sensor).

I am assuming that you use a third party photo app on the phone to have basic access to the settings a photo is taken with.
Note: After seeing a comparison video by Tony Northrup, I have changed some thoughts about low light photography.
Comment: Also, there is a significant difference in your mental focus when you're looking through your camera instead of at it.  The DSLR eyepiece blocking out everything but your frame can be a huge help to your concentration.
Comment: There's also something to be said for the more direct control a DSLR gives.  It's really nice to be able to zoom by twisting the ring instead of having to fiddle with a slider or pinching the phone screen.
Comment: I have to disagree with "hard or impossible on phone" for low light photography. It is actually much much easier with a modern phone to do that and the results will be very much decent in the eyes of many. Sure, if your goal is to print the result, it will not be adequate, but if the main purpose is to share it on phones, it is very much sufficient. With a DSLR, you need a good lens, a tripod, and experience. The algorithms in phones make incredible shots possible, it's not just about the lens and sensor
Comment: Novices don't even imagine the concept of NOT using full auto mode for better control.
Comment: `Photos in very wet environments`  Well, this is specific to the iPhone 12 and a few other highly waterproof phones.  DSLRs are pretty tough, and can put up with pretty challenging environments - moreso, I'd say, than most phones, generally.
Comment: @SaSSafraS1232 If you add your comments as an answer, I'll upvote; I think this is an important part of the overall experience (and result as well). Relatedly, I'd say it's much easier to hold an actual camera still (especially so if you prop it against your face when looking through the eyepiece). When snapping a photo with a smartphone, I find I need to take on average 3 shots to get something without obvious motion blur due to camera shake (phone shake).
Comment: @Kahovius there are a couple of factors that make this worse. One is also common on compact cameras without viewfinders - holding the device away from your face increases shake because it's on a longer lever and not touching your head. The other is that often shooting and almost always other controls are done by poking the screen, which at best encourages holding the phone badly, and at worst actively moves the camera as you shoot.  For static subjects a half-second delay would be helpful; for moving subjects the inherent delay (e.g. it decides to refocus) can be bad enough
Comment: @J... OP asks about entry level DSLRs...I've taken my XXD and XD Canon's into some pretty wet/dusty/just-overall-crap environments...but I'm not sure the entry level bodies or lenses would have survived (or survived to keep on working as designed for awhile)
Comment: @J...The op specifically mentioned the iPhone 12 - and while semi-pro and pro dslrs are usually astonishingly water resistant, he compares that to entry level ones, which are seldom very water resistant. And even if the cam is, the basic lenses lack any of that.
Comment: You forgot "being able to instantly post to social media" ;)
Comment: Does "sensor" also include the lens (light gathering capability)?
Comment: Knowing your automatic modes and how to bend them is very handy when you are short on time or other resources.
Comment: With a proper case one can go diving with DSLR. And the iPhone will die.
Comment: @Crowley I have no knowledge about diving with DSLRs, but pressure-wise I have a hard time believing that a DSLR in a case would go a lot further than an iPhone in a case. To be fair though, googling around the first deep diving case for iphones went 50 meters whilst the two I found for DSLRs went 61 en 100 meters.
Comment: To be fair high end smartcameras by this point take acceptable (still worse than DSLR) low light photos. I sincerely believe putting that in the 'impossible to hard' list is pushing it.
Comment: @DavidMulder For what purpose? I think the smathcams are still useless for large print quality because of A.I. corrections.
Comment: @Crowley the purpose would be to take photos, in the same way that that's always the purpose. I have no idea where you took the large print quality requirement from. The point is that you can go diving with both, although their is a huge difference in cost.
Comment: @DavidMulder because in large prints one can see the details the algorithms in smartphones extrapolate. If you target for 5" displays this is useless - the exptrapolated details are in order of 2 pixels... Even the 4K displays are silly compared to photography sensors regarding resolution.
Comment: @Crowley Your comment was that "with a proper case one can go diving with DSLR", then I pointed out that there was no difference, and you mentioned that that has no purpose as large prints would not be good enough... why would deep diving come with a large print requirement? And even beyond that not sure the claim is true, but don't really care anyway (big prints that are viewed from close up are super rare)
Comment: @DavidMulder The comment was agianst so-called waterproof phones (with many of them having tiny-letter claims that insurance does not cover long immersion in fluids including water) being able to underwater (without special diving cases). DSLRs are, in my opinion, for large prints, large displays or art photography. For moments, "see mom, I was there with Bob" the phones are perfect. If I would go diving, I would take phone in case (DSLR would be in this case like hunting rabbits with Katusha rocket launchers). If I would go diving to shoot fish down there, I would use DSLR.
Answer: (I'm promoting my comments to an answer now that I have a little more time.)
In addition to all the points brought up in other answers, there are several non-technical, "user experience", reasons that a DSLR is superior to a smart phone.
The first relates to the "immediacy" of the controls.  After a few (dozen) hours using a camera the controls become second-nature in a way that a phone never will.  The two most used functions of a camera are the shutter button and the zoom.  When you hold a DSLR these both are right where your hands naturally fall.  It is much easier, faster, and more precise to change focal length by twisting the ring that's already in your left hand than it is to move a slider or pinch your fingers on the screen of a phone.  Similarly, pushing a shutter button on a larger camera body is a lot less effort than pushing a tiny button on your phone that was designed for occasional use with your thumb.
The second is that there is a significant difference between looking through your camera and looking at your camera.  When your eye is to the viewfinder of a DSLR the rest of the world is blocked out and all you can see is your frame.  This allows a much deeper focus on what exactly is in the frame you're about to capture.  This may seem like a minor thing, but I think it actually makes a huge difference in how your end results look and how quickly you improve if you're taking the craft of photography seriously.
Comment: Actually, you can shoot both-eyes-open which, after some training, is very useful. One eye is completely blocked by the cam while the other is almost free. And the humongous advantage of the viewfinder is in the sunlight - while the screen can be hard to read, VF is perfectly visible.
Comment: I definitely agree on the ease of control.  I have a DSLR with a normal zoom setup and I have a bridge camera that I often carry hiking when I have no specific photographic objectives--it's got 25-600 effective but the zoom is not done with a ring--I find it much harder to use, I've lost a lot of shots at the far end of the zoom because it's so hard to hold the composition while zooming in close enough.
Answer: On top of what has been said, part of a photographer's skills is to make arbitrages between light received, exposure time, and depth of field.
With a smartphone, you may experiment with framing, which is very important, but you won't really be able to experiment with light, exposure and depth of field.
In a sense, it is like learning to play guitar with only 3 strings. You may make music but you will remain limited in your expression and subjects.
Comment: Rather than a "guitar with 3 strings", it's more like a synthesizer with auto-accompaniment and keys highlight...
Comment: You could say that, but some "keys" are indeed missing : you can not control aperture and you don't have enough light coming in :  you will not be able to control depth of field, you won't be able to render low-light moving objects.
Comment: @Zeus Did you mean comparing Guitar hero (TM) to a Fender Stratocaster(TM) with old Marshall(TM) amp?
Comment: Yes, and if you are into Portraits with constant light, it might work. I am following an Instagram account that does exactly that. I like what I see there. So, if it fits the niche, why not.
Comment: This answer could be improved by highlighting the strength of high end smartphones in comparison to low end dslrs. The counter of the point you raise for example is that it takes most amateur photographers more time to take a photo with a DSLR and that they might have to think about technical issues rather than the subject, thus limiting their expression and photos. Doesn't make your point less valid (it's true, lots of shots can't be taken with smartphones), but it's not a one way win. (Also worth noting that some cameras do allow a fair bit of technical control)
Comment: @DavidMulder I tend to think that the only real strength of the smartphone is that it is always available to you anywhere, so you can't miss a memory. I would seriously challenge that it is a recommended path to learn photography, as, as you said, most DSLRs have an automatic mode.
Answer: A lot of things have been touched on but upon re-reading your question and seeing you'd get multiple lenses 18-55 mm, 70-300 mm, and 50 mm prime. There is no way a camera phone is going to function with as much versatility as the package you're proposing.  Digital zoom is not a feature.  It's just cropping a photo.  You won't touch a 300mm lens with a camera phone.  What the camera phone is for, in my opinion: Its there, convenient and in your pocket.  Again, it does kinda depend on what you want a camera for.  You have a lot of lenses there that would have different use cases. Just an example, if you were going to use the 300mm lens for wildlife photos then obviously you're not going to get that with a phone.  If you're going to use the 50mm prime that has a super low f stop to make nice portraits, the phone might get closer but still is not going to have the same aesthetic. If you're genuinely interested in photography as a hobby or art, then get a dslr. if you just want to snap photos of stuff stick with the phone and save some money. I imagine though too that you already have some type of camera phone. I don't expect the iphone 12 to be THAT much different from what you have now.
Answer: Yes.
The smartphones are small, easy to use, allways connected to networks, stuffed with all the filters... They, actually, replaced them years ago. But through point-and-shoot cameras.
No.
The smartphone geometry will never allow to build such optics that can barely close to the DSLR/Mirrorless. Each pixel needs some area to gather photons, the more area it has the more photons it can gather at a time and thus one needs lower amplification to get same intensity value for the pixel. Also, if the pixel is too small it can't detect light anymore and quantum physics starts working against your needs.
You know that the smartphone sensor it is 4.5 mm milimeters wide (17.3 mm2). On the other hand, the fullframe sensor is 36 mm wide (864 mm2). Medium size (Kodak, Hasselblad) is 80mm square (6400 mm2).
Another problem is "the glass". Smartphone lenses are around 10 mm wide and thin stack, one can barely change the optical properties of the stack. That's why the ancient (smart)phones had one camera and the new photophones are having many cameras (the more camera, the more adidas). On the other hand DSLR lenses are 50 mm and more wide and significantly longer. Bigger things are easier to build with simillar or better accuracy and one can get wider range of setups.
In other words, for instant photography, the smartphones already replaced them. For prints and photography under not-ideal conditions the DSLR can be beaten only by mirrorless cameras. But in speed, it's hard to beat them.
So, if you are to be instagrammer, DSLR is not for you. If you want to think about things like apperture, shutter speed, flash units, depth-of-focus, then decent DSLR is for you.
Answer: There is, of course, an XKCD for this: https://xkcd.com/1235/
Basically, what everybody else has said with particular emphasis on not relying on "megapixelage" as the sole metric of how good a camera is. Broadly speaking, you'll get a better photo with an old DSLR (let's say 3 megapixels) with a true zoom lens which allows you to frame your subject properly than with a new 'phone which only supports "digital" zoom. And a camera with a true zoom (or a fixed-focus telephoto) is far kinder when photographing people since you don't get forced perspective making their nose stand out like a toucan's.
Thanks to @JS for pointing out that these days a 3 megapixel camera is so far down the relative quality curve that it's probably best avoided. 8-12Mpx cameras are readily available second hand, and even if recently manufactured 'phones are up around the 50Mpx mark a DSLR with a lesser sensor but better lenses will give one a run for its money.
Comment: [There's an xkcd for pretty much everything](https://xkcd.com/1014/)
Comment: A minor nit: OP, please do not buy any camera that only has 3 Mpix resolution.  Your future self will curse you if you do.  Source: Lots of 3 Mpix photos in my photo "books".  I couldn't do better at the time.  Today's photographers have no excuse.
Comment: @JS very true, but I was using it as for the purpose of comparison with a smartphone, and I did specifically say "old"... perhaps I could have usefully emphasised that.
Answer: A phone will be nowhere near as good as a camera if:

You want long-range (planes,  birds, wild-life, etc)
You want a bit more creative control (motion blur, shallow dof, etc)
You will edit the photos later on photoshop/lightroom/gimp/etc. I don't mean remove/add things, even for basic fixes like white balance, saturation, etc. Saving RAW, never jpeg.

My phone (galaxy note) is more expensive than all my gear combined (T6, EFS 24, 55-250, 60 macro), but there is no comparison once do one of those things. Once you start pixel peeping and trying new crops and etc, the phone just falls short by miles. I tried to used my phone as a B roll camera for when I'm using a long lens (like a 600mm rental for airshows) but it's disgustingly bad.
Btw, don't buy the Canon EF 75-300mm. I had one but following advice from here I traded it for the 55-250 STM and it is mindboggling better. I wouldn't give the 18-55 DC or the 75-300 DC to my worst enemy. Slow to focus, not sharp at all, not stabilized, just a waste of glass.
Answer: There are multiple good answers, but I'm going to approach it from a different direction:
On an easy shot a modern phone is within the ballpark of a DSLR.  While there still is a difference it rarely matters.
What does matter is when the shot isn't so easy for whatever reason.  Multiple answers have already touched on zoom--only optical zoom matters, digital "zoom" should be nuked from orbit, it's just cropping the shot, not zooming anything.
I can handhold a DSLR with reasonable success a couple of stops below what I can do with a phone and good vibration reduction can add another three stops or so--I have shot plenty of well-lit interior shots without running up the ISO (and thus the noise level.)  I even have some lucky ones that weren't well lit but came out good anyway.
You have no reasonable equivalent of a tourist remover filter on a phone.  On a DSLR you can put your camera on a tripod, compose, focus, carefully put a 10-stop filter on the camera and take your shot.  Basically anything mobile and not too dense in your scene vanishes--you get a shot of nobody around while people were walking back and forth the whole time.  (Somebody sitting in the scene is another matter, though.)
You also have no equivalent of a polarizing filter.  They can sometimes dramatically change the sky in landscape shots.
Note that high-ISO performance has gotten good enough that low light isn't as much of a stumbling block as it used to be.
Answer: In recent years, I have seen smartphone photos taken by others that totally blew away any reservation I previously had about using smartphones for photography or video.
The usual assertion has been that phone cameras :

Lack ability to change the focal length. But when you look at what they have done, its really not much different from using a prime lens on a Digital Camera, where the focal length is fixed. So this is really not such a big deal. And moreso now you have phones with multiple lenses with different fixed focal lengths, blurring the distinction between a fixed focal length lens and zooms.

Have small sensors, and do not let in much light. Sure its impossible to violate pure physics, but when you look at the improvements in sensors, and the increase in the size of sensors of more recent phones, that combination of improvements has narrowed the advantage that digital cameras have.

Obviously, todays phone cameras lack fully interchangeable lenses, and that's not in dispute, but really its always going to be a trade off, and this is not about just phone vs dedicated digital cameras. Every camera of any kind makes compromises in one way or another, including size or cost, and cannot be all things to all people, so lets think of it like choosing a car, we now have a choice - electric, hybrid, diesel, petrol - you choose, and all these engines can take you to the same destination however in different ways. Like food there are different kinds, home cooked, takeaway, fast food, 4 course meal in an Italian or French haute cuisine restaurant, and you choose what you want to eat at each point in time, based on your needs/constraints.

For most people, I can see a transition, where for most purposes they just use their phone camera to capture the moment, typically using auto mode... To capture the kind of photos which they might miss, cos unless you are an ardent professional, none carries a traditional digital camera everywhere with them.
And the traditional digital camera is clearly reserved for those events where there has been forethought enough to accommodate the lugging of a larger camera to the event.
Ultimately is really not about the camera type, but the end users preferences. And that is a matter of personal opinion. Who determines if photos taken by one camera or another are good enough? I think there is value in the focus of activity that a dedicated camera provides, similar to going to a cinema to watch a film and devote that time, undividedly to it, when you could obviously have streamed the same video over the internet and paid for this service.
Beyond the "quality" of the end results, which could be subjectively indistinguishable for many kind of photo styles, it comes down to personal preference, and which approach makes you take better photos, that you like.
Like different media in painting (oil, watercolor, acrylic, charcoal, etc) each camera has its own aesthetic that is imprinted on the photo, by design, and this is not a function of the format (dedicated vs integrated phone camera), and this also varies from one phone to another, each new model looking that bit more "clean", and same goes for digital dedicated cameras, each has their own "look".
What I would suggest is like food, try each one out, borrow one of each and experiment. The proof is in the eating, you'll know which one you prefer, or like me, appreciate each for their advantage and have both. It does not need to be a choice between one and the other, you can have both. Phone camera and DSLR/Mirrorless.
Answer: Summary:  Get the iPhone 12.  If you are carrying a DSLR you're gonna have a phone with you anyway. If it's a great phone, then why carry a DSLR? If you are really enjoying photography after a year, then go buy a used DSLR and get new lenses as your interests grow.  If you don't like it then sell it. If you want better, then sell it and buy better.
Reasoning:
Over the past two years I've won $500 in photo contest prize money with a Pentax K5, and $800 with the iPhone 6. Those are 12 year old and 8 year old products. The prizes were won primarily due to recognizing the photo opportunity, and secondarily having equipment that was just good enough.
The strength of the iPhone 6 is that it's always with me.  I can take it into difficult environments  where I wouldn't take the DSLR. In a ziplock bag when wading in deep water which I do a lot for work. So it's always ready for a spur of the moment image when the light and subject are right.  Using the DSLR must be planned in advance.
Answer: It depends on the type of photography you want to shoot. I personally couldn't see doing "street" photo without a camera that has immediate access to physical controls.
That said, personally I think the iPhone takes incredible photos for me and love using it for portraits/landscape type shots (I have the iPhone 12 Pro Max)
I'm attaching some shots with the most recent iPhone. Even the improvements in low light have impressed me (though a bit cumbersome to use "Nightmode".

Answer: While it has been mentioned, I don't believe it has been emphasized sufficiently. I am a serious amateur with a lot of DSLR equipment. I schlepped it all all over Asia and Europe, and got some amazing photographs. But now I have a iPhone 12 pro max and I will never go back. I am just too old to be carrying all that camera equipment with me every day on a long adventure. Taking it on the plane and through costumes and into and out of hotels and cars and vans and always making sure you have everything and that it is all secured carefully is a real hassle. I will not dispute some of the artistic and creative advantages of a DSLR but please do not overlook the convenience factor. The difference between simply putting an iPhone in your back pocket and logging around all of your camera equipment for many hours in a new environment cannot be overstated. And for me, the photo quality is not only sufficient it is outstanding. I mainly post my photos to social media and share them with friends. I made slide shows and similar presentations occasionally and I will print a special shot and give it to a friend at times. Just please do not overwork the convenience and portability of the iPhone when making your decision.Plus, it takes damn good shots.
Comment: until you start pixel peeping...  I don't disagree with the "carry around" argument tho. I'd argue for something like a canon RP with a pancake lens (or the r8), a6000 series, GH series from Pana... All very decent cameras, paired with a sensible small prime.


Are there rules for becoming blind or deaf from character birth or injury?

Question: There are special effects (psionics, magic, etc) which can cause blindness or deafness, but are there rules for being blind or deaf from character birth or becoming so from injury?
Comment: Pathfinder [has those rules](https://www.d20pfsrd.com/gamemastering/other-rules/called-shots/), if you are interested.
Answer: I am not aware of any
...and I am reasonably confident that my knowledge here is fairly comprehensive.
There definitely isn't anything in Player's Handbook, Dungeon Master's Guide, Player's Handbook II, or Dungeon Master's Guide II. There isn't anything in Unearthed Arcana. Rules Compendium doesn't mention it. And every other supplement is tailored to some particular facet of the game (certain classes, certain races, certain monsters, certain environments, etc.), rather than "global" rules like this would be, so it's very unlikely to be in any of those.
That pretty much just leaves Dragon and Dungeon magazines. I do not have comprehensive knowledge of what's in those, per se, so it's plausible that it can be found therein. If anything is found, however, it is assured to be awful—Paizo's game design is rarely strong, and this particular problem is, I'm fairly sure, literally impossible to balance. Blindness, in particular, is so monumentally debilitating that being an adventurer while suffering from it is basically implausible. To become an adventurer, magic would be necessary to cure or circumvent the blindness, and likewise, if an adventurer becomes blinded (and it doesn't clear up on its own), curing or mitigating that has to be the first order of business. Even the blindfold of true darkness (Arms & Equipment Guide) is an item of questionable utility, and that gives blind-sight out to 60 feet, which is amazing. Anything less than that—and barring magic, we should expect less than that—is going to create a character who is unable to convincingly adventure with the rest of the party.
Comment: If we're going down the route of "if it exists, then there would be a way to heal it", then there's plenty of limb loss questions that could be linked to support this e.g. https://rpg.stackexchange.com/q/63231/53359 . However, Restore Extremity comes to mind as a counterexample.
Comment: @J.Mini I wasn't; that's certainly how I'd respond to a question about losing an eye (how to, how to heal), but in this case I'm not even getting into that mess. Here, what I'm saying is, *however it happened*, you need to heal it to be an adventurer, *however you do that*. The answers to both "how it happened" and "how do I heal it" are left as an exercise to the reader (who is recommended to look up questions like the one you link on those subjects).
Answer: There is a Variant Rule on page 27 of the DMG called Damage to Specific Areas.

Sometimes, despite the abstract nature of combat, you're going to want
to apply damage to specific parts of the body, such as when a
character's hands are thrust into flames, when he steps on caltrops,
or when he peeks through a hole in the wall and someone shoots an
arrow into the hole from the other side. (...)

The rule suggests to apply a –2
penalty to any action that the character undertakes using that
portion of his body.  There is a table that shows which actions would suffer this penalty. It also says that

Severe damage to both eyes causes a character to become blinded.
Severe damage to both ears causes a character to become deafened.
Answer: Do rules about not becoming blind count? The Shadowspy from Complete Champion has this odd benefit:

Immunity to Blindness (Su): Beginning at 2nd level, you cannot be blinded by magical effects, spells, or bright light. Physical barriers to sight, such as blindfolds and solid objects, still prevent you from seeing. Additionally, any wounds that cause the destruction of your eyes still blind you.

I don't know why they put it there, but it appears that the authors of Complete Champion thought that wounds that cause blindness were a thing in the system. It might be worth skimming that book for any features that may cause it.


Page 184 of The Undoing Project

Question: Michael Lewis contends that for families with 6 children, the birth order BGBBBB is equally likely as GBGBBG. Setting aside the sequence, how is possible that in a pool of 50:50 B:G a random sample of 5:1 is just as likely as 3:3?
Comment: Please explain what you mean by "5:1" and "3:3". Hint: the answer to your question is embedded in an accurate account of that terminology.
Comment: closely related: http://stats.stackexchange.com/questions/256563/why-is-generating-8-random-bits-uniform-on-0-255/256566#256566
Answer: In general 3:3 is much more likely than 5:1 because there are many more ways to get 3:3 than 5:1. However, a specific 3:3 is the same probability as a specific 5:1.
Comment: Many thanks to w Huber and especially David Lane (who gave me more to work with). I think I get it but will have to think about it some more.
Comment: This is **the** answer to accept. Mine is just an attempt at making it very, very clear after your comment.
Answer: tl;dr: You're getting tripped up by the difference between the likelihood of the sequence (BGBBBB vs. GBGBBG) vs. likelihood of having five boys in a family with six children.
Let's simplify this slightly and consider sequences of four, rather than six children. The logic is exactly the same for families of six, but it's much easier to write down the sixteen possibilities for a family of four than the sixty-four possibilies for a family of six.
Here are all the possible sequences, grouped by number of boys (or girls):
$$\begin{array} {|r|r|}
\hline
\textbf{Sequence} & \textbf{# of boys}  & \textbf{# of girls}\\
\hline
BBBB &4 &0 \\
\hline
BBBG &3 & 1 \\
BBGB & 3 & 1 \\
BGBB & 3 & 1 \\
GBBB & 3 & 1 \\
\hline
BBGG & 2 & 2 \\
BGBG & 2 & 2 \\
GBBG & 2 & 2 \\
BGGB & 2 & 2 \\
GGBB & 2 & 2\\
GBGB & 2 & 2 \\
\hline
GGGB & 1 & 3\\
GGBG & 1 & 3\\
GBGG & 1 & 3\\
BGGG & 1 & 3\\
\hline
GGGG & 0 & 4\\
\hline
\end{array}
$$
Next, we need to establish the probability of seeing one of these sequences. Suppose we start with no children. Then, we flip a coin[*] to choose the child's sex. Regardless of the outcome, we then flip the coin again, then again, and again, until we have four children.
The probability of having a boy (or girl) is equally likely at the beginning, and the process has no memory (having a boy last time neither increases nor decreases the probabilities this time), so boys and girls are equally likely on each subsequent flip. Therefore, each sequence is also equally likely: $\frac{1}{16}$ of families with four children have all boys, another $\frac{1}{16}$ have all girls, and yet another $\frac{1}{16}$ alternated boy, girl, boy, girl. In other words, the specific sequence BGBG is just as likely as the sequence GGGG.
However, there are six sequences that yield families with two boys and two girls, while only one that yields a family with four boys. Thus, when you ignore the order, you find that the outcomes (as measured by the total number of boys/girls) are not equally likely.
The same logic holds for a family of six. There are $\binom{6}{3}$, or 20 possible families with three boys and three girls, making a family with that composition more likely than one of all boys. However, the specific sequences BBBBBB and BGBGBG are both equally likely and occur $\frac{1}{64}$th of the time each.
[*] Here, we're assuming that boys and girls are equally likely. This isn't quite true, but it's close enough--and the overall point stands even if it weren't.

This result, incidentally, is from Kahneman and Tversky's 1972 Cognitive Psychology paper. They argue that people expect random sequences to:

Look somewhat like the average "collapsed" outcome (i.e., have equal numbers of boys and girls), and
Show lots of alternations (in other words, "BGGBGB" seems more likely than "BBBGGG")

Neither of these are true, of course, but it's a strong cognitive bias nevertheless.
Answer: There are $6$ siblings in both cases. To get $3\text{ boys}:3\text{ girls}$ you have to calculate the possible combinations of $6$ choose $3$, or expressed mathematically, $\binom{6}{3}=20.$ The order does not matter, and it makes no difference if we are counting the ways of selecting $3$ boys or $3$ girls out of these siblings - if we pick boys, the others are necessarily girls. If instead we look at the ways of getting $5:1$, we have to calculate $\binom{6}{1}=6$, or the possible ways of picking the girl: older sibling, second sibling, etc.
The probability of getting $3:3$ or $5:1$ as a ratio of $\text{boys}:\text{girls}$ depends on the different number of ways you can end up with this ratio. For example, $5:1$ can be achieved with $\small \text{B,B,B,B,G}$, or $\small \text{B,B,B,G,G}$, etc. There are six possible combinations resulting in this ratio. On the other hand, there are $20$ combinations with a $3:3$ split.
However, each specific sequence, for instance  $\small \text{B,B,B,B,G}$, has exactly the same probability, because the $\small \Pr(\text{boy})=\Pr(\text{girl})=1/2.$ Each string has a probability of $\frac{1}{2^6}.$
Now for a ratio of boys and girls you would have to multiply this $\Pr(\text{any given string})$ $\times$ the number of possible strings resulting the particular ratio of boys and girls you are considering (e.g. $20$ in the case of equal split $3:3).$
Comment: Just an extended on **the** answer, which is nicely and tersely provided by David Lane. Accept his answer.
Comment: Very kind of M K and A P to weigh in. Very helpful.

Page 184 of The Undoing Project


Manipulating a picture pdf

Question: Is there a practical tool to modify (with eraser and pen) a pdf file whose content is a scanned document or a picture taken by a digital camera? If so, which one is good?
Answer: Inkscape has some pdf support. Gimp has some support as well.
Answer: pdfimages is one program to extract images:
NAME
       pdfimages - Portable Document Format (PDF) image extractor (version 3.00)

SYNOPSIS
       pdfimages [options] PDF-file image-root

DESCRIPTION
       Pdfimages saves images from a Portable Document Format (PDF) file as Portable Pixmap (PPM), Portable Bitmap (PBM), or JPEG files.

       Pdfimages reads the PDF file PDF-file, scans one or more pages, and writes one PPM, PBM, or JPEG file for each image, image-root-
       nnn.xxx, where nnn is the image number and xxx is the image type (.ppm, .pbm, .jpg).

pdfimages --help
pdfimages version 0.12.4
Copyright 2005-2009 The Poppler Developers - http://poppler.freedesktop.org
Copyright 1996-2004 Glyph & Cog, LLC
Usage: pdfimages [options] <PDF-file> <image-root>
  -f <int>       : first page to convert
  -l <int>       : last page to convert
  -j             : write JPEG images as JPEG files
  -opw <string>  : owner password (for encrypted files)
  -upw <string>  : user password (for encrypted files)
  -q             : don't print any messages or errors
  -v             : print copyright and version info
  -h             : print usage information
  -help          : print usage information
  --help         : print usage information
  -?             : print usage information

pdftoppm is another one:
NAME
       pdftoppm - Portable Document Format (PDF) to Portable Pixmap (PPM) converter (version 3.00)

SYNOPSIS
       pdftoppm [options] PDF-file PPM-root

DESCRIPTION
       Pdftoppm  converts  Portable  Document  Format  (PDF) files to color image files in Portable Pixmap (PPM) format, grayscale image
       files in Portable Graymap (PGM) format, or monochrome image files in Portable Bitmap (PBM) format.

       Pdftoppm reads the PDF file, PDF-file, and writes one PPM file for each page, PPM-root-nnnnnn.ppm, where nnnnnn is the page  num‐
       ber.

As already mentioned, you can try to open a PDF with your graphic manipulation software.
As last fallback, you can display your PDF, take a screenshot, and work on that.
Answer: For modifying a pdf file whose content is scanned document you may install Xournal on your system.
If you have a Debian or Ubuntu-based system, open the terminal and enter this commandL sudo apt-get install xournal, or else install it through your synaptic package manager. For Fedora, use sudo yum install xournal.

Manipulating a picture pdf


JPA NamedQuery Sub Query

Question: I am knocking my head off on a Named Query. I use JPA.. What I would like to achieve is to select all articles with active flags, for a specifc last state (passed as a parameter).
Here are my classes:

Article (intId)
ArticleState (An article may have one or many states, only only is active though)
State (State of an article)

Saved
Draft
Reworked
Approved
Archived
Retired

Here is my query:
<code>@NamedQuery(
    name =  "Article.listArticlesWithActiveFlags",
    query = "SELECT DISTINCT article " +
            "FROM Article article " +
            "INNER JOIN article.articleFlags articleFlag " +
            "INNER JOIN article.articleStates articleState " +
            "WHERE articleFlag.active = true " +
            "AND articleState.state.intId = :intStateId " +
            "AND articleState.intId = ( " +
            "      SELECT MAX(articleState2.intId) " +
            "      FROM Article article2 " +
            "      INNER JOIN article2.articleStates articleState2 " +
            "      WHERE articleState2.state.intId = :intStateId " +
            "      AND articleState2.article.intId = article.intId " +
            "      GROUP BY article2.intId) "
),
</code>
The query runs fine without any error. My problem: Let's say I have an article with the following lifecycle:
2012-02-24: created, so it is in "Saved" state
2012-02-25: submitted for approval, so it is now in "Draft" state
2012-02-26: a moderator modifies the articles to meet specific standards, so it is now in "Reworked" state
2012-03-01: the article is now approved for the entire community, so it is now "Approved"
2014-03-01: the article is now archived because it is no longer useful.
So, the article went through all possible states. My requirement is to display two seperate lists:
1. Approved articles with active flags (in case they requires some changes)
2. Archived articles with active flags (in case they are flagged as "still useful")
My problem is that my article shows up in both lists (approved and archived), even if the last state is in fact "Archived".
The named query is called like so:
        List articlesWithActiveFlags = new ArrayList();
<code>    Query q = em.createNamedQuery("Article.listArticlesWithActiveFlags");
    q.setParameter("intStateId", intStateId);

    articlesWithActiveFlags = q.setMaxResults(intRowLimit).getResultList();

    return articlesWithActiveFlags;
</code>
The query is called two times, one for each list. I have verified the parameter using the Eclipse debug mode, and they pass different parameters (4 for approved, and 5 for archived), which is correct.
Any idea?
Thank you
Answer: use @NamedNativeQuery instead @NamedQuery
here you have an example

JPA NamedQuery Sub Query


Was Harry Potter killed and then brought back to life?

Question: In the last movie, Harry was struck by the Avada Kedavra spell cast by Voldemort. Really, he should be dead. But obviously he was not dead because when Narcissa Malfoy (Draco's mother) asked about the life/death of her son, there was a pause hinting that Harry was talking to the woman. And knowing Malfoy is not dead, in return, the woman declared Harry was dead.
However, one should really be dead if struck by the Avada Kedavra spell.  Does this indicate the work of the Resurrection Stone?
Comment: @Javier: I hate people which refer to the movie and not to the book! :-)
Comment: I hate the movie for not explaining this.
Comment: I finished the book 4 years ago ( I think it is 4 ) and forget about the details.
Comment: I hate people who think books should be necessary to understand the movies.
Comment: Well I might as well continue the theme.. I hate how people who have only seen the film are under the impression they are knowledgeable enough to answer questions about anything other than the film and only the film. But in the end as long as they enjoy [it] that's what matters. Even if they're wrong which if it's only based on the film they probably are; and of course the books are always better though my brother makes a valid point: if he isn't going to read the book then the book isn't 'better' in a sense (though I don't agree entirely with that).
Answer: No, Harry dropped the Stone before his encounter with Voldemort in the Forbidden Forest.
If he survived, it's because :

When Harry met Voldemort in the Forbidden Forest, Voldemort used the Killing Curse on him almost immediately, but only destroyed the Horcrux, rendering his scar "normal." What was not revealed to Voldemort was that when he used Harry's blood three years prior to gain himself a new body, the blood passed Harry's mother's protection to Voldemort and anchored Harry to the living world through Voldemort. Harry was merely knocked to the ground and feigned death. Voldemort, as a result of destroying his soul shard in Harry, was also knocked out
  - Harry Potter wiki, "Tom Riddle" article, "Final battle and death" section
Comment: There's also the fact that the Elder Wand's allegiance was to Harry, not Voldemort.  When Voldemort cast the Killing Curse at a body with two souls, it killed the soul with which it was *not* aligned (the horcrux).
Comment: @gunbuster363 http://scifi.stackexchange.com/q/4610/45
Comment: Why I don't understand why he dropped the stone. It is one of the 3 deathly hallows!
Comment: "anchored Harry to the living world through Voldemort" So basically Voldemort became a Horcrux for Harry??
Answer: Harry Potter clearly did die. This is clear from, for example, the discussion revealed in Snape's memory between Snape and Dumbledore where it is explained to Snape that the only way to defeat Voldemort is for Potter to die.
What is not clear is how Potter comes back as neither the book nor the movie make any attempt to explain it. But his death is clearly necessary for Voldemort's defeat.
Comment: @Jeff: I don't think Dumbledore was wrong. Yes, he _told_ Snape that Harry had to die, but that doesn't mean he really thought so. In the end, the only thing necessary thing was that Harry had to be _convinced_ he had to die, and Harry seeing that memory of Snape helped convince Harry.
Comment: Snape and Dumbledore were wrong.  Harry didn't have to die, but the part of Big V's soul that was in him did.
Answer: Harry Potter did not die. Instead of killing Harry, Voldemort's Avada Kedavra killed the piece of his own soul that was attached to Harry and that made him the seventh Horcrux. Obviously the spell was powerful enough to nearly kill Harry as well, but as Dumbledore says, "Voldemort has clearly always underestimated the power of an intact soul". Harry had a choice at "King's Cross"; he could head back to the world of the living and try to make a difference, or he could "take a train". Harry's will to finish the fight led him to choose the former.
Comment: You could think of it as Harry having a near-death experience. As Dumbledore said: "Of course it's happening inside your head, Harry, but why should that mean it isn't real?".
Comment: So if V's killing curse only acted on the horcrux in Harry, then what was Dumbledore in "King's Cross"? Was it Dumbledore himself, or just a figment of Harry's own mind?
Answer: As Dumbledore explains to Harry while in "King's Cross", Voldemort made seven Horcruxes (soul was split into 8 parts, including voldemort's own body). The last one he never intended to make, and that Horcrux was Harry. So, rather than killing Harry, Voldemort unintentionally killed the Horcrux he never meant to make.
Comment: I think it was only 7 in total: diary, ring, locket, cup, diadem, Nagini, Harry. Did I miss anything? Funny thing though... in the movie, Tom talks to Slughorn about splitting his soul into seven pieces - suggesting intent to create 7 horcruxes... or only 6 for each horcrux + his own remaining self?
Comment: So, whether it's seven or eight depends on whether you count Voldemort's body as a Horcrux.  But Dumbledore didn't.
Comment: "He made *seven* Horcruxes?" said Harry, horror-struck, while several of the portraits on the wall made similar noises of shock and outrage.  "But they could be anywhere in the world — hidden — buried or invisible —"          ¶          "I am glad to see you appreciate the magnitude of the problem," said Dumbledore calmly.  "But firstly, no, Harry, not seven Horcruxes: six.  The seventh part of his soul, however maimed, resides inside his regenerated body.  …" — *Harry Potter and the Half-Blood Prince*, Chapter 23: "Horcruxes"
Comment: … Dumbledore smiled.  /  "You were the seventh Horcrux, Harry, the Horcrux he never meant to make.  …  He left part of himself latched to you, the would-be victim who had survived."    ¶    …     ¶    "He took your blood believing it would strengthen him.  He took into his body a tiny part of the enchantment your mother laid upon you when she died for you.  His body keeps her sacrifice alive, and while that enchantment survives, so do you …." — *Harry Potter and the Deathly Hallows*, Chapter 35, "King's Cross"
Comment: @PeregrineRook fixed!
Answer: Harry didn't really die - his blood in the Dark Lord tied him to life.
After the Killing Curse hit him, Harry asks Dumbledore if he's dead, and Dumbledore says no.

"Then … I'm dead too?'
'Ah,' said Dumbledore, smiling still more broadly. 'That is the question, isn't it? On the whole, dear boy, I think not.'
They looked at each other, the old man still beaming.
'Not?' repeated Harry.
'Not,' said Dumbledore." - Harry Potter and the Deathly Hallows, Chapter 35 (King's Cross)

The reason for this, Dumbledore goes on to explain, is that the Dark Lord taking his blood tethered him to life while the Dark Lord lived, since Lily's protection was then inside them both.

"He took your blood believing it would strengthen him. He took into his body a tiny part of the enchantment your mother laid upon you when she died for you. His body keeps her sacrifice alive, and while that enchantment survives, so do you and so does Voldemort's one last hope for himself." - Harry Potter and the Deathly Hallows, Chapter 35 (King's Cross)

Harry's blood in the Dark Lord tied him to life, so he didn't truly die. He was further helped by being the true master of the Elder Wand. It didn't want to kill its master, so the Killing Curse it cast against him wasn't as powerful as it could have been. It had nothing to do with the Resurrection Stone - that only brings back the "shadows" of people who are already dead, it doesn't prevent death.
Answer: He was shot with Avada Kedavra, but he never died. Voldemort had killed a part of himself.
Answer: Harry possesed the 3 Deathly Hallows. He was the master of death, and thus he could chose to come back to life.
Comment: He did not possess all three hallows when he died. And your assertion on his being able to choose to come back to life is not obvious at all, on what do you base this?
Comment: @Gilles: Because Dumbledore told him so in the "dream."


problem with textarea in javafx?

Question: I used textarea in javafx 2.0 but i need to add it scrolpane.how can i do that?
<code>Scrolllpane s = new Scrollpane();
s.setnode(textarea);
</code>
but when i click on scroll pnane it has doesn't move.
what is problem?
Answer: setNode() is the right method to call to set the node that the ScrollPane will scroll over. I've used ScrollPane extensively in my 2.0 app, but I have not tried it on Text Area.  Based on the API documentation for TextArea (http://download.oracle.com/javafx/2.0/api/com/javafx/preview/control/TextArea.html) it sounds like it has its own built in scroll bars? I would try setting the width/height of the TextArea, and also set the max width/height, and see if you can trigger scrollbars to appear automatically when the lines in the text area exceed the available space.
If you still want to put it in a ScrollPane, perhaps with some other nodes, you should use a container node such as VBox or something to wrap the TextArea, then set the VBox to be your scroll node on ScrollPane.
Also, bear in mind that TextArea is not a committed control for FX 2.0 yet and is therefore less hardened than the other FX controls.
Comment: thanks. i write this question in javafx 2.0 forum and understand that The TextArea is on developing process that's why it is kept on "com.javafx.preview.control" package. it may be fix in next release.
Answer: When we create a text area, scroll bar automatically appears when it goes beyond t

problem with textarea in javafx?


2 questions about local android development

Question: Let me first point out that I am a decently experienced sofware engineer. I am quite familiar with OOP principles and software system architecture. My background is mainly in AS3 but I am also sufficiently versed in Java, JavaScript and HTML(5). I thought I'd mention this because it probably makes a difference in the wording of your answer.
Now, the area I am pretty new to is nativa android development. I am currently building an app that will have some simple web integration, i.e. saving and requesting data in/from the cloud using some webservices. I am fairly early in the development stages so it's not too late for fundamental changes in design.
So far, I have simply pressed ahead and built the features as a straight up android/java app with the intent to incorporate a web service manager to get/post the data from/to the cloud. However, I have become aware of the WebView api and now I am wondering if I should stop building all the features in the app itself. Instead, I am thinking it might be a better idea to have the app simply be a wrapper for a WebView which in turn loads a url. That way I could write the actual app as a responsively designed html5 website that automatically adjusts to any screen size it's opened in. If this approach is viable, I am thinking it will mostly eliminate the headaches of developing for different screen sizes. It would also simplify getting/posting data, since it's easier/more tightly integrated to have server communication from a website than building a RESTful system for the app.
So here are my questions:
1) Is what I am describing above - aka building an app to be just a wrapper for a web app that it loads - a viable and smart way to set up an android app? Is it a common way to do this kind of thing?
2) How can I restrict the website/url to be only loadable from inside the app running on an android device and not from a browser running on a computer? Is this possible at all? Are there apis for this kind requirement? I need this to be an android app, not just a website that can be accessed from any platform in any browser.
3) Can anyone point me to a good tutorial/guide on responsive webpage design? I am pretty familiar with the basics but here's what I'm looking for in particular: I have seen responsive webpages that don't just adjust themselves "fluidly" as the browser window is resized (this kind of responsive design I am sufficiently familiar with and can set up easily). What they did instead was to maintain their original (aka biggest) layout until the browser window reached a certain smaller size and then the page snapped into a different layout, perfectly accommodating the smaller size of the browser window. This change included not only the layout but also the number of items visible and the activation of additional UI elements to make navigation in the smaller window easier. Imagine playing cards layed out next to each other in the window. Let's assume 5 cards fit next to each other when the window is in full screen mode. Now imagine the window is decreased in size. The layout stays the same until the first and the last card are almost out of the visible area. As the window gets to that size, the page "snaps" to a different layout, now only displaying the 3 cards in the center with arrows appearing on the left and right edges to signify that there are more cards to which the user can scroll. How is this kind of responsive design done?
Thanks in advance for any relevant replies!
Comment: You'd be way better off to break this up into smaller questions. The wall-of-text approach is going to scare off potential answerers.
Answer: This doesn't answer all your questions... but I'd check out something like PhoneGap, and start there.


Pushing file to server more efficiently

Question: I have a cluster of daemon running on Mac that generate a lot of jpg in a folder like this content/categoryname. The category name is considered as unique across multiple machine. So what is the easiest way to push all these file from multiple machine to the central server.
Currently I using mv command to do it and basically it overwriting existing file but since there is a huge chance the file already exist it waste a lot of time and IO in doing things unnecessarily.
The reason for doing these is the Mac machine have limited storage and I need them cleared constantly so they can continue generating more.
I am thinking of using rsync but not sure if that is the best way.
Answer: Try rsync
rsync -u <src> <dest>

it will copy filest but if file exists it will skip files that are newer on the destination

Pushing file to server more efficiently


insert comments template inside a loop

Question: i need to insert the comments template inside the loop of posts. My client don't wanna click on post to comment, he wanna comment os the posts list. How can I do this on wordpress?
thanks
Answer: you should use something like that:
<code><?php
  global $withcomments;
  $withcomments = true;
  comments_template( '', true );
?>
</code>
inside the loop of posts.
Comment: Thanks for answer. Also it may not help if you have override $post variable in your template.
Answer: The WordPress template editor allows you to modify these files through the administration UI.  You simply need to copy the lines of code from the comments template into the post loop.  If you've tried this and are having problems, please update your question with the specific issue.

insert comments template inside a loop


How can I get an hp laserjet 1000 printer to work with 64-bit Windows 7?

Question: Lots of people are asking this question but I haven't found an answer anywhere,.
Comment: Possible duplicate of [How to make HP Laserjet 1000 drivers work on Windows 7 64-bit?](https://superuser.com/questions/91474/how-to-make-hp-laserjet-1000-drivers-work-on-windows-7-64-bit)
Comment: an hour later, and I'm prettyh convinced it's not doable, especially because the printer uses what's called a "host based driver".
Answer: i have a LaserJet 1012 that i got working with Win7 RC (64-bit) by picking a similar driver (1015, i think). i did the same in Vista. but now i'm not seeing it in the RTM version so i'm also stuck. :(
if you can find and pick the 1015 driver through Device Manager it's worth a shot.
<rant>
given that my HP 1012 printer was manufactured in 2004 and Vista came out in 2006 (with widespread beta in 2005) and HP didn't even support Vista, i've added HP to my blacklist. i fought with getting drivers from within months of buying the stupid thing and will never again buy an HP product.
that level of support is ridiculous, especially for something like a printer and ESPECIALLY since people (including myself) were able to get it to work through trickery... until now at least, suggesting it would have taken HP little work to provide a real driver.
i'm sorry, but laser printers shouldn't be forced into obsolescence after only one or two years.
</rant>
~jewels
Comment: The line that makes this the accepted answer is "I've added HP to my blacklist".   I'm buying a new printer, not HP.
Comment: +1 for "I've added HP to my blacklist". I too am appalled that HP have not produced Vista/7 drivers for the HP 1000/1010 range.
Comment: Totally agree with ctrager. It's dirty behaviour. The PC companies do it, too -- bought an XP machine? No Vista drivers for you, sorry. Buy a new machine. FAIL.
Answer: I've scoured through Google searches without a result.   Interesting problem.
Not having an HP LJ1000 to play with, I can only suggest that perhaps try drivers for more recent LJ's?
I've gotten lucky that my Epson printers work great with Windows 7 Professional 64-bit.
Answer: It seems that laserjet 1000 is not even Vista compatible. Furthermore, it has been discontinued.
There is a workaround for Vista 32-bits that will also work for Windows 7, but not for 64-bits.
AFAIK, your options are as follows:

You might make the printer work in XP mode and share it. I have no experience with that.
You might use VirtualBox or Virtual PC to construct a 32-bits XP virtual machine, install the printer and share it. This might still not work without lots of fiddling.

I think the first option is the best, if it works.
If not, you could maybe instead convert to the 32-bits version of Windows 7, for which there is a solution.
Comment: Thanks for the ideas.   What are the steps to "make the printer work in XP mode"?

(Converting to the 32-bit version of windows for the sake of a $90 printer would be the tail wagging the dog...)
Comment: If XP mode is installed, you can get to it via Start Menu -> All Programs -> Windows Virtual PC -> Windows XP Mode (or maybe just type XP in the Start menu). You should be presented with a standard XP SP3 desktop. I got all that info from here : http://www.bleepingcomputer.com/tutorials/tutorial155.html.
Answer: I don't know how to reply to the other answer, but for the guy who was talking about the LaserJet 1012.  There is a Vista 64-bit driver that you can install in Windows 7.  I have this printer and have done this.  You do have to explicitly choose the driver and it will warn you about it, but it works.
HP LaserJet 1012 vista 64 driver
Answer: From memory, the Hp LJ1000 is almost EXACTLY the same as the LJ1200.  Not sure that makes a difference, but it there it is.
Answer: I finally got it to work by saving the Vista driver from the HP site to my machine, then going into the saved file and unzipping it, and resaving it.  When adding the device through Devices and Printers, you need to click Have Disk, then browse for the unzipped file.  The port has to be selected as DOT4_001GenericIEEE.  Even though the 1015 was selected as the printer in Devices and Printers, the icon now calls it the 1010, but it works!
Answer: I know how.
You download your driver or copy the files from the old install cd.  Then you go to the setup file in that and rt click it.  Go to the compatability tab on the window that opens and rell it to work with your version of windows up to like xp or such.  Close the window. Rt click the file again n tell it to run as administrator.  Close and the doubleclick your install file.
Its called compatability mode guys n it is in win 7 ultimate and any later windows os..
Enjoy


Notification Icon on HoneyComb is Too Dim

Question: I have an Android app that uses the NotificationManager to inform the user of certain events.  When I call .notify(), the icon I specify is shown in the status bar.  It works fine on various Android 2.2 and 2.3 phones.  But on a Galaxy Tab 10.1 running Android 3.1 the notification icon on the status bar is so dim it can barely be seen.  I've seen one other app that has a similar problem, but all the other apps I'm using that do notifications look OK.  I've followed the Guidelines at http://developer.android.com/guide/practices/ui_guidelines/icon_design_status_bar.html, including creating Android 2.3+ style icons and putting them in the drawable-hdpi-v9, drawable-mdpi-v9, etc. folders.  The icons all look OK when I look at them on my development machine; they are the right colors and are not dim.  What could I be doing wrong that is causing my notification icon to be shown so dim on the Honeycomb status bar?
Comment: Did you by chance figure out how to get it to not dim?  I can't tell if that was your intention.
Answer: As of today there is updated documentation available at the android developers web site:
http://developer.android.com/guide/practices/ui_guidelines/icon_design_status_bar.html
Comment: This updated documentation provides exactly the information I needed.  Thanks!


Practical Walls of Canvas Sukkah

Question: Without getting into the question of the walls of a canvas sukkah (see Shulchan Aruch OC 630:10), what are some easy and practical methods of making kosher walls in such a canvas sukkah? (We try the string method every year and it doesn't work out too well for us on many levels...)
Comment: It seems to me the very nature of this OP is "getting into the question of the walls of a canvas sukkah"
Comment: This year I am planning to use [this](https://smile.amazon.com/gp/product/B073RGS2D4/ref=ppx_yo_dt_b_asin_title_o05_s00?ie=UTF8&psc=1)
Comment: Have you tried using horizontal poles instead of string? They're definitely stronger an more durable to the elements?
Comment: Do the horizontal poles need to be attached to the vertical poles? (i.e.can the halachic "walls" be free standing but next to the canvas?)
Answer: I used to use string, but I graduated to using mailing tape between the upright poles. After I build the frame and before I add the canvas, I put mailing tape around the outside of the sukkah in place of strings (with the sticky side facing in). For practical reasons, I also put a second layer of tape on the inside over the first one so that things don't get stuck on the tape.
The tape holds its integrity over Sukkos, and doesn't slip. It also can help with wind blowing the canvas. The whole thing takes less than ten minutes, and the tape is cheap at the post office.

Practical Walls of Canvas Sukkah


Tag merge: [sequence] and [series]

Question: Can we merge series (2 questions) with sequence (12)? Because we don't really need both of 'em.
Answer: series and sequence are not synonyms. (Whether we actually need the series tag is another matter, since the only question that uses it correctly was closed as off-topic.)
The series tag is used for the mathematical definition of a series: the sum of the terms of a sequence. The first question to use the tag does not fit under the sequence tags (sequence or number-sequence) because it is not about finding the rule or next term for a sequence; instead, it is about an upper bound for the sum of the sequence. I think the other question with the series tag is probably mistagged.
Answer: Unless, of course, we decide to implement series for series' of questions, such as my clues series.
Comment: Using the tag for all questions that are part of a series would make it a meta-tag (bad), while [tags for each series](http://meta.puzzling.stackexchange.com/questions/2772/) have also been rejected.

Tag merge: [sequence] and [series]


I received half of my ex-husband's 401k in 2014, paid penalty fee, no income in 2014, should i file federal income tax for 2014?

Question: I got divorced in 2013,I got half of my ex_husband's 401k.The early withdrawal penalty was determined and prepaid by the settlement amount. no income for the year 2014, should i still file federal income tax? i filed an extension just in case it was needed
Comment: Please clarify _which year_ (2013? 2014?) you received the distribution from your ex-husband's 401k. Also, you seem to imply that the _cash_ amount that you received was reduced by the early withdrawal penalty which was sent to the IRS directly. Is this correct? Finally, does the divorce settlement say anything about the 401k? For properly set up settlements (QDROs), an early withdrawal penalty is not required, and you have the option of rolling over the amount into an IRA if you wish (presumably that ship has sailed already).
Comment: @DilipSarwate: I received distribution check in 2014 per divorce settlement using QDRO, yes 401 k was mentioned in divorce papers, I live in California, and I wasn't given the option of paying the penalty, it was made for me, penalty was taken from the $40,000. I wanted to use some of the monies for bills and such.
Answer: Yes, you should file your tax return. You paid the penalty, but the IRS doesn't know that, they just know that you paid something. Your tax return is the explanation of what it is the IRS got from you.
You might owe income tax on the distribution, in addition to the penalty.
Comment: 401(k) has a mandatory 20% federal withholding. She may owe more or get a refund, depending on he amount involved.


Why isn't this duplicate closed?

Question: I flagged this question as a duplicate, the flag is marked as helpful. But it didn't get closed, I commented in chat and it's still open.
Comment: My guess is it's sitting in the review queue. Somebody did review it and agreed with you, hence the helpful flag, but not enough others reviewed it yet to close.
Comment: @tpg2114 Four days in the review queue?
Answer: Close flags are marked as helpful the first time someone close votes. In this case, one user close voted and three others didn't , so the flag was marked helpful even if the post didn't get closed, and the review item was dequeued due to the majority of do-not-close votes.
A "helpful" flag means that the flag had some worth and you should not be discouraged from raising flags in similar cases later on, even if the flag is not acted on. When it comes to close flags, if a user agrees with you, that usually means that the flag has some merit and should be marked helpful.

At first glance, they probably should be closed, but I'd like to see the opinions of other community members on the matter first given that at least three people feel that it is not a dupe.
Comment: Could a question be created to discuss non closed question? Everyone could post the question as answer, vote and discuss.
Comment: @jinawee It's usually best to discuss these in separate threads. Like this one.
Comment: I voted to leave the question open. Although polarisation was mentioned in your duplicate the discussion of it got a bit lost in the noise. I voted to leave the question open because I think it presents a good opportunity for a definitive answer. It's not obvious to me what the answer is. For a scalar particle the answer is obviously that the wave can't be polarised, but what about a fermion or vector boson?
Comment: @JohnRennie Good point (feel free to modify the question to clarify that, it would make it more obviously not a dupe). _This_ is one of the main reasons that we don't like too many questions per post :/

Why isn't this duplicate closed?


Proving $\sum d\mu \left(\frac{n}{d}\right) = \frac{\mu\left(\frac{n}{(m,n)}\right)}{\phi \left(\frac{n}{(m, n)}\right)}\phi(n)$.

Question: I came across the formula $\sum_{d|\text{gcd}(m,n)} d\mu \left(\frac{n}{d}\right) = \frac{1}{\phi \left(\frac{n}{\text{gcd}(m, n)}\right)}\mu\left(\frac{n}{\text{gcd}(m,n)}\right)\phi(n)$, where $m,n \in \mathbb{N}$ and $d$ is a divisor of $\text{gcd}(m,n)$. I'm aware this eventually reduces to a counting argument, and that, given the Moebius $\mu$ function on the left-hand side, only the divisors $d$ that result in $\frac{n}{d}$ being a product of distinct primes (i.e. no prime factor having an exponent greater than one) contribute something to the sum, but how can I cleverly count the terms of the sum to show they add up to the right-hand side?
Comment: It would be helpful if you clarified the dependence of the left hand side on $m$.
Comment: That's partly what confused me. $m$ only appears on the left-hand side in the form of $d$, which is a divisor of $\text{gcd}(m,n)$.
Comment: @user30293 Since $m$ is basically arbitrary, and $\gcd(m,n) \mid n$, you can baically replace $\gcd(m,n)$ in all $3$ places with any factor of $n$. As such, the formula is equivalent to saying that for any positive integer $j \mid n$, you have $\sum_{d|j}d\mu \left(\frac{n}{d}\right) = \frac{1}{\phi\left(\frac{n}{j}\right)}\mu\left(\frac{n}{j}\right)\phi(n)$.
Comment: @JohnOmielan I see. The way I understood it, the $\phi(n)$ on the RHS just counts the number of integers less than $n$ that are coprime to $n$. The $\mu\left(\frac{n}{j}\right)$ takes care of the sign, but what about the $\phi\left(\frac{n}{j}\right)$? Where does that come in?
Comment: @user30293 I don't know offhand how to prove the formula, including about how that fraction, or where $\phi\left(\frac{n}{j}\right)$, applies. I just wanted to explain how the use of $m$ here in the $\gcd(m,n)$ statement can be simplified to the equivalent formula I gave.
Answer: A possible approach is to show that $n\mapsto f(n):=\sum_{d\,\mid\,(m,n)}d\mu(n/d)$ is a multiplicative function (with $m$ considered fixed). As the RHS of the formula is a multiplicative function of $n$ (since $\phi$, $\mu$ and $n\mapsto(m,n)$ are), it just remains (afterwards) to prove the formula for $n=p^k$ a prime power, which is easy.
For the former, we represent $f$ as a Dirichlet convolution of two multiplicative functions:
$$f(n)=\sum_{d\,\mid\,n}g(d)\mu(n/d),\qquad g(n):=\begin{cases}n,&n\mid m\\0,&n\nmid m\end{cases}$$ (the multiplicativity of $g$ is easy to check; as of $\mu$, it is well-known). Thus, $f$ is multiplicative.
Now if $n=p^k$ and $p^r\mid m$ with the largest possible $r\geqslant 0$, then $(m,n)=p^{\min\{k,r\}}$ and $$f(p^k)=\sum_{j=0}^{\min\{k,r\}}p^j\mu(p^{k-j})=\begin{cases}\hfill 0,\hfill&r<k-1\\\hfill-p^{k-1},\hfill&r=k-1\\p^k-p^{k-1},&r>k-1\end{cases}.$$ This coincides with the RHS of the formula being proven. Indeed, let $q=n/(m,n)$.
If $r>k-1$ then $q=1$ and $\phi(n)\mu(q)/\phi(q)=\phi(n)=\phi(p^k)=p^k-p^{k-1}$.
Otherwise $q=p^{k-r}$, and $\mu(q)=0$ if $r<k-1$. Finally, if $r=k-1$, then $q=p$ and $$\phi(n)\mu(q)/\phi(q)=(p^k-p^{k-1})(-1)/(p-1)=-p^{k-1}.$$

Update. H&W go a simpler way. With $g=(m,n)$ and $q=n/g$ (again), $$\sum_{d\,\mid\,g}d\mu(n/d)=\sum_{d\,\mid\,g}(g/d)\mu\big(n/(g/d)\big)=g\sum_{d\,\mid\,g}\mu(qd)/d=\ldots$$ [now $\mu(qd)=\mu(q)\mu(d)$ if $(d,q)=1$, and $\mu(qd)=0$ otherwise] $$\ldots=\mu(q)g\sum_{\substack{d\,\mid\, g\\(d,q)=1}}\frac{\mu(d)}{d}=\mu(q)g\prod_{\substack{p\,\mid\,g\\p\,\nmid\,q}}\left(1-\frac1p\right)=\mu(q)\frac{n}{q}\prod_{\substack{p\,\mid\,n\\p\,\nmid\,q}}\left(1-\frac1p\right),$$ clearly equal to the desired $\mu(q)\phi(n)/\phi(q)$.


Usage of "other" with "except for" and "apart from"

Question: Should I use other in the following sentence with except for and apart from?

Except for/apart from myself, There are four (other) people in my family.
Answer: Your options are the following:
You can say, after referring to yourself in conversation that there are four other people in my family. (Equally, you might have referred to yourself and your brother or sister, meaning that there were more than five in total.)
or
Apart from me, there are four people in my family.
To include other here is unnecessary although, again, some might do so for emphasis.
Apart from me is preferable to apart from myself although it's permissible to say apart from me myself for the sake of emphasis.
Apart from is more idiomatic than except for in this context although both are correct.
https://en.oxforddictionaries.com/grammar/when-to-use-myself-and-yourself


Comment moderation with disqus comments

Question: Comment moderation on custom post types this answer shows moderation on custom posts. Is this possible with disqus?
Comment: Do you want to include disqus only on some cpt? Or do you want to moderate disqus comments?
Answer: Disqus pre-moderation rules are set on http://disqus.com/admin/settings/ and can't be administered via Wordpress. Currently there are only options to pre-moderate all comments, or comments from unverified users globally.
If you wanted this kind of granularity, you can always register a new Disqus shortname (which is a container for all of your comments/settings) and install the Universal code on those custom post types with your new shortname. Just remember to remove "default" Wordpress comments for those post types so you aren't loading it twice.
It's on that new shortname that you'd set a global pre-moderation rule and it'll apply to those custom post types.

Comment moderation with disqus comments