Q:

ggplot2: Boxplots with points and fill separation

I have a data which can be divaded via two seperators. One is year and second is a field characteristics.
box<-as.data.frame(1:36)

box$year <- c(1996,1996,1996,1996,1996,1996,1996,1996,1996,
              1997,1997,1997,1997,1997,1997,1997,1997,1997,
              1996,1996,1996,1996,1996,1996,1996,1996,1996,
              1997,1997,1997,1997,1997,1997,1997,1997,1997)
box$year <- as.character(box$year)

box$case <- c(6.40,6.75,6.11,6.33,5.50,5.40,5.83,4.57,5.80,
              6.00,6.11,6.40,7.00,NA,5.44,6.00,  NA,6.00,
              6.00,6.20,6.40,6.64,6.33,6.60,7.14,6.89,7.10,
              6.73,6.27,6.64,6.41,6.42,6.17,6.05,5.89,5.82)

box$code <- c("L","L","L","L","L","L","L","L","L","L","L","L",
              "L","L","L","L","L","L","M","M","M","M","M","M",
              "M","M","M","M","M","M","M","M","M","M","M","M")

colour <- factor(box$code, labels = c("#F8766D", "#00BFC4"))

In boxplots, I want to display points over them, to see how data is distributed. That is easily done with one single boxplot for every year:
ggplot(box, aes(x = year, y = case, fill = "#F8766D")) +
  geom_boxplot(alpha = 0.80) +
  geom_point(colour = colour, size = 5) +
  theme(text = element_text(size = 18),
        axis.title.x = element_blank(),
        axis.title.y = element_blank(),
        panel.grid.minor.x = element_blank(),
        panel.grid.major.x = element_blank(),
        legend.position = "none")

But it become more complicated as I add fill parameter in them:
ggplot(box, aes(x = year, y = case, fill = code)) +
  geom_boxplot(alpha = 0.80) +
  geom_point(colour = colour, size = 5) +
  theme(text = element_text(size = 18),
        axis.title.x = element_blank(),
        axis.title.y = element_blank(),
        panel.grid.minor.x = element_blank(),
        panel.grid.major.x = element_blank(),
        legend.position = "none")

And now the question: How to move these points to boxplot axes, where they belong? As blue points to blue boxplot and red to red one.

A:

Like Henrik said, use position_jitterdodge() and shape = 21.  You can clean up your code a bit too:

No need to define box, then fill it piece by piece
You can let ggplot hash out the colors if you wish and skip constructing the colors factor. If you want to change the defaults, look into scale_fill_manual and scale_color_manual.
box <- data.frame(year = c(1996,1996,1996,1996,1996,1996,1996,1996,1996,
                  1997,1997,1997,1997,1997,1997,1997,1997,1997,
                  1996,1996,1996,1996,1996,1996,1996,1996,1996,
                  1997,1997,1997,1997,1997,1997,1997,1997,1997),
                  case  = c(6.40,6.75,6.11,6.33,5.50,5.40,5.83,4.57,5.80,
                  6.00,6.11,6.40,7.00,NA,5.44,6.00,  NA,6.00,
                  6.00,6.20,6.40,6.64,6.33,6.60,7.14,6.89,7.10,
                  6.73,6.27,6.64,6.41,6.42,6.17,6.05,5.89,5.82),
                  code = c("L","L","L","L","L","L","L","L","L","L","L","L",
                  "L","L","L","L","L","L","M","M","M","M","M","M",
                  "M","M","M","M","M","M","M","M","M","M","M","M"))

ggplot(box, aes(x = factor(year), y = case, fill = code)) +
  geom_boxplot(alpha = 0.80) +
  geom_point(aes(fill = code), size = 5, shape = 21, position = position_jitterdodge()) +
  theme(text = element_text(size = 18),
        axis.title.x = element_blank(),
        axis.title.y = element_blank(),
        panel.grid.minor.x = element_blank(),
        panel.grid.major.x = element_blank(),
        legend.position = "none")

A:

I see you've already accepted @JakeKaupp's nice answer, but I thought I would throw in a different option, using geom_dotplot. The data you are visualizing is rather small, so why not forego the boxplot?
ggplot(box, aes(x = factor(year), y = case, fill = code))+
    geom_dotplot(binaxis = 'y', stackdir = 'center',
                 position = position_dodge())


Q:

How do I use the "Barbara, Celarent, … etc." mnemonic?

Medieval logicians memorized this most famous logic mnemonic:
Barbara, Celarent, Darii, Ferio ← direct first figure
Baralipton, Celantes, Dabitis, Fapesmo, Frisesomorum ← indirect first figure
Cesare, Camestres, Festino, Baroco ← second figure
Darapti, Felapton, Disamis, Datisi, Bocardo, Ferison ← third figure
The 3 vowels of each name tell what the major, minor, and conclusion are; each vowel corresponds to one of 4 possibilities from the square of opposition:

So Barbara is an AAA syllogism, e.g.:

Every man is an animal.
Every animal is a creature.
∴ Every man is a creature.

There is more to the mnemonic than this. Apparently the consonants in the names allow one to reduce the corresponding syllogism to that of a simpler figure.
Are there any references that overview how to fully use all that is packed into this very elaborate, well-thought-out mnemonic?

A:

A good introduction is the second volume of Gabbay & Woods (2008), Handbook of the History of Logic, where you'll find the mnemonics explained on pp 331ff. The mnemonics themselves seems to have originated in 13th century textbooks. For the original, see: de Rijk (1967), Logica Modernorum, vol 2, pp 362ff. I would also recommend Kretzmann, Kenny & Pinborg's Cambridge History of Later Medieval Philosophy: Together with Gabbay this will give you a couple of hundred pages on the development of mediaeval logic, but it will also show you that it was rather more sophisticated than just an mnemonic which you could apply blindly. For even more detail see: Parry & Hacker (1991), Aristotelian Logic, which seems to give a very comprehensive exposition  (I have only skimmed this, though).
Unlike @jobermark, I find classical logic an endlessly fascinating topic (I am in no way an expert, though). The value in studying it? Partly seeing the development of an extremly sophisticated system over hundreds of years, partly experiencing the strain between the formal system and that which it is trying to formalize. I would not, however, recommend it as an alternative to modern logic; much less as a guide on how to think. For a very readable comparison with modern logic, see Jan Lukasiewicz (1957), Aristotle's Syllogistic from the Standpoint of Modern Formal Logic. And while you will often find a very polemical stance in 19th and 20th century philosophy, Karl Menger, »The New Logic« (in Sarkar (1996): Logical Empirism at its Peak) presents a rather nuanced motivation for modern logic.

A:

Explanation of the Mnemonic
Brody, Boruch A. "Logical Terms, Glossary of." Encyclopedia of Philosophy. Ed. Donald M. Borchert. 2nd ed. Vol. 5. Detroit: Macmillan Reference USA, 2006. 533-560. Gale Virtual Reference Library. Web. 19 May 2016.:

mnemonic terms
The names that the medieval logicians introduced for the valid syllogisms. One such term is "Barbara." The key for these mnemonics is as follows: The three vowels respectively indicate the three constituent propositions of the syllogism as A, E, I, or O. For first-figure syllogisms the initial consonants are arbitrarily the first four consonants; for the other figures the initial consonants indicate to which of the first-figure syllogisms the syllogism in question may be reduced. Other consonants occurring in second-, third-, and fourth-figure mnemonics indicate the operation that must be performed on the proposition indicated by the preceding vowel in order to reduce the syllogism to a first-figure syllogism. The key for this is as follows: "s" indicates simple conversion, "p" indicates conversion per accidens, "m" indicates metathesis (interchanging of the premises), "k" indicates obversion, and "c" indicates convertio syllogism (that is, the syllogism is to be reduced indirectly). In mnemonic terms the only meaningless letters are "r," "t," "l," "n," and noninitial "b" and "d." More elaborate mnemonics have been devised for syllogisms in which two or more of the premises exhibit modality. See entry "Logic, Traditional."
Mnemonic Terms
Name        Figure      Major   Minor   Conclusion
                        premise premise
Barbara     first       A       A       A
Baroco      second      A       O       O
Bocardo     third       O       A       O
Bramantip   fourth      A       A       I
Camenes     fourth      A       E       E
Camestres   second      A       E       E
Celarent    first       E       A       E
Cesare      second      E       A       E
Darapti     third       A       A       I
Darii       first       A       I       I
Datisi      third       A       I       I
Dimaris     fourth      I       A       I
Disamis     third       I       A       I
Felapton    third       E       A       O
Ferio       first       E       I       O
Ferison     third       E       I       O
Fesapo      fourth      E       A       O
Festino     second      E       I       O
Fresison    fourth      E       I       O

Reduction
So, what are the different types of reduction mentioned above?

simple conversion
conversion per accidens
metathesis (interchanging the premises)
obversion
convertio syllogism (indirect conversion)

reduction of syllogisms
The process whereby syllogisms in imperfect figures are expressed in the first figure. Reduction is direct when the original conclusion follows from premises in the first figure derived by conversion, obversion, etc., from premises in an imperfect figure. Reduction is indirect when a new syllogism is formed which establishes the validity of the original conclusion by showing the illegitimacy of its contradictory. See entry "Logic, Traditional."

conversion
In traditional logic, a type of immediate inference in which from a given proposition another proposition is inferred that has as its subject the predicate of the original proposition and as its predicate the subject of the original proposition (the quality of the proposition being retained). The process of conversion yields an equivalent proposition only when the original proposition is an E- or I-proposition; when it is an A-proposition traditional logicians allowed for conversion per accidens (or by limitation)—that is, conversion plus a change in the quantity of the proposition from universal to particular. Thus, the E-proposition "No men are immortal" yields "No immortals are men," but the A-proposition "All men are mortal" can be converted only by limitation, yielding "Some mortals are men." The process of conversion yields no equivalent proposition if the original proposition is an O-proposition. See entry "Logic, Traditional."

obversion
In traditional logic, a type of immediate inference in which from a given proposition another proposition is inferred whose subject is the same as the original subject, whose predicate is the contradictory of the original predicate, and whose quality is affirmative if the original proposition's quality was negative and vice versa. Obversion of a proposition yields an equivalent proposition when applied to all four types (A, E, I, and O) of propositions that traditional logicians considered. See entry "Logic, Traditional."


Q:

How to fix spans wrapping in a button

I have a button with span tags inside. The spans appear to take up the full width of the button, and every span is on a new line. How can I fix this so that the spans are all part of the same line?
What I want

What I get

Code (attributes not shown):
<button>
    [
    1/8
    1/8
    ]
    [
    1/4
    ]
    [
    1/8
    1/8
    ]
    [
    1/4
    ]
</button>

A:

Try using display: flex;
You can study more about display: flex here
Note: Add the style to the container element


Q:

Ionic slider with different image size or heights

I'm using ion-slide-box, but the issue is, my ion-slides image is not in the same size, its dynamically repeated different size image using ng-repeat

                    <ion-slide ng-repeat="sliderimages in sliderimages">
                        <img src={{sliderimages.url}} style="width:100%;height:auto;"/>
                    </ion-slide>
                </ion-slide-box>

I used this CSS to fit image height to all
.slider {
  height: 200px;
  width:100%;
}
.slider-slide {
  color: #000;
  background-color: #fff;
  height: 100%;
  width:100%;
}

but the height is not so fit

I have to add any size of images and that to be fit in the Ionic slider.

A:

max-width: 100vw !important;
max-height: 100vh !important;

this worked for me ;-)


Q:

-gc-sections discards used data

Using avr-gcc, avr-ld
I'm attempting to severely reduce the size of the output file by using fdata-sections -ffunction-sections and gc-sections. When compiled without these options I have an output of ~63KB, and with these options its ~30KB, so it seems great.
Unfortunately, after loading and testing the output I notice it doesn't work correctly. Garbage collection seems to have removed far more than I expected, and examining the .map I notice some key data is nonexistent.
Any idea on what at link time is causing these data/functions to be discarded? (I realize this may be too hopeful of a question with how little detail I provided, if any information is needed please ask and I'd do my best to provide it)
Is there a way to trace what symbols were tossed by garbage collection as they were "unused"?
Without using -fdata-sections -ffunction-sections -gc-sections, can I trace a symbol dependencies? (To verify gc-sections only collected what it should)
    - I noticed this this as an option, but it would be very painful for me to use the method suggested by Verax
EDIT: compiler and linker lines
avr-ld -mavrxmega6 -gc-sections -Tlinkerscript files libgcc.a -o firmware.elf
avr-gcc -Wall -Wstrict-prototypes -g -ffunction-sections -fdata-sections -Os -mmcu=atxmega256a3 -fno-jump-tables -std=gnu99 -fpack-struct -fno-common -mcall-prologues -c -o file.o file.c

A:

There was a pretty obvious ld option called -print-gc-sections to review what is being tossed out.
I never found a way to trace dependencies on a symbol, but ended up not needing to with reviewing -print-gc-sections.
I found this that described "magic sections" and I imagine this is similar to what I was seeing. There were many custom linker sections that were discared incorrectly, I used KEEP to prevent gc of these although I'm sure there is dead code not being removed now, but this may be the best I can do.


Q:

Pass arguments to a thread while resuming it. (WINAPI)

I have a thread(Thread 1) which suspends another thread(Thread 2). After sometime, Thread1 resumes Thread2, but I want to pass a structure from Thread 1 to Thread 2 when Thread 1 resumes Thread 2.
How can I do it?

A:

Make a message-driven thread. Design thread 2 so that it consists of a message loop using the GetMessage API. When it calls GetMessage it will suspend itself until a message arrives.
Then you can use PostThreadMessage to thread 2 and accomplish both goals. The message can carry a pointer to data to be processed, and receiving the message will unsuspend the thread. (I.e., the GetMessage call will return.)
After it processes the passed data it should then loop around to await the next message.


Q:

What does apt-get install do under the hood?

What does the apt-get install ... command do?
When I enter apt-get install ... command, there are some texts appearing on the screen, but that does not have enough information for me. I want to know if any file is created / edited, any service is started and other activities...
Is there any .sh file executed when the apt-get install ... run? If so, how can I see the content of that sh file?
The reason for this question is recently I tried to install tomcat7 with apt-get install tomcat7. Everything works fine until I install tomcat7-admin (manager web application), the server became unresponsive to any request. I tried this many times, and this always happen.

A:

Mostly, apt-get does the following things:

checks for dependencies (and asks to install them),
downloads the package, verifies it and then tells dpkg to install it.

dpkg will:

extract the package and copy the content to the right location, and check for pre-existing files and modifications on them,
run package maintainer scripts: preinst, postinst, (and prerm, postrm before these, if a package is being upgraded)
execute some actions based on triggers

You might be interested in the maintainer scripts, which are usually located at /var/lib/dpkg/info/<package-name>.{pre,post}{rm,inst}. These are usually shell scripts, but there's no hard rule. For example:
$ ls /var/lib/dpkg/info/xml-core.{pre,post}{rm,inst}
/var/lib/dpkg/info/xml-core.postinst
/var/lib/dpkg/info/xml-core.postrm
/var/lib/dpkg/info/xml-core.preinst
/var/lib/dpkg/info/xml-core.prerm

A:

In short: apt-get install does everything that is needed that your system can successfully execute the new installed software application.
Longer:
Preliminaries:
From the manpage:

All packages required by the package(s) specified for installation
  will also be retrieved and installed.

Those packages are stored on a repository in the network. So, apt-get downloads all the needed ones into a temporary directory (/var/cache/apt/archives/). They will be downloaded from a web- or a ftp-server. They are specified in the so called sources.list; a list of repositories. From then on they get installed one by one procedurally.
The first ones are the ones, that have no further dependencies; so no other package has to be installed for them. Through that, other packages (that had dependencies previously) have now no dependencies anymore. The system keeps doing that process over and over until the specified packages are installed.
Each package undergoes an installation procedure.
Package installation:
In Debian-based Linux distributions, as Ubuntu, those packages are in a specified standardized format called: deb - The Debian binary package format.
Such a package contains the files to be installed on the system. Also they contain a control file. That file contains scripts that the packaging system should execute in a specific situation; the so called maintainer scripts. Those scripts are split in:

preinst: before the installation of the files into the systems filehierarchy
postinst: after the installation
prerm: before the uninstallation
postrm: after the uninstallation

There is an interesting picture, showing the procedure of an installation of a new package:

There are also more control-files, the most important are as follows:

control: A list of the dependencies, and other useful information to identify the package
conffiles: A list of config files (usually those in /etc)
debian-binary: contains the deb-package version, currently 2.0
md5sums: A list of md5sums of each file in the package for verifying
templates: A file with error descriptions and dialogs during installation

A:

For the actual under-the-hood  stuff, you'll need to grab the Apt source. Fairly simple if you have source repositories enabled:
apt-get source apt

The apt-get command itself lives in cmdline/apt-get.cc. It's a pain to read through but most of apt-get's actions are spelled out quite extensively in there. Installation however, is mapped through a DoInstall function which lives in apt-private/private-install.{cc,h}.
You have to remember that apt-get is merely one side of the coin.
dpkg is handling the actual installation but DoInstall doesn't know about dpkg directly. apt-get is actually surprisingly package-manager agnostic. All the functionality is abstracted through apt-pkg/package-manager.cc
I'm only looking briefly but even there I can't see where this actually attaches to the dpkg systems. Some of this seems to be autoconfigured through apt-pkg/aptconfiguration.cc but this is a deep well. You could spend days unravelling this.
The source documentation is good though. You could do worse things than to go through each file and read the header to work out what's actually happening.


Q:

Convert String to Date in java - Time zone

I have a String, 2013-10-07T23:59:51.205-07:00, want to convert this to Java date object. I am getting parsing error.
date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").parse("2013-10-07T23:59:51.205-07:00");

A:

try
date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")
                 .parse("2013-10-07T23:59:51.205-0700");

The Z is not a literal and the timezone does not have a colon
See the examples at http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html
If java7 is being used then Z can be replaced with X and the timezone can have a colon

A:

Z shouldn't be inside quotes. I don't think Z would work for your given timezone. Before Java 7, I guess there wasn't any format to parse ISO 8601 format timezone with colon in between. You should use -0700 instead.
However, from Java 7 onwards, you have an option for parsing ISO 8601 format timezone using X instead of Z. See javadoc for SimpleDateFormat. Just use the following format:
// This would work from Java 7 onwards
date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX")
                     .parse("2013-10-07T23:59:51.205-07:00");

A:

Your pattern is wrong, you should use the following:
date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX")
                        .parse("2013-10-07T23:59:51.205-07:00");

The 'X' indicates the Time zone in the ISO 8601 format as expressed in your String here: '.205-07:00'
For more information read the doc: SimpleDateFormat


Q:

Support for Chat feature in Stack Overflow

I was feeling the need of a chat enabled service for discussions on Stack Overflow.
Don't you think, it should be implemented?

A:

It is being worked on. See here.
Please read the FAQ for more details: http://chat.meta.stackoverflow.com/faq


Q:

How can I get rid from the error in Visual Studio?

How can I get rid from the error in Visual Studio? I am  very new to C++ and Visual Studio and I can not get what is wrong with my program. What I am trying to do is just to compile it.
Here it is:

A:

What I am trying to do is just to compile it.

In order to compile a single source file in Visual Studio, you can use the "Compile" item in the "Build" menu. The shortcut is CTRL+F7.


Q:

focusout() and trigger.('focusout') not causing input to lose focus

I'm using the jQuery UI modal dialog, and populating it with some form fields.  Because of this bug: http://bugs.jqueryui.com/ticket/4731, the first input gains focus when the dialog opens.  To get around that, I'm trying to blur the affected input when the dialog is opened.
The problem is that there exists other functionality which is called for this input on a .blur(), and I don't want to fire that functionality for this.
So, I'm trying to use .focusout()and .trigger('focusout') to achieve the same effect, but with no results.
Doing either of these:
$('#input-id').focusout();
$('#input-id').trigger('focusout');

does not actually cause the input to lose focus, where using .blur() is successful.  Am I missing something, or is there another way to accomplish what I need?

A:

If you fancy a quick javascript hack you could use:
$(':focus').blur();

A:

My suggestion would be to set the focus to some other element in the dialog when it is opened instead of setting textbox to blur. This should overcome your problem.
Hope this Helps!!

A:

Focusout does not cause the element to lose focus. Instead focusout is triggered when an element loses focus. Check out http://api.jquery.com/focusout/


Q:

Programmatically get html of top.links in magento

I am trying to get the html of top.links using following ways
$blockHtml = Mage::getModel('cms/block')->getBlockHtml('top.links')
$blockHtml = Mage::app()->getLayout()->getBlock('top.links').toHtml()
$blockHtml = Mage::getSingleton('core/layout')->getBlock('top.links')->toHtml()
none of above is working for me, please guide how I can do this, thanks
UPDATE
I used
$layout = Mage::getSingleton('core/layout');
$block = $layout->createBlock('page/html')->setTemplate('page/html/top.links.phtml')->toHtml();

with the help of this question Add Top Links on condition basis in magento but still no luck. during this try I found that use of top.links.phtml is deprecated, any idea which template should I use for the links?
I think there is some dependency for top.links.phtml file, that's why it isn't working, when I tried to get footer.phtml it worked perfectly with above method.

A:

Wow! I was able to find a correct answer finally :) Load block outside Magento, and apply current template
So by following the the above question's answer, I did this to get generated top.links
    $layout = Mage::app()->getLayout();
    $layout->getUpdate()
            ->addHandle('default')
            ->load();

    $layout->generateXml()
            ->generateBlocks();

    echo $layout->getBlock('top.links')->toHtml();


Q:

Can Path Connectedness be Defined without Using the Unit Interval?

Can path connectedness be defined without using the unit interval or more generally the real numbers?
I.e., do we need Dedekind cuts or Cauchy convergence equivalence classes of the rational numbers (metric space completion) in order to define any object topologically equivalent to the unit interval?

Compared to the definition of connectedness, which only uses open and closed sets, having to use the unit interval to define path connectedness seems somewhat like using a sledgehammer.
I suspect that the answer might be no, since for every Hausdorff path connected space, the paths are homeomorphic to the unit interval (at least according to the relevant Wikipedia article). In particular, every locally path-connected Hausdorff space has a bunch of 1-manifolds as subsets.
Still it is unclear to me, since it seems like it should be able to specify all of the unit interval's topological properties without having to recourse to its analytic definition.
Your thoughts or help would both be greatly appreciated.
EDIT: this question probably has something to do with homotopy theory: https://en.wikipedia.org/wiki/Homotopy, with which I am rudimentarily familiar at best.

A:

There are really two separate questions here: can you define the unit interval space without talking about real numbers, and can you define path-connectedness without talking about the unit interval space?  The answer to both is yes; let me address the second question first.
Let $P$ be a topological space and let $a,b\in P$ be two points.  Say that a space $X$ is $(P,a,b)$-connected if for any $x,y\in X$, there is a continuous map $f:P\to X$ such that $f(a)=x$ and $f(b)=y$.  Of course, for $(P,a,b)=([0,1],0,1)$, this is just the usual definition of path-connectedness.
However, there is a more "universal" characterization of path-connectedness that doesn't require you to know about the space $[0,1]$.  Namely, a space $X$ is path-connected iff it is $(P,a,b)$-connected for all compact Hausdorff spaces $P$ with two distinct points $a,b\in P$.
To prove this, suppose $X$ is path-connected, $P$ is a compact Hausdorff space, $x,y\in X$, and $a,b\in P$ are distinct.  Since $X$ is path-connected, there is a path $g:[0,1]\to X$ such that $g(0)=x$ and $g(1)=y$.  By Urysohn's lemma, there is a continuous map $h:P\to [0,1]$ such that $h(a)=0$ and $h(b)=1$.  The composition $gh:P\to X$ is then continuous and satisfies $g(a)=x$ and $g(b)=y$.
The idea here is that you could use any space $P$ with two chosen points $a$ and $b$ to define a notion of "paths" in a space.  However, if you restrict to compact Hausdorff spaces $P$, then the ordinary interval $[0,1]$ is the "strongest possible kind of path" you can have in a space: if you have a $[0,1]$-path between two points, then you have a $P$-path for every other compact Hausdorff space $P$ as well.
(Of course, all we used about compact Hausdorff is that we know there is a map $P\to [0,1]$ separating $a$ and $b$.  However, I phrased everything in terms of the compact Hausdorff condition since this is a natural condition you can define without already knowing about the space $[0,1]$.)

OK, now let me say a little about the first question.  There are in fact many different ways to uniquely characterize the space $[0,1]$ up to homeomorphism without reference to the reals or anything that is essentially equivalent to constructing the reals.  In fact, you can deduce one from the answer I gave to the second question above.
Namely, say that a compact Hausdorff space $(P,a,b)$ equipped with two distinct points is a universal path if it has the special property of $[0,1]$ noted above: whenever there is a $(P,a,b)$-path between two points $x$ and $y$ of an arbitrary space, there is also a $(Q,c,d)$-path from $x$ to $y$ for any compact Hausdorff space $Q$ with two distinct points.  Say that a universal path $(P,a,b)$ is minimal if for any other universal path $(Q,c,d)$, there is an embedding $P\to Q$ sending $a$ to $c$ and $b$ to $d$.
I now claim that $([0,1],0,1)$ is the unique minimal universal path (up to homeomorphism).  We know it is universal.  To show that it is minimal, let $(Q,c,d)$ be any universal path.  Since the identity map $Q\to Q$ is a $(Q,c,d)$-path from $c$ to $d$ in $Q$, universality implies there is a $([0,1],0,1)$-path from $c$ to $d$ in $Q$.  But if there is a path between two points of a Hausdorff space, there is also a path which is an embedding (see Does path-connected imply simple path-connected?).  Thus there is an embedding $[0,1]\to Q$ sending $0$ to $c$ and $1$ to $d$.
Now suppose $(P,a,b)$ is any minimal universal path.  The previous paragraph shows that there is a $([0,1],0,1)$-path from $a$ to $b$ in $P$.  Now since $([0,1],0,1)$ is a universal path, minimality of $P$ says that $P$ embeds in $[0,1]$ sending $a$ to $0$ and $b$ to $1$.  But since $P$ contains a path from $a$ to $b$, the image of this embedding contains a path from $0$ to $1$, and thus contains all of $[0,1]$.  Thus the embedding is actually a homeomorphism $P\to [0,1]$.
As I mentioned, this is just one of many ways of characterizing $[0,1]$.  For another characterization that also relates closely to the intuitive notion of "paths", see this answer by Tom Leinster on MO.


Q:

list of n zeros in Haskell

This is probably very easy, but I cannot figure out how to do the equivalent of Python's
[0]*n

in Haskell, in order to get a list with n zeros.
[0]*n

doesn't work. Am I obliged to do something like: [0 | x <-[1..5]] ?

A:

You can do this:
λ> take 5 (repeat 0)
[0,0,0,0,0]

Or as @obadz points out, this is even more concise:
λ> replicate 5 0
[0,0,0,0,0]

I personally don't like the python syntax. * means multiplication but it does something else in your case. But that's just my opinion :).


Q:

What are the Disadvantages of Using "Var" inside the DAX Formula

Although the advantage of using "Var" is clear

It helps to keep the formula more readable.
It helps the user to return the output for every step.

What are the disadvantages of using Var declaration inside the Formula.

Does it affect performance ?
Does it affect calculation in any way ?
Any other things to keep in mind ?

A:

I can't think of any disadvantages per se, but there are cases where people misuse them.
The most frequent mistake I see is where people mistake VAR simply as a shortcut for reusing code without understanding that it's a fixed value that is not affected by filter context. For example, in the following the FILTER has no effect on Sum since the variable is fixed.
VAR Sum = SUM( Table[Value] )
CALCULATE( Sum, FILTER( Table, <Condition> ) )

Another thing to keep in mind is if you have a series of large table-valued variables in a measure, your calculation might be less efficient or take more memory than it needs to if it were written differently. But this is highly case-specific and not really a disadvantage of variables so much as a consideration in implementation optimization.


Q:

Showing branch hierarchy at the command line?

I'm curious if there is a way to show branch hierarchy on the command line? For instance if I use git branch, instead of seeing output like this:
* master
joes_work
refactoring
experiment

You see output like this:
* master
    joes_work
    refactoring
        experiment

That way it's easy to see which branch a particular branch.. branched off of. Even if there's no specific command that outputs a tree structure, is there a command that outputs information on which branch came from which branch? I can use a perl script to format the output.

A:

sehe's solution looks great, here is another one that seems to contain similar information, formatted differently, it uses git log, so it contains commit information as well (ignore the branch names, I kind of messed them up!):
git log --all --graph --decorate --oneline --simplify-by-decoration

* ae038ad (HEAD, branch2-1) add content to tmp1
| * f5a0029 (branch2-1-1) Add another
|/
* 3e56666 (branch1) Second wave of commits
| * 6c9af2a (branch1-2) add thing
|/
* bfcf30a (master) commit 1

A:

Try
git show-branch
git show-branch --all

Example output:
bash$ git show-branch --all
! [branchA] commitA only in branchA
 * [branchB] commitB
  ! [branchC] commitC only in branchC
---------------------
+   [branchA] commitA only in branchA
 *  [branchB] commitB
  + [branchC] commitC only in branchC
 *+ [branchC~1] commitB-1 also in branchC
 *+ [branchC~2] commitB-2 also in branchC
+++ [branchC~3] common ancestor
+++ [branchC~4] more common ancestors

A:

I want to complete the answer of @ctcherry.
I like when I can also see the user who did the commit and the date, so this is the following line to use :
git log --all --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit

However this is a pretty long line and difficult to memorize so you can use an alias.
You just have to use this in your terminal :
git config --global alias.lg "HERE GOES MY BIG LOG COMMAND LINE"

To summarize copy and paste the line below on your terminal:
git config --global alias.lg "log --all --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit"

Then you will just have to use git lg to get your log history tree.
Example:

src


Q:

SpriteKit - Selecting Node After Rotation

An SKSpriteNode, named “leaf” is added as a child to another SKSpriteNode, named “allObjects”.
allObjects is set to be the same width and height as the SKView.
I drag the leaf to a location on allObjects and click a distinctive part of its tip and using println get the following in the console.

touchBegan, touch.locationInNode(allObjects): (621.5, 156.75)
touchesEnded, touch.locationInNode: (621.5, 156.75)
touchesEnded, Leaf location: (695.375, 83.25)
touchesEnded, nodeAtPoint(location).name: Optional("leaf")

So far, so good. I can drag the leaf as much as I like at this point with no problem. The important part to note is that the nodeAtPoint is, as expected, ‘leaf’.
However, if I then rotate allObjects, like this:
var rotate = SKAction()
rotate = SKAction.rotateByAngle(0.4, duration: 0)
allObjects.runAction(rotate)

… And then click in the same location on the leaf (visually in IOS Simulator), I get the following in the console. I’m confused as to why I have rotated allObjects and clicked in the same location (and get the same co-ordinates) I am no longer selecting the leaf but missing it by a wide margin (nodeAtPoint shows I am hitting the background).

touchBegan, touch.locationInNode(allObjects): (620.813842773438,
  156.470306396484)
touchesEnded, touch.locationInNode: (620.813842773438, 156.470306396484)
touchesEnded, Leaf location: (695.375, 83.25)
touchesEnded, nodeAtPoint(location).name: Optional("allObjects")

Can anyone help?

A:

The node and coordinates used in the locationInNode and nodeAtPoint need to be consistent. In this case, the point returned by locationInNode is in allObjects coordinates while the nodeAtPoint call (i.e., self.nodeAtPoint) requires a point in scene coordinates. To resolve this, you can either replace
nodeAtPoint(location)

with
allObjects.nodeAtPoint(location)

or replace
let location = touch.locationInNode(allObjects)

with this
let location = touch.locationInNode(self)


Q:

How to get a list from a file in python

I am trying to get the contents of a file in a list. For reference: these are the contents of the file:
1. item1
2. item2
3. item3

I am able to open the files, and when I do file.read(), all I get from the interpreter is an empty string:
>>> file = open("C:\\Users\\vivrd\\Desktop\\testing.txt")
>>> file.read()
''

If I do file.readlines(), it displays a list, but even though the python docs say that file.readlines() returns a list, whenever I try to assign a variable to it (to access the list), all I get is an empty list:
>>> file.readlines()
['1. item1\n', '2. item2\n', '3. item3'] #returns the list
>>> item = file.readlines()
>>> item #but the list is empty!
[]

I have also tried to loop through the file, but it doesn't print out anything:
>>> for line in file:
print(line)

>>>

Also, for some reason, file.readlines() is only working once. I tried it a second time, and the interpreter didn't even display anything:
>>> file.readlines()
[]

My target is to get a list that looks like this: ["1. item1", "2. item2", "3. item3"] or even with the escape sequences (though not preferable): ["1. item1 \n", "2. item2 \n", "3. item3"]
How can I get to this point? Thanks!

A:

It will work only once, because after that, python is done reading the file (here's a question that discusses this in detail). Read it once and store it in a variable:
>>> f = open("C:\\Users\\vivrd\\Desktop\\testing.txt")
>>> items = f.readlines() # items should now be a list of lines in the file
>>> f.close() # make sure to close the file

If you want to re-read, move the 'cursor' back to the beginning of the file (before closing) using seek:
>>> items = f.readlines()
>>> f.seek(0)
>>> more_items = f.readlines()
>>> f.close()


Q:

On loading everything breaks for a sec CSS & HTML

I've just finished my website and I've discovered that when my website loads on mobile it shows me the "display text" format plus the responsive menu flashes(opens) for a sec and then the site fully loads.

CSS file linked in the head
JS files at the bottom
It shows me div's set to display: none; in CSS  on mobile for sec

I've tried to capture a screenshot:

I'm trying to figure out whats wrong hours now without success.
Any ideas?
Thank you

A:

After searching and removing code piece by piece, I've found a function that disables wp_emojicons that for some reason it makes the CSS to load late.
function disable_wp_emojicons() {

/* all actions related to emojis */
  remove_action( 'admin_print_styles', 'print_emoji_styles' );
  remove_action( 'wp_head', 'print_emoji_detection_script', 7 );
  remove_action( 'admin_print_scripts', 'print_emoji_detection_script' );
  remove_action( 'wp_print_styles', 'print_emoji_styles' );
  remove_filter( 'wp_mail', 'wp_staticize_emoji_for_email' );
  remove_filter( 'the_content_feed', 'wp_staticize_emoji' );
  remove_filter( 'comment_text_rss', 'wp_staticize_emoji' );

/* filter to remove TinyMCE emojis */
  add_filter( 'tiny_mce_plugins', 'disable_emojicons_tinymce' );
}


Q:

Can two Skinshifters affect each other?

If I have two Skinshifters in play, can I use the ability of one to affect the other?  For instance, if one of my Skinshifters has Ice Cage on it, can I use the other Skinshifter's ability to morph the "caged" one, thereby breaking the Ice Cage?

A:

No, you can't.
Breaking an Ice Cage on a Skinshifter with another Skinshifter's ability won't work for 2 reasons:
First and most straightforward, the Skinshifter's ability does not require a target, and Ice Cage requires the enchanted creature to be targeted by a spell or ability for it to break.
Second, you can use Skinshifter's ability only to change itself, not another Skinshifter.
If a card says "Something happens to CARD NAME", then this always references the card this text is printed on, unless explicitly stated otherwise. If a card references another card by name, the syntax is always something like "A card/creature named XY", for example like Llanowar Sentinel, or Angel's Herald.
The rules for that is this:

201.4. Text that refers to the object it's on by name means just that particular object and not any other objects with that name, regardless of any name changes caused by game effects.


Q:

Entity Framework won't persist data in SQL Express (MDF)

I was developing an application using Entity Framework and storing data in a .mdf database. My code can read the data, apparently it can save too, but only apparently. It get no erros, while the program is running it act like the data was saved, I can for example save an object, dispose the context, create a new one, and then when I search my object it's there! But when I query the database to see the stored data there's nothing there. If I close the app and run it again, all data is gone. Here's a example code I wrote just to test:
        using (DatabaseEntities e = new DatabaseEntities())
        {
            for (int i = 0; i < 50; i++)
            {
                User u = new User();
                u.Nome = "User" + i.ToString();
                e.AddToUser(u);
            }
            int c = e.SaveChanges(true);

            List<User> us = e.User.Where<User>(x => x.ID < 50).ToList<User>();

            foreach (User u in us)
                Console.WriteLine("ID: " + u.ID + " Hello from " + u.Nome);

            Console.ReadKey();
        }

When I run this I get the 50 outputs, if I look the content of the c variable in the debug, there's 50 changes, everythings seems to be fine, but when I start my query browser and look in the content of my MDF database, there's nothing there.
Probably it's something very simple but I can't see what it is, I need your help.

A:

I just found what was going wrong, and I guess there's nothing wrong actually. I forced an error, and then I could see the database that I was accessing was in the bin directory, the Visual Studio copied my database to the bin directory everytime I run the app, so that's why if I add some data manually I could see it, but the saves in the runtime aren't persisted. I always worked with database in servers, it's my first time with local databases, so I messed up it, but thankz a lot for the help!

Edit: Providing a Solution
If you wish to disable copying the database on build, then you have to acces the Copy to Output Directoy from the .mdf file from your Solution Explorer.
Simply change it to Copy if newer or Do not copy.
Be aware that Copy if newer holds some risks when accesing a .mdf Database.

A:

A few things leap to mind:

double/treble-check your connection string; are you really talking to the file that you think you are?
are you using transactions anywhere and not committing them?
do you have the mdf file set to "Copy Always" (or whatever it is).... i.e. are you constantly overwriting the mdf whenever you hit build/play?

Also - I don't think it'll matter in this case, but to verify data you should use a different entities/data-context:
using (DatabaseEntities e = new DatabaseEntities()) {
    for (int i = 0; i < 50; i++) {
        User u = new User();
        u.Nome = "User" + i.ToString();
        e.AddToUser(u);
    }
    int c = e.SaveChanges(true);
}
using (DatabaseEntities e = new DatabaseEntities()) {
    List<User> us = e.User.Where<User>(x => x.ID < 50).ToList<User>();
    foreach (User u in us)
        Console.WriteLine("ID: " + u.ID + " Hello from " + u.Nome);
}
Console.ReadKey();

Like I said - I doubt it'll matter here, but worth checking...


Q:

Setting up standard JavaScript prototypal inheritance within a namespace?

The standard prototypal inheritance in JavaScript is as follows:
function Animal() {
    this.legs = 0;
}
Animal.prototype.move = function () {
    alert("I'm moving!");
}

Bird.prototype = new Animal();
Bird.prototype.constructor = Bird;
function Bird() {
    this.legs = 2;
    this.wings = 2;
}
Bird.prototype.move = function () {
    alert("I'm flying!");
}

Does the function definition for Bird have to come after the assignment of Bird's prototype and constructor. I ask this because I'm trying to do this from within a namespace, and variable hoisting is causing my code to fail. As an example:
var namespace = {};
namespace.Animal = function () {
    this.legs = 0;
};
namespace.Animal.prototype.move = function () {
    alert("I'm moving!");
};

namespace.Bird.prototype = new namespace.Animal();
namespace.Bird.prototype.constructor = namespace.Bird;
namespace.Bird = function () {
    this.legs = 2;
    this.wings = 2;
};
namespace.Bird.prototype.move = function () {
    alert("I'm flying!");
};

Thanks to hoisting the namespace.Bird.prototype assignment statement and the namespace.Bird.prototype.constructor assignment statement fail. If I move the namespace.Bird function assignment above those two lines as shown in the following code block, however, the code seems to work.
namespace.Bird = function () {
    this.legs = 2;
    this.wings = 2;
};
namespace.Bird.prototype = new namespace.Animal();
namespace.Bird.prototype.constructor = namespace.Bird;

However, I don't know if there's a specific reason why most resources show the original order rather than having the function assignment come first.
Can someone please clarify?
Thanks!

A:

The reason has to do with parse-time availability of functions and runtime availability of functions.
For example:
var afunc = asdf;
function asdf(){}

is the same as
function asdf(){}
var afunc = asdf;

But,
var afunc = asdf;
var asdf = function(){};

is not the same as
var asdf = function(){};
var afunc = asdf;

Does that make sense why?
Also, the answers to this question would probably help you
var functionName = function() {} vs function functionName() {}


Q:

Smarty Template {foreachelse} postback if statement troubleshooting

I'm probably making this harder than it actually is but...My error, no results! is displaying before my form is submitted. Is there a way in Smarty template to check for postback from the server?
{foreach from=$book item=row}
{$row.DESCRIPTION}
{foreachelse}
{if ($postback) == "thisvalue"}
Error, no results!
{/if}
{/foreach}

I tried this on my form (which didn't work either):
<input type="hidden" type="text" name="postback" value='thisvalue'>

if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$postback = $_POST['postback'];
$tpl->assign("postback", $postback);
}

A:

You can check for a value in the post-data directly with {$smarty.post.postback}, which is equivalent to the PHP suberglobal $_POST['postback']. However, as the Smarty documentation page for this feature says:

Although Smarty provides direct access to PHP super globals for convenience, it should be used with caution. Directly accessing super globals mixes underlying application code structure with templates. A good practice is to assign specific needed values to template vars.

In your case, you are presumably processing the "postback" (i.e. form submission) in some PHP code somewhere, and then passing the result of that processing to Smarty for display. It is that PHP code which should be determining if a form submission has occurred, and validating the input submitted (e.g. was the field left blank, or did they simply search for something that returned no results?). The result of that validation can then be passed to the Smarty template as an extra variable, and used to determine what messages need displaying.


Q:

Parameter and view naming collisions in Play/Scala templates

I am new to Play Framework and still trying to wrap my head around some things with the new Scala template engine.
Let's say I have the following package structure:
app/
app/controllers/Items.scala
app/models/Item.scala
app/views/layouts/page.scala.html
app/views/item/show.scala.html
app/views/item/details.scala.html  //partial

And this is my item/show template:
    @(item: Item, form: Form[Item])(implicit flash: Flash)
    @layout.page() {
        @*want to include details partial, wont work due to item param*@
        @item.details(item)
    }

Since including another template (e.g. including item/details above) is the exact same syntax as accessing a template parameter (e.g. item above), obviously this existing naming convention won't work without something changing.
I know I can rename my "app.views.item" package to "app.views.items", and rely on singular/plural forms to differentiate the view from the param name, but this does not seem like a very straightforward solution. Also what if I really want the parameter name to be the same as the view package?
One idea I have is to prepend all my views with an extra top level package:
 app/views/views/item/details.scala.html

So the include syntax would be  @views.item.details(), but again this is obviously a hack.
What is a good way to avoid this issue?  How can I better organize my code to avoid such naming collisions?
Most other template engines use operations like "include" or  "render" to specify a partial include. I don't mean to offend anyone here, but is the Play Scala template engine syntax so terse that it actually dictates the organization of code?

A:

3 solutions:
First
Typpicaly for partial templates you should use tags as described in the docs, where app/views/tags folder is a base:
file: app/views/tags/product.scala.html
in the templates (no initial import required in the parent view full syntax will allow you to avoid name-clash: @tags.packageName.tagName()):

    @tags.product(item)

Of course in your case you can also use packages in the base folder
file: app/views/tags/item/product.scala.html

    @tags.item.product(item)

I'm pretty sure that'll solve your problem.
Second
To avoid clash without changing package's name you can just rename the item in your view, also I recommend do not use a form name for the Form[T] as it can conflict with helpers:
@(existingItem: Item, existingItemForm: Form[Item])(implicit flash: Flash)
@layout.page() {
    @item.details(existingItem)
}

Third
If you'll fill your Form[Item] before passing to the view with given Item object, you don't need to pass both, as most probably you can get data from the form:
@(itemForm: Form[Item])(implicit flash: Flash)
@layout.page() {

Name of item is: @itemForm("name").value (this is a replacemnet for @@existingItem.name

    @item.details(itemForm)
}

Of course in you product.scala.html you'll need to change the @(item: Item) param to @(itemForm: Form[Item])


Q:

Closed form for $\sum\limits_{k=0}^{b}k^na^k$

We can be sure that for $a>1$
$$\sum\limits_{k=1}^{\infty}(-k)^na^{-k}+\sum\limits_{k=0}^{b}k^na^k=a^b\sum\limits_{m=0}^{n}\binom{n}{m}b^{n-m}\sum\limits_{k=0}^{\infty}(-k)^ma^{-k}$$
where
$$\sum\limits_{k=0}^{\infty}k^na^{-k}=\frac{af(a,n)}{(a-1)^{n+1}}$$
$$f(a,n)=\sum\limits_{k=0}^{n}k!{n\brace k}(a-1)^{n-k}=\sum\limits_{k=0}^{n}\sum\limits_{j=0}^{k}\binom{k}{j}(a-1)^{n-k}j^{n}(-1)^{k-j}$$
$$\lim\limits_{n\to \infty}\frac{f(a,n+1)}{f(a,n)}-\frac{f(a,n)}{f(a,n-1)}=\frac{a-1}{\ln(a)}$$
so
$$\sum\limits_{k=1}^{n}\sum\limits_{j=1}^{k}\binom{k}{j}\frac{aj^n}{(a-1)^{k+1}}(-1)^{n+k-j}+\sum\limits_{k=0}^{b}k^na^k=\sum\limits_{m=0}^{n}\sum\limits_{k=0}^{m}\sum\limits_{j=0}^{k}\binom{n}{m}\binom{k}{j}\frac{a^{b+1}j^mb^{n-m}}{(a-1)^{m+1}}(-1)^{m+k-j}$$
Very nice technique for solving this problem we can find here, but result formulas a bit ugly.
Is there more simple closed form for this sum, which involving, for example, Bernoulli numbers?

A:

This has an answer using Mellin transform methods. We use the material
from this MSE link
which is  so very  similar that we  may use it  as a  template, making
adjustments as necessary.
Re-write your sum like this (here we have $a\gt 1$):
$$S_m(n) = \sum_{k=1}^n k^m a^k =
n^m \sum_{k=1}^n \left(\frac{k}{n}\right)^m a^k
\\ = n^m a^n + n^m \sum_{k=1}^{n-1} \left(\frac{k}{n}\right)^m a^k
= n^m a^n + n^m a^n \sum_{k=1}^{n-1}
\left(1 - \frac{k}{n}\right)^m a^{-k}.$$
Now consider the harmonic sum
$$S(x) = \sum_{k\ge 1} a^{-k} H_m(kx)$$
where $H_m(x)$ is the Heaviside step function defined by
$$H_0(x) = \begin{cases} & 1&\text{if}\quad x\in[0,1] \\
& 0 &\text{otherwise}\end{cases}
\quad\text{and}\quad H_m(x) = (1-x)^m H_0(x)
\quad\text{when}\quad m\in\mathbb{Z}^+.$$
We see that $$S(1/n) = \sum_{k=1}^n
a^{-k}  \left(1 - \frac{k}{n}\right)^m,$$
i.e. the sum that  remains to be computed.
But $S(x)$ is harmonic and may be evaluated by inverting its Mellin transform.
Recall the harmonic sum identity
$$\mathfrak{M}\left(\sum_{k\ge 1} \lambda_k g(\mu_k x);s\right) =
\left(\sum_{k\ge 1} \frac{\lambda_k}{\mu_k^s} \right) g^*(s)$$
where $g^*(s)$ is the Mellin transform of $g(x).$
In the present case we have
$$\lambda_k = a^{-k}, \quad \mu_k = k \quad \text{and} \quad
g(x) = H_m(x).$$
We need the Mellin transform $H_m^*(s)$ of $H_m(x)$ which is
$$\int_0^\infty H_m(x) x^{s-1} dx
= \frac{m!}{s(s+1)(s+2)\cdots(s+m)}$$
as is easily seen by induction using integration by parts.
It follows that the Mellin transform $Q(s)$ of $S(x)$ is given by
$$ Q(s) = \frac{m!}{s(s+1)(s+2)\cdots(s+m)} \mathrm{Li}_s(1/a)
\quad\text{because}\quad
\sum_{k\ge 1} \frac{\lambda_k}{\mu_k^s} = \mathrm{Li}_s(1/a).$$
We thus obtain  the Mellin inversion integral $$  S(x) = \frac{1}{2\pi
i} \int_{1/2-i\infty}^{1/2+i\infty} Q(s)/x^s ds$$ which we evaluate by
shifting it to the left for  an expansion about zero.  The fundamental
strip here is  $\langle 0,+\infty \rangle$ which is  determined by the
Heaviside step function term (the polylog converges everywhere).
For the pole at $s=0$ we get
$$\mathrm{Res}(Q(s)/x^s; s=0) =
\frac{m!}{m!} \mathrm{Li}_{0}(1/a) = \frac{1}{a-1}.$$
For the poles at $s=-1, -2, \ldots -m = -q$ we require
$$\mathrm{Li}_{-q}(z) =
\frac{1}{(1-z)^{q+1}} \sum_{p=0}^{q-1}
\left\langle {q\atop p} \right\rangle z^{q-p}.$$
Observe  that all  terms in  the sum  for $\mathrm{Li}_{-q}(1/a)$  are
positive  (cite  e.g. the  combinatorial  definition  of the  Eulerian
numbers)  and hence  none of  the poles  from the  Heaviside term  are
canceled. We may thus continue with
$$\mathrm{Res}(Q(s)/x^s; s=-q)
\\ = \left.\frac{m!}{s(s+1)\cdots(s+q-1)(s+q+1)\cdots(s+m)}
\frac{\mathrm{Li}_{s}(1/a)}{x^s}\right|_{s=-q}
\\= \frac{m!}{(-1)^q q!\times (m-q)!}
x^q \frac{1}{(1-1/a)^{q+1}} \sum_{p=0}^{q-1}
\left\langle {q\atop p} \right\rangle (1/a)^{q-p}
\\ = (-1)^{q} {m\choose q}
x^q \frac{1}{(a-1)^{q+1}} \sum_{p=0}^{q-1}
\left\langle {q\atop p} \right\rangle a^{p+1}.$$
Now returning to the sum and using $S(1/n)$ we finally have
$$S_m(n) = n^m a^n  +
n^m a^n \left(\frac{1}{a-1}
+ \sum_{q=1}^m (-1)^{q} {m\choose q}
n^{-q} \frac{1}{(a-1)^{q+1}} \sum_{p=0}^{q-1}
\left\langle {q\atop p} \right\rangle a^{p+1}\right).$$
This is
$$n^m \frac{a^{n+1}}{a-1}
- \sum_{q=1}^m n^{m-q} {m\choose q}
\frac{1}{(1-a)^{q+1}} \sum_{p=0}^{q-1}
\left\langle {q\atop p} \right\rangle a^{n+p+1}.$$
We discover  upon verification of  this formula  that it is  missing a
constant term  that does not depend  on $n,$ which indicates  that the
remainder integral does not vanish. To compute the constant we require
$$\sum_{q=1}^m  {m\choose q}
\frac{1}{(1-a)^{q}} \sum_{p=0}^{q-1}
\left\langle {q\atop p} \right\rangle a^{p}
\\ = \frac{1}{(1-a)^m} \sum_{q=1}^m  {m\choose q}
(1-a)^{m-q} \sum_{p=0}^{q}
\left\langle {q\atop p} \right\rangle a^{p}.$$
What we have here is a convolution of two EGFS that yield
$$m! (1-a)^{-m} [z^m]
\exp((1-a)z) \left(-1 + \frac{a-1}{a-\exp((a-1)z)}\right)
\\ = m! [z^m] \exp(z) \left(-1 + \frac{a-1}{a-\exp(-z)}\right)
= m! [z^m] \frac{1-\exp(z)}{a-\exp(-z)}.$$
Collecting everything we find
$$\frac{a^2}{1-a} + a +
\frac{a^2}{1-a} m! [z^m] \frac{1-\exp(z)}{a-\exp(-z)}
\\ = \frac{a^2}{1-a}
\left(1 + \frac{1-a}{a}
+ m! [z^m] \frac{1-\exp(z)}{a-\exp(-z)} \right)
\\ = \frac{a^2}{1-a}
m! [z^m] \left(\frac{1}{a} \exp(z)
+ \frac{1-\exp(z)}{a-\exp(-z)} \right)
\\ = \frac{a^2}{1-a}
m! [z^m] \frac{-1/a  + 1}{a-\exp(-z)}
= \frac{a}{1-a}
m! [z^m] \frac{a-1}{a-\exp(-z)}
\\ = \frac{a}{(1-a)^{m+1}}
m! [z^m] \frac{a-1}{a-\exp((a-1)z)}
= \frac{a}{(1-a)^{m+1}}
\sum_{p=0}^{m-1} \left\langle {m\atop p} \right\rangle a^{p}.$$
We have established the following conjecture for $S_m(n):$
$$\bbox[5px,border:2px solid #00A000]{
\color{blue}{n}^m \frac{a^{n+1}}{a-1}
- \sum_{q=1}^m \color{blue}{n}^{m-q} {m\choose q}
\frac{1}{(1-a)^{q+1}} \sum_{p=0}^{q-1}
\left\langle {q\atop p} \right\rangle a^{n+p+1}
+ \frac{a}{(1-a)^{m+1}}
\sum_{p=0}^{m-1} \left\langle {m\atop p} \right\rangle a^{p}.}$$
This is a finite expansion in $n$ and $a$ with $m+2$ terms. E.g. we obtain
for $m=5$ and $a=11:$
$${\frac {11\,{n}^{5}{11}^{n}}{10}}-{\frac {11\,{n}^{4}{11}^{n}}{20}}
+{\frac {33\,{n}^{3}{11}^{n}}{25}}-{\frac {913\,{n}^{2}{11}^{n}}{500}}
+{\frac {957\,n{11}^{n}}{625}}-{\frac {7909\,{11}^{n}}{12500}}
+{\frac {7909}{12500}}.$$
Addendum. We also have from first principles that
$$S_m(n) = [z^n] \frac{1}{1-z} \mathrm{Li}_{-m}(az)
= [z^n] \frac{1}{1-z} \frac{1}{(1-az)^{m+1}} \sum_{p=0}^{m-1}
\left\langle {m\atop p} \right\rangle a^{m-p} z^{m-p}.$$
This is
$$(-1)^m \mathrm{Res}_{z=0} \frac{1}{z^{n+1}}
\frac{1}{z-1} \frac{1}{(z-1/a)^{m+1}} \sum_{p=0}^{m-1}
\left\langle {m\atop p} \right\rangle \frac{1}{a^{p+1}} z^{m-p}.$$
Residues  sum  to  zero  and  the  residue  at  infinity  is  zero  by
inspection. We get from the residue at $z=1$ (flip sign)
$$(-1)^{m+1} \frac{1}{(1-1/a)^{m+1}} \sum_{p=0}^{m-1}
\left\langle {m\atop p} \right\rangle \frac{1}{a^{p+1}}
= (-1)^{m+1} \frac{a}{(a-1)^{m+1}} \sum_{p=0}^{m-1}
\left\langle {m\atop p} \right\rangle a^{m-1-p}
\\ = \frac{a}{(1-a)^{m+1}} \sum_{p=0}^{m-1}
\left\langle {m\atop p} \right\rangle a^p.$$
For the residue at $z=1/a$ we write (flip sign)
$$(-1)^{m+1} \sum_{p=0}^{m-1}
\left\langle {m\atop p} \right\rangle \frac{1}{a^{p+1}}
\mathrm{Res}_{z=0}
\frac{1}{z-1} \frac{1}{(z-1/a)^{m+1}} z^{m-p-n-1}.$$
We require the derivative
$$\frac{1}{m!} \left(\frac{1}{z-1} z^{m-p-n-1}\right)^{(m)}
\\ = \frac{1}{m!} \sum_{q=0}^m {m\choose q} \frac{(-1)^q q!}{(z-1)^{q+1}}
(m-p-n-1)^{\underline{m-q}} z^{m-p-n-1-(m-q)}
\\ = \sum_{q=0}^m \frac{(-1)^q}{(z-1)^{q+1}}
{m-p-n-1\choose m-q} z^{q-p-n-1}.$$
Evaluate at $z=1/a$ to get
$$(-1)^{m+1} \sum_{p=0}^{m-1}
\left\langle {m\atop p} \right\rangle \frac{1}{a^{p+1}}
\sum_{q=0}^m \frac{(-1)^q}{(1/a-1)^{q+1}}
{m-p-n-1\choose m-q} \frac{1}{a^{q-p-n-1}}
\\ = (-1)^{m+1} a^{n+1} \sum_{p=0}^{m-1}
\left\langle {m\atop p} \right\rangle
\sum_{q=0}^m \frac{(-1)^q}{(1-a)^{q+1}}
{m-p-n-1\choose m-q}.$$
With some algebra we have obtained the alternate closed form
$$\bbox[5px,border:2px solid #00A000]{
(-1)^{m+1} a^{n+1}
\sum_{q=0}^m \frac{(-1)^q}{(1-a)^{q+1}}
\sum_{p=0}^{m-1} \left\langle {m\atop p} \right\rangle
{p-n\choose m-q}
+ \frac{a}{(1-a)^{m+1}}
\sum_{p=0}^{m-1} \left\langle {m\atop p} \right\rangle a^{p}.}$$
Note that the binomial coefficient will produce polynomials in $n$ of
degree $m-q$ when we fix $m.$


Q:

Why doesn't Lightroom offer conversion from RGB to CMYK?

I have never fully understood why Lightroom works exclusively in the RGB colour space. I would assume that a large number of Lightroom users use the software to prepare their photos for print. Yet, I have to import my RGB images into Photoshop just to convert to CMYK. Is this limitation by design or just a feature that hasn't been added yet?

A:

Lightroom was never intended to be an all in one image editing solution. In the beginning it was limited to just raw conversion and slowly more Photoshop like features, such as local corrections have been added. I wouldn't be surprised if CMYK was added somewhere down the line.
Although a large number of users print images from Lightroom, doing your own CYMK conversion is a fairly advanced step that you only need to perform if you need total control over the conversion process, or if you need to use a specific black mix for magazine work. It is assumed that advanced users will have access to tools such as Photoshop to perform these steps.

A:

Lightroom operates in the ProPhoto color space and has built-in exporting to sRGB and AdobeRGB.  You can also export to any other ICC profile (for a home printer or other device).  Most photo labs require files to be in sRGB or AdobeRGB and sRGB is the color space of the web.
I would imagine that if you need to convert to CMYK for printing, Lightroom would be only the first stop in your process.  You would likely finish in another tool like Illustrator or Photoshop.


Q:

Lookup column with no duplicates

I have a library containing documents, each one regarding a project. I also have a custom list with tasks (for monitoring) which has a column PROJECT. There are more than one tasks per project so this column has many duplicates.
What I need is to create a lookup column for the documents pointing at the PROJECT column of the list. The problem is that even if SP can group the list items per project (sorry for the Greek characters, I hope you get the picture):

when I fill the columns for a new document at the library I get a list of duplicates:

Is there a way to filter out the duplicates, so I can only have PROJECT A, PROJECT B etc?

A:

I don't think that this is possible.
When you select an item in the lookup, SharePoint would internally store the ID of the item you selected. If the item is the result of a group by on multiple rows, which row should it refer to?
As far as I know, you won't be able to achieve your goal by standard means.
As an option, couldn't you put the information about the project in a separate list and have that list as a lookup on both the document and the task libs? That would avoid redundancy in the Task list and normalize your data (pretty much as you would do on a standard DB). Can this be reasonable for you?
Otherwise, I fear that custom development is the only solution that comes to my mind.

Edit: about the "create Projects list and update it automatically using the entries of Task list" option.
That would be possible but ootb lookup on list don't allow fill in choise. That mean that if you want to still have a lookup on the Task list you would still need to develop some custom component (probably you can get away with a simple custom field that extend the lookup one - good old Waldek has already given some point about that in the past).
Notice that if you use Mastykarz solution, that would also resolve the "update project item" problem. Otherwise, another option would be to use some list event receiver to intercept the item updated/updating event and write some custom code that update the project list as required.


Q:

How to extend a Textfield that is allready on the stage in Flash (AS3)?

I'm looking for a way to extend a TextField that's allready on the stage in Flash (AS3)
something like this:
public class ChildTextField extends TextField
{
    //code for childTextField comes here
}

I've placed a TextField with instance name 'thetextfield' on the stage. Now I would like to tell flash this textfield is of type ChildTextField. So in my Document Class I declare that textfield as a ChildTextField:
public class DocumentClass extends Sprite()
{
    public var thetextfield : ChildTextField;
}

This throws a Type Coercion failed Error.
Is it possible to change the class that is used for a textfield in the Flash IDE like you can do with library symbols?

A:

Afraid not. You will have to use ActionScript if you want to add your extended textfield class.
EDIT: there is a hack way. source: http://board.flashkit.com/board/archive/index.php/t-738887.html

Actually, I've run into this exact
  problem before. In my case, I was
  trying to create a textfield with
  extra behaviors for other some other
  non-coder artists to use. I'll tell
  you my original solution which is all
  as3, but had a fatal flaw, and my
  current solution, which is a
  combination of as3 and jsfl.
The all as3 solution is great except
  for 2 things: First, it happens at
  runtime rather than build-time. That
  means there's a small but real portion
  of time where the movie isn't
  correctly initialized. Second, it does
  not play well if there are multiple
  frames in the movie. The basic idea is
  to detect the TextFields you want to
  change, build things to replace them
  with, then replace them on stage. You
  can do this with either by extending
  TextField, or building a class which
  contains a TextField and handles the
  interface to it. Let's say you're
  doing the first. Add a constructor to
  SmartTextField that copies all the
  fields you care about:

public function SmartTextField(TextField tf)
{
this.text = tf.text; //continue with copy of anything relevant.
}

in your main movie have code which
  detects and replaces the TextFields
  you want to replace

 var toreplace:Array = findTextFields();
 var tf:TextField;
 var stf:SmartTextField;
 var where:int;
 for (int i = 0; i < toreplace.length;i++)
 { tf = TextField(toreplace[i]);
   stf = new SmartTextField(tf);
   where = getChildIndex(tf);
    addChildAt(stf,where);
    removeChild(tf);
 }

This works fine, except for the points
  above.
The JSFL solution is a bit too complex
  to go over in detail, but here's the
  basics. Have an as3 class which wraps
  a textfield with the new behavior you
  want. Write a jsfl script which
  iterates over the selected items, and
  if it's a textfield, converts to a
  symbol with a baseclass of your new
  wrapper class. This has the advantages
  that it happens at author time, and
  things like position, instancename and
  other stuff is automatically
  preserved. It has the disadvantage
  that jsfl has a lot of little annoying
  quirks to work through.
edit: Of course, if this is only for a
  single movie, you could forego the
  jsfl converter script, and just do it
  by hand. convert to symbol -> wrapper
  baseclass.


Q:

How do I solve this inequation system

I have the system of equations
$$\begin{eqnarray} 3a &=& A \\ 4b &=& B \\ 7c&=& C \\ a+b+c&=&S \end{eqnarray}$$
subject to
$$A>S,\quad B>S,\quad C>S$$
How can I find $a$, $b$ and $c$?

A:

I assume that $S$ is given and fixed, while we search for $a,b$ and $c$. To find a solution just draw a picture:
Start with the three axes of a coordiante system. The triangle with the corners $(0,0,S)$, $(0,S,0)$ and $(S,0,0)$ represents all solutions of the equation $a+b+c=S$.
Now you want to enforce the inequalities, i.e.
$a>S/3$, $b>S/4$ and $c>S/7$   (we got rid of $A,B,C$ here). Each of these conditions can be represented by a plane parellel to a coordinate plane with the given distance. For example for $a>S/3$ you draw a plane parallel to the $b$-$c$-plane, with distance $S/3$. You will cut out a part of the original triangle and thereby find all solutions. It is an easy exercise to explicitly compute the intersections of the planes and the triangle.


Q:

Misreading a k'suva

The k'suva text varies slightly depending on whether the bride is a virgin, independent of whether she has been married previously. (For one thing, the amount of money mentioned in it is different; for another, the word "בתולתא" is omitted from the k'suva of a non-virgin.) Now, there's a custom to read the k'suva aloud during the wedding ceremony. I have heard that, in the case of a non-virgin bride whose non-virginity may be a source of shame (e.g., she has never been married), the person reading the k'suva aloud reads it wrong deliberately, reciting instead the text of a virgin's k'suva, so that no one else hears that the bride is a non-virgin. I am looking for a source that indicates that that custom (of deliberately misreading the k'suva) is appropriate, inappropriate, practiced, or not practiced, or any source or provenance for it.

A:

For starters: in Ashkenazic custom (which I think the questioner was assuming), the kesubah has already been signed (i.e. executed) before the chupah, so the reading is nothing more than a pause between parts of the ceremony. It's accomplishing nothing of a halachic nature any more than reading the latest stock numbers would be, hence many rabbis have been lenient in exactly what's read.
This gets a bit trickier in the Sephardic world as the witnesses are signing it on the spot, under the chupah. They're announcing it as it's executed. It could seem weird to proclaim you're executing a document with terms A when you're secretly executing a document with terms B. I don't know what Sephardic rabbis would say about this.
Just to clarify: if a woman was born Jewish and never previously married, and was never involved with a non-Jewish man, then the appropriate word to both read and write is in fact besulta.
Igros Moshe OC4:118 -- addressing a religiously-serious young woman trying to repent for what she did in college:

Regarding the writing of the kesubah, there is no need to tell the officiating rabbi (about the bride's past actions) -- once the groom signs on the kesubah he has agreed to the kesuba of a besula, even if she really isn't, so long as she's not misleading him, as he has agreed to obligate himself in the kesuba amount of a besula ... and if she marries the fellow with whom he she had relations, it is more proper to write besula, as explained in EH 101, and the rabbi [discussed in that responsum] acted properly.
Even if she had relations with a different man than the one she is now marrying, if the relations were with a legitimate Jew than she is still kohen-eligible and hence this affects no laws, only a monetary sum  - if the groom knows this and opts for the kesuba of a besula, they can write it as such -- and therefore [the couple] should not tell the officiating rabbi -- nor anyone else [about the bride's past indiscretions], as I have written above [we don't believe in confessing sins to human beings!].

The questions come up when it's not widely known that the bride was divorced, widowed (very unlikely), converted, or had a non-Jewish boyfriend at some point. (In the latter case ideally it'sa is written if that's actually known, though don't ask me how often rabbis actually ask about this.)
Rabbi JD Bleich has a yutorah mp3 in which he says if the bride is visibly pregnant, you can still in theory write besulta, but if so the rabbi shouldn't sign as a witness on the kesubah. While technically valid, it makes the rabbi's personal credibility look shaky.
As to your question, I suspect a lot of this remains oral tradition, not written down, for obvious reasons; I was told of an instance where Rabbi Yaakov Kaminetsky had someone write a dummy kesubah for the purposes of reading, and I spoke with a seasoned moreh hora'ah who had a similar instance where he said "who says that what's written there is what you have to read?"
Afraid I don't have written sources.

A:

This is an excellent question that is best asked to your local Orthodox rabbi.
1
One important aspect of the question, which should not be minimized, is the public humiliation to the bride, who will be mortified that her lack of virginity will be revealed to her friends and family. Chazal say (Berachot 43b) about embarrassing someone in public that it better to cast oneself into a fiery furnace, that one who embarrasses someone in public has no share in the world to come (Avos 3:11) and that it is comparable to shedding of blood (Bava Metzia 58b). On a day that everyone has an obligation to cause the bride and groom to rejoice, to cause a measure of public humiliation would seem non-ideal, to say the least.
2
Another important aspect of the question is the halachic importance of reading the Ketuba under the chuppa. Rav Herschel Schachter traced the development of this practice through the Geonim and Rishonim, and concludes that it has a mere status of hefek. Thus,

Yes, even if a parrot or a monkey would read the kesuba, the marriage would be one hundred percent valid. Strictly speaking,the reading of the kesuba is not at all a part of the marriage ceremony. This minhag was introduced in the days of the rishonim after the geonim had done away with the ancient practice of having a long pause (of several months) between the erusin and the nissuin. When a young girl would be married for the first time, the pause would be "a yohr un a mitvoch". The date for the chuppah would be set for the first Wednesday following the entire year after the erusin (see Talmud Kesubos 2a). In the days of the Talmud there would have been no objection if "borei pri hagoffen" would have been recited over the cup of wine used for the six brachas of nissuin, despite the fact that that same bracha had already been recited in connection with the cup of wine used for the "birchas erusin" 1, because there was a pause of months in between the two occasions. However, once the geonim introduced the practice of having the nissuin follow immediately after the erusin, the reciting of the blessing of borei pri hagoffen the second time seems very strange! There was no longer a pause of several months between the two brachos, but merely a pause of a few moments, and the reciting of the second bracha really seems absolutely unnecessary! This is what prompted the rishonim to institute the slow reading of the kesuba in between the erusin and the nissuin, to establish a hefsek between the two "brachos al hakos", so that the second borei pri hagoffen will not seem so superfluous. It is for this reason that many have the practice that if someone is scheduled to speak under the chuppah, or if a chazzan is going to sing something, that these take place right after the reading of the kesuba. The greater the pause, the better. Some rabbis have the practice of reading the kesuba very quickly. I remember that when Rav Eliezer Silver zt"l would be called upon to read the kesuba at a chasuna, he would do so very slowly. Since the whole purpose of krias hekesuba is to introduce a pause between the brachos over the two cups of wine, the longer the pause - the better! (See Beikvei Hatzohn pg. 268.)

3
If it is a mere hefsek, a pause, then it stands to reason that one can (and should!) change what is publicly read into the microphone, so long as the ketuba itself is written properly, and the eidim and husband understand what is really going on. See Shalom's answer for an example of a Gadol, Rav Yaakov Kaminetzsky, who would read a dummy kesuba. The statement of the "seasoned moreh horaah" who said, "who says that what's written there is what you have to read?" reflects what I have heard as well.
For a practical example of someone who recommends changing the out-loud reading of a ketuba to avoid embarrassment to the kallah (though the example is to not read a specific name), see Minchas Yitzchak Chelek 5 siman 44.

4
Note that the witnesses and the chassan should know what they are signing and agreeing to. Of course. I don't know that "Our modern custom of reading the Ketubah comes from two primary halakhot in the Shulhan Arukh", that Rabbi Michael Tzaddok writes, is correct, and would like to see some concrete support to that speculation, contra the position that it is a mere din in hefsek that sparked the practice.
Especially since I've quite often seen the ketuba signed not under the chuppa, but at the chossan's tisch, and yet the ketuba is still read under the chuppa, we see that all it is functioning is a hefsek.
In those places where the minhag is that they also sign the ketuba under the chuppa, then perhaps there is a fear that the groom and witnesses will mistake the contents of the ketuba, such that a deliberate misreading would not be appropriate. I would like to see a written source of e.g. Rav Ovadia Yosef saying this. Which apparently there is, but I would like to see it inside before editing this post to include it. I would also like to see why the groom and witnesses cannot be instructed as to this portion of the ketuba contents off-mike, so that every gossip in the audience is not privy to the sordid past of the kallah.


Q:

Can't configure node.js on windows 7

I have problem with configuring NODE.JS. I was trying to install node.js with this tutorial, but when i typed:

./configure

I got error:

I will be very thankful for any help!

A:

The unable to remap error you've encounted is often an indication that you need to run the rebaseall program. Rerun the setup file you used to install the your cygwin environment, then run rebaseall -v and that should fix it. You'll need to make sure that no cygwin programs are running when you run rebaseall.


Q:

One page website change menu color each section

I'm currently building a one page website with a fixed navigation menu (with a blue background). This one page website has 4 sections, 2 with a blue background and 2 with a white background.
My idea to do with this menu is when i scroll (not mouse hover) over a blue section, the menu background turns white. and when i scroll over a white section, the background changes back to blue.
An example can be found here.
(Not my site, but look at the changing color of the menu while scrolling)
My HTML code looks like this:

        Home
        Over mij
        Kennis
        Projecten
        Contact

Section 1

Section 2

Section 3

Section 4

Is there a simple way to do this?
Thanks in advance.

A:

I've found/created a temporary fix for my problem.
$(window).scroll(function(e) {
var s1 = $('.s1'),
    s2 = $('.s2'),
    s3 = $('.s3'),
    s4 = $('.s4'),
    menu = $('.menu'),
    diff = s1[0].offsetTop - window.pageYOffset;
    diff2 = s2[0].offsetTop - window.pageYOffset;
    diff3 = s3[0].offsetTop - window.pageYOffset;
    diff4 = s4[0].offsetTop - window.pageYOffset;

    if(diff < 100) {
        $(".menu").addClass("white");
        $(".menu").removeClass("blue");
    }
    if(diff2 < 100) {
        $(".menu").addClass("blue");
        $(".menu").removeClass("white");
    }
    if(diff3 < 100) {
        $(".menu").addClass("white");
        $(".menu").removeClass("blue");
    }
    if(diff4 < 100) {
        $(".menu").addClass("blue");
        $(".menu").removeClass("white");
    }
    if(diff > 100) {
        $(".menu").removeClass("white");
        $(".menu").removeClass("blue");
    }

});
JSFIDDLE DEMO


Q:

Density Bar - what happens when it completely fills?

0 bar - low density
1 bar - medium density
2 bars - high density
3 bars - ????

also, just a side question, why are the first two bars shaded weirdly? Is it just a graphical glitch?

A:

There is no "next step" beyond high density as you suggest. Density is just low, medium and high. The density raises along with the Sims' happiness (thus the smiley face). If the density bar fills 100% it just means your Sims are really really happy and will stay high density. Think of it like a progression bar. Once they are continuously happy for a certain amount of time, they are ready to upgrade to the next level. However, roads can also prevent going to the next level of density.
Since Density is a progression bar based on their happiness, if they are really mad the building will either lower to the bottom level of their current Density level and sit there:

Or they will abandon for whatever reason they are mad. I don't think I've ever seen them downgrade a density level. Typically if they abandon, a same-sized building will move in.
As for the shading, I think the intent is to show the building has grown past the first 2 bars of density by shading the previous ones lighter. The reason why Land Value is different is because they will not actively lower Density (change their building) but they WILL actively lower their wealth value.


Q:

How do I disable mouse acceleration AND adjust tracking speed in High Sierra?

The obvious answer you can find everywhere is:
defaults write .GlobalPreferences com.apple.mouse.scaling -1
which disables mouse acceleration, but locks you at one sensitivity.
Old solutions:
SmoothMouse no longer works. Mouse Acceleration Preferences Pane and SteelSeries ExactMouse both behave the same as com.apple.mouse.scaling -1 at all tracking speed settings (but without restart required).
Is it possible to disable mouse acceleration while still being able to adjust the sensitivity?

A:

The built-in options are limited. To achieve your goal a combination of different software could be needed.
Sensitivity and mouse acceleration
Terminal
Like you have already mentioned, the following setting needs to be applied to disable mouse acceleration.
defaults write .GlobalPreferences com.apple.mouse.scaling -1

It can be a good idea to establish a script to automatically perform this action during login to ensure it is properly applied.
SteerMouse
SteerMouse can then be used to adjust your sensitivity. It does require a license, but it also resolves the issue.
Simply download and install the software, either from their homepage or by using e.g. Homebrew:
brew cask install steermouse

The Cursor settings can then be adjusted to your liking. Acceleration should be left at 0, while sensitivity can be tuned to your preference.

Speed = ON
Acceleration = 0
Sensitivity = 0-2000

If using e.g. BetterTouchTool, then remember to turn Buttons, Wheel and Chords off in SteerMouse. These are known to conflict and generate erratic mouse behavior, as they both utilize similar macOS API endpoints.

Scrolling
Semi-related are also modifications to scrolling which can improve the Mac mouse usage experience.
SmoothScroll
Scrolling with a mouse on macOS can feel unnatural. To improve this one can utilize applications such as SmoothScroll for a better flowing scroll. Further adjustments can be made to customize the speed and related settings to ones need.

It can be downloaded and installed directly from the homepage, or by using e.g. Homebrew:
brew cask install smoothscroll

Scroll direction
It can be preferential to have different scroll directions between the trackpad and mouse. This can be adjusted in System Preferences -> Mouse. Checking/unchecking Scroll direction: Natural modifies this behavior.

Notes

The recommended options have been tested to work on macOS Mojave 10.14.4.
Licenses might be required for the suggested software.
I am in no way affiliated with the software developers, just a satisfied user. These are workarounds I have found when attempting to resolve the issue(s).


Q:

Least CPU intensive way to Frequently & Repeately Draw Many Views

This Is a problem that I've been leaving and coming back to for a while now. I've never really nailed the problem.
What I've been trying to do use CADisplayLink to dynamically draw pie chart style progress. My code works fine when I have 1 - 4 uiviews updating simultaneously. When I add any more than that the drawing of the pies becomes very jerky.
I want to explain what I have been trying in the hope that somebody could point out the inefficiencies and suggest a better drawing method.
I create 16 uiviews and add a CAShapeLayer subview to each one. This is where I want to draw my pie slices.
I precalcuate 360 CGPaths representing 0 to 360 degrees of a circle  and store them in an array to try and improve performance.
In a master View  I start a displaylink,loop through all my other views, calculate how much of a full pie it should show, then find the right path and assign it to my shapelayer.
-(void)makepieslices
{
    pies=[[NSMutableArray alloc]initWithCapacity:360];
    float progress=0;
    for(int i=0;i<=360;i++)

    {
        progress= (i* M_PI)/180;
        CGMutablePathRef thePath = CGPathCreateMutable();
        CGPathMoveToPoint(thePath, NULL, 0.f, 0.f);
        CGPathAddLineToPoint(thePath, NULL, 28, 0.f);
        CGPathAddArc(thePath, NULL, 0.f,0.f, 28, 0.f, progress, NO);
        CGPathCloseSubpath(thePath);
        _pies[i]=thePath;

    }

}

- (void)updatePath:(CADisplayLink *)dLink {

    for (int idx=0; idx<[spinnydelegates count]; idx++) {

        id<SyncSpinUpdateDelegate> delegate = [spinnydelegates objectAtIndex:idx];
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [delegate updatePath:dLink];
        });

    }

}

- (void)updatePath:(CADisplayLink *)dLink {

    dispatch_async(dispatch_get_global_queue(0, 0), ^{

        currentarc=[engineref getsyncpercentForPad:cid pad:pid];

        int progress;

        progress = roundf(currentarc*360);

        dispatch_async(dispatch_get_main_queue(), ^{
            shapeLayer_.path = _pies[progress];

        });

    });

}

This technique just straight out isnt working for me when trying to simultaneously update more than 4 or 5 pies at the same time. 16 screen updates at the same time sounds like it should really not be that big of a deal for the ipad to me. So this leads me to think I doing something very very fundamentally  wrong.
I'd really appreciate if somebody could tell me why this technique results in jittery screen updates and also if they could suggest a different technique that I could go an investigate that will allow me to perform 16 simultaneous shapelayer updates smoothly.
EDIT Just to give you an idea of how bad performance is, when I have all 16 pies drawing the cpu goes up to 20%
*EDIT *
This is based on studevs advice but I don't see anything been drawn. segmentLayer is a CGLayerRef as a property of my pieview.
-(void)makepies
{

    self.layerobjects=[NSMutableArray arrayWithCapacity:360];

    CGFloat progress=0;

    CGContextRef context=UIGraphicsGetCurrentContext();

    for(int i =0;i<360;i++)
    {
        progress= (i*M_PI)/180.0f;

        CGLayerRef segmentlayer=CGLayerCreateWithContext(context, CGSizeMake(30, 30), NULL);
        CGContextRef layerContext=CGLayerGetContext(segmentlayer);
        CGMutablePathRef thePath = CGPathCreateMutable();
        CGPathMoveToPoint(thePath, NULL, 0.f, 0.f);
        CGPathAddLineToPoint(thePath, NULL, 28, 0.f);
        CGPathAddArc(thePath, NULL, 0.f,0.f, 28, 0.f, progress, NO);
        CGPathCloseSubpath(thePath);

        [layerobjects addObject:(id)segmentlayer];
        CGLayerRelease(segmentlayer);
    }

}

-(void)updatePath
{
    int progress;

    currentarc=[engineref getsyncpercent];
    progress = roundf(currentarc*360);

    //shapeLayer_.path = _pies[progress];

    self.pieView.segmentLayer=(CGLayerRef)[layerobjects objectAtIndex:progress];

    [self.pieView setNeedsDisplay];

}

-(void)drawRect:(CGRect)rect
{

    CGContextRef context=UIGraphicsGetCurrentContext();

    CGContextDrawLayerInRect(context, self.bounds, segmentLayer);

}

A:

I think one of the first things you should look to do is buffer your segments (currently represented by CGPath objects) offscreen using CGLayer objects. From the docs:

Layers are suited for the following:

High-quality offscreen rendering of drawing that you plan to reuse.
  For example, you might be building a scene and plan to reuse the same
  background. Draw the background scene to a layer and then draw the
  layer whenever you need it. One added benefit is that you don’t need
  to know color space or device-dependent information to draw to a
  layer.
Repeated drawing. For example, you might want to create a
  pattern that consists of the same item drawn over and over. Draw the
  item to a layer and then repeatedly draw the layer, as shown in Figure
  12-1. Any Quartz object that you draw repeatedly—including CGPath,
  CGShading, and CGPDFPage objects—benefits from improved performance if
  you draw it to a CGLayer. Note that a layer is not just for onscreen
  drawing; you can use it for graphics contexts that aren’t
  screen-oriented, such as a PDF graphics context.

Create a UIView subclass that draws the pie. Give it an instance variable for that pie's current progress, and override drawRect: to draw the layer representing that progress. The view needs to first get a reference the required CGLayer object, so implement a delegate with the method:
- (CGLayerRef)pieView:(PieView *)pieView segmentLayerForProgress:(NSInteger)progress context:(CGContextRef)context;

It will then become the delegate's job to return an existing CGLayerRef, or if it doesn't exist yet, create it. Since the CGLayer can only be created from within drawRect:, this delegate method should be called from PieView's drawRect: method. PieView should look something like this:
PieView.h
#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>

@class PieView;

@protocol PieViewDelegate <NSObject>

@required
- (CGLayerRef)pieView:(PieView *)pieView segmentLayerForProgress:(NSInteger)progress context:(CGContextRef)context;

@end

@interface PieView : UIView

@property(nonatomic, weak) id <PieViewDelegate> delegate;
@property(nonatomic) NSInteger progress;

@end

PieView.m
#import "PieView.h"

@implementation PieView

@synthesize delegate, progress;

- (void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGLayerRef segmentLayer = [delegate pieView:self segmentLayerForProgress:self.progress context:context];
    CGContextDrawLayerInRect(context, self.bounds, segmentLayer);
}

@end

Your PieView's delegate (most likely your view controller) then implements:
NSString *const SegmentCacheKey = @"SegmentForProgress:";

- (CGLayerRef)pieView:(PieView *)pieView segmentLayerForProgress:(NSInteger)progress context:(CGContextRef)context
{
    // First, try to retrieve the layer from the cache
    NSString *cacheKey = [SegmentCacheKey stringByAppendingFormat:@"%d", progress];
    CGLayerRef segmentLayer = (__bridge_retained CGLayerRef)[segmentsCache objectForKey:cacheKey];

    if (!segmentLayer) {    // If the layer hasn't been created yet
        CGFloat progressAngle = (progress * M_PI) / 180.0f;

        // Create the layer
        segmentLayer = CGLayerCreateWithContext(context, layerSize, NULL);
        CGContextRef layerContext = CGLayerGetContext(segmentLayer);

        // Draw the segment
        CGContextSetFillColorWithColor(layerContext, [[UIColor blueColor] CGColor]);
        CGContextMoveToPoint(layerContext, layerSize.width / 2.0f, layerSize.height / 2.0f);
        CGContextAddArc(layerContext, layerSize.width / 2.0f, layerSize.height / 2.0f, layerSize.width / 2.0f, 0.0f, progressAngle, NO);
        CGContextClosePath(layerContext);
        CGContextFillPath(layerContext);

        // Cache the layer
        [segmentsCache setObject:(__bridge_transfer id)segmentLayer forKey:cacheKey];
    }

    return segmentLayer;
}

So for each pie, create a new PieView and set it's delegate. When you need to update a pie, update the PieView's progress property and call setNeedsDisplay.
I'm using an NSCache here since there are a lot of graphics being stored, and it could take up a lot of memory. You could also limit the number of segments being drawn - 100 is probably plenty. Also, I agree with other comments/answers that you might try updating the views less often, as this will consume less CPU and battery power (60fps is probably not necessary).

I did some crude testing of this method on an iPad (1st gen) and managed to get well over 50 pies updating at 30fps.

A:

dubbeat: ...CADisplayLink...

Justin: do you need to draw at the display's refresh rate?

dubbeat: The progress of the pie drawing is supposed to represent the progress of an mp3s playback progress so I guess at the displays refresh rate at a minimum.

That's much faster than is necessary, unless you're trying to display some really, really, really exotic visualizer, which is very unlikely if your spinner's radius is 28pt. Also, there's no reason to draw faster than the display's frequency.
One side effect is that your spinner's superviews may also updating at this high frequency. If you can make the spinner view opaque, then you can reduce overdrawing of superviews (and subviews if you have them).
60fps is a good number for a really fast desktop game. For an ornament/progress bar, it's far more than necessary.
Try this:

not using CADisplayLink, but the standard view system
use an NSTimer on the main run loop, begin with a frequency of 8 Hz*
adjust timer to taste

then let us know if that is adequately fast.
*the timer callback calls [spinner setNeedsDisplay]


Q:

Async function not allowing return type of two promise types in typescript

node 14.7.0, npm 6.14.7, typescript 3.7.3.
I have a method that queries a postgres database and, depending on a param, will return the first row it finds or the entire result from the query. Similar to this:
async getRecord(options: {singleRow: boolean}): Promise<QueryResult> | Promise<Record> {
    const result:QueryResult = await postgres.query(...);

    if (options && options.singlerow) {
        return result.rows[0];
    }

    return result;
}

However, I receive the following error: The return type of an async function or method must be the global Promise<T> type. I do not receive an error when I remove the | Promise<Record> section, even though the first return (in the if statement) returns a Promise<Record>. What should I do to fix this?

A:

Return Promise<QueryResult | Record>
async functions need a Promise to box whatever type they return, there's just one top level Promise-type-generic that wraps the return type.


Q:

True /false Question regarding subfield question

This is the  orginal question
My attempt :
option C will be true    take $\mathbb{Q}[x] / (x^2 +1)$  that is  subfield  of  $\mathbb{Q}[X]/(2X^3 − 3X^2 + 6)$
similarly option D)  will aslo  True  same logics   in option C
Im  confused about option $A)$  and option $B)$
Any hints/solution will be apprecaited
thanks u

A:

Here are some hints that might help figure it out yourself:
i.) A cubic polynomial $f$ is irreducible over $\mathbb Q$ if and only if it has no roots in $\mathbb Q$
ii.) Making the polynomial monic doesn't change the field, i.e. $\mathbb Q[X] / (2X^3 - 3X^2 + 6) \cong \mathbb Q[X]/(X^3 - \frac{3}{2}X^2 + 3)$.
iii.) Note that if you have a monic irreducible polynomial $f$ and an element $\alpha \in \mathbb C$ with $f(\alpha) = 0$, then $f$ is the minimal polynomial of $\alpha$ and $\mathbb Q(\alpha) \cong \mathbb Q[X]/(f)$.
iv.) If you want to decide if such a field is contained in $\mathbb R$ or has elements that lie in $\mathbb C \setminus \mathbb R$, you will have to look at the roots. I think you can work out yourself how to decide that.
iv.) If you have roots $\alpha_1, \dots, \alpha_3$ of your polynomial $f$ above, note that you have $\mathbb Q(\alpha_1) \cong \mathbb Q(\alpha_2) \cong \mathbb Q(\alpha_3) \cong \mathbb Q[X]/(f)$. Hence you can look at all these three fields to decide if the statements above are true!
v.) Note that if a polynomial $f \in \mathbb Q[X]$ has a root in $\mathbb C \setminus \mathbb R$, then also the complex conjugate has to be a root. What does that tell you if $f$ is of degree 3?


Q:

How to setup listening port of dropbear under initramfs-tools

This is in reference to: Ubuntu will not boot into busybox for remote LUKS decryption using dropbear
I have really like this solution by BinaryShrub.
One question: what is the right way to set the listening port of dropbear in this setup?
Thank you!

A:

I've managed to find a solution (nothing helped me on internet...), I've tried many things as change port in /etc/default/dropbear or etc/init.d/dropbear without any effect...
So, after searching how initramfs works and how dropbear is launched at boot, here is the solution:
$ cd /usr/share/initramfs-tools/scripts/init-premount
$ nano dropbear

then go to the function run_dropbear(), you should find a line with something like this:
exec /sbin/dropbear ${DROPBEAR_OPTIONS:-$PKGOPTION_dropbear_OPTION} -Fs

Just add the following option at the end of line:
exec /sbin/dropbear ${DROPBEAR_OPTIONS:-$PKGOPTION_dropbear_OPTION} -Fs -p #### (where #### is your port number)

Don't forget to run update-initramfs -u after this modification.
Reboot. Your SSH at boot time should now be on the chosen port.
Cheers

A:

You can specify the options to dropbear in your /etc/initramfs-tools/initramfs.conf
DROPBEAR_OPTIONS="-p 2222"
And then rebuild the initramfs: update-initramfs -u


Q:

Simple Logarithmic question.

I was just wondering if i can do this.
Q. Solve $\log_{9}24=x $
$\implies9^x =24$
$\implies3^{2x}=2^3 3$
$\implies\log_3(3^{2x})= \log_3(2^3 3)$
$\implies2x=2 (3)^{1/3}$
$\implies x=3^{1/3} $
Is this actually correct or did i break some kind of log rule here? My answer appears to be out by 0.0038 compared to the book is that cause they used a calculator or is it just a fluke that my answer is so close?

A:

Your method is incorrect as pointed out by Mufasa (sorry I didn't spot that earlier) but it's not the way I'd have done it anyway (and probably not how the book answer was obtained). This way is better:
$9^x = 24$
$\implies x\ln 9 = \ln 24$
$\implies x = \frac{\ln 24}{\ln 9} = 1.44639...$


Q:

Loop through a nested python dictionary/list loaded from yaml

Ok, this is probably stupid. Basically i'm trying to loop through my nested yaml-file and do stuff with for example every key-a value in my list. I have read alot and i'm able to loop through a nested dictionary without the list but I don't wan't to use unique key's for the nodes.
This works:
lev-0a:
  lev-1a:
    node1:
     key-a: '1'
node2:
 key-a: '2'

But when i'm trying to iterate a nested dict with "list" objects it fails.
Yaml:
lev-0a:
  lev-1a:
    - key-a: '1'
      key-b: '2'
      key-c: '3'
      key-d:
        level-2:
          - key: 'a'
          - key: 'b'
          - key: 'c'

    - key-a: '7'
      key-b: '8'
      key-c: '9'
      key-d:
        level-2:
          - key: 'x'
          - key: 'y'
          - key: 'z'

Print settings from python:
{'lev-0a': {'lev-1a': [{'key-c': '3', 'key-b': '2', 'key-a': '1', 'key-d': {'level-2': [{'key': 'a'}, {'key': 'b'}, {'key': 'c'}]}}, {'key-c': '9', 'key-b': '8', 'key-a': '7', 'key-d': {'level-2': [{'key': 'x'}, {'key': 'y'}, {'key': 'z'}]}}]}}

My code:
env.settings_file = env.setting_path + '/settings.yaml'

def load_settings(settings=env.settings_file):
    try:
        with open(settings) as stream:
            data = yaml.load(stream)
            return data
    except IOError as error:
        print ('File error: ' + str(error))

def dev(settings=load_settings()):

    for k, v in settings['lev-0a']['lev-1a'].iteritems():
        print v['key-a']
        # do stuff with every key-a value

Error:
TypeError: list indices must be integers, not str

If I do this:
for k, v in settings['lev-0a']['lev-1a'][0].iteritems():
    print k,v

I will get:
key-c 3
key-b 2
key-a 1
key-d {'level-2': [{'key': 'a'}, {'key': 'b'}, {'key': 'c'}]}

Thanks!

A:

This alone should have raised an error: settings['lev-0a']['lev-1a'].iteritems():. In your code, the value pointed to by ['lev-1a'] appears to be a list, not a dict, so calling iteritems() on it is very suspect.
What you seem to have been looking for is something like:
for dict1a in settings['lev-0a']['lev-1a']:
    print dict1a['key-a']

That prints both [key-a] values found inside of the two dicts from the ['lev-1a'] list. Does this answer your question at all? I have to admit I am not certain I fully understand your question. Feel free to elaborate and I'll edit accordingly.


Q:

Trying to add CSS file to HTML but getting 404 error

Here is my folder hierarchy:
/flask_app_2
    run.py
    /main
    __init__.py
    /static
        /js
        /styles
            styles.css
    /templates
        html_page.html

I am trying to add styles.css to my html_page but I keep getting a 404 error.
<link rel="stylesheet" type = "text/css" href="/static/style/style.css">
Am I loading it correctly? Or do I possibly have a typo in my CSS file?

A:

You're missing an "s" from your path.
<link rel="stylesheet" type = "text/css" href="/static/style/style.css">

Should be
<link rel="stylesheet" type = "text/css" href="/static/styles/style.css">

so "/static/styleS/style.css" instead of "/static/style/style.css".