What are the semantics of 'stat' on a dirhandle in Perl?

Question: On researching another question I noted that the stat function in Perl can take a dirhandle as its argument (instead of a filehandle or filename).
However I can't find any examples of correct use of this - there are none in the Perl manual.
Can anyone show an example of how to use it?
Answer: You use it in the same way you do for a file or filehandle:
#!/usr/bin/perl
use strict;

my $dir = shift;
opendir(DIR, $dir) or die "Failed to open $dir: $!\n";
my @stats = stat DIR;
closedir(DIR);
my $atime = scalar localtime $stats[8];

print "Last access time on $dir: $atime\n";

The ability to use stat on directory handles was just added around Perl 5.10 so it should be avoided if you care about portability.
Comment: so it just stats() the directory itself, and isn't anything to do with readdir() ?
Comment: @Alnitak: that is correct, it is the same as "stat $dir" just as "stat FILEHANDLE" is the same as "stat $file".
Answer: You use it just like you would stat on a filehandle:
<~> $ mkdir -v foo ; perl -e 'opendir($dh , "./foo"); @s = stat $dh; print "@s"'
mkdir: created directory `foo'
2049 11681802 16877 2 1001 1001 0 4096 1228059876 1228059876 1228059876 4096 8

(Personally, I like using File::stat to get nice named accessors, so that I don't have to remember (or lookup) that the fifth element is the UID...)
Answer: Just be aware that a if a handle was ever used as a filehandle, as well as a dirhandle, the stat will apply to the file, not the directory:
$ perl -wl
opendir $h, "." or die;
open $h, "/etc/services" or die;
print "dir:".readdir($h);
print "file:".readline($h);
print stat("/etc/services");
print stat(".");
print stat($h);
close($h);
print stat($h);
__END__
dir:.
file:# Network services, Internet style

205527886633188100018274122800783211967194861209994037409640
20551515522168777410001000020480122803711512280371021228037102409640
205527886633188100018274122800783211967194861209994037409640
stat() on closed filehandle $h at - line 1.
    (Are you trying to call stat() on dirhandle $h?)

Answer: I use Perl 5.10.1 on windows (ActivePerl) and doing stat on a dirhandle doesn't work. But doing a stat on the path string of the directory works.
works
  my $mtime = (stat( $directory ))[ 9 ];
  print "D $directory $mtime\n";

this doesn't ("The dirfd function is unimplemented...")
  my $dh;
  if( opendir( $dh, $directory ) == 0 ) {
    print "ERROR: can't open directory '$directory': $!\n";
    return;
  }
  $mtime = (stat( $dh ))[ 9 ];
  print "D $directory $mtime\n";


If you double ISO and halve shutter duration, how would it affect SNR?

Question: Assuming the SNR is shot limited. Would it be the square root of 2 because of the shutter speed?
Comment: Related: [Why would using higher ISO and faster shutter speed yield more noise than using lower ISO and slower shutter speed?](https://photo.stackexchange.com/questions/93214/why-would-using-higher-iso-and-faster-shutter-speed-yield-more-noise-than-using)
Answer: Yes, cutting the amount of light in half cuts the number of collected electrons in half.  Under the usual assumption of a Gaussian error the fractional standard deviation is multiplied by the square root of 2, so the signal to noise ratio is divided by the square root of 2.
Comment: You should consider the electronic noise. If going from ISO 100 to 200 it will probably be unnoticeable, but working at high ISOs, the electronic noise is probably much higher than the "light" noise.
Comment: Quite the opposite. The less light there is, noise due to the randomness of light, what we call Poisson distribution or "shot" noise, [is a higher percentage](https://photo.stackexchange.com/a/40192/15871) of the total noise.
Answer: The primary cause of noise in modern cameras is shot noise, which follows a Poisson distribution... that is, the noise component is equal to the sqrt of the signal collected (photoelectrons).
E.G. if the original SS collected 10,000PE the noise component would be 100 for an SNR of 100:1.
Then at 2 x SS you collected 5,000PE the noise component would be 71.7 for an SNR of 70:1.
The longer shutter duration collects both more signal and more noise, but it also results in a better SNR.
Read (conversion) noise is also variable in that it is also more prominent when the ADC is provided with a lower quality/noisier signal.


Manual unpacking petya ransom

Question: I want to manually unpack red Petya ransomware. I used Ollydbg for unpacking and set breakpoint on VirtualAlloc to see the "MZ" header in memory dump, and saved it to a file. But the saved file is not valid, PEiD say it is not a valid file for example. I think it destroys its data directories. Is there any solution for repair this executable that I can try?
Comment: wouldnt it be nice if you provided the samples and the unpacking steps you used to get to whatever it is you got..
Comment: well. if you say so..
it would be easier to answer your question if you..
- provided the sample.
- provided the steps to reproduce your issue.
Comment: @Sigtran i followed this : http://paulslaboratory.blogspot.nl/2014/04/unpacking-using-ollydbg.html
Comment: I dont think this blog describes the unpacking of petya. looking at the VT detections this is Fareit/zbot.. from  2013. is this the same sample you are trying to unpack?
Comment: @Sigtran No i want to unpack red petya, but Petya also uses virtual alloc.
Answer: hasherezade from malwarebytes did an excellent analysis for Red Petya (version 1) including a step-by-step process on how to unpack it.

However, if we try to dump it, we don't get a valid executable. Its data directories are destroyed. The PE file have been processed by the cryptor in order to be loaded in a continuous space, not divided by sections. It lost the ability to run independently, without being loaded by the cryptor's stub. Addresses saved as RVA are in reality raw addresses.
  I have remapped them using a custom tool, and it revealed more information, i.e. the name of this PE file is Setup.dll:
Answer: Generally, solution is to properly understand what the malware does instead of just breakpointing VirtualAlloc and waiting for a functioning PE to be handed to you on a silver platter.
This usually entails debugging the malware before PE file is being loaded and and after the VirtualAlloc call is made, and taking not on everything done on the file. It might be beneficial to use a more interactive debugger for that phase, such as IDA or radare2, so tracking manipulation of the file will be easier.

Manual unpacking petya ransom


Comment tooltip: improving wrong answers

Question: The tooltip for a question comment reads:

Use comments to ask for more information or suggest improvements.  Avoid answering questions in comments.

The tooltip for an answer comment reads:

Use comments to ask for more information or suggest improvements.  Avoid comments like "+1" or "thanks".

The wording of these tooltips makes more sense for computer programming than than it does for politics.
To a commentator favoring one spot on the political spectrum, "suggest improvements" often seems to imply, and is therefore inferred to mean, that they should help by extolling the norms and virtues of their preferred spot, or by condemning those spots occupied by that particular question or answer.  Since the commentator is only helping a misguided person who seems lost, such extolling and condemnation often seems, to them, compliant with the "Be Nice" policy.
How does a user "improve" a wrong answer?  Or an answer that seems to them, given their orientation, wrong?  Is the verb "improve" ill-suited to political discussion?
Comment: Is there an example of this problem occurring? I haven't interpreted the tool tip that way and it would be enlightening to see how this went.
Comment: @indigochild, Example: often we see comment threads devolve into partisan contrariness, sometimes due to spite, other times owing to a fog of mutually oppositional obliviousness.  The *best* (*i.e.* worst) examples have probably been deleted, and finding a good example that hasn't would probably get *that* deleted.  Impartial readings of the tooltip seem less common.
Answer:
How does a user "improve" a wrong answer? Or an answer that seems to them, given their orientation, wrong?

By posting their own (right) answer.
The fundamental error here is that one should "fix" an answer with which one merely disagrees.
Comment: We agree; but this Q is more about the current wording of the tooltips, and that wording's common but undesired interpretation, (or *mis*interpretation), rather than the correct or best usage of comments and answers.


Ignore URLs and email addresses in spell file

Question: Is there a way to have vim not flag HTTP URLs and email addresses as spelling errors? Or, more generally, a way to list regexes of valid spellings?
Answer: You can add custom syntax rules, and give them the
@nospell keyword,
this will tell Vim not to apply spell checking to this syntax match. For example:
:syn match UrlNoSpell "\w\+:\/\/[^[:space:]]\+" contains=@NoSpell

The above will work for text files, and some filetypes (such as
markdown), but not for all filetypes.
Note that I used a fairly simple regex here; see How do I parse URL's from the text for some alternatives.

For other filetypes, you need to do a bit more work. For example, for python files, comments are contained in a pythonComment
group, from /usr/share/vim/vim74/syntax/python.vim:
syn match   pythonComment   "#.*$" contains=pythonTodo,@Spell

To override this, we need to do:
:syn match UrlNoSpellComment "\w\+:\/\/[^[:space:]]\+" contains=@NoSpell containedin=pythonComment
:highlight def link UrlNoSpellComment Comment

The trick is to add a list of previously matched syntax matches in which our
custom syntax match may be contained with containedin= This tells Vim to look for the
UrlNoSpell regex within the pythonComment matches.
We also need to use highlight to set the correct colours, since these aren't
inherited.
You need to do this in a number of places, for example for Python strings:
:syn match UrlNoSpellString "\w\+:\/\/[^[:space:]]\+" contains=@NoSpell containedin=pythonString
:highlight def link UrlNoSpellString String

We need 2 different syntax match groups so we can apply the correct syntax highlighting.
Of course, for other filestypes you need to use other containedin= syntax
matches... There is, AFAIK, no "universal" solution, but looking up the correct
ones in /usr/share/vim/vim74/syntax/*.vim should not be too difficult.

Note that all of the above commands must be executed after the syntax files;
there are 2 ways to do this:

From a command or key mapping, this must be invoked manually every time. e.g.
fun! NoUrlSpell()
    if &filetype == 'python'
        :syn match UrlNoSpellComment "\w\+:\/\/[^[:space:]]\+" contains=@NoSpell containedin=pythonComment
        :highlight def link UrlNoSpellComment Comment
        :syn match UrlNoSpellString "\w\+:\/\/[^[:space:]]\+" contains=@NoSpell containedin=pythonString
        :highlight def link UrlNoSpellString String
    elseif &filetype == 'ruby'
        " ...
    else
        syn match   pythonComment   "#.*$" contains=pythonTodo,@Spell
    endif
endfun
command NoUrlSpell :call NoUrlSpell()

Put the commands in in the ~/.vim/after/syntax/[filetype].vim. Vim will pick up
these files and execute them after the default syntax files (see:
:help after-directory).
Comment: "We also need to use `highlight` to set the correct colours, since these aren't inherited. […] We need 2 different syntax match groups so we can apply the correct syntax highlighting." You can also mark the matchgroup as being `transparent`. This way, the matched bits keep the style of their containing group and you don't need a different rule for each containing group. However a `transparent` matchgroup apparently isn't matched at toplevel, so you'd still need two rules (one for toplevel, one for contained), but that is still simpler.
Comment: It looks like Cecil Curry's newer answer already covers that @Maëlan. I don't think I knew about `transparent` back in 2015.
Comment: Indeed I saw that afterwards.
Answer: Martin Tournoij's otherwise excellent answer fails to behave as expected for me – probably due to my leveraging diraol's phenomenal python-mode plugin rather than Vim's default syntax file for Python.
To avoid highlighting URIs in Python comments, strings, or docstrings under python-mode, add the following concise one-liner to your user-specific ~/.vim/after/syntax/python.vim file:
syntax match NoSpellUriPython '\w\+:\/\/[^[:space:]]\+' transparent contained containedin=pythonComment,python.*String contains=@NoSpell

That's it. Crucially, note that this compresses what would have been twelve separate lines in Martin's answer into a single line. How? Elementary, my dear Vim-based Watson. We add:

The transparent keyword, instructing Vim to inherit the highlight properties for this child syntax from its parent syntax (e.g., comments, strings). This enables us to avoid explicitly restating highlight def link for each child syntax group.
The contained keyword, preventing this child syntax from extending past the boundaries of its parent syntax (e.g., EOL for comments, string delimiters for strings).
All parent syntax groups delimited by commas to the containedin keyword. The .* regex operator enables us to cleverly match all Python string syntax groups (i.e., pythonString, pythonUniString, pythonRawString, pythonUniRawString, pythonDocstring) with minimal pain and maximal forward compatibility.

Although technically valid, the vimscript embedded in Martin's answer violates the DRY (Don't Repeat Yourself) principle. See also this similar answer for further details.
But wait... there's more.
Unasked-for Improvements for Great Glory
I'm sufficiently annoyed by both Vim's overly naïve default spell checking and third-party plugins (e.g., Spelunker, which unconditionally spell checks the entire buffer rather than merely code comments and strings) that I've decided... to actually do something about that. </gasp>
The well-tested Vim snippet below intelligently avoids spell checking all of the following within Python comments and strings:

URIs (as above).
CamelCase identifiers.
snake_case identifiers.
UPPERCASE  identifiers.
@-prefixed identifiers (e.g., @muhdecorator).
"-delimited filetyped filenames (e.g., "muh_module.py").
:-delimited substrings (e.g., the :func: in :func:`re.sub`).
`-delimited substrings (e.g., the <code>re.sub</code> in :func:`re.sub`).

Add some or all of the following to your user-specific ~/.vim/after/syntax/python.vim file and gasp in delight as Vim actually spell checks the RightStuff™ for once:
" Avoid spell checking URIs.
syntax match NoSpellPythonUri /\v\w+:\/\/[^[:space:]]+/ transparent contained containedin=pythonComment,python.*String contains=@NoSpell

" Avoid spell checking both CamelCase-formatted identifiers and uppercase
" identifiers. Since most languages (excluding Raku) prohibit Unicode in
" identifiers, these matches are intentionally confined to ASCII codepoints
" (e.g., "[A-Z]" rather than "[[:upper:]]").
syntax match NoSpellPythonCaps /\v<[A-Z]([A-Z0-9]{-1,}|[a-z0-9]+[A-Z0-9].{-})>/ transparent contained containedin=pythonComment,python.*String contains=@NoSpell

"FIXME: For unknown reasons, enabling this and *ONLY* this "syntax" statement
"causes subtle (but horrible) failures across "python-mode" indentation and
"syntax highlighting. While lamentable, we need "python-mode" more than we need
"to avoid spell checking snake_case-formatted identifiers. See also this
"currently unresolved upstream issue:
"    https://github.com/python-mode/python-mode/issues/1083
"
" " Avoid spell checking snake_case-formatted identifiers.
" syntax match NoSpellPythonSnake
"   \ /\v<\w+_.{-1,}>/ transparent
"   \ contained containedin=pythonComment,python.*String contains=@NoSpell

" Avoid spell checking "@"-prefixed identifiers.
syntax match NoSpellPythonDecorator /\v\@[a-zA-Z].{-}>/ transparent contained containedin=pythonComment,python.*String contains=@NoSpell

" Avoid spell checking ":"-delimited substrings.
syntax match NoSpellPythonColons /\v:[^:]+:/ transparent contained containedin=pythonComment,python.*String contains=@NoSpell

" Avoid spell checking "`"-delimited substrings.
syntax match NoSpellPythonTicks /\v`[^`]+`/ transparent contained containedin=pythonComment,python.*String contains=@NoSpell

" Avoid spell checking '"'-delimited filetyped filenames matched as a
" double-quoted substring containing a filename prefix, a period, and one to
" four characters comprising a filetype.
syntax match NoSpellPythonPath /\v"[^"]+.[^"]{1,4}"/ transparent contained containedin=pythonComment,python.*String contains=@NoSpell

Of course, all of the above could (and possibly should) be reduced to a single one-liner matching one Godzilla-like regular expression that no one including myself would ever be able to maintain or even read. For everyone's sanity, I didn't do that.
If someone who is not me would like to make a GitHub-hosted Vim plugin expanding the above to other popular languages, that'd be just great. Vim's default spell checking implementation is almost there, folks; it just needs a helping hand from the open-source community.
Until then, may the StackOverflow be with you always!
Comment: I kinda figured out this whole Vim syntax highlighting thing while writing answers here. I didn't always know what I was doing to be honest, so especially some of the older answers may be less-than-optimal
Comment: You're too modest, Martin. Without your "breaking the ice" answer, I and many others wouldn't have even known where to begin. Thanks for getting this editor party started! Rome may not have been built in a day, but at least we can spell check it in one now.
Answer: Elaborating on Martin and Cecil's excellent answers, I came up with this.
All the code I give is to be put in your vimrc, after :syntax enable (so that you can plug onto the syntax linter by doing :au Syntax * ...).
So, the annoying part in the problem at hand is that you need to specify for all filetypes you care about, all the matchgroups in which you want your spelling exception to apply. There is no way around that, but you can relieve the task a bit by defining a cluster. I use this one.
au Syntax * syn cluster AllSpell contains=
\cComment,cCommentL,cString,cCppString,
\javaComment,javaLineComment,javaCommentTitle,javaString,
\javascriptComment,javascriptLineComment,jsonString,
\scalaMultilineComment,scalaTrailingComment,
\hsLineComment,hsBlockComment,
\ocamlComment,ocamlString,opamComment,opamString,
\lispComment,lispCommentRegion,lispString,
\makeComment,
\shComment,shSingleQuote,shDoubleQuote,zshComment,
\vimComment,vim9Comment,vimLineComment,vim9LineComment,vimMtchComment,vimString,
\pythonComment,pythonString,pythonRawString,
\luaComment,luaString,luaString2,
\perlComment,perlPOD,
\prologComment,prologCComment,prologString,
\texComment,bibField,bibComment,bibComment2,bibComment3,bibQuote,bibBrace,bibParen,
\xmlComment,xmlString,htmlComment,cssComment,

To figure out the matchgroups you want to insert into, you need to look into the code of the linters for the filetypes you care about (e.g. in /usr/share/vim/vimXX/yourfiletype.vim). Grepping for Spell helps. Typically that will be the matchgroups for comments and string literals.
According to Cecil's answer you can use wildcards in matchgroup names, so for instance I could have shortened vimComment,vim9Comment,vimLineComment,vim9LineComment,vimMtchComment to just vim.*Comment. Perhaps catching all of .*Comment,.*String would be a good idea, if brutal? Still, not all matchgroup names follow this pattern so you still need to do that work of looking into the linting code. Edited 2022-06-16: Wildcards are expanded early so this will likely not work, because the matchgroups are not defined yet.
Then, you can do:
au Syntax * syn match Url
  \ "\w\+:\/\/[:/?#[\]@!$&'()*+,;=0-9[:lower:][:upper:]_\-.~]\+"
  \ contains=@NoSpell containedin=@AllSpell transparent
au Syntax * syn match Url
  \ "\w\+:\/\/[:/?#[\]@!$&'()*+,;=0-9[:lower:][:upper:]_\-.~]\+"
  \ contains=@NoSpell

This uses a more satisfying regex for URLs (it matches a protocol:// followed by any succession of valid URL characters—as per RFC 3986—and Unicode letters).
The first rule matches contained URLs, thanks to the cluster just defined. It has the transparent option so that it lets the containing matchgroup style the URL. Because of that option, the rule apparently doesn't match URLs at toplevel, so a second rule is needed. (Of course, if you wanted to, you could also style the URL differently, e.g. :hi def link Url Underlined; then you must remove the transparent option and only one rule is needed.)
We can avoid repeating ourselves with a function:
fun! MatchNoSpell(group, regex)
  let l:cmd = 'au Syntax * syn match ' . a:group . ' /'.a:regex.'/ contains=@NoSpell'
  exe l:cmd . ' containedin=@AllSpell transparent'
  exe l:cmd
endfun

call MatchNoSpell('Url',
  \ '\w\+:\/\/[:/?#[\]@!$&''()*+,;=0-9[:lower:][:upper:]_\-.~]\+' )

This function is useful because it can be used for more spelling exceptions.


How to make a realistic spotlight with defocus effects

Question: I'm trying to use spotlight to project image on a plane, and hope to get blurred images with different defocus level in different position, just like a realistic projector. But actully the projected image is always clear no matter how I change the position of the plane. My node tree of the spotlight is shown below. Is there any way to solve it?
Comment: You should check the material of the image. If it is an emission one, no matter the lighting, the image will always be visible clearly.
Answer: If you wish to use the light falloff node to control intensity, then you need to use the quadratic output, not the linear output.  You also need to move the light much farther away from the projection screen to give the falloff a chance to work.  If you do this, you do not need to manipulate the XYZ coordinates and you end up with a node tree along these lines:

However, I prefer to have more control over the falloff, so instead of the light falloff node, I use a spherical gradient node and a math node.
Here is my entire node tree for such a projector.

The top part of the tree, in the frame labeled Only project forward is cosmetic and not related to the falloff.  It merely makes sure that the plane I'm using as a projector only projects in one direction.
The second part, labeled Image to Project is, of course, how you attach the image to the Emission node.  In this case, since I imported the image using the Images as Planes add-on, I don't really need the Texture Coordinate or top mapping nodes.
The third part is the "fun" part.

The bottom mapping node is needed to center the gradient.  Without it, the sphere will be centered in the lower left corner of the lamp plane.  By mapping with a (-.5, -.5) offset, I've moved the center of the sphere to the center of the image.  So the gradient looks like this:

The gradient node does the math to give the falloff.  As you can see, the corners are darker than the edges.
The math node controls how intense the light is.  Multiplying by a number smaller than 1 gives a greater falloff.  The smaller the number, the more pronounced the effect.

That's a multiply node, but I sometimes use a multiply/add node.  The multiply controls the effect while the add sets the basic intensity of the light.
Here's an example setup.  The smaller plane is the "spotlight". The larger plane is the projection screen.

Even so, the effect is very subtle unless you move the spotlight farther from the screen.
Comment: Thanks for your answer. It's very close to the effect I want. Can I focus on a object or adjust focus distance through this way?
Comment: Other than changing the math node to a color ramp and hand tuning the color ramp to get the falloff pattern you want, I don't know of a way. It could probably be done with geometry nodes in 2.93, but I don't know enough to say how.


Reason for nomenclature of azeotropic mixtures

Question: The book states the solution which shows large positive deviation from Raoult's Law form minimum boiling azeotrope
What is meant by " minimum boiling azeotrope" or I should say what does minimum signify here
Comment: I think the meaning is very clear from the attached figure. A minimum boiling azeotrope boils at lower temperature than any other mixing composition of the two compounds.
Comment: I wanted the reason as well and Max w has done it lots of thanks
Answer:
What is meant by minimum boiling azeotrope?

Two red lines have been drawn in the phase diagram below. Both are parallel to the horizontal axis. The first is at the boiling point of ethanol, and the second is at the boiling point of water.

Now look at the liquid curve.
(1) As the % Water increases from 0% the curve starts down, outside of the zone defined between the two red lines. The curve can't go down forever since at 100% water the curve must reach 373 K. So between 0% Water and 100% Water there must be a minimum in the curve.
(2) Since the curve falls below the zone defined between the two red lines an azetrope must form at the minimum. Remember that if the liquid is changing composition so must the vapor.

The converse is true too. If the vapor line goes above the zone defined between the two red lines, then a maximum boiling azeotrope must form.


Can't change galaxy s4 lock screen wallpaper if security is in place

Question: If I use no security for galaxy s4 lock screen I can use a custom wallpaper for the lock screen. But if I use a Pin security then the lock screen uses the default wallpaper of a kid running with a bunch of balloons when entering my pin. Can someone confirm this please? Thanks
Answer: From what I've read this is a known "issue" with the S4.  When using pin security you can't change any lock screen widgets either.  If I was sure that my Fitbit Flex would continue to work with the S4 I'd have flashed CyanogenMod onto my S4 (they have been producing nightly versions for the S4 for a couple of weeks now).
Comment: Thanks for your answer. Surprisingly i restarted the device and the problem fixed itself. Hooray


Necessary and sufficient condition for vector spaces

Question: Any specific reasons for defining a vector space to have the properties like closed under addition, closed under multiplication, associative, distributive...Why only these properties? (What makes these properties necessary and sufficient?)
Comment: These properties make linear combination possible.
Answer: The ten axioms that a set of vectors must satisfy in order to be considered a vector space are necessary in order to have a mathematical model that can actually be applied to the real world.
For instance, if you have the vector space consisting of all polynomials, it wouldn't make any sense to add two polynomials (two vectors in that space) and have their sum be a member of a different space, say the set of all two by two matrices.
As to why those axioms are sufficient, they were just determined to be that way by whoever was coming up with the definition of a vector space. Definitions that didn't contain all of these axioms, on the other hand, weren't sufficient and didn't provide adequate models. They were found to be inconsistent somehow.


Upstart script doesn't work on boot - only manually

Question: I followed this tutorial on setting up Flask with nginx + uwsgi.
I created an upstart script at /etc/init/flask-uwsgi.conf:
start on [2345]
stop on [06]

pre-start script
    mkdir -p /var/run/flask-uwsgi
    chown www-data:www-data /var/run/flask-uwsgi
end script

script
    cd /var/flask-uwsgi
    exec uwsgi --ini /etc/flask-uwsgi/flask-uwsgi.ini
end script

In order to work, the directory /var/run/flask-uwsgi must be created with its owner set to www-data.
If I do a hard reboot, this script (and the service) doesn't start automatically.
If I run service flask-uwsgi start manually , it works fine.
I tried adding setuid root to this script, thinking that you need root privileges to create directories in /var/run, but that didn't help.
My syntax appears fine:
init-checkconf /etc/init/flask-uwsgi.conf
File /etc/init/flask-uwsgi.conf: syntax ok

And, the log file /var/log/upstart/flask-uwsgi.log is empty.
What am I missing?
Answer: It was an issue with the stop on part of the upstart script.
Corrected:
start on [2345]
stop on [!2345]

pre-start script
    mkdir -p /var/run/flask-uwsgi
    chown www-data:www-data /var/run/flask-uwsgi
end script

script
    cd /var/flask-uwsgi
    exec uwsgi --ini /etc/flask-uwsgi/flask-uwsgi.ini
end script


Undo upvote if the comment is edited

Question: There should be an option to undo your comment upvote if a comment gets edited. It is likely that you upvote something else which gets useless or provides incorrect information after the edit.
Comment: Given that there's a 5 minute time limit to editing a comment... not usually a problem.
Comment: No, Oded says it is usually not a problem, which makes the development effort too high compared to the little gain.
Comment: It's just a comment. And comment upvotes have really no real meaning. So it's not a big deal at all.
Comment: Maybe, but as it stands it's simply not considered an important feature of Stack Exchange.
Comment: @Oded So you suggest that a person should keep waiting for 5 minutes to see if it gets edited or not? Seriously?
Comment: @ShadowWizard An upvote says that *it adds something useful to the post*. If comment upvotes don't really have no meaning then may be there is no need for the feature of upvoting comments
Comment: Well it's not really that big of an issue, but in any case: Note that you already have [60 seconds to undo a comment upvote](http://meta.stackexchange.com/questions/1170/cancelling-upvote-on-comment?rq=1) (lot's of interesting discussion there as well). The only way I could see this request possibly getting traction, @Sardar_Usama, is if you frame it as an increase in the time limit to 5 minutes, to match the edit time limit, which doesn't seem like an unreasonable thing to want. You might want to add some rationale along these lines to your request, though.
Comment: It should be allowed to undo vote unconditionally as proposed in https://meta.stackexchange.com/questions/134302/comment-upvote-undo-and-then-re-upvote-why-not/361775#361775            "we all have the right to change our minds about any topic, for any reason, and hence vote and re-vote accordingly."
From https://meta.stackexchange.com/questions/171694/dont-lock-votes-on-meta-sites/252636#252636
Answer: I haven't had very many cases where I would have wanted this.
Either it doesn't matter too much, just like an incorrect upvote or downvote on a post, or there is another way out (flagging if the edit is really terrible). And comments are second class citizens; they don't have any influence on reputation and they can be removed at will of the moderator, so no need to worry too much about them.
All these points combined shows that there is no need for this feature.
Answer: While it may not be the most critical feature for Stack Exchange, I agree it would be nice to have.
In addition to giving the option to undo an upvote on edited comments, I'm a fan of this idea on a similar post. You could let the user know a comment they have voted on has been edited by sending a notification.

Undo upvote if the comment is edited


Publishing open-source code similar to unfinished master's work

Question: My electrical engineering master's program was a disaster. My advisor gave me three different projects:

The first one was interesting, challenging, and solvable, but initial peer review of the paper revealed it to be irrelevant to the field. Essentially it was a very marginal improvement on an obsolete technology. The reviewers used colorful language.
The second assignment was too vague to be actionable, and would have amounted to re-creating a huge, expensive physical modeling package. In order to understand this scope problem, I did a ton of research and coursework. (It would've been easier if the advisor had told me about the pre-existing software in the first place.)
The third was basically just a programming task. I coded it up without learning much — no coursework related to this one. The program solved most, but not all, of its problem set. The advisor said this didn't matter, and to write it up anyway.

At this point, the degree seemed to lack validity, the field had lost its luster, and I was very literally losing my sanity. I stuck around and took some humanities courses, then in December 2008 told my advisor I'd take a hiatus. It was our last communication. I moved to another state and quit programming for a while.
I hate giving up. In September 2009 I started a writing a new program related to the third project, solving the same problem set. I worked on it on-and-off for a year until I got a job. (The problem was an open challenge. Unbeknownst to me, competitions were held in 2011 and 2012.)
Now, six years later, I'd like to polish up my independent work and post it to GitHub. Do I have any obligation to the advisor or to the university, or can I just go ahead and release it?
Answer: As long as your new project is entirely original and does not infringe any patents, there is no issue with releasing it.
It is highly unlikely your professor or old institution would possess any patents for a simple program. It's impossible for me to state anything with certainty as I do no know the nature of the software, but software patents are already fairly uncommon and legally questionable. You could look up the concept and professor's name somewhere like Google Scholar to be sure.
The primary concern would be if you re-used source from the time you were at the institution. This depends on the agreements you made with the university; if you are reusing components, you should review what you signed related to your master's program and possibly contact the institution's legal department for advice. You could of course cut out such components as well, which is what I would suggest.
The fact you learned something you later applied does not give those who taught it to you any legal or moral rights over the work. Especially considering it sounds like you did all the leg work in the first place.
If you are worried in an academic context of accusations of plagiarism, you could simply acknowledge where the concept came from / previous work in a README file. If you are not infringing patents or copyrights, there is no reason not to.


Why does a number of completed tasks in Mapreduce decrease?

Question: When running hadoop jobs, I noticed that sometimes the number of completed tasks decreases and number of canceled tasks increases.
How is this possible? Why does this happen?
Answer: I've only experienced this when our cluster was in a strange state, so I'm not sure if this is the same issue. Basically, map tasks would complete, and then the reducers would start... and then mappers would be reprocessed.
I believe that the problem is that mapper output hangs around on that data node waiting for reducers to pick it up. If that node has issues or it dies, the JobTracker decides that it needs to rerun that task again, even if it had completed. Our issue was that the system our NameNode was on was having some non-Hadoop related issues and once those were resolves it seemed to go away.
Sorry if my experience was not relevant to your issue. Perhaps, can you post more details? Do you see any error messages? Is there anything weird in your JobTracker or NameNode logs?


Shouldn't "some of the phenomenon" be plural?

Question: The paragraph:

Our team conducts fundamental research in Philosophy, trying to push
  the boundaries of what is possible with new techniques, and also trying
  to understand and formalize some of the phenomenon observed in
  practice.
Source

My Greek instinct read phenomena instead of phenomenon... Am I correct? Or, in English it's OK to use it like this?
Comment: Yes you are, and no it's not.
Comment: . . . unless it is a single phenomenon—and *some* is referring to just a part of it. Then the singular would be fine. But, semantically, I don't see how that makes sense.
Comment: @JasonBassford that's why I included the whole paragraph..To cross check that I am not misunderstanding the semantics here...!
Answer:
…some of the phenomenon…

Consider that usage as a typo, it's like criteria vs criterion, many use the former thinking it is an uncountable noun while other speakers add an "s", i.e. criterias, to make it plural.
The study of Greek and Latin does not enjoy the same prestige as it used to in the past, so we shall hear the following with increasing frequency: phenomenons and datas and agendas in the future.

The OED's evidence shows that the plurals datas (first recorded in 1645) and medias (appearing in 1927) have a long history and crop up in varied sources, from scientific and academic journals to The Times.
Oxford Dictionaries Blog

I found this 2011 article in the Daily Telegraph, an exemplary hodgepodge, but at least both forms are recognizable as being plural.

Weird weather: the top ten strangest phenomenons
Scientists now believe that tiny bugs in the earth's atmosphere can cause storm clouds to form. Here is a list of 10 other amazing weather phenomena

Shouldn't “some of the phenomenon” be plural?


Should Test Code be Separate from Source/Production Code

Question: Even if we have a Makefile or something similar to separate the test code when shipping product.
In my opinion, they should be separate, but i am not entirely convinced as to WHY
Comment: depends on the tools being used, but for C  and Python, and using Jenkins its just easier to manage plus we can use the code coverage and static analysis tools supported by Jenkins seemlessly.
Comment: Our test code lives in the projects with the code it tests. Our build process doesn't copy them to the deploy folder.  (C# projects, MSBuild, MSTest) Why would you want separation?
Answer: Yes, they should be separate (folders and preferably projects). Some reasons:

GREP. Searching for a string in production source is easier.
Code coverage. Imagine trying to specify which files to include for coverage.
Different standards. You may want to run static analysis, etc. only on production code.
Simplified makefiles/build scripts.

Modern IDEs will allow you to work on code from separate projects/folders as if they were adjacent.
The worst thing you can do is to include test and production code in the same file (with conditional compilation, different entry points, etc.). Not only can this confuse developers trying to read the code, you always run the risk of accidentally shipping test code.
Comment: well said , i am also reading up on http://en.wikipedia.org/wiki/Separation_of_concerns applied to testing code
Answer: Since I had a chance to work with both approaches (separated and with project code), here's few tiny-things that were getting in a way to note (C#, Visual Studio, MsBuild).
Same project approach

References/external libraries dependencies: unit testing and mocking frameworks usually come with few dependencies on it's own, combine that with libraries you need for actual project and list grows very quickly (and nobody likes huge lists, right?)
Naming collisions: having class named MyClass, common approach is to name test class MyClassTest - this causes tiny annoyances when using navigation/naming completition tools (since there's bigger chance you'll have more than one result to chose from for quick navigation)
overall feeling of ubiquitous mess

Naming collisions can actually get even more tiresome, considering how classes relating to similar functionality usually share prefix (eg. ListManager ... Converter, Formatter, Provider). Navigating between comprehensible number of items (usually 3-7) is not a problem - enter tests, enter long lists again.
Separated approach

Projects number: you'll have to count the number of libraries you produce twice. Once for project code alone, another time for tests. When bigger projects are involved (200-300+ sub-projects/libraries) having that number doubled by test projects extends IDE startup time in a way you never want to experience

Of course, modern machines will mitigate projects number issue. Unless this really becomes a problem, I'd always go for separated projects approach - it's just more neat and clean and way easier to manage.
Comment: @TrueWill: makes me think navigation is actually more than *tiny annoyance*... especially when few classes share same prefix (which is fairly common). Talk about *quick* navigation between 14 types.
Answer: In fully automated building and unit testing framework, you can essentially separate them out.
It makes more sense to fire up the automated unit tests after the nightly build is done.
Keeping them separate makes it easier for maintenance purposes.


Is my matic lost?

Question: Recently I sent erc20 matic from an eth wallet to an matic wallet address the tx was successful on etherscan but my sent amount or tx is not found in the destination matic address and or polyscan. Is it now lost?
Comment: Please add links to your transactions if you want us to be able to help you.
Answer: assuming you have control of the address on polygon through metamask your matic is fine. Its just waiting for you at the same address but on mainnet, you can recover it by sending some ether to this address to pay for gas and then transferring it to an address you use (or bridge it to polygon using https://wallet.matic.network/bridge/)

Is my matic lost?


Encoding features with big amount of classes

Question: Is it worth to encode features with big amount of classes ( such as 60 )? Or should I leave it as it is ?
Answer: big amount of classes are called High-cardinality refers to columns with values that are very uncommon or unique.
Dealing on High Cardinality depends upon the data/use case/model,
The Following are the methods we can use to handle High Cardinality:

Drop (According to business case)
Embed with frequency/count.
Target encoding/ CatBoost encodings.
Reducing Cardinality by using a simple Aggregating function

Refer below links

Encoding of categorical variables with high cardinality
How to encode a categorical feature with high cardinality?
Answer: Usually when we have Categorical variables, we do one hot encoding to convert to numerical data and use in model. If we have n classes we get n variables.

Now, High Cardinality Variables are those categorical variables which have large number of classes and doing one hot encoding may lead to a high dimensional data which we try to avoid.
But in a lot of these cases these high cardinality variables may have a lot of information and we want to use them as part of training data. To do so we can apply following techniques :
<code>      1. Try to drop the category which in less frequent or has a frequency of less then 1% or you can encode it with some special category say("rare"). You can use some business hypothesis to do that

      2. Replace the Categorical Variables by using Smoothed Weight of evidence encoding

      3. Use algorithms like CatBoost which encodes using Target encoding.
</code>
Like any other variables, if cardinal variables seems some relation with Target variables it may seem sense to encode it otherwise not.
For a more detailed analysis please refer to this link


Customizing hover text in lightning-combobox

Question: We are using lightning-combobox (in  lwc) to display a dynamic dropdown list.  We are adding just the standard 2 attributes per option i.e label and value. When a user hovers on any of the options, then the label is displayed as the hover text.  Is there a way to customize that hover text?  I tried adding "title" as an attribute to the option, but that did not have any effect.
Comment: Can you add an example and screenshot on whats missing?
Comment: @MohithShrivastava I added a screenshot above.  The hover text always shows the same value as the label, even if we add the title attribute to the option.  You can also see this in the LWC reference for lightning-combobox: https://developer.salesforce.com/docs/component-library/bundle/lightning-combobox/example
Answer: Out of the box, this is not possible as of today as this is not exposed for component consumers to override this behavior.
However, if you want this functionality I would look into the source code that's available here.
There is a hierarchy below of components forming this component.
<code>combobox
  baseCombobox
    baseComboboxItem
      baseComboboxFormattedText
</code>
All you will need to do is modify the component to make sure the title is passed.


Citrix and Ubuntu Server / Ubuntu Clients for VDI

Question: does anyone have any experience running ubuntu as a hosted desktop using XenServer have any reasons why I should not pursue this option?
Answer: I have an Ubuntu server running under XenServer right now.  There are no issues with getting this to work, except for the fact that Citrix does not provide a pre-packaged template for installing Ubuntu under XenServer.
The most simple to do this is to grab the image from here, and do a File->Import from XenServer:
http://www.isaaczarb.com/ubuntu-9-10-x64-template-for-xenserver-5-x/
After you do this, you may want to upgrade ubuntu to the latest version with a do-release-upgrade, you can do that following the instructions here: http://www.ubuntu.com/download/ubuntu/upgrade
Regards, Port Forward Podcast
http://portforwardpodcast.com/


MSP430 Programming BSL vs Spy-Bi_Wire

Question: Does an MSP430 (Specifically the LaunchPad F5529) retain its code which was transferred via the Spy-Bi-Wire (SBW) Port? Or do I need to use the BSL to program the chip? In layman's terms what is the difference between the two, and why would I need one over the other? Thanks!
Comment: pretty sure both do the job, one vs another is depending on what host software you are using.  Mspdebug for example supports bsl for that board.
Answer: Spy-Bi-Wire is:

more powerful. It is an implementation of JTAG interface, so it allows not only program, but also to debug the MCU (single-step, insert breakpoints, etc).
more complex. Typically requires a dedicated chip to operate. LaunchPads have that chip on board, but custom-made PCBs are unlikely to have it, so originally a special and expensive programming board was required to program them. However, with the introduction of LaunchPads things have changed: a spare LaunchPad can be reused in the role of this programming board for other devices as well, for a fraction of the price.
synchronous protocol (more reliable).

BSL is:

more generic. In general, only the newer models of MSP430 support Spy-Bi-Wire. However, "a few low-end MSP430 members cannot be programmed by BSL initially, they can only be programmed by 4-wire JTAG or SBW" (source).
simpler: the programmer side usually can be implemented in software. However, some msp430 Series 5 chips have a bug, due to which they require very fast BSL command turnaround times, far higher than can realistically implemented in software, at least in userspace applications on Linux or Windows. So for those chips this BSL benefit is nullified. This is not an issue for F5539 though, according to TI errata documentation.
asynchronous protocol (less reliable).

MSP430 Programming BSL vs Spy-Bi_Wire


Finding the minimal coverage of an interval with subintervals

Question: Suppose I have an interval (a,b), and a number of subintervals {(ai,bi)}i whose union is all of (a,b).  Is there an efficient way to choose a minimal-cardinality subset of these subintervals which still covers (a,b)?
Comment: Are you looking for the smallest number of subintervals, or the set of subintervals that has the fewest elements (and hence, the fewest duplicates)?
Answer: A greedy algorithm starting at a or b always gives the optimal solution.
Proof: consider the set Sa of all the subintervals covering a. Clearly, one of them has to belong to the optimal solution. If we replace it with a subinterval (amax,bmax) from Sa whose right endpoint bmax is maximal in Sa (reaches furthest to the right), the remaining uncovered interval (bmax,b) will be a subset of the remaining interval from the optimal solution, so it can be covered with no more subintervals than the analogous uncovered interval from the optimal solution. Therefore, a solution constructed from (amax,bmax) and the optimal solution for the remaining interval (bmax,b) will also be optimal.
So, just start at a and iteratively pick the interval reaching furthest right (and covering the end of previous interval), repeat until you hit b. I believe that picking the next interval can be done in log(n) if you store the intervals in an augmented interval tree.
Comment: "If we replace it with a subinterval (amax,bmax) from Sa...": Do you mean the sub-interval (amin, bmax)? And I'm not so sure about (bmax, b) either.
Comment: Could you elaborate: "the remaining uncovered interval (bmax,b) will be a subset of the remaining interval from the optimal solution"?
Comment: @JFS: Suppose that the optimal solution starts with an interval (ai,bi) that covers (a,bi) and leaves (bi,b) uncovered. From the definition of (amax,bmax) we have that bmax>=bi, so (bmax,b) is a subset (subinterval) of (bi,b).
Comment: @user183037 The 'max' is just an index for the whole interval. Interval 'foo' is (a_foo,b_foo). (b_max,b) is the remaining interval.
Answer: Sounds like dynamic programming.
Here's an illustration of the algorithm (assume intervals are in a list sorted by ending time):
<code>//works backwards from the end
int minCard(int current, int must_end_after)
{
    if (current < 0)
        if (must_end_after == 0)
            return 0; //no more intervals needed
        else
            return infinity; //doesn't cover (a,b)

    if (intervals[current].end < must_end_after)
        return infinity; //doesn't cover (a,b)

    return min( 1 + minCard(current - 1, intervals[current].start),
                    minCard(current - 1, must_end_after) );
    //include current interval or not?
}
</code>
But it should also involve caching (memoisation).
Comment: `minCard()` is intended to get a minimal cardinality but the question asks for a subset with minimal cardinality.
Comment: It would just be an extension of this algorithm that also keeps track of which subset was used to form that optimum value.
Comment: @Artelius What is the complexity of your algorithm ?
Comment: The complexity is O(n^2) in the worst case. For example when all intervals have an identical end point but different start points, all of those start points are going to propagate back to the beginning. The greedy approach is better.
Answer: There are two cases to consider:
Case 1: There are no over-lapping intervals after the finish time of an interval. In this case, pick the next interval with the smallest starting time and the longest finishing time. (amin, bmax).
Case 2: There are 1 or more intervals overlapping with the last interval you're looking at. In this case, the start time doesn't matter because you've already covered that. So optimize for the finishing time. (a, bmax).
Case 1 always picks the first interval as the first interval in the optimal set as well (the proof is the same as what @RafalDowgrid provided).
Comment: Where in the question does `time` rear its daunting head?
Answer: You mean so that the subintervals still overlap in such a way that (a,b) remains completely covered at all points?
Maybe splitting up the subintervals themselves into basic blocks associated with where they came from, so you can list options for each basic block interval accounting for other regions covered by the subinterval also. Then you can use a search based on each sub-subinterval and at least be sure no gaps are left.
Then would need to search.. efficiently.. that would be harder.
Could eliminate any collection of intervals that are entirely covered by another set of smaller number and work the problem after the preprocessing.
Wouldn't the minimal for the whole be minimal for at least one half? I'm not sure.
Found a link to a journal but couldn't read it. :(
This would be a hitting set problem and be NP_hard in general.
Couldn't read this either but looks like opposite kind of problem.
Couldn't read it but another link that mentions splitting intervals up.
Here is an available reference on Randomized Algorithms for GeometricOptimization Problems.
Page 35 of this pdf has a greedy algorithm.
Page 11 of Karp (1972) mentions hitting-set and is cited alot.
Google result. Researching was fun but I have to go now.


Heatsink land pattern interpretation (DPAK heatsink)

Question: I'm looking at using a D Series heatsink from Ohmite. The land patterns on the last page of the product PDF are very lightly labeled and I'm not entirely sure how to interpret them https://www.ohmite.com/assets/docs/sink_d.pdf?r=false. From what I've seen elsewhere I think the first rectangle is the actual copper area under the back pad of the device and the second trio of rectangles are the solder mask openings.  I think the dashed outline rectangles under both of those are supposed to be the pads for the leads but they don't seem to be spaced right, at least not on the first diagram.
Answer: If you look at the picture of the heat sink, you will notice there are (relatively) narrow pads at the sides:

Looking at the front view, we can see that clearly:

So the land patterns are for either a single pad (where the transistor and heat sink have been mated prior to soldering) or for two pads (where the transistor and heat sink have not necessarily been mated prior to soldering, noticing that the overall dimensions of the pads are almost the same:

So there are two possible pads, depending on process flow. A single pad would make it difficult to solder the heat sink after the transistor has been soldered.
The best heat sink performance is for a single pad obviously; these devices are designed such that the top mating part will actually be in contact with the transistor (see datasheet); clearly separate pads will eliminate one heat path, but will make soldering the heat sink alone much easier.
In production, it is not unusual to pre-mate the parts using thermally conductive adhesives of which there are many (and then they can be handled as a single part).
Comment: In some cases you may not want the heatsink at the same voltage as the pad.
Comment: My understanding of these heat sinks (which matches the picture of them) is that they don't actually mate with the component directly and all heat flow has to go through the PCB to get to the heatsink. In that case having separate pads would be counter productive as there would be a huge amount of thermal conductivity loss in the gap between pads.
Comment: Updated to address the thermal performance; clearly a single pad is best but may not be suitable for all applications.
Comment: I'm still not seeing how you get "these devices are designed such that the top mating part will actually be in contact with the transistor (see datasheet)". Looking at the heat sinks themselves in the first image in your answer there are fins above the IC itself. I really doubt an IC would mount directly to fins. From what I see the heat sinks straddle the IC but don't mate with it directly, hence the need to have a heat path across the PCB.
Answer: I have another interpretation of the two patterns. I think the simple pattern is the minimum copper under the heatsink. The more complex pattern is for the solder paste. The larger center solder paste goes on the tab of the TO-2xx part, the two narrow solder paste areas adhere to the "rollers" of the heat sink. You'll have to determine the location of pins 1 and 3 pads based on where the TO-2xx part centers up. But for thermal effectivity, the PCB copper must be continuous, no gaps.I also believe that the simple rectangle pattern could be much larger if your PCB allows it. All that heat sinking will make reflow a tricky proposition, but most CMs can handle it.


What languages llama2 supports?

Question: Which languages llama2 supports? I looked at the docs and huggingface but I couldn't find a list. Just it says usage in other languages than English as out-of-scope.
Comment: hi @heyula, welcome to the forum. If you find the answers to your question useful, please consider upvoting them, and accepting one by checking the tick mark next to it. If you don't find them helpful, please clarify in a comment why.
Answer: From the Llama2 paper here: "Language Identification. While our pretraining data is mostly English, it also includes text from a small
number of other languages. Table 10 shows the distribution of languages in our corpus, subsetted to those
found in more than 0.005% of the documents. Our analysis uses the fastText (Bojanowski et al., 2016) language
identification tool and a threshold of 0.5 for the language detection. A training corpus with a majority in
English means that the model may not be suitable for use in other languages.
"

It's probably better at python than French.

What languages llama2 supports?


What is "CrankShaftScript" in Node.js?

Question: There are more and more references in the Node.js community to "CrankShaftScript" (and "CrankShaftJS") on Twitter, GitHub, and Facebook group discussions. I thought Node.js was written in C++ and JavaScript, so what is CrankShaftScript referring to in performance regression bugs like this one:
https://github.com/nodejs/CTC/issues/146#issue-237435588
Answer: CrankShaftScript is the name given by the community to JS idioms (such as certain types of loops) that run faster(est?) on V8's CrankShaft engine.
CrankShaft is being replaced by an engine named TurboFan. Lots of JS code written by devs over the years has been written specifically to run fast on CrankShaft (e.g. written in "CrankShaftScript") using the known idioms that run fast on CrankShaft - this is no longer necessarily the case because the V8 engine is now different and the code that ran fastest on CrankShaft is not necessarily guaranteed to run fastest on TurboFan.
In case my answer is too verbose, here's a great comment on the NodeJS Benchmarks thread that may detail it better:

...I noticed that some parts of Node core are sort-of written in
  CrankshaftScript, i.e. carefully tuned towards stuff that works
  extremely well in Crankshaft.
Answer: CrankShaftScript is a community-adopted term used for non-idiomatic and/or non-standard compliant JavaScript that will only execute and/or perform well in the specific versions of the v8 JavaScript runtime that employ the CrankShaft JIT compiler. Specific examples include: loops written in a difficult-to-maintain fashion to work around JIT optimization deficiencies in v8, and use of v8-specific built-in functions/globals.
This term was originally coined to describe some root performance issues in node-chakracore and spidernode, which are Node.js distributions that employ the ChakraCore and SpiderMonkey runtimes instead of v8.
It is now being used as shorthand to explain why the Node.js 8.1 release series, which updated to a newer version of v8, has several performance regressions in micro- and macro-benchmarks due to v8's CrankShaft JIT being superseded by TurboFan (sometimes referred to as "TF"). As in these issues:

https://github.com/nodejs/node/issues/11851#issuecomment-287253082
https://github.com/nodejs/CTC/issues/146#issuecomment-310229393
https://twitter.com/matteocollina/status/870580613266501632

For these reasons, the Node.js community is actively working on excising instances of CrankShaftScript in Node.js core code, as well as in common npm packages. This should help alternative Node.js distributions like node-chakracore perform better and ease the risk of future upgrades to the JavaScript runtime in Node.js.
Comment: A version of node v8.x with V8 5.9+ (which enables TurboFan by default) has *not* been released yet as of this writing. Node v8.0.0 did however bring V8 5.8 (although that version of V8 does not enable TurboFan by default).
Comment: My comment is still relevant for node v8.1.x, which only has V8 5.8. While there may have been some regressions with 5.8, it's not because of the switch to TurboFan as the default because as previously stated, the switch of the default engine only happened in 5.9. Also, node v8.1.x will never see a V8 bump to 5.9+ (only node v8.2.x or later) due to semver.
Comment: thanks for the clarification! I've edited the question.
Comment: Is there any documentation on what these idioms are?
Comment: The key point is that it's *optimized* for Crankshaft, which mostly means avoiding some things (like `try..catch`) that Crankshaft doesn't like. "CrankshaftScript" code is absolutely standards compliant, and would run anywhere, it just happens to be optimized for Crankshaft.
Answer: CrankShaft is the compilation infrastructure for V8, Node.js' Javascript runtime (details).
It's now being replaced by TurboFan.

What is "CrankShaftScript" in Node.js?


How to use cloth sim for flat surface?

Question: I'm trying to put a picnic blanket sort of thing onto a flat surface. When I do this, the cloth doesn't crumple or move (I'm guessing because there is nothing to bend it?, but I want to get a more natural and 'soft' blanket look, how would I achieve this? I have attached a picture of what it looks like now, I have the plane set to default cloth settings with 20 subdivisions and the ground set as a collision object. Sorry if this is a dumb question, I'm still really new to blender!
Comment: can u pls add a picture how it should look like? the problem with just textual picture descriptions is: it will be always vague. So one picture says more than 10.000 words...thx. Just give the pane a bit rotation and you will see "something".
Answer: You could create a Force Field > Turbulence for example, here I give it a Strength of 2000 at the beginning, and the cloth will fold:

How to use cloth sim for flat surface?


a finite sets problem

Question: I was given the next riddle in one of the lectures:
A jet plane with m ( a natural number) seats  which is filled up to the maximum is about to take off. each passenger holds a card with a natural number in his hand which he cannot see nor can he see the cards that his fellow passengers hold.
The plane will take off only if each of the passengers will guess what number it is that they hold. The captain decides to display a single number (a natural number) which will help the passengers figure out each of their own numbers.
The question is, what is that number?
P.S- the seats are numbered and each passenger knows the number of his seat.
I'd really like some hints with this one! Thank you so much!
*The captain can see each and every one of the numbers
Comment: I suppose the Captain could, given his knowledge of the mapping from seat numbers to card numbers, express that mapping as encoded in a single natural number.  Of course the corresponding "mapping" number will be much larger than the card numbers, and nothing might have prepared the passengers to be able to "decode" that number in order to deduce their individual card numbers.
Answer: Suppose the numbers (positive integers) are $N_1,N_2,\dots,N_m.$ The pilot displays the number $10^{N_1}+10^{N_1+N_2}+\cdots+10^{N_1+N_2+\cdots+N_m}.$
Comment: @JorgeFernándezHidalgo Thanks for catching my "typo"!
Comment: nice!${}{}{}{}{}$
Comment: Assuming this gives a proper bijection, how do all passengers know this encoding was used?
Answer: Suppose that passenger $k$ has number $f(k)$.
Then the pilot can show the number $\prod\limits_{n=1}^N p_n^{f(n)}$. Where $p_n$ is the $n$'th prime and $N$ is the number of passengers.
By the fundamental theorem of arithmetic every passenger can determine every person's number.
Comment: I guess they decide on a strategy beforehand, otherwise there isn't a strategy. its possible some of them don't know what a number is.
Comment: The OP says that no one can see any of the cards, not their own and not others'.
Comment: But how do the passengers know that prime factorization was used for encoding, there are other methods as well that result in a single natural number.
Comment: A sum with really help. As stated above, no one can see any of the cards. D:
Comment: will not * my mistake
Comment: you are completely welcome. I think the key idea is recalling that $\mathbb N ^k$ has the same cardinality as $\mathbb N$ for all positive integer $k$
Answer: Edit: here's a second answer, probably shortest so far and easiest to decode.
Suppose the longest number has $d$ digits. The captain pads each number with zeroes on the left so that it's $d$ digits long, then concatenates them in seat order. Since the passengers know the number of seats  they can compute $d$ from the length of the number they're told, then count off to their seat number. If the number of seats is unknown too then the caption uses $d$ as a prefix, padded the same way.

First solution:
Since the captain knows the numbers that correspond to seats he can tell the passengers the product of the numbers $(p_n)^{c}$ where $p_n$ is the $n$th prime and $c$ is the number held by the passenger in seat $n$.
The passengers will have to be pretty good at arithmetic. Maybe their cell phones can factor big numbers.
Comment: factoring will be easier, since they know exactly which primes are being used. This can be done in time $N\log(N)n$. (where $N$ is the number of passengers and n is the size of numbers.)
Comment: But passengers with even seat numbers might decode using Cantor pairing functions, the passengers with odd seat numbers try prime factorization, How to sync them to the proper encoding?
Comment: @mvw The captain and passengers must have agreed on a coding scheme in advance, else the problem is unsolvable. Several other comments address this question. It should be made explicit in the question.
Answer: Another idea is to order these numbers according to seats and describe them for example in a binary representations (using $0$s and $1$s) while separating individual numbers by digit that is not present in that representation (e.g. $2$). So for example numbers $1$,$5$ and $7$, which have binary representations $1$,$101$ and $111$, could be encoded into number $121012111$.
Comment: nice, this reminds me of the conway $13$ function.
Comment: But where is the hint that all passengers agree on that encoding?
Comment: @mvw Well that is a required assumption, without that the riddle seems to be pointless... But it would be nice to have this clarified by OP
Answer: Suppose the plane has just 4 seats. The captain could display the number $13243241$ to show that seat 1 was assigned number 3, seat 2 was assigned number 4, seat 3 was assigned number 2 and seat 4 was assigned number 1. More seats can be dealt with in an analogous way that requires no computations.
Comment: Does $12222$ mean seat $1$ was assigned number $2$ and seat $2$ was assigned number $22$ or is it the other way around?
Comment: I was assuming that the assigned numbers are all $\leq m$, or even $\leq N$ where $N$ is known. If no upper bound for the assigned numbers is known I guess the simple method I described is not applicable
Comment: but what happens when numbers larger than $9$ appear?
Comment: $3421$ would suffice.
Answer: Because $\mathbb{N}$ can be bijectively mapped to $\mathbb{N}^m$ the captain can encode all $m$ numbers $k_i$, ordered by the number of the seat into one natural number:
$$
N = \langle k_1, \dotsc, k_m\rangle
$$
However this leaves the passengers to guess what encoding scheme (Cantor pairing, prime number factorization, ..) he might have used.
So can we infer from $N$ what encoding was used?
Comment: One can definitely not infer from $N$ how it was encoded. An encoding, after all, is just an injective map $\mathbb N^k\rightarrow \mathbb N$ and, for any $x\in \mathbb N^k$ and $y\in \mathbb N$ there is such a map $f$ with $f(x)=y$.
Answer: The pilot displays the number of digits of number held by passenger 1. Eg: if passenger 1 holds the number 403, then pilot displays 000403 and passenger 1 counts 403 after 3 zeros. The same logic is continued after 403 for second passenger. It works only if the passengers donot have additional 0 in front of the number they hold. The only problem is pilot should a huge display and passengers should keep the count.
Edit: the same logic modified by using 1s to indicate initial zeros in a number, can used to tell the exact sequence and not just the number.
Answer: Simplest answer would be to come up with a n-digit mapping scheme between seat numbers and card numbers.
For example, suppose the seats were 1-100 and the numbers were 1-1000. Then the pilot would write a number with ordered groupings starting from 100 (to prevent leading zeroes) and descending, using 0's to preserve space.
So it would look something like this:
10010000990878098...
Or in formatted fashion
100 1000 099 0878 098 ...

a finite sets problem


'Takeown' command not working

Question: I'm trying to reduce the size of the 'ManifestCache' folder on a 32-bit Windows Vista Ultimate computer.  I type "Takeown /f c:\windows\winsxs\ManifestCache*" and I get the following error message: "The current logged on user does not have ownership privileges on the file (or folder): "c:\windows\winsxs\ManifestCache\6.0.6002.18005_001c11ba_blobs.bin".  The user is in a workgroup and has administrator privileges.  Also, I shut down the the 'trustedinstaller' prior to attempting to take ownership.  Thanks, in advance, for your help!
- Charles
Answer: You most likely are not running this from an elevated command prompt.
Click Start > type cmd into the search box > right click on cmd.exe and select Run As Administrator
Then try the command again.
Comment: @Charles, The best way to notice this is to ensure that the UI for two type of cmd prompts (administrator or not) are different. E.g. If I open an administrator cmd prompt, the background is green as opposed to white background if its opened without cmd prompt.

'Takeown' command not working


Merge two images with using a sprite

Question: I have an image and an image sprite. I want to merge certain parts of the sprite on top of the image. I have got this working with just one part of the sprite, however when the sprite is merged on top of the image, the sprite loses its transparency.
$image = $homepath.'/images/orig.png';
$sprite = $homepath.'/images/sprite.png';
$image = imagecreatefromstring(file_get_contents($image));
$sprite = imagecreatefromstring(file_get_contents($sprite));

imagecopymerge($image, $sprite, 50, 50, 80, 0, 80, 100, 100);

imagepng($image, $homepath.'/images/output.png');

Example output: https://i.stack.imgur.com/LC70m.png
Whatever the dimensions are that I set for the sprite is what has a background color. The color is the same color as the sprite. So in the case, the word "text" are part of the sprite, but if this text was green, the rectangle would be green.
///EDIT///
Figured it out: imagecopyresampled
Answer: You probably want another gd function: imagecopyresampled.

Merge two images with using a sprite


My phone uses excessive data 0

Question: I have a sansung s7.  It is gobbling up data.  I've disabled as many programs as i dare from running in the background but no help.  Is there anything i can do about it?
Answer: That's not good to hear! If your Samsung S7 Edge is rooted then I would suggest running an application such as AFWall+ and setting custom rules to block applications communicating to web-servers etc.
You did not mention how much data you have to play with, but you could go ahead and install an application such as 3G Watchdog to view what applications are using an excessive amount of data. (This can also be viewed in Settings --> Data)
I would suggest you ensure your accounts are not set to sync frequently, and that apps are not updating over 4G.
Lastly if that all does not help, here are some good forums:
Android Authority - Android OS destroying my Data!
Samsung Forum - OS Application using extensive data
Reddit - S7 Edge using heaps of data
All the best.
Answer: Try disabling background data and also stopping sync services like photo backup. Sometimes cloud storage services provide the option of keeping the cloud files on the device. Which means if this facility is on, any large file may be downloaded to you device from the server to keep sync.

My phone uses excessive data 0


Replacing android Fragment from Main activity

Question: I'm new to Android and am completely stuck. I keep getting an exception when I try to inflate my Fragment.
Here's my project details:
 This is a TabHost project. I have a "dummy" activity for each tab. Each tab "dummy" activity has a linear layout that I use to inflate the group of Fragments for that tab to. When I create the activity under a given tab from my main activity, I add a default Fragment for that activity. Everything works perfect.
Now for my issue:
 I have an ActionBar Menu that is dynamically built depending on which tab is focused. When the user clicks a menu item, I need to replace the current Fragment on the focused tab activity. Because the ActionBar is on Main Activity and not the host activity for the focused Fragment, I am having trouble inflating the Fragment from the Main Activity. I've spent a few full days now trying to figure out how to do this. No matter what I do, I get "No view found for id 0XXXXXXX Fragment.". I'm assuming this is because the Main Activity is not tied to the FragmentManager of the tab activity that is used to host the Fragments.
Any suggestions on how I can replace the fragment on the host activity from the Main Activity?
Thanks in advance!
Answer: Check out the use of FragmentActivity at http://thepseudocoder.wordpress.com/2011/10/04/android-tabs-the-fragment-way/


In terms of results, how similar is a bunch of telescopes across the globe to an Earth-sized telescope?

Question: The Event Horizon Telescope emulates an Earth-sized telescope by syncing a bunch of radio telescopes across the planet to do take pictures with a small enough angular resolution to take pictures of a black hole. Would the angular resolution, or perhaps just general performance, of an Earth-sized telescope be appreciably higher than this?
Comment: Obviously, the received light doesn't emulate such an Earth-sized telescope.
Comment: @Felicia that's such an important point that I think it deserves an answer of its own. Resolution based on aperture assumes a long enough exposure that it's not limited by signal to noise ratio (SNR). With low SNR you can have uncertainties in size and position much larger than what a simple point-spread function (PSF) might suggest. *Consider adding an answer?*
Answer: In regards of resolution a virtual telescope acts identical to a normal telescope: size matters:
More accurately, the optic's diameter $D$ and the wavelength $\lambda$ determine the resolution or optical resolving power: $\theta = 1.22\cdot\frac{\lambda}{D}$. This is called the Rayleigh criterion which states that at this fraction two adjacent dots can be distinguished as then their airy disks of the diffraction patterns of the two adjacent point sources are sufficiently separate to indentify them separately in the image. Note that the area of your telescope does not play a role in the resolution, but only the diameter of the optics.
Now, why use a large disk? The larger your collecting area is, the more of the signal you gather, the better is your signal to noise ratio, the brighter the source compared to the background (like you see with binoculars fainter objects than with your naked eye, and with a larger telescope fainter ones than with a binocular). Thus the sensitivity simply scales with the actual collecting area of your instrument. Thus more or larger disks do help to detect fainter sources.
The Australian Telescope National Facility has a nice illustration of these two phenomena.
So in summary: a virtual earth-sized telescope is as good as one big telescope when it comes to see the spatial detail. But more and larger telescope as part of this virtual telescope help increase the contrast, thus allow to identify spatially-resolved details which only vary slightly in brightness.
Comment: This isn't actually quite true. EHT goes through heroic efforts to try to hide the diffraction due to its woefully-under-sampled aperture. And large ratio telescopes depend on long exposures such that the Earth's rotation moves the array around in UV space in order to try to get cleaner images, but it still has to be post-processed. [Math behind a uv plot in interferometry?](https://astronomy.stackexchange.com/q/26413/7982)
Answer: Aside from trying to phase-sync optical scopes across such large distances, the problem is one of spatial frequency filtering.  If you look thru any decent book on optics (I highly recommend Smith's Engineering Optics), you'll see that, due to the "magic" of Fourier Transforms,  a small lens (or primary mirror) handles low spatial frequencies well but not high spatial frequencies.  A large lens will handle higher and higher spatial frequencies as well.   But if you use a "doughnut" lens, i.e. with large central obscuration, you lose all the lower spatial frequencies.
So if you scatter a bunch of phased-up optical scopes, you will at best only get some of the higher spatial frequencies in your final image.
Comment: @uhoh  I completely agree.  Just sort of warning that you can't  just randomly scatter 'scopes around and expect a "large aperture equivalent" performance.
Comment: Certainly [donuts do not good telescopes make](https://astronomy.stackexchange.com/a/34247/7982), but array telescopes are never donuts with receivers only at the edges. In fact they're the opposite. Look at any arrangement of ALMA or VLA and density is almost always highest in the center. This isn't possible with the EHT but those exposures exploit the rotation of the Earth to allow many receivers to pass through the center of the "aperture".


How to add a display mode to a VirtualBox VM?

Question: I am using my first VirtualBox VM in order to run Windows 8 Preview on my Windows 7 machine.  It looks like only a few resolutions are available for me to choose.  My physical display is 1600x900, so I'd like to be able to set my Windows 8 VM to that in order to have a fullscreen experience.  How do I add a 1600x900 to the choices I have in the "Screen Resolution" dialog?
Comment: Seeing similar issues with the released version of Windows 8 and Ubuntu for host
Comment: Have you by any chance enabled the VirtualBox hardware 3D support ?
Comment: @harrymc yes, everything is enabled for me.
Answer: You can use VBoxManage setextradata "<vm-name>" "CustomVideoMode1" "1600x900x32"
(See the VirtualBox manual for more information).
Comment: I tried this after installing the Guest Additions.  The command seemed to work, but I do not see the video mode available in the Screen Resolution dialog.
Comment: Ditto. See my (deleted) question http://superuser.com/questions/500141/windows8-in-virtualbox-set-resolution-to-1600x900x32
Comment: Worked for me with Windows 10 Technical Preview. Thanks!
Comment: This in conjunction with installing guest additions is the more correct answer as eventually the display mode started working. However it took a few restarts and now it is locked into this exact display mode, it doesn't change with the window size as it did win windows 7. That's a pretty big hassle so I'm still hoping for some insight as far as what is going on.
Answer: This solution worked once for me but now that I have 2 physical monitors it is not working.
You can set the video mode on a running VM by using the following virutalbox command
Windows
"c:\Program Files\Oracle\VirtualBox\VBoxManage.exe" controlvm "YOURVMGUESTNAME" setvideomodehint 1920 1200 32
*nix
VBoxManage controlvm "YOURVMGUESTNAME" setvideomodehint 1920 1200 32
This setting will take effect immediately and sometimes survive reboot.
Answer: Sounds like all you need to do is install the "Guest Additions" inside your guest OS (which would be Windows 8). It's pretty easy since it's Windows. Just press your host key (probably the right CTRL key) and D. This will mount the Guest Additions .iso as if inserting a CD into a real drive and run the guest additions installer while you're in Windows 8. When done, just reboot the guest (Windows 8) and you should be able to resize to whatever resolution you want. And to go full screen, press the host key (again, probably the right CTRL key) and F to toggle between full screen and a normal window.
There are other ways to do this but that would probably be the easiest. Hope it helps.
Comment: This seemed like a good answer, but I followed your steps and it seems like the Windows 8 display resizes to whatever size window I have. However, the screen blacks out when I go to full-screen and various parts of it flicker on and off when I try to interact. Very unusable. Have you seen this before?   I'm using VirtualBox 4.1.18r78361=.
Comment: I tried this with 4.2 and latest guest extensions (loaded in both host and guest) and resizing works great.
Comment: I'm running the latest of everything (Windows 8 RC on top of Windows 7). Guest additions don't help. I tried reinstalling it, reinstalling VirtualBox, and reinstalling the guest OS. Autoresize doesn't work except occasionally when it feels like. It only picks 4:3 aspect ratios, apparently. Dual monitors aren't detected at all. I don't think they have the kinks worked out for Windows 8. I'll stick with VMware Player until then.


upsampling vs class weights in mini-batch SGD

Question: Let's consider using mini-batch SGD in (neural network) binary classification problem with imbalanced dataset. Let's say that the ratio between the number of examples in each class is positive:negative=1:99. Let's say I want to balance the dataset. Then, there are two options: upsample the minority class OR add weights to the loss function. I often hear that both are equivalent. However, I think using class weights make the minimum search more stochastic and probably leads to less stable results.
Consider a mini-batch SGD update:

where L is the loss function,  is the learning rate,  are current model parameters, X are our mini-batch samples.
Now we take the weights that are inverse proportional to the number of examples, s.t. the sum of weights equals the number of classes. This gives w_0=0.02 for the negative class and w_1=1.98 for the positive class.
Now the mini-batch SGD update becomes:

where  is the loss computed for positive-class examples and  is the loss computed for negative-class examples in the minibatch.
So, the effective learning rate for classes changes proportional to class weights. In particular, the learning rate for the majority class sees a 50x drop!
Now let's say we train in mini-batches of N_batch = 16. If we create our minibatches by randomly taking samples from the dataset, most of the minibatches will consist of negative examples only. As a result, the change in model parameters due to such a minibatch will be extremely low as the learning rate is leveraged by the too small class weight. With such a low learning rate there is a risk to get stuck in a local minimum of . despite training in batches.
However, in minibatches where there is at least one positive example the loss function will be dominated by the contribution of the positive examples due to large w_1. This can kick us out of the local minimum trap and move closer to the minimum of loss function for positive examples .
What happens when we do upsampling instead of placing class weights?
The number of positive examples gets equal to the number of negative examples, no need to impose class weights, the learning rate is adequate for both classes and in each minibatch there are as many positive examples as negative. At each SGD update both positive and negative examples are considered and we gradually move towards the true minimum of  instead of sporadically exploring the parameter search space by jumping between the minima of  and .
So, it seems upsampling should lead to faster convergence and less variation in final results than using class weights. Please share your thoughts.
Answer: Did you hear about class scaling and WeightedRandomSampler.
I think if your data set is 1:10 class imbalance, it is fine to use class weight or upsampling. 1:99 is not class imbalance problem, it is kind of outlier detection.
In term of model convergernce, I agree with your idea, but it really depends the data, the model.


Proprietary graphics completely broken on MacBook Pro 7,1

Question: I just installed Xenial, and I attempted to install the proprietary NVidia drivers. However, when I rebooted, the system went to a black screen (not even the backlight was on) and I had to reinstall. This happens with all three of the available choices of drivers (304, 304 updates, 340).
I'm using a MacBook Pro 7,1 with a GeForce 320m inside. The Nouveau drivers eventually crash the machine after about six hours of uptime and aren't good while they're running anyway.
Thanks!
Answer: Thank you Mr. IRC Man.
I installed Bumblebee, and it now works except for the brightness control (for some reason nvidia-xconfig wasn't installed).


Is the auto insurance quote I have been provided a rip off?

Question: I just moved to Philadelphia, PA from Houston, TX and wanted to update my auto insurance policy (with Allstate). I gave them a call, and with 1:1 coverage options AND a newly-acquired (ie I did not have this in Houston) multi-policy discount, they told me my monthly premium would go from ~$190 to ~$415. This seems outrageous to me. A quick google search informs me that the average car insurance in Philly is ~$870/year and my new policy is all of a sudden more than 5 times the average? Granted, I am 24 y/o, (I know this increases my insurance rate), and have pretty comprehensive coverage but still... 5.5 times more expensive? Are they ripping me off? What's going on here?
Part 2 of this question. In case this is reasonable given my situation... is it  a bad idea to reconfigure my coverage options to get a lower premium? As a general concept, is that a good idea?
Comment: I'm not sure this is best answered on Money.SE. The best way to know if that quote is a "rip off" is to get competitive quotes for the same coverage from other insurers. An independent insurance agent can help you do that, or you can get the quotes yourself. In terms of changing your options to get a lower premium - that's really a personal decision for you, based on your own risk tolerance.
Comment: You mention a multi-policy discount; are you sure the $415 is for *just* this one auto policy, or could it possibly be the combined total of the multiple policies?
Comment: Assuming the new premium _isn't_ for multiple cars (as yoozer hypothesises)... to get some idea of whether a 5.5-times multiplier is "expected", how does your $190/month compare with "average car insurance" in Houston? Alternatively, try and narrow the averages you're seeking to 24-year-olds.
Comment: First, you should also ask the quote after no-claim discount (NCD) . Get the policy itemised the coverage. Since Philadelphia auto theft is way lower than Houston, maybe there are many unnecessary loading inside the quotes. E.g. floods, mirror damage, tyres theft, etc. Some auto-insurer may insist one to install those anti-theft, theft tracking system.
Answer: Auto insurance prices vary heavily between regions/states of the US, as the laws and regulations not only differ but so do the rate of claims and losses, nature of competition in each market, etc.
The only way to define a good rate or a bad rate is to get competing quotes from other companies. With the internet this has become much easier and less time consuming than it used to be. You can go online and check out Progressive, Esurance (owned by Allstate), GEICO, American Family, etc, and see what they are offering.
You may also want to request additional quotes for different coverage amounts, as just because high coverage costs the least with one company does not mean low coverage would also cost the least with that same company.
As a rule of thumb, if you get comparable rates from 3 different independent/competing insurance companies, then no matter what the rate is that is effectively the baseline you may have to pay. You can also hunt around with more companies and hope to get less, and sometimes you can get lucky - sometimes not.
From working for an insurance company for a little while, I learned that internally the rate models that are used have become sufficiently complicated that for most companies even their own reps have limited ability to explain why the rate is what it is, and an answer for "why" between markets tends to only be understood to their actuaries/analysts and is not something they can or will attempt to explain to a customer. The rate is what it is. The companies can often provide some cost breakdown, and will generally tell you if there are special costs determined by governing agencies - but the bulk of the cost is the special sauce of that company, based heavily upon observed and/or predicted losses from the last X number of years.
The models and costs are provided to government insurance regulators for approval in most (all?) states, so they generally must be determined to be within some range of "reasonable" or at least "technically legal" - but in the US insurance companies are allowed wide discretion in the range of prices they charge.
Still, this is cold comfort when you get quoted a high price, especially one much higher than you had in a previous state (been there!). The only meaningful option I'm aware of is to just request quotes from competing companies and try alternate quotes with different potential coverage options and see what options you have. Then go with whatever the best option available is - which may or may not be awful, but when you are legally required to carry insurance, your options can be more limited than any of us would like.


Which one is the regression line of x on y?

Question: I have the two regression lines $6x+y=30$ and $3x+2y=25$. How do I identify which one is which? It is given that the first one is the regression line of x on y. How is that? Any ideas?
Comment: See https://stats.stackexchange.com/questions/22718/.  It implies that when you plot both lines on x,y axes, the one with steeper slope will be for the regression of x as a function of y, so just draw a picture.
Comment: Context, please. It is unclear what you're asking.
Comment: @Dave this is simple linear regression
Comment: Okay...so the first one is the regression equation for some data set. What is the other equation?
Comment: @Dave okay so for the same dataset, we can have two regression lines. One which will minimise the squared distances of the points along the x axis and another which will minimise the squared distances of the points along the y axis
Answer: Take any one of the lines to be the regression line of $x$ on $y$. Find the regression coefficient of $y$ on $x$ and of $x$ and $y$ from the given lines. Call them $b_{yx}$ and $b_{xy}$ respectively. Then we know that $b_{yx}\cdot b_{xy}=r^2$. If this is less than or equal to $1$, your choice was correct; otherwise not.


How do I assign a role to a user after the user's email is confirmed?

Question: I want to assign a role to a user after the user confirms his/her email.
How do I do this?
Comment: Please mention your Drupal version (6 or 7 ?)
Answer: You'll want to take a look at Rules and LoginToboggan (as per this answer on Drupal Answers).
Rules will allow you to add a "trigger", such as adding a role to a user, and LoginToboggan will provide the "trigger" for when the account is validated.
Answer: You can use hook_user_login(&$edit, $account) which is called from user_login_finalize().
When $edit parameter is empty is because is called from user_pass_reset() menu callback:
// user_login_finalize() also updates the login timestamp of the
// user, which invalidates further use of the one-time login link.
user_login_finalize();

This example should work:
function MYMODULE_user_login(&$edit, $account) {
  if (empty($edit)) {
    // @todo Add role to $account->roles array
  }
}


IP address in SubjectAltName

Question: Is it allowed to specify IP as DNS name for SAN certificate ?
Answer:
Is it allowed to specify IP as DNS name for SAN certificate ?

According to RFC 5280 dNSName is a IA5String which means in theory you could put the string of an IPv4 or IPv6 address as string inside it. And sometimes it is also necessary even though the proper type for IP addresses in SAN is iPAddress since:

MSIE and MS Edge tend to ignore iPAddress and expect the value as string in dNSName. Same does Python 2.
but Chrome, Safari, Firefox don't expect an IP address as dNSName but need it as iPAddress. Same does Python 3.

Thus the best compatibility can actually be reached by giving the IP address both as iPAddress and dNSName.
Answer:
Is it allowed to specify IP as DNS name for SAN certificate ?

First of all, you should realize that there is a specific iPAddress alternative name format, designed to hold dotted quads (IPv4) or 16 octets (IPv6).  If you wish to slap an IP address onto your certificate, that's probably the right way to do it.  See RFC 5280 section 126.96.36.199. Browser/client compatibility will vary.
Secondly, yes, it is legal to specify a dotted quad in a dNSName field of the SAN.  To quote RFC 5280,

The name MUST be in the "preferred name syntax", as specified by
Section 3.5 of RFC1034 and as modified by Section 2.1 of
RFC1123

The latter suggests that software should be tolerant of finding IP addresses in "host name" fields:

Whenever a user inputs the identity of an Internet host, it SHOULD be
possible to enter either (1) a host domain name or (2) an IP address
in dotted-decimal ("#.#.#.#") form.  The host SHOULD check the string
syntactically for a dotted-decimal number before looking it up in the
Domain Name System.

Again, these are just RFCs, so your mileage will vary by client.
Please note also that, per RFC 5280:

Because the subject alternative name is considered to be definitively
bound to the public key, all parts of the subject alternative name
MUST be verified by the CA.

So if you submit a request to a public CA with, for example, a private RFC 1918 IP address (10.1.2.3), they should decline to sign that request.  And as for CAs validating ownership of an IP address - when the "ownership" of an IP address usually differs from the allocated user - things could get interesting.
Comment: Just to make sure I understood: according to the document, iPAddresses should be in "network byte order", which, apparently, is always big-endian:

https://www.ibm.com/docs/en/zos/2.4.0?topic=hosts-network-byte-order

So, in other words, for say 10.10.0.1, we should specify, 126.96.36.199 as a Subject Alt Name?
Answer: Yes technically it can go in the Subject Alternative Name (SAN) along with any domain names. The systems in which you use the certificate may or may not correctly make use of the information (application dependent).
Therefore yes it's legal to do what you want, but it may not work.
Comment: How validation goes for example I want ip of my vps to be in SAN ?
Comment: If you create a X509 certificate with the IP of your VPS in the SAN then that should work. My point was sometimes it may not, for example your VPS might not understand it and/or your browser. This will be application specific.
Comment: @user3448600 - I hope the above was helpful. Let me know if you have any other questions
Answer: Yes it can be used that way, but it generally only make sense for private Private Key Infrastructure. In that case, you can have a private server that will be used directly with its IP address, so it makes sense to use it in the SAN field.
But AFAIK is is seldom used (if used at all) for public PKI and public servers.

IP address in SubjectAltName


How to report a user who edits questions and answers that are not required?

Question: How to report user who are editing question and answer unrelated? I found many users that edit answers with too minor and invalidating edits. I want to know how can I report these users.
Answer: Flag one of the editor's posts for moderation attention once, and clearly explain what's going on. The moderators will take it from there.
Comment: But how to Knw SO take action for it flag..?
Comment: I just did that today. Thought it would be best to let a moderator know about what a user is doing. Just adding few extra spaces and done. That's an edit for me to review. :-(


log configuration for existing application

Question: I have to disable the log for the application that is at my hands now.
Application is composed of its own source and number of other components imported by means of jars,
It uses hibernate, and when hibernate functionality executes, it prints everything to the console.
Now, I think Log4J is in use there somehow, but only through commons-logging, that comes with hibernate distribution.  I see no log4j.properties file anywhere.  And there is no xml coniguration for hibernate that has loging settings.
How can I disable the log output going to console, but keeping that going into file.
I got this application to update it's build system, so technically I didn't introduce anything source code works with,- no new properties, no new setting.  Just updated some build.xml and other xml files which are part of build process.  I am told, that it wasn't directing output to the screen before.  Could it be that I included some library that is not needed and that is causing this to happen?
Thanks fo t
Answer: Some libraries ship with their own log4j configuration, and that will clash with other libraries. This is specially true in AppServers environments. The only way I have found to override this behavior is to (re)configure log4j in my application.