Fresh OSX Install Failing

Question: I have a MacBook Pro A1990 EMC3215 (2018 15", either i7 or i9 [I'm not sure which]).  I'm having trouble reinstalling the OS.  When I try a fresh install using Command-Option-r via WiFi, I get a -2100F fail code after about an hour.  I followed the steps on https://support.apple.com/en-za/HT201065 to get a fresh install of the OS.  At the "Erase your Mac and reinstall MacOS" step, I followed https://support.apple.com/en-us/HT208496.
I've tried to boot to recovery mode via Command-r, but the machine only goes to the prompt to enter the WiFi name and password.
I created a bootable USB with Monterey on it.  (My other laptop is mid-2012, so I had to download the .pkg from https://mrmacintosh.com/macos-12-monterey-full-installer-database-download-directly-from-apple/.)  When I start with the USB plugged in (via a USB to C connector) and hold the Option key, the USB flashes and I do see the Install Monterey option.  However when I choose that option, I'm immediately given the WiFi prompt again, and the USB light goes dead.  All appearances suggest that the machine is trying a standard WiFi recovery.  After about an hour, I see a -2003F fail code.
I suspect the problem is 1) the current boot is corrupted (hence the lack of Recovery Mode) and 2) the "security chip that offers the prevention of external boot media to be used to startup a Mac" as noted in https://osxdaily.com/2021/08/25/mac-wont-boot-bootable-disk-why/.  However, that article goes on to describe that deactivating this security feature requires one to boot into Recovery Mode, which I seem unable to access.
I'll probably go into the office tonight or tomorrow to try a different WiFi connection.  (I'm doubtful about this as a solution; I'm currently on a home WiFi connection, which shouldn't be restricted.)  I don't have an ethernet to C connector, so ethernet's not a possibility.
I'm currently in South Africa, so taking the laptop in to an Apple store isn't an option.
Any ideas how I might proceed?
Thank you very much in advance for your help.
EDIT: I seem to be able to boot up the laptop to act as an external drive by holding t on start.  However, when I connect my mid-2012 Catalina laptop using a USB to USB-C connector, I don't see an external drive.  I also don't see an external drive when I connect my 4th gen iPad to the laptop using a USB-C to USB-C connector.
Answer: Long story short, my work WiFi allowed me to get to the Recovery Mode screen.  I'm shocked, but the online advice of trying a different WiFi connection really worked.  (I figured what's the difference between one WiFi connection and another.)

Fresh OSX Install Failing


Objective test for self-awareness?

Question: Are there any means by which an observed entity (e.g.: an AI) can be tested for self-awareness using/applying/affecting mainly its visual-oral-auditory-senses and observed responses of same? Failing that, are there any such tests for organic life-forms?
Answer: To test self-awareness in animals there is the Mirror test. It involves painting something on the animal's head/face without their knowledge and observing what they do when they notice the paint in their own reflection in a mirror.
Additionally, robots have been tested for simple self-awareness by researchers at Rensselaer Polytechnic Institute.
Comment: I know of the mirror-test - they also used it with babies (a vid on youtube about it), put a sticker on their foreheads IIRC. The robot-test concerns proprietary theory/algorithm so cannot really conclude anything, but seems suspiciously like just a well written expert-system.

Objective test for self-awareness?


Is it better to store class constants in data members or in methods?

Question: I recently wrote a class that renders B-spline curves. These curves are defined by a number of control points. Originally, I had intended to use eight control points, so I added a constant to the class, like so:
class Curve
{
   public:
      static const int CONTROL_POINT_COUNT = 8;
};

Now I want to extend this class to allow an arbitrary amount of control points. So I want to change this to:
class Curve
{
   public:
      int getControlPointCount() {return _controlPointCount;}
};

The question is whether it isn't better to store constants in methods to begin with, to facilitate adaptability. In other words, isn't it better to have started thus:
class Curve
{
   public:
      int getControlPointCount() {return 8;}
};

The advantage of this is that I could have just changed one symbol in the method in question, instead of moving around constants etc.
Is this a good practice or a bad one?
Comment: i honestly don't understand the question. what is different from changing the 8 in the method to changing the 8 in the initializer of the static? Both require the same amount of work. the method has the downside that it isn't a pure compile time constant anymore and thus can't be used for some stuff
Answer: int getControlPointCount() {return _controlPointCount;}

This is an accessor. Swapping a const static for an accessor is not really a gain as litb has pointed out. What you really need to future-proof is probably a pair of accessor and mutator.
int getControlPointCount() {return _controlPointCount;} // accessor

I'd also throw in a design-const for the accessor and make it:
int getControlPointCount() const {return _controlPointCount;} // accessor

and the corresponding:
void setControlPointCount(int cpc) { _controlPointCount = cpc;} //mutator

Now, the big difference with a static object is that the control-point count is no longer a class-level attribute but an instance level one. This is a design change. Do you want it this way?
Nit: Your class level static count is public and hence does not need an accessor.
Answer: To better answer your question, one should also know how the controlPointCount variable is set. Is it set outside from your class? In this case, you should also define a setter. Or the Curve class is the sole responsible for setting it? Is it set only on compile time or also on runtime.
Anyway, avoid a magic number even in this form:
int getControlPointCount() {return 8;}

This is better:
int getControlPointCount() {return CONTROL_POINT_COUNT;}

A method has the advantage that you can modify the internal implementation (use a constant value, read from a configuration file, alter the value dynamically), without affecting the external of the class.
Comment: Why couldn't you define CONTROL_POINT_COUNT as a method as well?!
Comment: @Earwicker: If it is a method, then it is better to have a signature of a method.
@fluffels: Magic numbers make code less readable and less maintainable. If at some point you need to change the value of the constant, it is easier if there is a definition of it.
Answer: Typically I favour maintaining as few couplings manually as possible.
The number of control points in the curve is, well, the number of control points in the curve. It's not an independent variable that can be set at will.
So I usually would expose a const standard container reference:
class Curve
{
    private:
        std::vector<Point>& _controlPoints;

    public:
        Curve ( const std::vector<Point>& controlPoints) : _controlPoints(controlPoints)
        {
        }

        const std::vector<Point>& getControlPoints ()
        {
            return _controlPoints;
        }
};

And if you want to know how many control points, then use curve.getControlPoints().size(). I'd suspect that in most of the use cases you'd want the points as well as the count anyway, and by exposing a standard container you can use the standard library's iterator idioms and built-in algorithms, rather getting the count and calling a function like getControlPointWithIndex in a loop.
If there really is nothing else in the curve class, I might even go as far as:
typedef std::vector<Point> Curve;

(often a curve won't render itself, as a renderer class can have details about the rendering pipeline, leaving a curve as purely the geometric artifact)
Comment: Great answer :) You make a very good point about minimizing the amount of dependencies. The points are stored in my own custom Matrix class though. Don't you feel that exposing this level of implementation detail potentially increases coupling between client and class?
Answer: In general, all your data should be private and accessed via getters and setters.  Otherwise you violate encapsulation.  Namely, if you expose the underlying data you lock yourself and your class into a particular representation of that underlying data.
In this specific case I would have done the something like the following I think:
class Curve
{

   protected:

      int getControlPointCount() {return _controlPointCount;}
      int setControlPointCount(int c) { _controlPointCount = c; }

   private:

      static int _controlPointCount = 0;
};

Comment: I don't like mixing the static and non-static parts. If you go for a static attribute, initialize it in the declaration of the variable and not in every construction of the object. Both setters and getters should be static.
Comment: (cont'd) Your implementation above will reset the variable to 0 whenever a new instance is created, discarding previous sets
Answer: class Curve
{
    private:
        int _controlPointCount;

        void setControlPointCount(int cpc_arg)
        {
            _controlPointCount = cpc_arg;
        }

    public:
        curve()
        {
            _controlPointCount = 8;
        }

        int getControlPointCount() const
        {
            return _controlPointCount;
        }
};

I will create a code like this, with set function in private, so that no body can play with control point count, until we move to the next phase of development..where we update start to update the control point count at runtime. at that time, we can move this set method from private to public scope.
Answer: While understanding the question, I have a number of conceptual problems with the example:

What is the return value for getControlPointCount() when the number of control points is not limited?

Is it MAXINT?
Is it the current number of control points on the curve (thus breaking the logic that says that this is the largest possible number of points?)

What happens when you actually attempt to create a curve with MAXINT points? You will run out of memory eventually.

The interface itself seems problematic to me. Like other standard collection classes, the class should have encapsulated its limitation on number of points, and its AddControlPoint() should have returned an error if a limitation on size, memory, or any other violation has occurred.
As for the specific answer, I agree with kgiannakakis: a member function allows more flexibility.
Answer: I tend to use configuration + constant (default value) for all 'stable' values through the execution of the program. With plain constants for values that cannot change (360 degrees -> 2 pi radians, 60 seconds -> 1 minute) or whose change would break the running code (minimum/maximum values for algorithms that make them unstable).
You are dealing with some different design issues. First you must know whether the number of control points is a class or instance level value. Then whether it is a constant at any of the two levels.
If all curves must share the same number of control points in your application then it is a class level (static) value. If different curves can have different number of control points then it is not a class level value, but rather a instance level one.
In this case, if the number of control points will be constant during the whole life of the curve then it is a instance level constant, if it can change then it is not constant at this level either.
// Assuming that different curves can have different
// number of control points, but that the value cannot
// change dynamically for a curve.
class Curve
{
public:
   explicit Curve( int control_points )
      : control_points_( control_points )
   {}
   // ...
private:
   const int control_points_;
};

namespace constant
{
   const int spline_control_points = 8;
}
class Config
{
public:
   Config();
   void readFile( std::string const & file );

   // returns the configured value for SplineControlPoints or
   // constant::spline_control_points if the option does not
   // appear in config.
   int getSplineControlPoints() const;
};

int main()
{
   Config config;
   config.readFile( "~/.configuration" ); // read config

   Curve c( config.getSplineControlPoints() );
}

Answer: For integral type I'm usualy using:
class Curve
{
   public:
      enum
      {
          CONTROL_POINT_COUNT = 8
      };
};

If constant doesn't need for any entities except class implementation I declare constants in *.cpp file.
namespace
{
const int CONTROL_POINT_COUNT = 8;
}

Answer: Constants in general should not be defined inside methods. The example you're choosing has two unique features. First, it's a getter; second, the type being returned is an int. But the point of defining constants is to use them more than once, and to be able to refer to them in a convenient way. Typing "8" as opposed to "controlPointCount" may save you time, and may not seem to incur a maintenance cost, but this won't typically be true if you always define constants inside methods.


What additives can make an ethanol flame incandescent? (Historical setting)

Question: How can I make the flame in a wicked lamp incandescent when using azeotropic ethanol (95% ethanol with 5% water) as the primary fuel in a 'hurricane lamp'? (Ethanol burns with an almost invisible flame. It is not suitable as a lamp-fuel for light.)
Would incandescence be improved by dissolving a little table salt in the azeotropic ethanol?
If yes, and if sodium ions in the flame are emitting radiation in the yellow part of the visible spectrum, what happens to the chlorine ions? Would that be an unsuitable solution from a chlorine toxicity viewpoint?
Or would incandescence be improved by dissolving a little tallow in the azeoptrope?
The problem is to be solved in mid-nineteenth-century setting in which ethanol is freely available and kerosene, paraffin and turpentine are not available.
Comment: I added a little sodium chloride to my homemade alcohol lamp and it looked like this: https://chemistry.stackexchange.com/a/164168/79678. The chlorine goes off in the exhaust or reacts with flame species. Interesting challenge.
Comment: In case of the ultimate goal is the light itself, there are camping lamps based on LPG flame and thorium dioxide(?)  fabric, that makes the shining. It could be used for ethanol too.
Comment: Thanks, Poutnik, but the setting is nineteenth century.
Comment: How about naphtha? The recipe of Greek fire is long lost, but naphtha  has been suggested as a plausible ingredient. Pine oil as well.
Comment: @Ed V, Thanks for pine oil idea. But I wonder whether it would be soluble in ethanol/water base-fuel? (Ethanol is feely available in the historical setting. Alcohols are the driver, except for the almost invisible flame if used as fuel without additives.)
Comment: I don't know about the solubility of pine oil in the ethanol/water, but an emulsion might do the trick, kind of like modern day canned Sterno or napalm.
Comment: IHmmmmmmmm. I wonder whether an emulsion would suffer separation while moving up the wick. For the purpose of my nineteenth century setting, maybe that's of no consequence. Thank you.
Answer: Yes, a very little $\ce{Na+}$ goes a long way to make a bright yellow flame. Little would dissolve in EtOH with only 5% water, but that little should be more than sufficient.
Though the chlorine likely would react to a very small extent to form halogenated hydrocarbons, pre-1900, houses were quite drafty, and I don't believe much would accumulate, unless the lamps were used in closed-end tunnels or mines. Another issue with burning EtOH is that incomplete combustion produces acetaldehyde. Hot brass fixtures could act catalytically, creating larger amounts.
Consider "wood alcohol" (methanol) as a fuel, too. Due to tax laws, it is usually cheaper than ethanol, and was made by destructive distillation of wood waste. (Originally, I had misread the question and assumed that would be the fuel of choice.)
Also consider the limelight, which approached carbon-arc lamp brightness and intensity. "During the American Civil War in July and August 1863 calcium lights were used during the siege of Fort Wagner." Perhaps EtOH + forced air would be sufficient to get that lime glowing, though not as intensely as in oxy-hydrogen flame.
Comment: If the alcohol is 140-proof liquor (70%alcohol by volume) containing some fusel oil,  would that also burn in a Hurricane lamp? If yes, would that (with some NaCl) produce a brighter flame because of the presence of the higher alcohol?
Any comment on my tallow idea?
Thanks in advance.
Comment: Tallow might work -- you could easily test it at home. BTW, the wealthy, in the 19th century, used whale oil, or fish oil ("hooligan oil" among the Northwest Native American (First Nations, if you prefer). https://en.wikipedia.org/wiki/Whale_oil#Applications and https://www.fws.gov/story/salvation-fish See also "conspicuous consumption".
Comment: Thanks, DrMoishe. That adds to my body-of-knowledge.


Can a woman engage in excessive conversation with a man?

Question: chapter one of Pirkei Avot states "And do not engage in excessive conversation with a woman. This is said even regarding one's own wife--how much more so regarding the wife of another." does this apply to females as well? Or are they allowed to engage in "excessive conversation" with males?
Comment: Oh, how nice an edited version of that would look in needlepoint font in a frame on the wall, suitable for pointing at to remind the wife or mother-in-law when the headache starts!
Comment: @Gary aspirin and ear plugs are much cheaper and more effective.
Answer: Avot Derav Natan 7:3 describes what this excessive conversation is about. You can read the source, there. In summary, it says that if one was embarrassed by his friend in the Bet Midrash, or he had a confrontation with his friend, there, he should not mention the details of it to his wife, because his wife will make fun of him, and he will lose his respect from his wife.
Since women are unlikely to study in the Bet Midrash, it would seem that the Mishna mentions this prohibition regarding men talking excessively with women.
However, if you were to follow a more general adage from Avot 1:17, Shimon ben Gamliel says that the best thing for the body is silence. That Mishnah is not specific to men but applies to everyone.
I'm going to follow his suggestion by stating, "Enough said."
Answer: From my understanding of the Torah, which is only a few years, there appears to be no clear admonishing for a woman, though it does seem in many places it is discouraged.

The commentaries of the Chumash suggests that Dina was raped by the prince of Shechem because she was extroverted and spoke much in the city. There may be an issue of lifnei iver depending on the circumstances, e.g. if without her speaking certain words a man would not have wicked thoughts.

The Maharal also explains that the reason for the passage in Avot is that women tend to be more practically and worldly-minded from men. Talking excessively with a woman would pull a man away from the eternal concerns of the Torah, which is more damaging than merely wasting time not learning Torah, as one may do with a man of comparable virtue.

Minhag Yisroel, among Orthodox communities, which may have significant Halachic weight, is that women minimize conversation with men who are not their husbands. I believe this practice is to be followed.


Downhill Simplex Method

Question: Is it possible to use Downhill Simplex Method for template matching?Let's say I have 40 landmarks on the edges of an object and I have pixel intesities of normal vectors on these landmarks and I want to use  Downhill Simplex Method for strecthing the template I have with iterations after each iteration i will check mean square of errors of the pixels I have in the template object and image I am working on?Anyone got an idea?Thanks
Answer: The answer to your question is yes. But Mean Square Error doesn't give you the best solution, I recommend using the Mahalanobis distance instead. Further details are to be found on the following reference: F. Arambula Cosio, J. Marquez Flores, and M. Padilla Castañeda. Use of simplex search in active shape models for improved boundary segmentation. Pattern Recognition Letters, 31:806—817, 2010.

Downhill Simplex Method


Game clips keep disappearing/getting deleted

Question: For some reason, I've had problems with trying to keep funny moments and cool game captures on my Xbox One, as they keep disappearing. Just now, I was going to upload a funny clip so that it wouldn't get deleted yet when I got online - it's gone. Any idea on how to fix this?
Comment: I think clips are only ever deleted from xbox live automatically, and I'm not sure what the expiration is, but you're saying they're completely gone from your xbox as well?
Comment: Yes, it was there and then it got deleted the moment I connected to the internet. I disconnected and it still wasn't there and it deleted all my screen shots aswell.
Comment: Gotcha, just to clarify though, if you go to your captures, there is a dropdown menu to switch between "this xbox" and "xbox live". If you are sure you are looking at "this xbox" and they're not visible, that's definitely strange. I only suggest it because I have had clips fail to upload, and they're only found by using that dropdown, they appear to be missing by default.
Comment: Yeah they're gone even after switching from 'xbox live' to 'this xbox' :(
Answer: See this page which states the following (as of October 2018):

Players now have double the amount of storage space they used to have for Xbox Live Captures. So that players use this space efficiently, Microsoft will now be automatically deleting existing video clips over 90 days old that have no views. Any new clips recorded from this point onwards will be deleted after 30 days if they haven't got any views. Players can still back up their clips to a virtual drive or external storage before that expiration period

This would include your personal clips and it looks like they will need to be backed up to external storage or elsewhere in order to keep them.


How can I make the GNOME Shell Activities Bar small all the time?

Question: When I have no apps running, or I'm in the activities screen in GNOME shell, the activities bar is maybe 20px high. When I am running an application, this expands to 70px, possibly to fit the 64x64 application icon it uses for the application. Can I make this bar smaller the whole time?
Comment: Using Minecraft (which has a smaller icon) has confirmed that it is resizing to fit the icons.
Answer: You have to edit the CSS of the gnome shell theme. The default gnome shell CSS file is kept at /usr/share/gnome-shell/theme/ - make sure that to edit the file you  have "root" privileges, then edit  "gnome-shell.css".
The styling of the panel (or activities bar) is at #panel (just do a search) - the panel expanding is probably due to the effects of font-size & height
Answer: Don't know if you ever found an answer to this, but yep, you can. You will need to dive into the CSS of the theme you're using, though (and where that is will depend on your Gnome Shell version and whether you're using a built in or custom theme).
Once you find the CSS file, open it in something like Gedit and find the references to the Activities bar and change whatever settings you want (for your question in particular, you'll want the height setting). There will probably be about two or three places you'll need to find (the "regular" when nothing is running, one when the activities window is open, and one when an app is open). Once you've made your changes, save the file and restart Gnome Shell (alt+F2, r, enter).
Alternatively, you can just install a new Gnome-Shell theme. If you haven't already, install Gnome-Tweak-Tool. Then, you can download your favorite theme and install it from the Gnome-Tweak-Tool.


Which .net Web Application Framework to use?

Question: I am looking for a solid and easy to pick up .NET Web Application Framework for company-wide development use. I am considering DotNetNuke. Is it good ? What else can you recommend ?
Answer: If you're wanting a framework for "Web Applications" in .NET, then your choices boil down to ASP.NET or ASP.NET MVC (both from Microsoft), or an open source alternative like Castle Monorail.
ASP.NET would be the way to go if you want to have maximum use of vendor controls, and you're putting together small, form based applications.
For anything larger or more complex, and if you can do without vendor controls, ASP.NET MVC or Castle Monorail are going to give you a better result because they forces you into better practices.
However, if you're looking for an existing web application to use as a basis for customization, then your starting point needs to be to tell us more detail about what you want to achieve.
Depending on your requirements, Dotnetnuke may be a great fit for your needs, or it might be a spectaularly bad choice. Without more information we can't tell.
Answer: DotNetNuke is a Content Management System.  There are quite a few out there, and more vendor solutions than you can shake a stick at.  It all depends on what you need/want, and whether cost is an issue.  Some more information would help.  Is this more of a wiki-oriented project? An intranet site? A bit of both? Is 24/7 support an issue?
Are you looking for a framework? Or a Content Management System?
List of Content Management Systems.  There are also commercial ones, like SharePoint, as well as a whole host of custom vendor solutions.
Answer: For any complex application, ASP.NET webforms are better as you just have to deal with C# and event driven programming is easier. managing a large sized ASP.NET MVC application is just a nightmare. Don't be lured by Unit testing in MVC.
If you are using webforms you would stay focused on the application rather then coding complexities. + you have so many webcontrols to make your job easier.
There might be some frameworks that you may use for instance framework for logging, or Microsft Enterprise Framework to make application more configurable.
also visit Ext.NET. they have some controls specifically for ASP.NET web forms that would make   your application look better.
Answer: SharePoint is an option but I don't recommend it.  I've always wanted to try DotNetNuke.  It has a strong community and a lot of growth.
Our team worked on SharePoint features for 5 months before we ditched it. Deployment and debugging are awful experiences. We had to resort to lengthy build scripts within Visual Studio and we used a few open source tools (WspBuilder, SharePoint Installer, etc.) just to make the process half-way manageable.
Maybe SharePoint will grow up and get real Visual Studio integration some day (I hear that is the plan with VS 2010). Until then, it is just too much trouble. The learning curve is steep and you will have to spend a lot of time searching XML config files to track down problems. SharePoint will probably make you despise XML configurations!
UPDATE:
Sharepoint is getting some much needed attention in VS2010. See: http://www.cmswire.com/cms/enterpr...
Answer: In the end you will need multiple frameworks.  It's difficult to support any complex business environment with just one.  Sounds like your dedicated to .NET so I would stick with ASP.NET or ASP.NET MVC. Use ASP.NET MVC for larger applications requiring domain driven development with testing.  Use ASP.NET for data driven applications that closely match your SQL schema (quick and dirty applications without much complexity).  Assuming you are using MS SQL for persistence.  I would also consider the latest version of SharePoint. It's now based on ASP.NET 2.0 and bit easier to deal with than it was in the past.  If a lot of your business requirements are simple you can provide a great deal of functionality with SharePoint out of the box.  Of course with SharePoint you will need a good support staff for backup, maintenance, and recovery.


Difference of professor salaries between different department in the United States

Question: Is there any research/study/survey/... that looked at the difference of professor salaries between different department in the United States?
Answer: Here's one that's readily accessible, though the full data isn't public (but can be obtained).   Here's another one in a much more concise format, though a bit older.
At least for public universities, it's not too hard to do such a survey since our salaries are public record.  I haven't actually checked but I would imagine that the groups that have done these surveys keep them updated every so many years so you can use the ones I linked to to find more.
Comment: Note that sometimes the salaries you find online are not accurate.  My university's salaries were once posted by a 3rd party site in a very misleading manner to make the salaries seem higher than they are.
Comment: I'm skeptical the data in the second link is not misleading.  (Though +1--it's not your fault!)  It tells you something, but the variance among schools for a fixed department is so large (e.g., compare research vs teaching, and public vs private) that this should be controlled for to get a better sense of things.  E.g., the variance at my school among certain departments is much larger than what that aggregate data would indicate.


Is it possible to read unknown number of lines from console in C#?

Question: There is a function, which can read a single line from the console input (Console.ReadLine()), but I wish to read or some arbitrary number of lines, which is unknown at compile time.
Answer: Of course it is. Just use just read a single line (using ReadLine() or whatever else you please) at a time within either a for loop (if you know at the beginning of reading how many lines you need) or within a while loop (if you want to stop reading when you reach EOF or a certain input).
EDIT:
Sure:
while ((line = Console.ReadLine()) != null) {
    // Do whatever you want here with line
}

Comment: It will keep executing waiting for a line until it receives an indication that there are no more lines coming, which is the end of file signal, which is ctrl-Z on Windows I believe.
Comment: I do not know how to do it with while loop, I do not know how to check if there is a next line or not! Some hints or an example, please!
Comment: Thanks, it is helpful, but how could I to determine which line is the last one? Currently the program will wait for a new line input.
Comment: I miss to comment about "(if you know at the beginning of reading how many lines you need)" - it is unknown, if there is no longer an input, that should mean end of it.
Answer: Some of the other answers here loop until a null line is encountered while others expect the user to type something special like "EXIT".  Keep in mind that reading from the console could be either a person typing or a redirected input file:
myprog.exe < somefile.txt

In the case of redirected input Console.ReadLine() would return null when it hits the end of the file.  In the case of a user running the program interactively they'd have to know to how to enter the end of file character (Ctrl+Z followed by enter or F6 followed by enter). If it is an interactive user you might need to let them know how to signal the end of input.
Answer: The best thing to do here is use a loop:
string input;

Console.WriteLine("Input your text (type EXIT to terminate): ");
input = Console.ReadLine();

while (input.ToUpper() != "EXIT")
{
    // do something with input

    Console.WriteLine("Input your text(type EXIT to terminate): ");
    input = Console.ReadLine();
}

Or you could do something like this:
string input;

do
{
    Console.WriteLine("Input your text (type EXIT to terminate): ");
    input = Console.ReadLine();

    if (input.ToUpper() != "EXIT")
    {
        // do something with the input
    }
} while (input.ToUpper() != "EXIT");

Answer: simple example:
class Program
{
static void Main()
{
CountLinesInFile("test.txt"); // sample input in file format
}

static long CountLinesInFile(string f)
{
long count = 0;
using (StreamReader r = new StreamReader(f))
{
    string line;
    while ((line = r.ReadLine()) != null)
    {
    count++;
    }
}
return count;
}
}


How can I add a voiceover to my Keynote presentation?

Question: I have a MacBook Pro with OS X 10.9.4 and Keynote 6.2.2.  I have a presentation done in Keynote with slide and music.  Now I want add a voice over.  Can I do that and if so how?
Answer: Go to Play → Record Slideshow and click the Record button at the bottom to begin.

Answer: You could also use QuickTime Player to record the audio separately, in case you want to edit it, add pauses, etc. QTP is actually a pretty versatile tool; it can do screencasting and general recording but most people don't even know it's there.
Answer: Update for Keynote 12.0 (and perhaps some previous version(s)):
In the Keynote menubar: Insert > Record Audio


ffmpeg set report log filename

Question: I am running ffmpeg.exe on command prompt. I am trying to generate a report file using the <code>-report</code> option.  How to explicitly specify the report name?
Comment: See also the main Q&A about ffmpeg reports: http://stackoverflow.com/questions/2066076/how-do-i-enable-ffmpeg-logging-and-where-can-i-find-the-ffmpeg-log-file
Answer: looks like it can only be set [?] with an environment variable
export FFREPORT=file=/home/someone/log/ffmpeg-$(date +%Y%m%s).log
this is because, otherwise, it would have to parse the output filename from the command line parameters, which means "ffmpeg is already running, so has already started logging things" so kind of a cat or mouse game, apparently.
ref: https://ffmpeg.org/trac/ffmpeg/ticket/1823 and some mailing list posts.
Answer: The easy method on Windows 7 is:

ffmpeg  -i filename.mp4  -hide_banner  2>  filename_Info.txt

.
My prefered solution in a batch file is:
<code>:: Location of file
SET file=filename

:: Location of FFMPEG
SET ffmpeg=C:\Program Files\FFmpeg\ffmpeg.exe

:: Analyse File
"%ffmpeg%" -i "%file%.mp4" -hide_banner  2> "%file%_Info.txt"
</code>
For my single option "-hide_banner" you can substitute whatever you need to use in the way of options/switches for your intended command line.
You please yourself as to the name and path of the report file, which can be any valid filepath.

ffmpeg set report log filename


how to disable quick access popup(Open all Menu) for a profile user except admin?

Question: I need that a sales profile user can not see the other Main menu  except sales and analytics while other user can see all the main mainu list.
there is a shortcut image(small computer) with tool tip name "open all menu" . when we click on it it opens all the menus with its submneus . that i have to disable for same profile user while other users can see this image.
Answer: You go to Setting > Profiles then:
Manage user-specific modules access to different Roles


Installing Ubuntu on one of two hard drives

Question: I have two hard drives. One is used for Windows and one is empty. I want to install Ubuntu on the empty hard drive. The Windows hard drive is disk0 in Windows and the empty hard drive is disk1. When I install Ubuntu and it asks where I want to install it, I choose "Something Else" but I am stuck there. What do I choose for "boot loader installation"?
Comment: You want to install it side by side
Answer: Put the boot loader (known as the GRUB) in the hard drive that you are installing Ubuntu on. If Windows is in /dev/sda put GRUB in the MBR of /dev/sdb. That is, do not put GRUB in /dev/sdb1 or another partition.
In the BIOS set to boot from the Ubuntu drive. This may boot straight to Ubuntu at first. If that happens open a terminal by pressing Ctrl+Alt+T and type sudo update-grub. From the next boot you should get the choice to boot Ubuntu or Windows.
See How do I set up multiple HDD?
Answer: Installing Ubuntu on 2nd hard drive, Windows on 1st

Unplug Windows hard drive.

Install Ubuntu on second hard drive.

Plug Windows drive back in.

Set Ubuntu hard drive as the first HDD in BIOS.

Boot Ubuntu hard drive.

In Terminal run:
  sudo update-grub

This should automatically add a Windows menuentry to the grub boot menu.
You can change back to Windows bootloader, (first HDD), using BIOS if desired.
Comment: Thank you karel, my "code" button does not seem to be working. Any idea how to fix?
Comment: Pressing the code button inserts 4 spaces in front of the selected text if it starts on a new line and 2 spaces after it. If the selected text is in the middle of the line it formats it as code inline. Either of these functions can be duplicated from the keyboard manually. If the code  is in as numbered or bulleted list then 8 spaces must be inserted before the code in order to position it correctly in the list.
Answer: I connected up one drive and installed Ubuntu. Then disconnected the drive. Then connected another drive and installed Windows 7. Then I connected up both drives and in the Bios set the computer to boot from CD as 1 then the Windows 7 as 2 and lastly the Ubuntu drive. Now when I start up it boots into Windows 7 without any menu. When I want Ubuntu as it is booting up I press F11 and choose the hard drive Ubuntu is on.


How to restore dismissed reminders in Outlook 2010?

Question: How would I retrieve all the dismissed reminders in Outlook 2010?
Comment: It's a pity that Dismiss doesn't "do what you mean" and only dismiss the reminder once for a reoccurring reminder, rather than forever.
Comment: It's an old question admittedly but the solution is the second answer posted below (and should be accepted ;) )
Answer: Your question asks to "retrieve all dismissed reminders".  I am not sure if, by "retrieve", you mean to view a list of all dismissed reminders or if you want to "undismiss" them.  I've been looking for a solution to the latter for a long time and just now stumbled upon it.  You first open the meeting or appointment (I double-click the event in my calendar).  At the top, you will see this:

If you dismissed the reminder then the Reminder field will say None.  Change it to a new interval and then click Save & Close.  You should get the reminder again.
Comment: You must also select a reminder that did not pass, otherwise it will go back to "none" after you save.
Answer: It is not possible to restore already dismissed reminders.
But you can open the calendar view and search by modification date:

In Outlook 2007 or Outlook 2010 use modified:date format in the search field.

For example, I would type modified:2.10.2012 to see items I might have dismissed today

It's not 100% accurate as many things can modify the item, but if you do this soon after dismissing the reminders, it should be 100% accurate.
Comment: I find it very hard to believe that Outlook 2010 has absolutely no way at all to restore an accidentally dismissed meeting reminder.
Comment: At least in outlook 2013 "today" is an acceptable value too, so to find dismissed calendar items you can search for "modified:today". Also works for tasks.
Comment: I use Outlook daily and would be happy to upvote your answer where you describe how to restore them
Comment: For some of us, `modified:8.22.2022` does not work, but `modified:8/22/2022` works.
Answer: I accidentally dismissed some old reminders and the other answers didn't work for me for recovering them, so I restored a recent backup and reverted to that temporarily which brought them up.  If you don't have a backup, there's a possibility you can use the "Restore previous versions" option in the right-click menu of the PST file (or its parent folder) in Windows explorer to get a recent version.
To be safe, I closed Outlook, backed up my current PST, and disabled my network connection before restoring the old PST.
Answer: If your reminders are from emails you can sort by date then flag status. You'll see all the emails with red flags. For each one add a new reminder.


How do I find Lydia? She disappeared after I told her to wait

Question: I told Lydia to wait so I could go kill a dragon because I didn't want her being killed. She wasn't in a cave. She was in a witch's hut. I slowly made my way back to her (because I was over my carry weight) and she was gone. This has happened before but she just popped back up. I've waited for her and she hasn't popped back up or returned to Dragonsreach. Is there a way to get her back? Or can she die if she's not with me? I'm playing on the PS3.
Comment: How many in-game days has it been since this happened?  Do you own Breezehome?  Are you able to hire other followers, or does the game indicate that you already have a follower?
Comment: Try waiting for one in-game week. It might take her a long time to get back. If not, it is very possible that she's dead.
Answer: If you don't have a mod to prevent it she can be killed. Any follower can. If she was attacked wherever you left her she will move around as she fights. If she lives she will the stand in her last location and may not be easy to find. When Followers get tired of waiting for you they go "home" wherever home is for you.
Also try fast traveling from one hold to another. If she's alive she'll show up after a couple of these. If you fast travel through several holds and she doesn't show up you have my condolences. On xbox I use a mod called "No More Dead Followers". Maybe its on PS3.


Control to select from a list and change order of selected items

Question: I want to use a control I've seen many times before, but I don't know what it's called, so I don't know how to look for it.  The control would have two listboxes.  The box on the left would list available items.  The box on the right would list selected items.  Buttons between the two lists would allow the user to move all items from the available list to the selected list, to move one item from available to selected, to remove one item from the selected list and return it to the available list, and to remove all items from the selected list.  There would be two other buttons, typically located on the right side of the selected list, that would allow the user to move one of the selected items up or down in the list of selected items.  Where can I find that control?
The question referenced as a duplicate to this is not a duplicate.
The referenced question asks how to do this.  I know perfectly well how to develop this control, and it won't take that long for me to do.  It will definitely be worth the time it would take to do it.  But because many, many programs have this type of functionality, I figured that somebody somewhere had written this control already, and uploaded it someplace for the rest of us to use so we don't have to spend half a day writing our own.  The point of my question, and the reason that it is not a duplicate, is that I am not asking how to develop this control.  I am asking if anybody here can point me to such a control that has already been developed.
Comment: I was going to ask a further question, but I see the answer
Answer: There is no common control like this. You have to develop it yourself.
Answer: There is no standard Windows control that I am familiar with that offers this functionality out-of-the-box, however it would be pretty straightforward to implement your own UserControl which contains these components:

Two ListBox controls, one anchored top-left-bottom, the other top-right-bottom.
Two Button controls in between with left and right arrows, anchored top only
Button controls underneath the lists to move items up and down.
Comment: Yes, it would be easy enough to do it myself, and probably worth doing, but I am hoping someone somewhere had already done it and put it up on the web someplace.


SanDisk SecureAccess software

Question: SanDisk USB flash drives come with a password and file encryption software called SecureAccess v1.0 and the update is v2.0. This doesn't work on my UBUntu Studio 12.04 LTS OS. Their website states its only supported in Wndws and Mac. THe error says 'please run SecureAccess from an external Sandisk device'. I'm ok with it not working for now since I haven't stored files in the protected 'Vault' folder yet, however it would be nice to use such. WINE is having problems running this software. Any suggestions?
Comment: I'd personally use TrueCrypt or the fork VeraCrypt instead. Wanna bet that there is not either a serious security flaw or an NSA backdoor somewhere in SanDisk SecureAccess?
Answer: I know it won't help you with any files you've written from a Mac or Windows computer, but you might consider using the ecryptfs system, in the ecryptfs-utils package.  There is even a PAM module which uses the passphrase you provide to log in to encrypt the passphrase used for encrypting the files and filenames on your USB drive.  Basically, using the standard ecrypt system, you could mount your USB drive at $HOME/.Private and then use the ecryptfs-[u]mount-private utilities to (u)mount your crypted USB drive.
Also of note, yeah....this wouldn't help if you wanted those crypted files to be able to be read on a Mac or Windows 'puter.  Sorry.
Answer: You need to go into winecfg using Wine Tricks. Once there, head to the Drives tab click "Auto Detect". Once that is done, plug your USB in and see if your USB is detected. If not, manually set the location of your USB.
Answer: I don't believe SanDisk secure software works with Linux. SanDisk's software is the only way to utilize the built in hardware encryption. So you're stuck with ether using the encryption and only using the drive with Windows or Mac OS machines. Or using an alternative such as VeraCrypt, but without the hardware encryption benefits. Nothing's lost from a security point of view, just encryption speeds may be slower.

SanDisk SecureAccess software


Thermal Resistance of PSU's heat sinks

Question: I have a non functional PC power supply unit, and I would like to keep its heat sinks, but they have no model or part number in them. Is there a way to estimate, calculate or measure their thermal resitance? The PSU is a Sentey BCP 450-OC, here is a picture of the heat sinks
Comment: A look in heatsink catalogs will give you a reasonable idea.
Answer: Measuring the effective heat resistance should be pretty straightforward: you'd affix load resistors to where you'd later put the components that should stay cool. You work in a controlled temperature environment (i.e. indoors at 20°C).
You put a measurable amount of power through the resistors (e.g. by using a lab voltage supply and measuring the voltage over and current through the resistors). You measure the temperature and wait until you've reached a stable state.
The difference of resistor temperature to ambient divided by the power is your thermal resistance.
But: honestly, I don't think this is worth it. Both the shape and the fact they're fixed right in front of a fan means that they are to be used with forced cooling, i.e. with a fan in a specially shaped enclosure. You'd have to measure in the enclosure and with the fans you're planning to use.
Answer: Is there a way to estimate, calculate or measure their thermal resistance?
Yes. I am assuming that you want to know the heatsink to ambient thermal resistance.
The calculations are complicated, somewhat easier for forced air (fan), than natural convection. I wouldn't trust any calculation that I would perform without verifying it with a test. So, ...
It is easiest to test. This heatsink is designed for forced air, it won't be very good without a fan.
Attach something to the heatsink that you can be made to dissipate a known amount of power. A chassis mount resistor will be a good choice. Measure the temperature rise of the heatsink, subtract the ambient temperature, divide by the power.
Answer: The fluid aerodynamics of forced air velocity overwing surface determines the thermal resistance coefficient in °C/Watt for case temp. rise.
The air velocity over the surface, not the fan exit, significantly lowers the resistance by some constant, k (< 1) times the Rca, Resistance case-ambient. This is more of an aerodynamic design requirement.  One could come up with a more accurate answer, but based on my exposure to heatsink design and testing I would estimate 8 °C/W and with that airflow 1~2 °C/W.

Thermal Resistance of PSU's heat sinks


Why are the Mandalorian Supercomandos blaster bolts yellow?

Question: In Clone Wars, the blasts from the weapons of the Galactic Republic were blue (extra ionization) to be more effective against the droids of the Confederation. In general, blaster bolts appear to be red. Since this is the case, why does Gar Saxon's group of super commandos fire yellow ammunition?
Answer: To put it simply, the color of your blaster bolt depends on the gas used as ammunition.

Blaster bolts came in different colors. Red was the most common color,
and was made from cheaper gas. This color was used by the Confederacy
of Independent Systems, the Rebel Alliance, the Galactic Empire, and
the First Order. Blue was used by the Galactic Republic, and the
Resistance. This was an ionized type of blaster bolt that specialized
in disabling machinery such as droids but was also effective against
organic beings. Green was used by Naboo Security Forces, and the
Umbarans, as well as the Starfighter Corps of the Galactic Empire.
This was a more expensive and more powerful type of blaster gas.
Yellow was used by Mandalorians. Purple was used by the Geonosian
Starfighters, the Malevolence and most notably the Magna Guards.
Purple was also used by the Techno Union octuptarra tri-droid variants
on the planet Skako Minor. Orange was used by the Marksman-H training
remote and training droids on Kamino as a low power and non-lethal
type of blaster bolt. Cyan was a low-powered version of the blue
blaster bolt that was used by clone cadets in their training sessions
against training droids.
Source : Star Wars Wiki
Comment: basically, there's no reason, just it says so?


How do I detect an item with a name in someones inventory for 1.13?

Question: So I'm trying to make a thing where you walk up to it and a gate opens if you have a paper that is named on you but since the 1.13 update I don't know how to do that
Answer: The things that have changed since 1.12 are the JSON formatting of custom names, the position of the NBT data of the command and the /execute command itself.
Let's say I would like to test if I have a paper on me that is named "Card". Here's what the command would look like:
/execute if entity @p[nbt={Inventory:[{id:"minecraft:paper",tag:{display:{Name:"{\"text\":\"Card\"}"}}}]}]

First of all, I use /execute if instead of /testfor. Next, I put the NBT into a different position, @p[nbt={NBT}] instead of just @p {NBT}. Finally, the JSON formatting. Instead of {Name:"<Name>"} I used {Name:"{\"text\":\"<Name>\"}"}.


how to make use of web service in iphone app?

Question: I'm just starting to make use of webService in iphone apps.Firstly I want to add Facebook login in my app. for that I have downloaded fresh copy of Facebook SDK BUT I can not install it , at the end it says "installation failed" every time. and can any one put well form steps to make use of web service?
Answer: Install the Facebook SDK from this link: https://github.com/facebook/facebook-ios-sdk
If you only want to integrate sharing via Twitter or Facebook: take a look at this tutorial: http://www.appcoda.com/ios-programming-101-integrate-twitter-and-facebook-sharing-in-ios-6/
There are many ways to connect to a webservice, you have to be more specific in order for us to help you with the thing you want to accomplish. But take a look at this link:
http://www.icodeblog.com/2008/11/03/iphone-programming-tutorial-intro-to-soap-web-services/ and http://mobile.tutsplus.com/tutorials/iphone/iphone-json-twitter-api/


How do I auto-blank text console on laptop?

Question: How do I set up the console of the laptop to auto-blank after X minutes. I want to set this natively to the console, not a logged in terminal, because I may not log into it very often, and it may be sitting at a login prompt most of the time.
I would like the console to wake up and display when a key is pressed, and go back to powersave/blank mode after X minutes.
I can't believe it's so hard to find this -- I've been looking for some time. This is something that I got used to on NetBSD and FreeBSD as just a normal configuration parameter for the console. Surely it has to be possible.
I've already tried a few different things.  Most of them are based on explicitly manipulating the display or terminal settings.  This should be automatic.  I've tried using this in my grub config, but it seems to have no effect:
GRUB_CMDLINE_LINUX_DEFAULT="consoleblank=60 maybe-ubiquity"
This is on Ubuntu 18.04.4.
Answer: The setting is in Settings → Power → Power Saving → Blank Screen then set time before screen blanks.


Why doesn't my wireless mouse connect automatically?

Question: Every time I want to use my wireless mouse (Apple Magic Mouse) with my Macbook Pro, I need to plug in a USB mouse and "Connect" the mouse manually via the bluetooth menubar widget. Is there anything I can do to make this happen automatically?
Answer: If you've paired it before, clicking the mouse after turning it on should do it.
Comment: Well ... it's simple, but it's not very discoverable. I guess I just expected it to work - after all, the green light on my mouse is flashing. I assumed that was a "trying to connect" signal - who would've thought it needed an extra 'kick' to get things going? Not me, obviously!
Comment: I hadn't tried this until just now - I think a small part of me just didn't believe it could possibly be that simple. Thanks :-)
Comment: as I was reading the comments, I was like 'these people are so sarcastic' but it actually worked. lolz! because when i turned it ON i just hover it around and i don't see the cursor moving, so i assumed it's not working. the solution is 'click the mouse'. very helpful! thanks!
Comment: OMG. Was this simple? I was so frustrated already. Thanks a lot!
Comment: Glad I could help! Isn't Apple great like that?
Answer: If you are connecting/pairing for the first time, use a USB mouse/keyboard + trackpad to do the following:-

Turn on your Magic Mouse
Go to System Preferences from the Apple Menu
Click on Mouse
Your device should be able to detect the Magic Mouse
Click on Connect
Once you see a message "Connected", mouse is ready to use.

If you have connected/paired your mouse with your Macbook/computer before,

Turn on Magic Mouse
After a 2 sec pause, click and it should work.
Comment: My keyboard would connect automatically after powering on, but the mouse wouldn't. I thought my mouse had some problems. Click to connect wasn't intuitive. Thanks for the tip.


Would immortality medicine be legal?

Question: Suppose some incredible breakthrough in medicine was made allowing people to live for 300+ years by means of genetic enhancement or some special medicine or medical procedure. Would thus be allowed by governments? I think many would oppose extending the lives of everyone currently alive for such a long period of time, and that the human population needs to be replenished for several reasons. I hope you can identify some of the downsides of implementing such a technology, and if it would be allowed by governments.
Comment: You are correct. This is a duplicate, and the other question is posed better anyways. Sorry!
Answer: As @Magic-Mouse already stated, longevity will be expensive. Not necessary because the actual way of achieving it is expensive, but because it would be very valuable to some, and that would reflect in the price tag (unless it would be so simple that spreading the how-to alone would make it achievable for (almost) everybody).
Assuming that most politicians like power, they would most likely like the power to live longer. That would prevent them from making it illegal. But it would also encourage them to make it hard to get (for others, not for themselves).
That means: It would most likely not be illegal, but restricted. Maybe comparable to firearms laws in most countries.
A side note: Since overpopulation would be a problem if everybody lived four times as long as today, you could enter a limiting factor, for example by allowing longevity only for people without or with only one child, or something implicit like that the treatment for longevity makes people sterile (which would not prevent them from having many chilren before the treatment though).
Comment: This is what I was getting at. The overpopulation is what would be controversial.
Answer: In different stories, there is different kinds of artificial longevity. Either by surgery, medicaiton, replacement, cloning.
No matter how they do it and if it is permernent or just extension of life, there is always some common factor, money - Mostly it is some kind of noble or richman who have access to the extension formula.
Along with that - another common is that people living in those societies often have shortened lifespan, either due to bad medical care, crime, evil masters who make sure people work them selves to death and such.
This is due to the capacity of our planet. Without peoples ability to die, everything would get crowded and people would start panic. (Look at the Dr.Who Spinoff - torchwood, last season "Miracle Day" for reference).
As for the question in the title, i dont think it matters if it is legal or not, if it exists and you got money, you will have it.

Would immortality medicine be legal?


Only accept a certain file type in FileField, server-side

Question: How can I restrict FileField to only accept a certain type of file (video, audio, pdf, etc.) in an elegant way, server-side?
Comment: To get the open dialog to restrict files to certain types client-side, [see this question](http://stackoverflow.com/a/40847649/247696).
Answer: One very easy way is to use a custom validator.
In your app's validators.py:
def validate_file_extension(value):
    import os
    from django.core.exceptions import ValidationError
    ext = os.path.splitext(value.name)[1]  # [0] returns path+filename
    valid_extensions = ['.pdf', '.doc', '.docx', '.jpg', '.png', '.xlsx', '.xls']
    if not ext.lower() in valid_extensions:
        raise ValidationError('Unsupported file extension.')

Then in your models.py:
from .validators import validate_file_extension

... and use the validator for your form field:
class Document(models.Model):
    file = models.FileField(upload_to="documents/%Y/%m/%d", validators=[validate_file_extension])

See also: How to limit file types on file uploads for ModelForms with FileFields?.

Warning
For securing your code execution environment from malicious media files

Use Exif libraries to properly validate the media files.
Separate your media files from your application code
execution environment
If possible use solutions like S3, GCS, Minio or
anything similar
When loading media files on client side, use client native methods (for example if you are loading the media files non securely in a
browser, it may cause execution of "crafted" JavaScript code)
Comment: @dabad using just extension is not good for filevalidation, these kind of answers makes security loopholes; please guys who sees these answers check also CVE related to different formats & validators, take the case of pillow/PIL for example :O
Comment: @RenjithThankachan even sometimes images exif data can be modified with arbitrary code but this trick was use to work in the past with PHP apps.
Comment: One thing we can do is use solutions like S3, Minio to seperate media files of users from application code execution environment @AmmadKhalid
Answer: Django in version 1.11 has a newly added FileExtensionValidator for model fields, the docs is here: https://docs.djangoproject.com/en/dev/ref/validators/#fileextensionvalidator.
An example of how to validate a file extension:
from django.core.validators import FileExtensionValidator
from django.db import models

class MyModel(models.Model):
    pdf_file = models.FileField(
        upload_to="foo/", validators=[FileExtensionValidator(allowed_extensions=["pdf"])]
    )

Note that this method is not safe. Citation from Django docs:

Don't rely on validation of the file extension to determine a file's
type. Files can be renamed to have any extension no matter what data
they contain.

There is also new validate_image_file_extension for validating image extensions (using Pillow). Another option is to use ImageField in such a case, which also enforces the check that a valid image has been uploaded.
Comment: file got uploaded even though it was not added in `allowed_extensions` for some reason. Using Django Rest Framework.
Comment: @VineethSai I guess you need to also set the validator inside your serializer, not just in the model.
Answer: A few people have suggested using python-magic to validate that the file actually is of the type you are expecting to receive. This can be incorporated into the validator suggested in the accepted answer:
import os
import magic
from django.core.exceptions import ValidationError

def validate_is_pdf(file):
    valid_mime_types = ['application/pdf']
    file_mime_type = magic.from_buffer(file.read(1024), mime=True)
    if file_mime_type not in valid_mime_types:
        raise ValidationError('Unsupported file type.')
    valid_file_extensions = ['.pdf']
    ext = os.path.splitext(file.name)[1]
    if ext.lower() not in valid_file_extensions:
        raise ValidationError('Unacceptable file extension.')

This example only validates a pdf, but any number of mime-types and file extensions can be added to the arrays.
Assuming you saved the above in validators.py you can incorporate this into your model like so:
from myapp.validators import validate_is_pdf

class PdfFile(models.Model):
    file = models.FileField(upload_to='pdfs/', validators=(validate_is_pdf,))

Comment: Definitely the most secure answer on the page!
Comment: I wish Django had an in-the-box solution for confirming that approved mime-types and file extensions match without installing a third-party library. The magic library has different requirements based on your OS which adds more steps to consider during deployment. Great answer, but unfortunate that this is necessary at all.
Comment: In case it returns "application/octet-stream" for specific known images, you will need to do like this

`initial_pos = file.tell()`
`file.seek(0)`
`mime_type = magic.from_buffer(file.read(2048), mime=True)`
`file.seek(initial_pos)`
Comment: If it makes sense for it to be included, Django doesn't have it, has no plans of adding it, and has some patronizing word salad about why you don't need it.
Comment: After a couple of hours of searching this seems to be the most secure and effective way to ensure the file type. It does include an extra library but what are you gonna do?
Answer: You can use the below to restrict filetypes in your Form
file = forms.FileField(widget=forms.FileInput(attrs={'accept':'application/pdf'}))

Comment: this is for forms, but does not validate the model
Answer: There's a Django snippet that does this:
import os

from django import forms

class ExtFileField(forms.FileField):
    """
    Same as forms.FileField, but you can specify a file extension whitelist.

    >>> from django.core.files.uploadedfile import SimpleUploadedFile
    >>>
    >>> t = ExtFileField(ext_whitelist=(".pdf", ".txt"))
    >>>
    >>> t.clean(SimpleUploadedFile('filename.pdf', 'Some File Content'))
    >>> t.clean(SimpleUploadedFile('filename.txt', 'Some File Content'))
    >>>
    >>> t.clean(SimpleUploadedFile('filename.exe', 'Some File Content'))
    Traceback (most recent call last):
    ...
    ValidationError: [u'Not allowed filetype!']
    """
    def __init__(self, *args, **kwargs):
        ext_whitelist = kwargs.pop("ext_whitelist")
        self.ext_whitelist = [i.lower() for i in ext_whitelist]

        super(ExtFileField, self).__init__(*args, **kwargs)

    def clean(self, *args, **kwargs):
        data = super(ExtFileField, self).clean(*args, **kwargs)
        filename = data.name
        ext = os.path.splitext(filename)[1]
        ext = ext.lower()
        if ext not in self.ext_whitelist:
            raise forms.ValidationError("Not allowed filetype!")

#-------------------------------------------------------------------------

if __name__ == "__main__":
    import doctest, datetime
    doctest.testmod()

Comment: Try this link: http://nemesisdesign.net/blog/coding/django-filefield-content-type-size-validation/
Comment: This is a filter based on extension, wich is not reliable at all. I was thinking about analysing the file after uploading finishes.
Comment: You can use python-magic (wrapper for libmagic) to get the mimetype and then accept/reject based on that.
Comment: @user126795 - that still doesn't actually determine that it's the right type - it appears to just rely on the specified content-type - which may not be reliable.
Comment: @maroxe Did you find a solution to this? I just have the same issue with determining wether files are audiofiles or not.
Comment: A combination of checking the extension, content_type, and using python-magic will handle most circumstances. Note that it is also a good idea to check for the size of the file being uploaded. Also, this snippet has some issues as described here: http://stackoverflow.com/a/12392470/685109
Answer: First. Create a file named formatChecker.py inside the app where the you have the model that has the FileField that you want to accept a certain file type.
This is your formatChecker.py:
from django.db.models import FileField
from django.forms import forms
from django.template.defaultfilters import filesizeformat
from django.utils.translation import ugettext_lazy as _

class ContentTypeRestrictedFileField(FileField):
    """
    Same as FileField, but you can specify:
        * content_types - list containing allowed content_types. Example: ['application/pdf', 'image/jpeg']
        * max_upload_size - a number indicating the maximum file size allowed for upload.
            2.5MB - 2621440
            5MB - 5242880
            10MB - 10485760
            20MB - 20971520
            50MB - 5242880
            100MB 104857600
            250MB - 214958080
            500MB - 429916160
"""
def __init__(self, *args, **kwargs):
    self.content_types = kwargs.pop("content_types")
    self.max_upload_size = kwargs.pop("max_upload_size")

    super(ContentTypeRestrictedFileField, self).__init__(*args, **kwargs)

def clean(self, *args, **kwargs):
    data = super(ContentTypeRestrictedFileField, self).clean(*args, **kwargs)

    file = data.file
    try:
        content_type = file.content_type
        if content_type in self.content_types:
            if file._size > self.max_upload_size:
                raise forms.ValidationError(_('Please keep filesize under %s. Current filesize %s') % (filesizeformat(self.max_upload_size), filesizeformat(file._size)))
        else:
            raise forms.ValidationError(_('Filetype not supported.'))
    except AttributeError:
        pass

    return data

Second. In your models.py, add this:
from formatChecker import ContentTypeRestrictedFileField

Then instead of using 'FileField', use this 'ContentTypeRestrictedFileField'.
Example:
class Stuff(models.Model):
    title = models.CharField(max_length=245)
    handout = ContentTypeRestrictedFileField(upload_to='uploads/', content_types=['video/x-msvideo', 'application/pdf', 'video/mp4', 'audio/mpeg', ],max_upload_size=5242880,blank=True, null=True)

Those are the things you have to when you want to only accept a certain file type in FileField.
Comment: Adding this line before the super call:  self.widget = ClearableFileInput(attrs={ 'accept': ','.join(self.content_types) })
will make only accepted content types selectable in the modal window.
Comment: content-type is easy cheated
Comment: Works in chrome, FF doesn't give a ****. I found out it's better to filter by extension than content type anyway. The later is set almost arbitrarily by your browser + os.
Comment: @laffuste Having upvoted your comment, this doesn't seem to work on Mac (i.e. any files are selectable). Haven't tested under Windows though.
Answer: after I checked the accepted answer, I decided to share a tip based on Django documentation. There is already a validator for use to validate file extension. You don't need to rewrite your own custom function to validate whether your file extension is allowed or not.
https://docs.djangoproject.com/en/3.0/ref/validators/#fileextensionvalidator

Warning
Don't rely on validation of the file extension to determine a file's
type. Files can be renamed to have any extension no matter what data
they contain.
Comment: This answer just repeats [what was already said 3 years prior](https://stackoverflow.com/posts/43540603/revisions).
Answer: I think you would be best suited using the ExtFileField that Dominic Rodger specified in his answer and python-magic that Daniel Quinn mentioned is the best way to go. If someone is smart enough to change the extension at least you will catch them with the headers.
Comment: Since you've determined that this is the best method, why not post some code to demonstrate it to the rest of us!?
Answer: You can define a list of accepted mime types in settings and then define a validator which uses python-magic to detect the mime-type and raises ValidationError if the mime-type is not accepted. Set that validator on the file form field.
The only problem is that sometimes the mime type is application/octet-stream, which could correspond to different file formats. Did someone of you overcome this issue?
Answer: Additionally i Will extend this class with some extra behaviour.
class ContentTypeRestrictedFileField(forms.FileField):
    ...
    widget = None
    ...
    def __init__(self, *args, **kwargs):
        ...
        self.widget = forms.ClearableFileInput(attrs={'accept':kwargs.pop('accept', None)})
        super(ContentTypeRestrictedFileField, self).__init__(*args, **kwargs)

When we create instance with param accept=".pdf,.txt", in popup with file structure as a default we will see files with passed extension.
Answer: Just a minor tweak to @Thismatters answer since I can't comment. According to the README of python-magic:

recommend using at least the first 2048 bytes, as less can produce incorrect identification

So changing 1024 bytes to 2048 to read the contents of the file and get the mime type base from that can give the most accurate result, hence:
def validate_extension(file):
    valid_mime_types = ["application/pdf", "image/jpeg", "image/png", "image/jpg"]
    file_mime_type = magic.from_buffer(file.read(2048), mime=True) #  Changed this to 1024 to 2048

    if file_mime_type not in valid_mime_types:
        raise ValidationError("Unsupported file type.")

    valid_file_extensions = [".pdf", ".jpeg", ".png", ".jpg"]
    ext = os.path.splitext(file.name)[1]

    if ext.lower() not in valid_file_extensions:
        raise ValidationError("Unacceptable file extension.")


Is right way to show Tooltip on keyboard navigation?

Question: Gmail shows tooltip on keyboard navigation. My question is whether the Tooltip can be shown on keyboard navigation?
Answer: The answer is yes. You should give as similar as possible experience for users independently of how they are visiting your site. Here is a quote from Google Material specifically about accessibility and hover information:

Keyboard/mouse interfaces should have every task and all hover information accessible by keyboard-only.

As @SteveD says in the comments it is also a requirement in "WCAG 2.0 under 2.1 Keyboard Accessible":

When all functionality of content can be operated through a keyboard or keyboard interface, it can be operated by those with no vision as well as by those who must use alternate keyboards or input devices that act as keyboard emulators like speech input software or on-screen keyboards.
Comment: Yes, only Google has given tooltip on keyboard navigation. Is there any UI standards.
Comment: I usually refer to Google standards (in the link I posted). Other than those you can check several guides in [this answer](http://ux.stackexchange.com/a/101752/32130).
Comment: It is also an accessibility requirement in WCAG 2.0 under 2.1 Keyboard Accessible.
Answer: For accessibility your system/product should be capable of showing tooltips for both mouse and keyboard users alike.
If you're asking about how to make it work (which you should really be asking on Stack Overflow and not here) then the :focus pseudo class in CSS and JQuery is what you want to be looking for.
Answer: The most awesome experience involving tooltips I have had as a heavy keyboard user, was when I recently stumbled across the ESTA application process.
I don't like to use a mouse, and will forcefully Tab my way through forms at pretty much any cost. However, I was pleasantly surprised when I found that the tooltip button attached to each form input had hijacked an increment of the tabindex property.
As a result, the first Tab press focused and opened the tooltip, while my second Tab press focused on the actual form input. This meant that it effectively took two Tab presses to proceed to the next form input -- however, the extra time it took me to press Tab twice instead of once, was inarguably time saved not having to reach for the mouse and hover over the tooltip button.
All in all, a surprisingly awesome -- and accessible -- implementation (in that that it conforms to the relevant WCAG 2.0 guideline). Especially considering that the ESTA application process involves a lot of form inputs where the user (often foreign like me) has to get it explained by the tooltip.

(Sorry for potato gif - screen capturing is not my strongest asset.)


Were the Unforgivable Curses legalized during the Battle of Hogwarts or prior to that?

Question: Were the Unforgivable Curses legalized during the Battle of Hogwarts or was it legalized when the Ministry of Magic fell against Voldemort?
Comment: What makes you think they were?
Answer: They were never legalised.
What changed in the era that Voldemort was in charge of the Ministry (through his puppet, Pius Thicknesse) was that the law was not properly enforced. The Unforgivable Curses were still illegal but the Ministry simply turned a blind eye.

"What you've got to realize, Harry, is that the Death Eaters have got the full might of the Ministry on their side now," said Lupin. "They've got the power to perform brutal spells without fear of identification or arrest."
(Deathly Hallows, Chapter 11, The Bribe).
Comment: That quote is a great find!
Answer: Depends on what you mean by "legal." Keep in mind that Voldemort was the de facto Minister of Magic towards the end of the series because the government was being run by his puppets. I can't remember if they were ever officially legalized, but Voldemort wasn't officially running the government either.
Towards the end of the book, Dark magic (including unforgivable curses) was explicitly encouraged at Hogwarts, and the Cruciatus Curse was routinely and openly used as a punishment.
Note that Order members used unforgivable curses too:

 Harry Potter used the Imperius Curse to get into Gringott's and steal the Horcrux from Bellatrix Lestrange's vault and used the Cruciatus Curse on a Death Eater in revenge for spiting in McGonagall's face. McGonagall then used the Imperius Curse to force the Death Eater to stay out of the ensuing fight.


Having multiple artboard on the same window

Question: Like you can have multiple artboard on the same window in Adobe Illustrator, is it possible to have multiple working areas on the same window for Inkscape (instead of duplicating the current window)?
Comment: Hi. Welcome to GDSE.  No. Inkscape doesn't support multiple artboards/pages.
Comment: @billy Aah i see.Thanks for the info!
Comment: Note that you can put objects outside the page area in Inkscape. So this might work if you just need to have the graphics somewhere you can easily access them, all within the same document.
Answer: Inkscape has no multi artboard/page support.
However, there are some possible workarounds.
It's entirely possible to have objects outside the page area. This could be useful if you just need them to be easily accessible.
With a bit more effort, it would be possible to change the Document Properties, to hide the Page Border, and change the background colour to grey. Then you could construct "psuedo-pages" from a white rectangle grouped with the content.  Obviously, when outputting a final SVG or PNG, you would have to select the psuedo-page, and do Edit > Resize page to selection, and possibly delete the white rectangle before outputting if you don't want a white background..
Here's an example showing a set up with pseudo-pages made from groups.
Answer: Some people use layers for this - you can hide and show layers (e.g. all except the current one) in the layers dialog.


Notation of numbers in numbers with high bases

Question: Evening all,
I'm looking at a problem that looks like there may be a pattern dependant upon the base of a number, and that a value I'm looking for within that pattern improves as the base (or more specifically, the number of unique prime factors of the base) increases.
I'm familiar with Binary, Decimal, Hex, etc but I can't seem to find if there is a standardised way to notate values with very high base values - how would one write 1999 in base 1000 or 19999 in base 10000?
Thanks in advance,
Ben
Comment: As you wrote them. they are digits. Anything less than the base is a digit. You can set any code representations of them.
Comment: Ah, my bad. I have edited the question so that it actually makes sense, I hope.
Answer: There is no standard.
Say  "If we let $K$ be the digit representing $999_{10}$ then $1999_{10}$ will be represent as $1K_{1000}$."
Or you could say "For the purpose of this problem I will refer to the digit represent a value $K: 10 \le K \le b-1$ as $[K]$"
or you could say "For the purpose of this problem I will refer to the digit represent a value $K: 10 \le K \le b-1$ as $a_K$"
Make up your solution and stick to it.
If it were may I'd so ${1a_{999}}_{1000} = 1\times 1000^1 + 999\times 1000^0 = 1999_{10}$
Or ${a_{32}7a_{528}}_{1000} = 32\times 1000^2 + 7\times 1000 + 528$ but
"$[32][7][528]_{1000}$ or $A7B; A=32, B=528;$"
All acceptable.


How fast can I send data to firebase from nodemcu 1.0?

Question: I was sending some variable value to the firebase database I have created: how fast can I send it? What would be minimum time interval between two values nodemcu can send and fire base can receive? I was counting IV fluid(saline bottle)drip rate and sending rate value to database, what can I do so that my mcu would not miss any drop count?
Comment: you can probably have a counter set up and count the value and at a particular interval of time, you can upload it to the database. You can store the data in EEPROM/SPIFFS if there is any chance of internet connectivity loss and can store the count of that particular interval of time and when an Internet connection is up you can send all data together by this you will have data with periodic time. And I think the time interval of firebase is like 10sec min.
Answer: There are many different possible limits:

limits of Firebase, as well as limits for the Firebase free quota. You can find them here: https://firebase.google.com/docs/firestore/quotas
They include a 20000 document writes per day limit on the free quota and a 1 write per document per second limit. There are also limits in terms of amount of data and more. Of course, depending on how many devices you have and the granularity you need, this may be either plentiful or very little.
limits of your hardware (sensor etc.), of which we don't know much
limits of your network connection. Not quite the same thing if you send the data over LoRa, BLE, Zigbee or NB-IoT on one hand, or over Wi-Fi or Ethernet on the other, with lots of other possibilities in between, and of course other links on the path between your MCU and Firebase. You're probably using WiFi, but we lack a lot of details.

As commented by Lucifer, you should probably aggregate data over intervals rather than each drop individually, but that really depends on what you are actually trying to measure.


Running tests in Google App Engine package?

Question: I have a question concerning the way in which Python imports modules and creates objects within packages, I'm using Flask on Google App Engine but I think the problem is more general.
My app has the following structure:
app/
   application/
       __init__.py
       flaskr.py
       models.py
       mainConfig.py
       etc...
   tests/
       tests.py
       configtest.py
   apptest.py
   run.py

I am using Google App Engine launcher and it works okay most of the time. When I want to run the app I simply use dev_appserver.py. Appserver requires the path to my app as an argument, when it gets it it imports stuff from google app engine folder and executes my app. I'm happy with that.
The problem I'm having concerns my tests, most importantly I have a problem with the way tests load their configuration at runtime. I have separate configuration for tests, I don't want them to use mainConfig.py, they should use configTests.py. Unfortunately at the moment each time I run my tests the tests are using default app configuration and not their own specific options - for example they insert data to app database, and not to testing database that they have hardcoded in config.
I run tests through apptest.py, the file is fairly simple and it looks like this:
#!/usr/bin/python
import optparse
import sys
import unittest2

USAGE = """%prog SDK_PATH TEST_PATH
Run unit tests for App Engine apps.

SDK_PATH    Path to the SDK installation
TEST_PATH   Path to package containing test modules"""

def main(sdk_path, test_path):
    sys.path.insert(0, sdk_path)
    import dev_appserver
    dev_appserver.fix_sys_path()
    suite = unittest2.loader.TestLoader().discover(test_path)
    unittest2.TextTestRunner(verbosity=2).run(suite)

if __name__ == '__main__':
    SDK_PATH = u"pathToGoogle\\Google\\google_appengine"
    TEST_PATH = u"pathtoapp\\app\\tests\\"
    main(SDK_PATH, TEST_PATH)

I am trying to fiddle around this issue for a while, moving tests here or there within my application directory, editing code in my tests setUp method, but my fiddling around is quite pointless since I don't really understand what is going on here.
I know that app object is created in init within application folder, and it gets its settings from there. I should probably mention that nothing from the configuration in hardcoded in files in application folder, all files load the name of database by simply using app.config["DATABASE"](config is a dictionary like object, available everywhere within application). The main line in tests.py which sets up app.test_client goes like this:
from application import app

class FlaskrTestCase(unittest.TestCase):
    def setUp(self):
        app.config.from_object('configtest')
        self.app = app.test_client()

What is going on here, and how can one fix it? What should I do in order to force tests.py to get their configuration from their folder instead of getting it from application folder?
Answer: I believe to solve this you should add an __init__.py file to the tests folder to make it a module and change app.config.from_object('configtest') to app.config.from_object('tests.configtest').
Comment: Thanks for help I'll try and see if that'll fix it.
Comment: Nope, doesn't work. Still loads configuration from __init__ in app folder. I will just ask this question at flask irc channel maybe they will help me.


Magento 2.2 credit card details hacked

Question: For a few days we have detected that in our Magento 2.2 the user is asked for their credit card details when it is something that was not done since the user is directly redirected to pay on the bank page.
Today a client told us that a charge had appeared on her card with which she bought on our casino page and we believe that the store has been hacked. Some help?
Comment: Hello, it seems strange, extensions do not store CC information... would you mind sharing your site URL and what payment gateway do you use for CC ?
Comment: We finally managed to find the problem. They were putting code in the footer of the page, it was eliminated and the problem disappeared.
Answer: Seem your site have some modules or included malware scripts that you don't know.
Try this tool in link https://github.com/gwillem/magento-malware-scanner may help

Magento 2.2 credit card details hacked


How can I tell if a fish can safely be prepared "crudo"?

Question: Is there something you can look for? Am I left to the seller's word and my own discernment?
Comment: http://en.wikipedia.org/wiki/Ceviche
Comment: "Crudo"? You mean raw fish like sashimi?
Comment: Sort of - crudo is uncooked but often seasoned with oil and spices and usually "cooked" with the addition of vinegar and/or citrus juice (lemon/lime).
Answer: Well, your discernment is indeed what you are looking for. You want really fresh fish. The usual advice for detecting really fresh fish apply. It can't hurt to have a fish source that you have good reason to trust.
Answer: General food safety guidelines give you four hours of time between 40F and 140F; more than that, and unsavory bacteria exceed nominally safe limits.
So, there's your safety limit. Total time counts, that is, in a bag back from the grocer for 2 hours, then in the fridge and back down to 34F and then out for 1 hour on the counter = 1 hour left until it needs to go over 140 for ten minutes (or 165 for 1 minute) or into your mouth.
And of course, there's the amount of time it was left on the dock, etc. etc.
That said, if you left fish in the fridge for a week, it would be mushy and bad tasting raw -- so you also must use your tastebuds and nose to see if you want to eat it raw; food safety isn't the only concern.
Comment: Update: in the US, FDA requires freezing for a short period (depending on temperature) to kill parasites in order to receive a 'sushi grade' designation. This would probably be a good idea if you're extra concerned about being safe.
Comment: It never hurts to bring a cooler with a couple ice packs to the grocery/fish monger. Especially if you live a decent distance away.


Photon in a weighted superposition of states

Question: Consider an experiment that produces photons in an entangled state such as $1/\sqrt{2}(|{H,H}\rangle+|{V,V}\rangle)$.  The photons are in a superposition of horizontal and vertical polarization, and the way we analyze this is to say that the photons are in both states at the same time. Though this is odd, I can eventually reconcile it. However, the photons can also be in an entangled state such as $\sqrt{0.2}|H,H\rangle+\sqrt{0.8}|V,V\rangle$.  Again, the photons are in both states at the same time, but do we say that they is somehow more in one state than the other?  How can we think of this unevenly weighted superposition of states?
Comment: You don't want to use the word "entangled" here as it is generally applied to systems with two or more component each of which may be in a mixed state. "Mixed" and "superposition" are the words generally used for simple systems in non-eigenstates of whatever bass you are using.
Comment: Sorry, @dmckee, I am very confused by all parts of your comment. The OP seem to be asking about the entanglement of 2 photons so what's wrong with the word "entangled"? Also, you seem to be confusing "mixed" and "superpositions". These are different things. "Superposition" is used for pure states (can be expressed via a vector in the Hilbert space), "mixed" is used for mixed states i.e. those that aren't pure (require density matrix).
Comment: @LubošMotl That would be because I paid more attention to the text before the edit than the math. It is clear that Jon does mean "entangled".
Answer: Consider a quantum system with a two-dimensional state space.  Let $\Omega$ be an observable on the system with normalized eigenstates $|1\rangle$ and $|2\rangle$ corresponding to eigenvalues $\omega_1$ and $\omega_2$.  If a state $|\psi\rangle$ is in some superposition of these states
$$
  |\psi\rangle = a_1|1\rangle + a_2|2\rangle,
$$
then the coefficients can be interpreted as probability amplitudes.  This means that if a measurement of the observable $\Omega$ is made on the the system, then the probabilities $p_1$ and $p_2$ that the measurement will yield the eigenvalues $\omega_1$ and $\omega_2$ are
$$
  p_1 = |a_1|^2, \qquad p_2 = |a_2|^2
$$
This general analysis applies to your example as well.  The coefficients should be interpreted as probability amplitudes that if a measurement of the photon polarization is made, then corresponding results (either vertical or horizontal) will be obtained.
Comment: I'd say that to some extent, the interpretation you're attempting to make is a matter of conceptual taste.  However, most physicists would not use the phrase "the photons are in both states" but rather "the photon is in a superposition of states."  I can't see anything particularly "wrong" with the intuition that the photons are "more vertical than horizontal," but when it comes down to it, it's most important and meaningful in my opinion to use the precise, operational meaning of probability amplitudes in terms of state preparation and measurement.
Comment: @Jon: "Can we say that the photons are more vertical than horizontal?" How would you answer any other isomorphic question about uncertain information that we experience in the real world? For example, a woman gets pregnant. You may ask: Can we say that the baby is more female than male? (51+ percent of the newborns are girls.) What's the answer? It's exactly the same thing. We don't know the sex of the baby or polarization of the photons; they're only determined after/via a measurement and probabilities may be predicted in advance. The answers male/fem. and horizontal/vert. are mutually excl.
Comment: Concerning the last comment, one may accurately say that "the expectation value of the vector (well, actually the tensor) giving the polarization axis is more vertical" and "the expectation value of the sex of a newborn is closer to female". But it's misleading to say the same sentence without the "expectation values" because such sentences incorrectly suggest that the horizontal/vertical polarization or male/female sex of the baby (one particular answer) are already known at that moment which they're not.
Comment: Right.  So in my example, since the probability amplitude of $|V,V\rangle$ is higher than that of $|H,H\rangle$, it is more likely that the photons will be measured to be in the vertical state.  However, prior to measurement, we must assume the photons are in both states, so if we know that the probability amplitudes are not equal, can we say that the photons are more vertical than horizontal?
Comment: Now, the difference is that the sex may be approximately thought of in classical physics because it's a property of macroscopic bodies that quickly decohere etc. In classical physics, one doesn't run into contradictions if he assumes that the answers/properties of objects already objectively exist even before any measurement is made. In quantum mechanics, it is not possible to assume that: all quantities can't be sharply given before measurements (after all, they refuse to commute with each other). But when it comes to "what we can say before the measurement", the situations are identical.


What exactly is a Christian Witch?

Question: I am a Wiccan looking into converting into Christianity. Doing some research, I know that the Lord is against witchcraft. So why is there even such a thing as a Christian Witch, and what are they?
Comment: Hi person, glad to see you're giving Christ a shot.  I'm not sure we've got a ton of answers for you, I haven't seen anybody post anything here about Christian Witches. You'll probably have to explain where you heard of it.   There were many Druid and Norse converts in the dark ages, as far as I know, they become regular old fashioned Catholics.  I can tell for certain that there's no approve cult within mainline Christian denominations that approves of witchcraft.  So this has the mark of an esoteric question.
Comment: Which denominations have witches? None that I am aware of!
Comment: a Christian witch might be a confused wiccan
Comment: If you would please indicate a source or book or article that explains where this idea was formed or where you got it, that would be helpful in forming an answer.  **I heard the reference from a Wiccan website** Which one?   Where? What's the url?
Comment: Sorry for absence, I had to mess with the wifi, anyways, I heard the reference from a Wiccan website, detailing the many traditions. I saw Chriso-Pagainism and came back to it once I converted.
Comment: also, if you would, in which chapter of the Bible are the 10 commandments detailed?
Comment: exodus 20 has the 10 commandments
Comment: A Christian witch is one who has gone to the dark side!
Answer: This is not something I had ever heard of and I have only done some brief digging but, here are my (protestant) 2 cents.
This is from the website of the Esoteric Interfaith Church describing what Christo-paganism purports to be.  Here you can become ordained today! and/or earn degrees from bachelors to PhD.

What is this term, Christo-Pagan or Christian-Pagan? Isn't it a contradiction?  Well, the truth is: your ancestors were probably Christo-Pagans.  In Europe the historical Dual Faith period lasted from approximately 450 AD to 1100 AD, some say it began with Christianity itself. Indeed, Christianity has undeniable pagan roots.

There are some charts and explanations (not overly burdened by evidence) describing the pagan and gnostic roots of not only certain Christian practices (Quakers and Old Catholics (?) are mentioned) but also forms of Judaism, Zen Buddhism, and Taoism.
There is also some poorly understood early Church history detailing how the Nicene council was a superficially Christian, predominantly pagan device used by the pagan Constantine to consolidate pagan factions into what became the Roman Catholic Church so as to choose sides in the earliest Christian schism between gnostics and pistics.  There is so much more but it appears to be a hot mess of jumbled fact, mythologized history, and baseless speculation.  The statue of Peter in Rome is said to actually be the statue of Jupiter (Jo-Peter), for example.
There is also, according to the Esoteric Interfaith Church, a full return to the embrace of the Feminine Divine which provides a balance that resonates with the natural.

One of the things modern Dual-Faithers bring back to Christianity is the presence of the Feminine Divine. Too long has Christianity been a lopsided masculine only "family" of God. Ironic that mainstream Christianity uses the phrase "family of God" since it is a dysfunctional family with no females, daughters or spouses. Humans naturally resonate with and respond to both a God and a Goddess. Christo-Paganism restores a much needed balance.

The idea seems to be that Roman Catholicism has hung on to and developed some aspects of it's pagan roots such as a highly inflated Mariology reflecting only a partial departure from the original 'Feminine Divine', and so many others.
Another website indicates that Christo-paganism is, at heart, a release from patristic human doctrines imposed on the church by men.

So what is Christo-Paganism? It is a shedding of the doctrine of man imposed on the church. A way of washing away what doesn't align with the true intent of God as well as a journey into the vast world of Pagan arts, sciences, and theories of what it all means when it comes to our existence.

It appears that a Christian Witch, at least as described in the small amount of research represented here, is a person who is attempting to honor the Scriptures in some way (possibly in word only) while at the same time outright rejecting vast acreage of clear biblical truth.  There appears to be a deliberate use and misrepresentation of difficult to ascertain history, mixed with mythology, and designed to deflate the primacy of the inspired Scriptures (including, but not limited to, equal appeal to canonical and non-canonical books).  This all works together to make it not only easy but beneficial for the aspiring Christo-Pagan to take what is wanted from the Bible, from whatever paganism suits, from science, from mysticism, from wherever, and to create one's own mish-mosh of personal deity, belief, and practice.
Christianity says that there is one God that has self-revealed to humanity first and generally in Creation, second and specifically in the 66 books of the Bible, and finally and personally in Jesus Christ, the Son of God.  Christianity says that while some of what is written in Scripture is difficult to understand, much of it is quite clear and none of it is disposable or takes second place to history, tradition, or personal preference.
Christianity says very clearly that, rather than the many and various paths of Christo-Paganism, there is but one, narrow path to God.

Enter by the narrow gate. For the gate is wide and the way is easy that leads to destruction, and those who enter by it are many. For the gate is narrow and the way is hard that leads to life, and those who find it are few. - Matthew 7:13-14
Jesus said to him, "I am the way, and the truth, and the life. No one comes to the Father except through me. - John 14:6

In short I would say that it is impossible to be and remain a Christian Pagan because:
a) a Christian has rejected and is in the lifelong process of identifying and abandoning in themselves every belief and practice that is contrary to what Scripture teaches. Christianity is a continual elevation of the Word of God.

We destroy arguments and every lofty opinion raised against the knowledge of God, and take every thought captive to obey Christ,  - 2 Corinthians 10:5

b) the Christo-Pagan actively discards and dismisses Scriptural revelation whenever it is necessary for the accommodation of conflicting beliefs and practices.  Christo-Paganism is a process of bringing God's Word down to a level equal to other sources of 'revelation'.
If you are truly considering conversion to Christianity it must also be a conversion from Wicca.  From personal experience it will be very difficult (like dying) and you must pour yourself into the Scriptures (John is a good place to start) and desire for God to reveal Christ to you at the expense of everything else.  He will respond!

You will seek me and find me, when you seek me with all your heart. - Jeremiah 29:13
And without faith it is impossible to please him, for whoever would draw near to God must believe that he exists and that he rewards those who seek him. - Hebrews 11:6
Comment: Sounds like more than two cents. lol
Comment: Sounds like a best answer to me! +1
Answer: A Christian Witch is obviously an oxymoron. No person can really be a Christian and a Witch at the same time

What exactly is a Christian Witch?