instruction
stringlengths
17
7.84k
output
stringlengths
15
13.7k
input
stringclasses
1 value
Can brain cells move? By movement I mean long distance migration (preferably within the brain only).
The question is relatively broad and one should take into account that the brain not only consists of neurons, but also glial cells (supportive cells) and pre-mitotic neuronal stem cells. Furthermore, as critical fellow-scientists have indicated, developmental stage is very important, as the developing embryonic brain is very different from the adult brain. However, after sifting through various publications, the answer to the question is actually remarkably simple: Yes, brain cells migrate. In the adult brain glial cells migrate in the brain (Klämbt, 2009). Glial cells are involved in a myriad of functions, but a notable example of migrating glial cells are the oligodendrocytes that migrate relative long distances to find their target axons onto which they wrap themselves to form the insulating myelin sheath (Tsai and Miller, 2002). Neuronal stem cells migrate over long distances in response to injury (Imitola et al., 2004) and they migrate from specific stem-cell locations (e.g., hippocampus and subventricular zone) to other regions (Clarke, 2003). Post-mitotic, but non-differentiated neurons have been shown to migrate in the adult brain in fish (Scott et al., 2012), and in mammals and non-human primates as well (Sawada et al., 2011). Not surprisingly, glial cells, stem cells and neurons also migrate during embryonic development. Most notably, post-mitotic neurons destined to fulfill peripheral functions have to migrate over relatively long distances from the neural crest to their target locations (Neuroscience, 2nd ed, Neuronal Migration).
In our computer systems lecture we were introduced to the MIPS processor. It was (re)developed over the course of the term and has in fact been quite easy to understand. It uses a RISC design, that is its elementary commands are regularly encoded and there are only few of them in order to keep the wires simple. It was mentioned that CISC follows a different philosophy. I looked briefly at the x86 instruction set and was shocked. I can not image how anyone would want to build a processor that uses so complex a command set! So I figure there have to be good arguments why large portions of the processor market use CISC architectures. What are they?
There is a general historical trend. In the olden days, memories were small, and so programs were perforce small. Also, compilers were not very smart, and many programs were written in assembler, so it was considered a good thing to be able to write a program using few instructions. Instruction pipelines were simple, and processors grabbed one instruction at a time to execute it. The machinery inside the processor was quite complex anyway; decoding instructions was not felt to be much of a burden. In the 1970s, CPU and compiler designers realized that having such complex instructions was not so helpful after all. It was difficult to design processors in which those instructions were really efficient, and it was difficult to design compilers that really took advantage of these instructions. Chip area and compiler complexity was better spent on more generic pursuits such as more general-purpose registers. The Wikipedia article on RISC explains this in more detail. MIPS is the ultimate RISC architecture, which is why it's taught so often. The x86 family is a bit different. It was originally a CISC architecture meant for systems with very small memory (no room for large instructions), and has undergone many successive versions. Today's x86 instruction set is not only complicated because it's CISC, but because it's really a 8088 with a 80386 with a Pentium possibly with an x86_64 processor. In today's world, RISC and CISC are no longer the black-and-white distinction they might have been once. Most CPU architectures have evolved to different shades of grey. On the RISC side, some modern MIPS variants have added multiplication and division instructions, with a non-uniform encoding. ARM processors have become more complex: many of them have a 16-bit instruction set called Thumb in addition to the “original” 32-bit instructions, not to mention Jazelle to execute JVM instructions on the CPU. Modern ARM processors also have SIMD instructions for multimedia applications: some complex instructions do pay after all. On the CISC side, all recent processors are to some extent RISC inside. They have microcode to define all these complex macro instructions. The sheer complexity of the processor makes the design of each model take several years, even with a RISC design, what with the large number of components, with pipelining and predictive execution and whatnot. So why do the fastest processors remain CISC outside? Part of it, in the case of the x86 (32-bit and 64-bit) family, is historical compatibility. But that's not the whole of it. In the early 2000s, Intel tried pushing the Itanium architecture. Itanium is an extreme case of complex instructions (not really CISC, though: its design has been dubbed EPIC). It even does away with the old-fashioned idea of executing instructions in sequence: all instructions are executed in parallel until the next barrier. One of the reasons Itanium didn't take is that nobody, whether at Intel or elsewhere, could write a decent compiler for it. Now a good old mostly-sequential processor like x86_64, that's something we understand.
View tabular file such as CSV from command line, having horizontal and vertical scrolling would be great.
Sure, please take a look at csvkit. It provides a set of tools that adhere to the UNIX philosophy (meaning they are small, simple, single-purposed and can be combined). Here is an example that extracts the ten most populated cities in Germany from the free Maxmind World Cities database and displays the result in a console-readable format: ```$ csvgrep -e iso-8859-1 -c 1 -m "de" worldcitiespop | csvgrep -c 5 -r "\d+" | csvsort -r -c 5 -l | csvcut -c 1,2,4,6 | head -n 11 | csvlook ----------------------------------------------------- | line_number | Country | AccentCity | Population | ----------------------------------------------------- | 1 | de | Berlin | 3398362 | | 2 | de | Hamburg | 1733846 | | 3 | de | Munich | 1246133 | | 4 | de | Cologne | 968823 | | 5 | de | Frankfurt | 648034 | | 6 | de | Dortmund | 594255 | | 7 | de | Stuttgart | 591688 | | 8 | de | Düsseldorf | 577139 | | 9 | de | Essen | 576914 | | 10 | de | Bremen | 546429 | ----------------------------------------------------- ``` Csvkit is platform independent because it is written in Python.
Slater type orbitals (STO) are considered to be more accurate than gaussian type orbitals (GTO) for atomic and molecular QM calculations because - among other reasons - they decay with $e^{-\alpha r}$ as $r \to \infty$. But GTOs are more popular because they are easier to calculate with. GTOs decay with $e^{-\alpha r^2}$, so its adequate to sometimes add diffuse functions to the GTO basis set to compensate for gaussian decay behaviour. Also, exact hydrogen wavefunctions decay exponentially, so the motivation for STOs. I understand that the only boundary requirement for solving the Schrödinger equation for atoms and molecules in free space is that the wavefunction goes zero as $r \to \infty$, but there are no a priori requirements for the way it decays as it does so. My question is: do we have theoretical (ab initio) and/or experimental reasons to believe that all atomic and molecular wavefunctions decay like $e^{-\alpha r}$ as $r \to \infty$.
I'll answer this question from the theoretical side. The exponential behavior follows simply from the Schrödinger equation. Consider the one-electron Schrödinger equation: $$ (-\frac{1}{2}\nabla^2 + V(\mathbf{r}))\psi(\mathbf{r}) = \epsilon\psi(\mathbf{r}), \epsilon < 0 $$ At spatial points that are very far away from the nucleus, $V(\mathbf{r})\approx 0$, so that the asymptotic solution is given by $$ -\frac{1}{2}\nabla^2\psi(\mathbf{r}) = \epsilon\psi(\mathbf{r}), \epsilon < 0 $$ This differential equation has basic solutions of the form $$ \psi(\mathbf{r}) = Ce^{-\sqrt{-2\epsilon}\mathbf{k}\cdot\mathbf{r}} $$ for some unit vector $\mathbf{k}$. The real asymptotic behavior of $\psi(\mathbf{r})$ is thus a linear combination of these basic solutions. The linear combination may bring a polynomial prefactor to the exponential, but will never alter the exponent. Thus we have not only proved the exponential behavior, but also derived the correct exponent $\alpha = \sqrt{-2\epsilon}$. For a multi-electronic, non-interacting system, the overall decay rate is governed by the slowest decaying orbital, i.e. the HOMO. Of course, the real wavefunction can only be described by a multi-electron Schrödinger equation. But we can work on the equivalent Kohn-Sham system and show that the Kohn-Sham wavefunction decays at a rate given by the Kohn-Sham HOMO energy. By Janak's theorem, the Kohn-Sham HOMO energy is just the negative of the ionization potential of the exact system. To see this, consider a huge ensemble of $N$ identical, non-interacting molecules. If we remove one electron from the ensemble and let the hole delocalize evenly between all the molecules, then as $N\to +\infty$, the electron removal has a negligible impact on the electron density of any molecule (and therefore the Kohn-Sham potential of each molecule). Therefore under the Kohn-Sham framework we see that removing such an electron costs an energy of $-\epsilon_{\mathrm{HOMO}}$ (it does not matter whether the HOMO refers to that of the ensemble or that of a molecule, since their orbital energies are equal), since the electron is taken from an energy level whose energy is $\epsilon_{\mathrm{HOMO}}$ and the Hamiltonian is not changed in this process. On the other hand, from the perspective of the real system it is clear that the energy cost is equal to the first ionization energy of one of the molecules, $I$. Therefore we have $\epsilon_{\mathrm{HOMO}} = -I$, which means that the Kohn-Sham wavefunction decays like (again up to a possible polynomial prefactor; the precise determination of this polynomial prefactor is a much more difficult question) $$ \psi(\mathbf{r}) = Ce^{-\sqrt{2I}\mathbf{k}\cdot\mathbf{r}} $$ Although the Kohn-Sham wavefunction is fictional, its density is equal to the true multielectronic density, and in order for the true density to have the same asymptotic behavior as the Kohn-Sham density, the true wavefunction must have the same asymptotic behavior as the Kohn-Sham wavefunction. Q.E.D.
Explain what "git reset" does. I come from a SVN background and Git is a whole new paradigm. I got mercurial easily, but Git is much more technical. I think ```git reset``` is close to ```hg revert```, but it seems there are differences. Please include detailed explanations about: * the options ```--hard```, ```--soft``` and ```--merge```; * the strange notation you use with ```HEAD``` such as ```HEAD^``` and ```HEAD~1```; * concrete use cases and work flows; * consequences on the working copy, the ```HEAD``` and your global stress level.
Remember that in ```git``` you have: * the ```HEAD``` pointer, which tells you what commit you're working on * the working tree, which represents the state of the files on your system * the staging area (also called the index), which "stages" changes so that they can later be committed together > Please include detailed explanations about: ```--hard```, ```--soft``` and ```--merge```; In increasing order of dangerous-ness: * ```--soft``` moves ```HEAD``` but doesn't touch the staging area or the working tree. * ```--mixed``` moves ```HEAD``` and updates the staging area, but not the working tree. * ```--merge``` moves ```HEAD```, resets the staging area, and tries to move all the changes in your working tree into the new working tree. * ```--hard``` moves ```HEAD``` and adjusts your staging area and working tree to the new ```HEAD```, throwing away everything. > concrete use cases and workflows; * Use ```--soft``` when you want to move to another commit and patch things up without "losing your place". It's pretty rare that you need this. ``` # git reset --soft example touch foo // Add a file, make some changes. git add foo // git commit -m "bad commit message" // Commit... D'oh, that was a mistake! git reset --soft HEAD^ // Go back one commit and fix things. git commit -m "good commit" // There, now it's right. ``` -- * Use ```--mixed``` (which is the default) when you want to see what things look like at another commit, but you don't want to lose any changes you already have. * Use ```--merge``` when you want to move to a new spot but incorporate the changes you already have into that the working tree. * Use ```--hard``` to wipe everything out and start a fresh slate at the new commit.
I am looking to use Java to get the MD5 checksum of a file. How is it done?
The com.google.common.hash API offers: * A unified user-friendly API for all hash functions * Seedable 32- and 128-bit implementations of murmur3 * md5(), sha1(), sha256(), sha512() adapters, change only one line of code to switch between these, and murmur. * goodFastHash(int bits), for when you don't care what algorithm you use * General utilities for HashCode instances, like combineOrdered / combineUnordered Read the User Guide (IO Explained, Hashing Explained). For your use-case ```Files.hash()``` computes and returns the digest value for a file. For example a sha-1 digest calculation (change SHA-1 to MD5 to get MD5 digest) ```HashCode hc = Files.asByteSource(file).hash(Hashing.sha1()); "SHA-1: " + hc.toString(); ``` Note that crc32 is much faster than md5, so use crc32 if you do not need a cryptographically secure checksum. Note also that md5 should not be used to store passwords and the like since it is to easy to brute force, for passwords use bcrypt, scrypt or sha-256 instead. For long term protection with hashes a Merkle signature scheme adds to the security and The Post Quantum Cryptography Study Group sponsored by the European Commission has recommended use of this cryptography for long term protection against quantum computers (ref). Note that crc32 has a higher collision rate than the others. What part of Files.hash as stated above does not cover Files.hash ?
I'm converting a video to GIF file with ```ffmpeg```: ```ffmpeg \ -i input.flv \ -ss 00:00:00.000 \ -pix_fmt rgb24 \ -r 10 \ -s 320x240 \ -t 00:00:10.000 \ output.gif ``` It works great, but output gif file has a very low quality. Any ideas how can I improve quality of converted gif?
If you would prefer to avoid intermediate image files, the commands provided by LordNeckBeard can be piped between ```ffmpeg``` and ImageMagick's ```convert``` so that no intermediate files are required: ```ffmpeg -i input.flv -vf scale=320:-1 -r 10 -f image2pipe -vcodec ppm - | convert -delay 10 -loop 0 - output.gif ``` The ```-f image2pipe``` tells ffmpeg to split the video into images and make it suitable to be piped out, and ```-vcodec ppm``` specifies the output format to be ppm (for some reason if the format is png, either ```convert``` does not read all the images from the pipe, or ffmpeg does not output them all). The ```-``` for both commands specifies that a pipe will be used for output and input respectively. To optimize the result without saving a file, you can pipe the output from ```convert``` to a second ```convert``` command: ```ffmpeg -i input.flv -vf scale=320:-1 -r 10 -f image2pipe -vcodec ppm - | convert -delay 10 -loop 0 - gif:- | convert -layers Optimize - output.gif ``` The ```gif:-``` tells ```convert``` to pipe its output as gif formatted data and ```-layers Optimize``` tells the second ```convert``` to perform ```optimize-frame``` and ```optimize-transparancy``` methods (see the ImageMagick Introduction to Animation Optimization). Note that the output from the ```-layers Optimize``` may not always provide a smaller file size, so you may want to try converting to a gif without optimization first to be sure. Remember that during this whole process everything is in memory so you may need sufficient memory if the images are quite large.
Tor can only handle TCP connections, but DNS is a UDP protocol. How does Tor route DNS requests over its TCP based network? Why can the same approach not be used to route all UDP traffic over Tor?
Tor clients do not, in general, directly do DNS requests. When you open a connection through the tor network you usually ask your client (on its socks ports) to connect you to a hostname and port, say www.example.com:80. Your tor client, once it has created a circuit, will send that hostname and port to the exit node in its RELAY_BEGIN cell. The exit node will then do a DNS resolve and open a TCP connection to the target. Once that's established it will tell your client that the connection is open, and for informational purposes will also tell your client what address that hostname resolved to. Tor, in addition to that, has some sort of "remote DNS resolve" protocol built in. This support allows clients to query for certain resource types, like IPv4 or IPv6 addresses. Here too, the exit node does the actual DNS packet sending and receiving and just relays the answer to the client. No UDP packets are actually ever routed from the client. There's also a proposal to add more full featured DNS support to Tor. So far it hasn't been implemented. Tor Protocol Specification references * 6.2. Opening streams and transferring data * 6.4. Remote hostname lookup * Proposal 219 - Support for full DNS and DNSSEC resolution in Tor
Why does this throw ```NullPointerException``` ```public static void main(String[] args) throws Exception { Boolean b = true ? returnsNull() : false; // NPE on this line. System.out.println(b); } public static Boolean returnsNull() { return null; } ``` while this doesn't ```public static void main(String[] args) throws Exception { Boolean b = true ? null : false; System.out.println(b); // null } ``` ? The solution is by the way to replace ```false``` by ```Boolean.FALSE``` to avoid ```null``` being unboxed to ```boolean``` --which isn't possible. But that isn't the question. The question is why? Are there any references in JLS which confirms this behaviour, especially of the 2nd case?
The difference is that the explicit type of the ```returnsNull()``` method affects the static typing of the expressions at compile time: ```E1: `true ? returnsNull() : false` - boolean (auto-unboxing 2nd operand to boolean) E2: `true ? null : false` - Boolean (autoboxing of 3rd operand to Boolean) ``` See Java Language Specification, section 15.25 Conditional Operator ? : * For E1, the types of the 2nd and 3rd operands are ```Boolean``` and ```boolean``` respectively, so this clause applies: If one of the second and third operands is of type boolean and the type of the other is of type Boolean, then the type of the conditional expression is boolean. Since the type of the expression is ```boolean```, the 2nd operand must be coerced to ```boolean```. The compiler inserts auto-unboxing code to the 2nd operand (return value of ```returnsNull()```) to make it type ```boolean```. This of course causes the NPE from the ```null``` returned at run-time. * For E2, types of the 2nd and 3rd operands are `````` (not ```Boolean``` as in E1!) and ```boolean``` respectively, so no specific typing clause applies (go read 'em!), so the final "otherwise" clause applies: Otherwise, the second and third operands are of types S1 and S2 respectively. Let T1 be the type that results from applying boxing conversion to S1, and let T2 be the type that results from applying boxing conversion to S2. The type of the conditional expression is the result of applying capture conversion (§5.1.10) to lub(T1, T2) (§15.12.2.7). * S1 == `````` (see §4.1) * S2 == ```boolean``` * T1 == box(S1) == `````` (see last item in list of boxing conversions in §5.1.7) * T2 == box(S2) == `Boolean * lub(T1, T2) == ```Boolean``` So the type of the conditional expression is ```Boolean``` and the 3rd operand must be coerced to ```Boolean```. The compiler inserts auto-boxing code for the 3rd operand (```false```). The 2nd operand doesn't need the auto-unboxing as in ```E1```, so no auto-unboxing NPE when ```null``` is returned. This question needs a similar type analysis: Java conditional operator ?: result type
How do DOS games like DOOM benefit from a PCI graphics card?
DOOM itself doesn’t do anything special to benefit from PCI graphics cards. It runs faster with PCI graphics cards (and VLB, AGP, and PCI Express cards) than with ISA graphics cards because the supporting bus is faster, so reads from and writes to video memory take less time. PCI goes to great lengths to preserve backwards compatibility with ISA-based VGA, providing support for “VGA compatible” adapters so that they can appear in memory at the same locations and use the same I/O ports as ISA VGA cards. So accesses to the VGA registers and to the VGA buffer (at 0xA0000) go directly to the main PCI VGA compatible adapter in the system, with no change required in the operating system or programs running on it. (This is the reason why there’s a specific “VGA compatible controller” device type in PCI. Such shenanigans are impossible for other device types in PCI, which is why PCI sound cards have so much trouble providing compatibility with programs written for ISA sound cards.) A faster bus and/or faster video memory immediately leads to higher performance in video-intensive programs because software doesn’t need to be careful about how it accesses video memory (except on CGA, and on all platforms with vertical blank synchronisation if it cares about tearing). So ```REP MOVSW``` or ```REP MOVSD``` with no waiting in software, once the program decides to write a frame, is perfectly fine, and will go faster and faster as the underlying hardware improves. On platforms where this can’t work in hardware (e.g. on an 8088 with a VGA card), the hardware takes care of specifics — for example on an 8088 the bus unit will split up 16-bit accesses. Your question is specific to DOOM but other DOS games are in a similar situation. Later games tended to rely on VBE (often using UniVBE) to access video modes beyond those provided by VGA, but they mostly didn’t use anything beyond video-mode setup and framebuffer configuration (see also Were any DOS games (or software) known to use VBE/AF?), so improved video speed came mostly from bus speed increases, faster video memory, and speed increases in the cards themselves (which was already a factor in the ISA era, compare most Trident cards to Tseng cards for example). For an excellent explanation of the intricacies of VGA programming and its memory layout, see Fabien Sanglard’s Game Engine Black Book series. The DOOM update loop is shown on page 185 of the DOOM book; it doesn’t use any assembly language (unlike the renderer, see pp. 290 and following), but it does have one perhaps surprising feature given the 32-bit nature of the code: VGA updates are done 16 bits at a time. Section 2.3 of the same book, pp. 59 and following, describes some of the improvements to VGA adapters around the time DOOM was released, in particular the switch to the VESA Local Bus on 486s. The benchmark table on page 287 shows the importance of the bus.
I need to be able to open a document using its default application in Windows and Mac OS. Basically, I want to do the same thing that happens when you double-click on the document icon in Explorer or Finder. What is the best way to do this in Python?
```open``` and ```start``` are command-interpreter things for Mac OS/X and Windows respectively, to do this. To call them from Python, you can either use ```subprocess``` module or ```os.system()```. Here are considerations on which package to use: * You can call them via ```os.system```, which works, but... Escaping: ```os.system``` only works with filenames that don't have any spaces or other shell metacharacters in the pathname (e.g. ```A:\abc\def\a.txt```), or else these need to be escaped. There is ```shlex.quote``` for Unix-like systems, but nothing really standard for Windows. Maybe see also python, windows : parsing command lines with shlex * MacOS/X: ```os.system("open " + shlex.quote(filename))``` * Windows: ```os.system("start " + filename)``` where properly speaking ```filename``` should be escaped, too. * You can also call them via ```subprocess``` module, but... For Python 2.7 and newer, simply use ```subprocess.check_call(['open', filename]) ``` In Python 3.5+ you can equivalently use the slightly more complex but also somewhat more versatile ```subprocess.run(['open', filename], check=True) ``` If you need to be compatible all the way back to Python 2.4, you can use ```subprocess.call()``` and implement your own error checking: ```try: retcode = subprocess.call("open " + filename, shell=True) if retcode < 0: print >>sys.stderr, "Child was terminated by signal", -retcode else: print >>sys.stderr, "Child returned", retcode except OSError, e: print >>sys.stderr, "Execution failed:", e ``` Now, what are the advantages of using ```subprocess```? * Security: In theory, this is more secure, but in fact we're needing to execute a command line one way or the other; in either environment, we need the environment and services to interpret, get paths, and so forth. In neither case are we executing arbitrary text, so it doesn't have an inherent "but you can type ```'filename ; rm -rf /'```" problem, and if the file name can be corrupted, using ```subprocess.call``` gives us little additional protection. * Error handling: It doesn't actually give us any more error detection, we're still depending on the ```retcode``` in either case; but the behavior to explicitly raise an exception in the case of an error will certainly help you notice if there is a failure (though in some scenarios, a traceback might not at all be more helpful than simply ignoring the error). * Spawns a (non-blocking) subprocess: We don't need to wait for the child process, since we're by problem statement starting a separate process. To the objection "But ```subprocess``` is preferred." However, ```os.system()``` is not deprecated, and it's in some sense the simplest tool for this particular job. Conclusion: using ```os.system()``` is therefore also a correct answer. A marked disadvantage is that the Windows ```start``` command requires you to pass in ```shell=True``` which negates most of the benefits of using ```subprocess```.
Why does PRC devalue its currency on purpose, but Turkey is worried about the devaluation of its currency?
Trade surplus/deficit Devaluing one's currency means mostly one thing: It becomes more expensive to import products from abroad, while one's own products become comparably cheaper to buy on the world market. That means a country which exports lots of goods wants to devalue their currency while a country which imports lots of goods does not. In 2016, Turkey imported goods worth US $186 billion and exported goods worth US $156 billion. That means they had a trade deficit of 19%. However, China only imported goods worth US $1.23 trillion and exported goods worth US $2.27 trillion in 2016. That means they had a trade surplus of 84%. Which is why China wants to devalue their currency while Turkey does not. Debt management Another reason to devalue one's currency is that it reduces any debts denoted in that currency. If a country has a problem of too much public and private debt, then an easy way to get rid of it is to cause a hyperinflation. China happens to have a debt-to-gdp ratio of 47.6% while Turkey only has one of 28.3%. When you look at the private debt (debt of private citizens and companies in the country), you see the same picture. Private debit in Turkey was 170% of GDP, while China's is rumored to be over 300%. Which is why reducing debt through causing inflation seems more attractive to China than to Turkey. Foreign investor relations So why don't all countries get rid of their debt by adding a few zeroes to their bank notes? Because inflating your currency is a surefire way to drive away any foreign investors. Nobody will invest money into your country when that money might be worth nothing in a few years. Investors want stable currencies. Again, we observe the same difference in motivation between Turkey and China here. Turkey is actively inviting foreign investors, but China is quite reluctant to allow foreign economic influence in their country.
"I have a ```String[]``` with values like so: ```public static final String[] VALUES = new String[] {""AB"",""BC"",""CD"",""AE""}; ``` Given ```String s```, is there a good way of testing whether ```VALUES``` contains ```s```?" How do I determine whether an array contains a particular value in Java?
Four Different Ways to Check If an Array Contains a Value: * Using ```List```: ```public static boolean useList(String[] arr, String targetValue) { return Arrays.asList(arr).contains(targetValue); } ``` * Using ```Set```: ```public static boolean useSet(String[] arr, String targetValue) { Set set = new HashSet(Arrays.asList(arr)); return set.contains(targetValue); } ``` * Using a simple loop: ```public static boolean useLoop(String[] arr, String targetValue) { for (String s: arr) { if (s.equals(targetValue)) return true; } return false; } ``` * Using ```Arrays.binarySearch()```: The code below is wrong, it is listed here for completeness. ```binarySearch()``` can ONLY be used on sorted arrays. You will find the result is weird below. This is the best option when array is sorted. ```public static boolean binarySearch(String[] arr, String targetValue) { return Arrays.binarySearch(arr, targetValue) >= 0; } ``` Quick Example: ```String testValue="test"; String newValueNotInList="newValue"; String[] valueArray = { "this", "is", "java" , "test" }; Arrays.asList(valueArray).contains(testValue); // returns true Arrays.asList(valueArray).contains(newValueNotInList); // returns false ```
How can I copy a string (e.g "hello") to the System Clipboard in C#, so next time I press CTRL+V I'll get "hello"?
There are two classes that lives in different assemblies and different namespaces. * WinForms: use following namespace declaration, make sure ```Main``` is marked with ```[STAThread]``` attribute: ```using System.Windows.Forms; ``` * WPF: use following namespace declaration ```using System.Windows; ``` * console: add reference to ```System.Windows.Forms```, use following namespace declaration, make sure ```Main``` is marked with ```[STAThread]``` attribute. Step-by-step guide in another answer ```using System.Windows.Forms; ``` To copy an exact string (literal in this case): ```Clipboard.SetText("Hello, clipboard"); ``` To copy the contents of a textbox either use TextBox.Copy() or get text first and then set clipboard value: ```Clipboard.SetText(txtClipboard.Text); ``` See here for an example. Or... Official MSDN documentation or Here for WPF. Remarks: * Clipboard is desktop UI concept, trying to set it in server side code like ASP.Net will only set value on the server and has no impact on what user can see in they browser. While linked answer lets one to run Clipboard access code server side with ```SetApartmentState``` it is unlikely what you want to achieve. * If after following information in this question code still gets an exception see &quot;Current thread must be set to single thread apartment (STA)&quot; error in copy string to clipboard * This question/answer covers regular .NET, for .NET Core see - .Net Core - copy to clipboard?
I want to put a draft watermark using the below script but the problem is that the watermark don't come over the images and I want it to come over it. ```\usepackage{draftwatermark} \SetWatermarkText{DRAFT} \SetWatermarkScale{1} ```
The problem is that the ```draftwatermark``` places the material in the background, so other elements (for example, figures and listings) might cover the included material; to prevent this, instead of using the ```draftwatermark``` package, you can use the ```xwatermark``` package; the starred variant of ```\newwatermark``` places the material in the foreground which seems to be what you need. A little example: First, with the unstarred variant (material on the background, so a figure will be placed on top of it): ```\documentclass{article} \usepackage[printwatermark]{xwatermark} \usepackage{xcolor} \usepackage{graphicx} \usepackage{lipsum} \newwatermark[allpages,color=red!50,angle=45,scale=3,xpos=0,ypos=0]{DRAFT} \begin{document} \lipsum[1-2] \begin{figure}[!ht] \centering \includegraphics[width=3cm]{example-image-a} \end{figure} \lipsum[1-2] \end{document} ``` And now, with the starred variant (material on the foreground, so it will appear on top of figures): ```\documentclass{article} \usepackage[printwatermark]{xwatermark} \usepackage{xcolor} \usepackage{graphicx} \usepackage{lipsum} \newwatermark*[allpages,color=red!50,angle=45,scale=3,xpos=0,ypos=0]{DRAFT} \begin{document} \lipsum[1-2] \begin{figure}[!ht] \centering \includegraphics[width=3cm]{example-image-a} \end{figure} \lipsum[1-2] \end{document} ```
Understanding the Rails Authenticity Token
What is CSRF? The Authenticity Token is a countermeasure to Cross-Site Request Forgery (CSRF). What is CSRF, you ask? It's a way that an attacker can potentially hijack sessions without even knowing session tokens. Scenario: * Visit your bank's site, log in. * Then visit the attacker's site (e.g. sponsored ad from an untrusted organization). * Attacker's page includes form with same fields as the bank's "Transfer Funds" form. * Attacker knows your account info, and has pre-filled form fields to transfer money from your account to attacker's account. * Attacker's page includes Javascript that submits form to your bank. * When form gets submitted, browser includes your cookies for the bank site, including the session token. * Bank transfers money to attacker's account. * The form can be in an iframe that is invisible, so you never know the attack occurred. * This is called Cross-Site Request Forgery (CSRF). CSRF solution: * Server can mark forms that came from the server itself * Every form must contain an additional authentication token as a hidden field. * Token must be unpredictable (attacker can't guess it). * Server provides valid token in forms in its pages. * Server checks token when form posted, rejects forms without proper token. * Example token: session identifier encrypted with server secret key. * Rails automatically generates such tokens: see the authenticity_token input field in every form.
Why is FIFA against adding instant replay to the game?
There are a few fundamental considerations: * Uncertainty is a part of the game. The referee and linesmen are the arbiters of the action. Instant replay would limit their authority. * Football is global. Many places do not have access to the technology necessary to implement instant replay. * Football is a fast-paced game with few opportunities for stoppage. Instant replay would unnecessarily slow the pace. In 2008, FiFA President Sepp Blatter said: "Let it be as it is and let's leave [football] with errors. The television companies will have the right to say [the referee] was right or wrong, but still the referee makes the decision – a man, not a machine." Blatter and others at FIFA have repeatedly argued against using instant replay. But lately, FIFA has begun to come around on the idea. At FIFA's Congress in São Paulo prior to the 2014 World Cup, Blatter proposed allowing managers 2 challenges per game, much like the NFL handles challenges today. Although it's not quite "instant replay," in 2012 FIFA approved two different goal-line technologies to improve referee accuracy: "Hawk-Eye" -- which uses visual triangulation to determine ball location -- and "GoalRef" -- which uses a microchip in the ball and magnetic sensors within goalposts. (Many say FIFA approved the technologies in response to Frank Lampard's snubbed "goal" against Germany in the 2010 World Cup.) In 2013, FIFA announced it would use GoalControl, a German competitor to Hawk-Eye, at the Confederations Cup, basically a rehearsal for the World Cup. After a successful run at that tournament, FIFA announced it would implement GoalControl at the 2014 World Cup. The Guardian provides a pretty helpful FAQ on the technology. FIFA may choose to implement further changes to approved goal-line technology and referee rules when it meets again after the World Cup.
If we should encrypt the message rather than the method of transfer, why do we care about wifi security? Is this just security theatre?
Network encryption protects against different set of threats than application layer encryption like TLS. In particular, network encryption like Wifi encryption are primarily designed to protect from a local attacker from being able to watch network patterns (by recording who you're making connections with, and discovering what devices are on the local network), observing/tampering of low level messages like ARP/DNS, and protecting network broadcasts from devices that aren't supposed to be in the network, and from tampering or selective interference. TLS doesn't protect the low level TCP/IP packets, which leaks information like the IP address of the machine you're connecting with, and the TLS handshake also by design leaks a number of information about the connection like Server Name Indication (SNI) header. The side effect of needing to do all this is that Wifi hardware already need to have enough code and processing power to handle encryption, so it becomes easier to just encrypt all wifi packets rather than selectively figuring out what needs protection or not. This come also with the side benefit that unsecured HTTP connection will still be at least marginally protected, even if at least to protect users of the infrastructure from each other, but not from the infrastructure provider. Network encryption is designed to protect the network, not the service. Application encryption is designed to protect the connection to the service, but it doesn't protect the network. They complement each other, but neither completely makes the other unnecessary.
Applying filter in scipy.signal: Use lfilter or filtfilt?
* ```filtfilt``` is zero-phase filtering, which doesn't shift the signal as it filters. Since the phase is zero at all frequencies, it is also linear-phase. Filtering backwards in time requires you to predict the future, so it can't be used in "online" real-life applications, only for offline processing of recordings of signals. * ```lfilter``` is causal forward-in-time filtering only, similar to a real-life electronic filter. It can't be zero-phase. It can be linear-phase (symmetrical FIR), but usually isn't. Usually it adds different amounts of delay at different frequencies. An example and image should make it obvious. Although the magnitude of the frequency response of the filters is identical (top left and top right), the zero-phase lowpass lines up with the original signal, just without high frequency content, while the minimum phase filtering delays the signal in a causal way: ```from __future__ import division, print_function import numpy as np from numpy.random import randn from numpy.fft import rfft from scipy import signal import matplotlib.pyplot as plt b, a = signal.butter(4, 0.03, analog=False) # Show that frequency response is the same impulse = np.zeros(1000) impulse[500] = 1 # Applies filter forward and backward in time imp_ff = signal.filtfilt(b, a, impulse) # Applies filter forward in time twice (for same frequency response) imp_lf = signal.lfilter(b, a, signal.lfilter(b, a, impulse)) plt.subplot(2, 2, 1) plt.semilogx(20*np.log10(np.abs(rfft(imp_lf)))) plt.ylim(-100, 20) plt.grid(True, which='both') plt.title('lfilter') plt.subplot(2, 2, 2) plt.semilogx(20*np.log10(np.abs(rfft(imp_ff)))) plt.ylim(-100, 20) plt.grid(True, which='both') plt.title('filtfilt') sig = np.cumsum(randn(800)) # Brownian noise sig_ff = signal.filtfilt(b, a, sig) sig_lf = signal.lfilter(b, a, signal.lfilter(b, a, sig)) plt.subplot(2, 1, 2) plt.plot(sig, color='silver', label='Original') plt.plot(sig_ff, color='#3465a4', label='filtfilt') plt.plot(sig_lf, color='#cc0000', label='lfilter') plt.grid(True, which='both') plt.legend(loc="best") ```
What do different people in the department expect from a postdoc? By different people I mean the advisor, graduate students and PhD students. I know it mainly depends on the job description but there are few basic things that a postdoc must be expected to do. How aggressive (proactive) must one be? This question is important since a postdoc cannot just wait for the adviser to give him/her inputs. Rather the postdoc must take the project(s) as another PhD research of his own but be completely accountable to the adviser in terms of what he/she is doing and how is he/she doing that. The above are my thoughts. My question is divided into the following sub-parts: * What would you as a professor expect from your postdoc? * What preparation one must do to rise to the expected level? * Is the preparation merely restricted to having sound academic record and experience?
You'll very quickly learn that being an academic involves more than just writing research papers. Your time as a postdoc is when you can start learning about these other aspects, while building your own profile. A postdoc needs to do the following: * Build a publication record. This will involve both what you are paid to do and your own line of research. * Get involved with supervising students. Help with the PhDs in the lab, and get involved in supervising masters students. * Get involved with obtaining funding. This can either be by helping your employer or (ideally) obtaining your own funding. * Build an international reputation. * Start collaborating with external parties. * Gain some teaching experience. This is absolutely crucial if you want a faculty position. * Learn how to manage projects and a lab. This includes overseeing the progress of projects, allocating your time (and others), presenting results at meetings and writing deliverables. If you are in a lab setting, you will need to learn how to fix/calibrate/maintain critical equipment and software so that you can start your own lab some day, and you will need to become proficient in teaching more junior members on how to use that equipment. * Start to devise a strategic research plan. While it is fun to do opportunistic research, solving a problem that comes along or investigating any idea that pops into your head, a better long term strategy is to formulate an interesting long term research plan and follow it, building result upon result. Be as proactive as humanly possible, without being annoying. Talk to everyone in the department, especially people whose research interests are close to your. Go to conferences and sit down and work with interesting people (not necessarily the superstars).
Can someone explain to me what the ```contentInset``` property in a ```UIScrollView``` instance is used for? And maybe provide an example?
While jball's answer is an excellent description of content insets, it doesn't answer the question of when to use it. I'll borrow from his diagrams: ``` _|←_cW_→_|_↓_ | | --------------- |content| ↑ ↑ |content| contentInset.top cH |content| ↓ |content| contentInset.bottom |content| ↓ --------------- |content| -------------↑- ``` That's what you get when you do it, but the usefulness of it only shows when you scroll: ``` _|←_cW_→_|_↓_ |content| ← content is still visible --------------- |content| ↑ ↑ |content| contentInset.top cH |content| ↓ |content| contentInset.bottom |content| ↓ --------------- _|_______|___ ↑ ``` That top row of content will still be visible because it's still inside the frame of the scroll view. One way to think of the top offset is "how much to shift the content down the scroll view when we're scrolled all the way to the top" To see a place where this is actually used, look at the build-in Photos app on the iphone. The Navigation bar and status bar are transparent, and the contents of the scroll view are visible underneath. That's because the scroll view's frame extends out that far. But if it wasn't for the content inset, you would never be able to have the top of the content clear that transparent navigation bar when you go all the way to the top.
How is arc defined in TikZ?
```\draw (x,y) arc (start:stop:radius);``` draws an arc * with radius ```radius``` * starts from ```(x,y)``` * with center ```(x-r*cos(start), y-r*sin(start))``` and * ends at ```(x-r*cos(start)+r*cos(stop), y-r*sin(start)+r*sin(stop))```. For example, ``` \draw[red] (0,0) arc (30:60:3); ``` draws an arc * of radius ```3``` * starting from ```(0,0)``` * with center ```(0-3*cos(30),0-3*sin(30))``` and * ending at ```(0-3*cos(30)+3*cos(60),0-3*sin(30)+3*sin(60))```. ```\draw[blue] (0,0) -- ++(30+180:3) -- +(60:3); ``` draw a blue line to the arc to make a complete sector. Minimal Working Example ```\documentclass[tikz,border=12pt]{standalone} \begin{document} \foreach \start/\stop in {30/60,45/90,135/180,0/180,45/315} { \begin{tikzpicture} \draw[lightgray,ultra thin] (-6,-6) grid (6,6); \draw[red] (0,0) arc (\start:\stop:3); \draw[blue] (0,0) -- ++(\start+180:3) -- +(\stop:3); \node[anchor=north] at (0,6) {$(\start:\stop:3)$}; \end{tikzpicture} } \end{document} ```
How to connect mysql workbench to running mysql inside docker?
By default after deployment MySQL has following connection restrictions: ```mysql> select host, user from mysql.user; +-----------+---------------+ | host | user | +-----------+---------------+ | localhost | healthchecker | | localhost | mysql.session | | localhost | mysql.sys | | localhost | root | +-----------+---------------+ 4 rows in set (0.00 sec) ``` Apparently, for the security purposes you will not be able to connect to it outside of the docker image. If you need to change that to allow root to connect from any host (say, for development purposes), do: * Start your mysql image with all port mappings required: ```docker run -p 3306:3306 --name=mysql57 -d mysql/mysql-server:5.7``` or, if the complete port mapping is required: ```docker run -p 3306:3306 -p 33060:33060 --name=mysql57 -d mysql/mysql-server:5.7 ``` * If this is the fresh installation - grab the default password: ```docker logs mysql57 2>&1 | grep GENERATED``` * Connect using ```mysql``` client directly to the mysqld in docker: ```docker exec -it mysql57 mysql -uroot -p``` * If this is the fresh installation you will be asked to change the password using ```ALTER USER``` command. Do it. * Run SQL: ```update mysql.user set host = '%' where user='root';``` * Quit the ```mysql``` client. * Restart the container: ```docker restart mysql57``` Now you will be able to connect from MySQL Workbench to ```host: `0.0.0.0` port: `3306` ``` After all the changes the query will show: ```select host, user from mysql.user; +-----------+---------------+ | host | user | +-----------+---------------+ | % | root | | localhost | healthchecker | | localhost | mysql.session | | localhost | mysql.sys | +-----------+---------------+ ```
Can meat spoil outside the fridge if it's baked into bread as a filling?
There are two differences between your buns and a tin can. First, your buns were heated to a core temperature of under 100°C. Yes, your oven was probably set way higher, but the water content in your filling prevents it from getting hotter than boiling water. Commercial canning is done in the vicinity of 120-130°C, which is possible because the cans are cooked under pressure. So unlike in a can, most pathogens were destroyed, but not necessarily all of them. For human consumption, that’s perfectly fine as long as the remaining ones don’t get the time-temperature combo to regrow. Second, a bread dough may be dense (although the aim is usually something different), but by no means airtight. Interestingly, wrapping meat in dense dough was used as preservation method in medieval times - the “ancestor” of today’s pork pies and pastries. But while the hard flour crust (not intended to be eaten originally) did form a protective layer and usually extended the shelf life more or less, it was by no means food safe judged by modern standards - although some pies were stored for months. But your fluffy buns are truly not a protective layer. Which means you should refrigerate your buns, but also that you get to enjoy the whole dish.
I'm wondering how the XML Schema specification handles these cases: ``` ``` No maxOccurs given -> Is this the cardinality [1..1]? ``` ``` I suppose this is simply invalid? ``` ``` Is this the cardinality [0..2] or [1..2]? Is there an "official" definition on how the XML Schema spec handles these cases?
New, expanded answer to an old, commonly asked question... Default Values * Occurrence constraints ```minOccurs``` and ```maxOccurs``` default to ```1```. Common Cases Explained ``` ``` means ```A``` is required and must appear exactly once. ``` ``` means ```A``` is optional and may appear at most once. ``` ``` means ```A``` is required and may repeat an unlimited number of times. ``` ``` means ```A``` is optional and may repeat an unlimited number of times. See Also * W3C XML Schema Part 0: Primer In general, an element is required to appear when the value of minOccurs is 1 or more. The maximum number of times an element may appear is determined by the value of a maxOccurs attribute in its declaration. This value may be a positive integer such as 41, or the term unbounded to indicate there is no maximum number of occurrences. The default value for both the minOccurs and the maxOccurs attributes is 1. Thus, when an element such as comment is declared without a maxOccurs attribute, the element may not occur more than once. Be sure that if you specify a value for only the minOccurs attribute, it is less than or equal to the default value of maxOccurs, i.e. it is 0 or 1. Similarly, if you specify a value for only the maxOccurs attribute, it must be greater than or equal to the default value of minOccurs, i.e. 1 or more. If both attributes are omitted, the element must appear exactly once. * W3C XML Schema Part 1: Structures Second Edition ```<element maxOccurs = (nonNegativeInteger | unbounded) : 1 minOccurs = nonNegativeInteger : 1 > ```
Were there any flying dinosaurs?
Birds are both flying dinosaurs and flying reptiles. Yes, that's potentially confusing. To understand the apparent contradiction, you have to understand how modern classification of organisms works (phylogenetic systematics). Under the old (Linnean) classification system, Reptilia (reptiles) was an order and Aves (birds) was a separate order. Phylogenetic systematics, which has completely replaced the Linnean system, views all organisms as interrelated in a nested set of monophyletic groups (clades). It's like a set of venn diagrams, where all organisms fall into a giant circle and then successively smaller circles classify more and more specific groups. The clade Reptilia includes snakes, lizards, crocodiles, and lots of extinct groups, including dinosaurs. So all dinosaurs are reptiles. The clade Dinosauria includes all the extinct dinosaurs (Stegosaurus, Triceratops, sauropods, etc.), including theropod dinosaurs, which include well known dinosaurs like Tyrannosaurus and Allosaurus. Based on a mountain on anatomical evidence, including lots of transitional fossils, living birds are a sub-group of theropod dinosaurs. So all birds (Aves) are theropod dinosaurs (Dinosauria: Theropoda). All dinosaurs are reptiles. Therefore, birds are dinosaurs and reptiles. They are just more closely related to dinosaurs than to other reptiles. The tricky part is that most people have an intuitive idea of what "reptiles" and "dinosaurs" are. To a systematist, whose job it is to classify organisms, these terms don't mean the same thing as they do to most people. Systematists think about groups like Reptilia and Dinosauria and how those groups are related to one another. So they have no problem saying that birds are dinosaurs and reptiles, because birds are nested within both of those groups. A few words about pterosaurs Along with birds and bats, pterosaurs are the other clade of vertebrates capable of powered, flapping flight. Pterosaurs fall within Reptilia (and Diapsida and Archosauria) along with Dinosauria, which includes birds. There are a lot of other extinct lineages in the tree that are not shown, e.g., ornithodirans that are not dinosaurs and not pterosaurs. Pterosaurs and birds share anatomical features that all reptiles, diapsids, archosaurs, and ornithodirans have, which is how we know that they are more closely related to each other than to other groups, like crocodiles. But their flight structures evolved independently and are anatomically distinct fro one another. So pterosaurs are flying reptiles but not flying dinosaurs. These images might help you understand the above explanation.
I see a low use of Mathematica in Kaggle competitions. Why would one use the Wolfram Language versus R, Python, or Julia for machine learning? Besides prettier plots and the Manipulate function, do we have something that is useful for ML that other languages are lacking?
Mathematica doesn't have the depth of algorithm support that is present in R or Python. Julia has much more limited algorithm support but does exhibit a good turn of speed. The few algorithms that Mathematica does support are not particularly well exposed for the type of tweaking needed to win Kaggle competitions. Mathematica, as of version 10, supports the following classifiers: "LogisticRegression", "Markov", "NaiveBayes", "NearestNeighbors", "NeuralNetwork", "RandomForest", "SupportVectorMachine". Whilst it does offer one ensemble method, RandomForest, it lacks both Bagging and any flavour of boosting, such as Adaboost. These latter general ensemble methods allow you to leverage the power of a base classifier, either built-in or, of greater utility when exploring performance improvements, of your own design. This limits significantly the potential for creating novel methods within the existing machine learning framework. Mathematica's strengths lay with it's expressive, compact, language, strong visualisation capabilities and easy parallelization. These make it very efficient to explore new strategies and combinations of ML algorithms you may already have implemented. A less often mentioned benefit is that use of Mathematica in a functional programming style tends to lead to fewer bugs in the final code.
I'm using wp_nav_menu and am trying to create custom output for the sub-level drop downs. I came across the "items_wrap" argument but there's really not much information as to what it is, how it works, and what kind of things can be done with it. What exactly is "%1$s" and "%2$s"? (Can anyone explain it in layman's terms?)
The parameter ```'items_wrap'``` for ```wp_nav_menu()``` defaults to: ```'%3$s' ``` This a a template that is parsed with ```sprintf()```: ```$nav_menu .= sprintf( $args->items_wrap , esc_attr( $wrap_id ) // %1$s , esc_attr( $wrap_class ) // %2$s , $items // %3$s ); ``` The numbered placeholders – ```%1$s```, ```%2$s```, ```%3$s``` – refer to the arguments after the first argument in ```sprintf()```. The percent sign marks a placeholder, the number the position and the type ```s``` means it should be treated as a string. Do not change the type unless you really know what you do. :) * ```$wrap_id``` is the parameter ```'menu_id'``` if you have it set, else it is ```'menu-' . $menu->slug```. * ```$wrap_class``` is the parameter ```'menu_class'``` if you have it set, else it is empty. * ```$items``` is a string of the inner content of the menu. Let’s say you don’t need a ```class```. Just omit the second string: ```wp_nav_menu( array( 'items_wrap' => '%3$s' ) ); ``` If you don’t need the ```class``` and the ```id```, and you want another container (because you used a custom walker): ```wp_nav_menu( array( 'items_wrap' => '%3$s' ) ); ``` The main point is: You have to use the numbers for the replacements given in ```wp_nav_menu()```. ```%3$s``` is always the list of items.
Did two dissenting Supreme Court justices agree that Trump was "absolutely immune" to the Manhattan DA's subpoena?
If you are interested in the gory details, please see the full decision in Trump v. Vance. The first half of the linked document contains the Court's majority opinion and the concurring opinion of Justices Kavanaugh and Gorsuch, followed by the separate dissenting opinions of Justices Thomas and Alito. Based on a quick read, it's apparent that Justice Thomas agrees with the general court's opinion that a sitting President &quot;is not entitled to absolute immunity from issuance of [a] subpoena&quot;. Thomas dissents on the grounds that the President &quot;may be entitled to relief against [a subpoena's] enforcement&quot; based on his special status as president. Thomas argues (agreeing with the president) that the case should be vacated and returned to the lower court, so that the President can argue that his duties to the nation take up all of his time and attention and he thus deserves relief from the subpoena. Justice Alito makes a stronger dissent. While he agrees that a sitting President is not absolutely immune from a state subpoena, he argues that such a subpoena should not be enforced unless it meets a stringent legal test, such that: * It does not interfere with the President's execution of his duties of office, and * It carries a weight of urgency — e.g., subpoenaing information related to suspected treason — as a guarantee it is not merely issued to harass. In the absence of those conditions, in Alito's opinion, the President is only subject to the constitutional process of impeachment and trial in Congress. So no, neither dissenting Justice suggests that the President is absolutely immune from this kind of subpoena. Instead, they are concerned that the issuance of such subpoenas might negatively impact on the President's ability to perform the duties of the office, and argue that the President might legitimately be granted varying degrees of relief from such legal actions at a court's discretion.
Just curious, given how heavily from Tolkien D&D drew, and the fact that games like Wizardry used Hobbits, is there a good design reason why Gygax and company used Halflings (a term that also appears in Tolkien) vice Hobbits as the term for our little friends?
Halflings were originally called hobbits prior to a legal challenge. According to Gary Gygax himself, it was due to a legal claim on &quot;hobbit&quot; by a company who purchased the merchandising rights on Tolkien's works in 1976: TSR was served with papers threatening damages to the tune of half a mil by the Saul Zantes (sp?) division of Elan Merchandising on behalf of the tolkien Estate. The main objection was to the boardgame we were publishing, The Battle of Five Armies. The author of that game had given us a letter from his attorney claiming the work was grandfathered because it was published after the copyrights for JRRT's works had lapsed and before any renewals were made. The action also demanded we remove balrog, dragon, dwarf, elf, ent, goblin, hobbit, orc, and warg from the D&D game. Although only balrog and warg were unique names we agreed to hobbit as well, kept the rest, of course. The boardgame was dumped, and thus the suit was settled out of court at that. Halflings were originally called &quot;hobbits&quot; in the Dungeons & Dragons box set first released in 1974. Later printings changed this to &quot;halfling&quot;. According to The Acaeum, this change occurred between the fifth printing (Dec 1975 - Apr 1976) and sixth printing (1977), with the six printing being marked the Original Collector's Edition. However, Tim Kask has said that box sets were generally thrown together with whichever printings of the books were on hand, so the distinctions between printings are inexact. The Acaeum notes at least one box set shipped having the revised booklets but no Original Collector's Edition mark. Due to an oversight, a single reference to &quot;hobbit&quot; remained on page 6 of Men & Magic, which was fixed in the 2013 Deluxe reprint and PDF copies. According to Wikipedia, J.R.R. Tolkien sold the film, stage, and merchandising rights to The Hobbit and Lord of the Rings to United Artists in 1968, who sold them in turn to Saul Zaentz in 1976. Zaents would go on to produce the 1978 Lord of the Rings animated movie.
My USB drive used to be originally 8GB when I bought it. I'm trying to reformatted in Windows 7 by right clicking on the drive and selecting ```Format...```. But the capacity only shows 250MB. Is there something I can do to get the original size back? Maybe it got partitioned in a weird way? The flash drive is a SanDisk Cruzer Micro 8GB.
The command line procedure is not simple, but it is the most likely thing to work. When re-formatting the "drive" you're actually only formatting a partition on the drive. You need to use the diskpart utility to remove the partitions and create 1 single partition covering the full volume. ```diskpart``` can be a bit dangerous, because if you pick the wrong disk or partition, you can remove data or partitions that are extremely, EXTREMELY important and lose all data on your machine. Proceed with extreme caution! Open up a command prompt as administrator (open the start menu, type ```cmd``` and press Enter.) Type ```diskpart``` and press Enter. You'll end up with a new prompt that looks like this: ```DISKPART> ``` Type ```list disk ``` and you'll get a listing of all drives on your machine. Type ```select disk # ``` to select a disk, where ```#``` is the number of the disk Windows screw-balled. Usually, the device is disk 1, but it's always best to make sure. Then type ```list partition ``` to get a listing of all partitions on the disk. If you're sure you have the right disk/partition, you can then repeat typing ```select partition # delete partition ``` until all partitions are removed from that drive (you may need to type ```delete partition override``` for protected partitions). Once the drive is empty, exit diskpart and remove the drive. Wait at least 5 minutes, then re-insert the drive. DO NOT CLICK FORMAT – this will most likely re-create the problem. Instead, enter diskpart again, and select the disk. Then type ```create partition primary ``` Once you have created the partition, exit ```diskpart``` and, in the command promt, type ```diskmgmt.msc ``` This will provide a reliable way to create a FAT32 partition. On the drive you would like to format (NEVER TOUCH DISK 0!), right click and select ```format```. The ```allocation unit size``` option should be default, and the ```File System``` option should be set to ```FAT32```. The format may take a while, depending on the disk size, be patient. This should fix partition troubles on any readable USB flash drive.
I am a Tor developer. I understand that the .onion address is a public key of sorts, but not much more than that (I can vaguely guess, though). When nobody knows the IP of the .onion address, how do requests reach it? Are they bounced between nodes in the P2P network till someone decrypts it with the corresponding private key?
Up to at least October 2013 the hidden services work like this: * A hidden service calculates its key pair (private and public key, asymmetric encryption). * Then the hidden service picks some relays as its introduction points. * It tells its public key to those introduction points over Tor circuits. * After that the hidden-service creates a hidden service descriptor, containing its public key and what its introduction points are. * The hidden service signs the hidden service descriptor with its private key. * It then uploads the hidden service descriptor to a distributed hash table (DHT). * Clients learn the .onion address from a hidden service out-of-band. (e.g. public website) (A $hash.onion is a 16 character name derived from the service's public key.) * After retrieving the .onion address the client connects to the DHT and asks for that $hash. * If it exists the client learns about the hidden service's public key and its introduction points. * The client picks a relay at random to build a circuit to it, to tell it a one-time secret. The picked relay acts as rendezvous point. * The client creates a introduce message, containing the address of the rendezvous point and the one-time secret, before encrypting the message with the hidden service's public key. * The client sends its message over a Tor circuit to one of the introduction points, demanding it to be forwarded to the hidden service. * The hidden service decrypts the introduce message with its private key to learn about the rendezvous point and the one-time secret. * The hidden service creates a rendezvous message, containing the one-time secret and sends it over a circuit to the rendezvous point. * The rendezvous point tells the client that a connection was established. * Client and hidden service talk to each other over this rendezvous point. All traffic is end-to-end encrypted and the rendezvous point just relays it back and forth. Note that each of them, client and hidden service, build a circuit to the rendezvous point; at three hops per circuit this makes six hops in total.
Is there a phrase that means "too important" and "attracting too much attention"?
There is the term "overdominant": From Collins dictionary: >overdominant [adjective] excessively dominant To begin with, the design aspect is the most striking and arguably remains overdominant. [Times, Sunday Times (2010)] Here is an example: > [Steps must be taken to prevent any one] religious or ethnic group being overdominant. Otherwise, we will see a repeat of the unfortunate history of much of the 20th Century... Other possible terms that have similar meaning include "overpowered", "obtrusive" and "preponderant".
I am wondering how to generate uniformly distributed points on the surface of the 3-d unit sphere? Also after generating those points, what is the best way to visualize and check whether they are truly uniform on the surface $x^2+y^2+z^2=1$?
A standard method is to generate three standard normals and construct a unit vector from them. That is, when $X_i \sim N(0,1)$ and $\lambda^2 = X_1^2 + X_2^2 + X_3^2$, then $(X_1/\lambda, X_2/\lambda, X_3/\lambda)$ is uniformly distributed on the sphere. This method works well for $d$-dimensional spheres, too. In 3D you can use rejection sampling: draw $X_i$ from a uniform$[-1,1]$ distribution until the length of $(X_1, X_2, X_3)$ is less than or equal to 1, then--just as with the preceding method--normalize the vector to unit length. The expected number of trials per spherical point equals $2^3/(4 \pi / 3)$ = 1.91. In higher dimensions the expected number of trials gets so large this rapidly becomes impracticable. There are many ways to check uniformity. A neat way, although somewhat computationally intensive, is with Ripley's K function. The expected number of points within (3D Euclidean) distance $\rho$ of any location on the sphere is proportional to the area of the sphere within distance $\rho$, which equals $\pi\rho^2$. By computing all interpoint distances you can compare the data to this ideal. General principles of constructing statistical graphics suggest a good way to make the comparison is to plot variance-stabilized residuals $e_i(d_{[i]} - e_i)$ against $i = 1, 2, \ldots, n(n-1)/2=m$ where $d_{[i]}$ is the $i^\text{th}$ smallest of the mutual distances and $e_i = 2\sqrt{i/m}$. The plot should be close to zero.
In Shutter Island, at the end of the movie Teddy had a chat with Chuck, in that scene Teddy told to Chuck as, Which would be worse: To live as a monster, or to die as a good man? What's the implicit meaning of this dialogue? Who's the monster as Teddy mentioned? And, who's a good man?
To Live as a Monster If he accepts his guilt and becomes sane he will become the Monster. His delusions are his brains way of removing this guilt and hiding the fact that he ignored his family, did not act on his wife's mental illness, allowed her to murder their children and then murdered her. By accepting what the doctors are telling him he will need to go on living in the knowledge that he allowed terrible things to happen and did terrible things. The doctors will be able to treat him without a lobotomy but he will be fully aware of the crimes he committed. To die as a good man In his delusion he is a good man. He truly believes that he is on the side of law and order and that he is doing right. If he chooses to continue to believe this he will be lobotomised and will no longer have relevant brain function to question what he did or did not do. The death is not literal as the other answer suggests. It is about the fact that if he continues to believe he is this good man he will be lobotomised and effectively "die" believing in this. He will not die in a literal sense until later, but he will do so in the belief he was a good man. What is most exciting and cathartic about this decision is that this appears to be a moment of lucidity where he understands what has happened and is not in thrall of his delusions. He at this point of lucidity makes the decision that he can not live with his crimes and would prefer to lie to his doctor as he knows this will result in his lobotomy. By making the statement to his doctor he makes him aware of this also and by virtue of this you could also argue that he is being a good man by electing to be punished as well as the belief in his delusion that he is good.
To set the minimal distance between flexbox items I'm using ```margin: 0 5px``` on ```.item``` and ```margin: 0 -5px``` on container. For me it seems like a hack, but I can't find any better way to do this. ```#box { display: flex; width: 100px; margin: 0 -5px; } .item { background: gray; width: 50px; height: 50px; margin: 0 5px; }``` ``` ```
This solution will work for all cases even if there are multiple rows or any number of elements. But the count of the section should be same you want 4 in first row and 3 is second row it won't work that way the space for the 4th content will be blank the container won't fill. We are using ```display: grid;``` and its properties. ```#box { display: grid; width: 100px; grid-gap: 5px; /* Space between items */ grid-template-columns: repeat(4,1fr); /* Decide the number of columns(4) and size(1fr | 1 Fraction | you can use pixels and other values also) */ } .item { background: gray; width: 100%; /* width is not necessary only added this to understand that width works as 100% to the grid template allocated space **DEFAULT WIDTH WILL BE 100%** */ height: 50px; }``` ``` ``` The Downside of this method is in Mobile Opera Mini will not be supported and in PC this works only after IE10. Note for complete browser compatability including IE11 please use Autoprefixer OLD ANSWER Don't think of it as an old solution, it's still one of the best if you only want single row of elements and it will work with all the browsers. This method is used by CSS sibling combination, so you can manipulate it many other ways also, but if your combination is wrong it may cause issues also. ```.item+.item{ margin-left: 5px; } ``` The below code will do the trick. In this method, there is no need to give ```margin: 0 -5px;``` to the ```#box``` wrapper. A working sample for you: ```#box { display: flex; width: 100px; } .item { background: gray; width: 22px; height: 50px; } .item+.item{ margin-left: 5px; }``` ``` ```
I have been puzzling over where to put the submit button, on the left or the right. In researching, I noticed that many sites put buttons on the bottom right in dialogue boxes, and on the bottom left in forms. It makes sense: in a dialogue box it seems to denote finality, being in the endpoint of the window for left–right readers; in a form, the bottom right could be in a different position relative to the rest of the form if the window is resized. It seems to be a convention, but should the OK/Cancel buttons be aligned right or centered? Should the OK/Cancel buttons be aligned right or centered?
Where to put the submit button should be decided in order to meet user expectations, it was best to put the button in the place that users expect to find it in the context of the form or dialogue they are using and with regard to the window size. Forms tend to be left justified while the browser window can leave a ton of white space to fill up a large monitor (especially in full-screen mode). Since the users' eyes never leave the left portion of the window, we place the button on the bottom left. This is especially important for forms that use the field name above the field, with most fields lying flush left on the form (as opposed to fields to the right of their names). Small Dialogue & Modal Windows are fixed width and tend to be small. Most contain simple phrases or questions, read right to left: having a button on the bottom right feels like both the most progressive position and the final resting place for the eye. Were the modal window large enough to contain a long form, we would probably follow the first principal for forms. In the end, the heuristic is this: * Large Windows & Forms get the button on the bottom left. * Small Windows & Dialogues get the button on the bottom right. Note the buttons on stackexchange sites: * Post Your Answer button at the bottom-left of the longer form * Add Comment button to the right of a small field Furthermore, with mobile-first responsive being the new law of the land, the button placement varies even more based on context and user expectation. Sometimes, it's in the middle, too! We're now starting to just put buttons on the left for even small forms if they're inline … and more forms are showing up inline through javascript.
Is it at all possible to update object's properties with ```setState```? Something like: ```this.state = { jasper: { name: 'jasper', age: 28 }, } ``` I have tried: ```this.setState({jasper.name: 'someOtherName'}); ``` and this: ```this.setState({jasper: {name: 'someothername'}}) ``` The first results in a syntax error and the second just does nothing. Any ideas?
There are multiple ways of doing this, since state update is a async operation, so to update the state object, we need to use updater function with ```setState```. 1- Simplest one: First create a copy of ```jasper``` then do the changes in that: ```this.setState(prevState => { let jasper = Object.assign({}, prevState.jasper); // creating copy of state variable jasper jasper.name = 'someothername'; // update the name property, assign a new value return { jasper }; // return new object jasper object }) ``` Instead of using ```Object.assign``` we can also write it like this: ```let jasper = { ...prevState.jasper }; ``` 2- Using spread syntax: ```this.setState(prevState => ({ jasper: { // object that we want to update ...prevState.jasper, // keep all other key-value pairs name: 'something' // update the value of specific key } })) ``` Note: ```Object.assign``` and ```Spread Operator``` creates only shallow copy, so if you have defined nested object or array of objects, you need a different approach. Updating nested state object: Assume you have defined state as: ```this.state = { food: { sandwich: { capsicum: true, crackers: true, mayonnaise: true }, pizza: { jalapeno: true, extraCheese: false } } } ``` To update extraCheese of pizza object: ```this.setState(prevState => ({ food: { ...prevState.food, // copy all other key-value pairs of food object pizza: { // specific object of food object ...prevState.food.pizza, // copy all pizza key-value pairs extraCheese: true // update value of specific key } } })) ``` Updating array of objects: Lets assume you have a todo app, and you are managing the data in this form: ```this.state = { todoItems: [ { name: 'Learn React Basics', status: 'pending' }, { name: 'Check Codebase', status: 'pending' } ] } ``` To update the status of any todo object, run a map on the array and check for some unique value of each object, in case of ```condition=true```, return the new object with updated value, else same object. ```let key = 2; this.setState(prevState => ({ todoItems: prevState.todoItems.map( el => el.key === key? { ...el, status: 'done' }: el ) })) ``` Suggestion: If object doesn't have a unique value, then use array index.
What is the difference between Non-Player Characters (NPCs) and bots in video games?
The key distinction is that a Bot represents an automated player; an NPC, by contrast, isn't playing the game at all. In general, an NPC is a part of the game; a placed object which is designed by the creator and exists to interact with the player. Examples would include vendors, quest givers, or enemies. In some games, (particularly RPG's), the term is also used to refer to characters under the control of, but not generated by the player. They are often distinguished by having distinct personalities and dialog, whereas a ""Player Character"" is meant as more of an extension of the player themselves. Think of the companion party members in the Mass Effect series for an example. A Bot, by contrast, is essentially a player of the game controlled by a computer. This can be populated within a single instance, as a feature in some games (i.e. AI opponents in a normally multiplayer game), or, in some cases, actually represents a separate instance of the application running on a networked computer and being controlled by some manner of AI script (as is common in many MMO's, much to the dismay of the communities playing the game). The term 'Bot' is also often used to refer to software used to enhance or replace the skills of a human player of the game; for example, an 'Aim-Bot' that handles targeting, or a 'Farming Bot' in an MMO that performs tedious or menial tasks. Such bots are usually (though not always), considered cheating and a violation of the Terms of Service of the game in question.
Is there anything like ```static class``` in java? What is the meaning of such a class. Do all the methods of the static class need to be ```static``` too? Is it required the other way round, that if a class contains all the static methods, shall the class be static too? What are static classes good for?
Java has static nested classes but it sounds like you're looking for a top-level static class. Java has no way of making a top-level class static but you can simulate a static class like this: * Declare your class ```final``` - Prevents extension of the class since extending a static class makes no sense * Make the constructor ```private``` - Prevents instantiation by client code as it makes no sense to instantiate a static class * Make all the members and functions of the class ```static``` - Since the class cannot be instantiated no instance methods can be called or instance fields accessed * Note that the compiler will not prevent you from declaring an instance (non-static) member. The issue will only show up if you attempt to call the instance member Simple example per suggestions from above: ```public class TestMyStaticClass { public static void main(String []args){ MyStaticClass.setMyStaticMember(5); System.out.println("Static value: " + MyStaticClass.getMyStaticMember()); System.out.println("Value squared: " + MyStaticClass.squareMyStaticMember()); // MyStaticClass x = new MyStaticClass(); // results in compile time error } } // A top-level Java class mimicking static class behavior public final class MyStaticClass { private MyStaticClass () { // private constructor myStaticMember = 1; } private static int myStaticMember; public static void setMyStaticMember(int val) { myStaticMember = val; } public static int getMyStaticMember() { return myStaticMember; } public static int squareMyStaticMember() { return myStaticMember * myStaticMember; } } ``` What good are static classes? A good use of a static class is in defining one-off, utility and/or library classes where instantiation would not make sense. A great example is the Math class that contains some mathematical constants such as PI and E and simply provides mathematical calculations. Requiring instantiation in such a case would be unnecessary and confusing. See the ```Math``` class and source code. Notice that it is ```final``` and all of its members are ```static```. If Java allowed top-level classes to be declared ```static``` then the Math class would indeed be static.
The Episode IV-VI movies never mention the Emperor's name. In Episodes I-III, we can guess that Darth Sidious will be the emperor, but what about Chancellor Palpatine? If the audience didn't know that he was Sidious, the impact of the reveal would be far different than if they did. But I did. In all the novels and comics that came out after "Return of the Jedi", the Emperor's name was stated plainly: Palpatine. So when I saw the prologue movies, for the life of me I couldn't figure out: was I supposed to know that Palpatine was the villain? Maybe the filmmakers figured that most of the moviegoing public never got into the Expanded Universe. But they had to know that the hardcore fans would know. Or maybe when you watched the movie, even if you hadn't heard of Palpatine, it was supposed to be obvious? What was the intent?
Palpatine's name was first given in the prologue to Alan Dean Foster's novelization of Star Wars (it was credited to Lucas, but he didn't write it), which came out in November 1976, six months before the May 25, 1977 release of the actual film. So Palpatine being the Emperor was literally known before the public ever saw a Star Wars movie. It was, in fact, one of the very first things people could find out about the Star Wars universe. The point of the films wasn't to conceal the fact Palpatine would end up the Emperor (or was Darth Sidious), it was to show that he was a masterful chessmaster who conned everyone, and that in large part it was the good guys responsible for his rise because of their own blindness. Amidala initiated the vote that removed his predecessor. Jar-Jar initiated the vote that gave him emergency powers. The Jedi Council allowed him to operate under their noses. Anakin never suspected he was being manipulated until too late, and so on. Just as the trilogy was meant as a tragedy showing Anakin Skywalker's rise and fall, it was an additional tragedy in that the person responsible for the whole mess was standing right there the entire time, in the case of the celebration at the end of The Phantom Menace quite literally.
So, students in Gryffindor are supposed to represent bravery. How does Neville represent bravery, to the point in being accepted into the house. I've always thought of his strongest traits being things like loyalty, willingness to work hard, etc, and these things would tend to put him in Hufflepuff.
First of all, in the first 4 years, it isn't really shown that Neville is NOT brave - the only thing he's really afraid of is his Grandmother and maybe Snape during Potions. With good reason. :) You may be confusing a lack of confidence/assertiveness with not being brave, but they are not the same (for a good in-universe illustration of the opposite, think Prof. Lockhart). First four books, he's clumsy, and is not yet showing any magical talent. Starting with the fifth year, Neville is shown to have been changed, and repeatedly proves his bravery and willingness to fight. NOTE: He first shows bravery in the First Year (see System's great answer for details), but the real Gryffindor-y Neville emerges in the Fifth year. There's another instance of him showing a Gryffindor quality - more specifically, integrity. He argued with the Hat to sort him into Hufflepuff (src: Pottermore), because he felt he wasn't brave enough to be a Gryffindor. Fifth year * He joins DA * He shows marked and significant improvement in his magical abilities while in DA * He voluntarily joins the DA members who accompany Harry to Ministry of Magic battle in the end of OoP, even arguing with Harry about it: Neville: &quot;We were all in the D.A. together. It was all supposed to be about fighting You-Know-Who, wasn't it? And this is the first chance we've had to do something real — or was that all just a game or something?&quot; Harry: &quot;No — of course it wasn't —&quot; Neville: &quot;Then we should come too. We want to help.&quot; * During the battle at the Ministry, he refused to leave as per Harry's suggestion after Dolohov broke Neville's nose and wand. * When being threatened and tortured by Death Eaters, he told Harry not to give them the Prophecy Sixth year * participated in the Battle of the Astronomy Tower. Along with Luna Lovegood, he was the only member of Dumbledore's Army to reply to the summons via the coins. Seventh year * Neville got in trouble with the Carrows for refusing to practise the Cruciatus Curse on other students as a method of punishment, as well as for standing up against their bigotry and cruelty. * along with Ginny and Luna, restarted Dumbledore's Army. * attempted to steal Godric Gryffindor's Sword from Snape's office * Neville was eventually left alone to lead the rebellion efforts (Luna and Ginny were not in Hogwarts anymore). When avoiding the Death Eaters at one point, Neville stumbled into the Room of Requirement, which he was able to turn into a hiding place for the D.A., and to connect to the Hog's Head in order to get food from Aberforth Dumbledore. By May, most of the D.A. had taken to living there. * During the first round of battle, Neville used various plants to attack Death Eaters, and helped transport the injured and dead when a temporary cease-fire was called. * When the Death Eaters approached with a &quot;dead&quot; Harry, Neville stood up in defiance of Voldemort. He was subsequently forced to wear the Sorting Hat as it burned because he refused to join Voldemort. Fortunately, due to Harry's sacrifice, Neville was able to shrug off the Full Body-Bind Curse. * Because of his tremendous bravery shown on the battlefield, Neville was able to pull Godric Gryffindor's Sword from the burning hat, in the process proving himself a true Gryffindor, something that was doubted constantly throughout due to his apparently weak-willed, shy, and bumbling nature. In a single stroke, he killed Nagini, destroying Voldemort's last remaining Horcrux. * Neville subsequently teamed up with Ron Weasley as the defenders of Hogwarts and Death Eaters were forced into the Great Hall and defeated Fenrir Greyback. All in all, pretty convincing evidence of someone's bravery.
This claim was made popular by being said in the movie The Social Network. It exactly says: > Did you know there are more people with genius IQs living in China than there are people of any kind living in the United States?
This claim can actually be tested very easily. Others have done it, e.g. Brian Dickerson: The perils of repeating political nonsense and came to the conclusion that the claim was wrong. You just need the chance a random person from a large group has a genius level IQ, then multiply it with the number of people in China and compare the result with the number of people in the USA. The IQ follows a Gaussian distribution where 100 is the mean by definition and a standard deviation (SD) of 15 (after Wechsler) or 16 (after Stanford-Binet). The rarity of a particular IQ can be calculated easily and are listed by the IQ Comparison Site. These numbers give the percentage of people with an IQ equal or lower than the given IQ and the rarity of this occurring. The main question actually is what an genius level IQ is. There is no definite answer. According to the IQ Comparison Site, it is 140 or higher ("Genius or near genius") while another source states it as at least 160. The rarity of such an IQ is 1/261 (with a SD of 15) or 1/161 (SD=16) for an IQ of 140 and 1/31,560 (SD=15) or 1/11,307 (SD=16) for an IQ of 160 according to Wikipedia. The population of USA for 2012 is about 313,221,000 according to the U.S. Census Bureau. The population of China for 2011 is about 1,370,537,000. Taking the lowest rarity of 1/161 from above then there are about 1,370,537,000/161 = about 8,513,000 geniuses in China, which is significantly less then the 313,221,000 Americans. If you take the 15 SD value of 1/261 then you get only about 5,251,000 Chinese geniuses. With the 160 IQ points, which are more realistic to indicate a real genius, the numbers are even smaller (about 43,400 or 12,100). Note that 1,370,537,000/313,221,000 = 4.375, so in order for this claim to be true actually one of every four (or say five) Chinese would need to be a Genius. Even without the numbers above, it can be easily understood that this is not the case. Conclusion: This claim is wrong according to the definition and probabilities of the IQ. Supplement: It has been pointed out, that there are published research results showing that China and other Asian countries have a higher average IQ of about 106 (or even as high as 115) as the normed average of 100. This would increase the number of geniuses in China: The above factor of 1/161 would drop to about 1/60 or, for a Chinese average of 115, even to about 1/17. These numbers can be easily calculated using the standard deviation, e.g. using MS Excel's function ```NORM.DIST(140, 106, 16, TRUE)```. However, both these factors are not in any way close to the US/Chinese population ratio of about 1/4.375, so the original conclusion still holds.
I am trying to get my program to print out ```"banana"``` from the dictionary. What would be the simplest way to do this? This is my dictionary: ```prices = { "banana" : 4, "apple" : 2, "orange" : 1.5, "pear" : 3 } ```
As of Python 3.7, insertion order is maintained, so you don't need an ```OrderedDict``` here. You can use the below approaches with a normal ```dict``` Changed in version 3.7: Dictionary order is guaranteed to be insertion order. This behavior was an implementation detail of CPython from 3.6. source Python 3.6 and earlier* If you are talking about a regular ```dict```, then the &quot;first key&quot; doesn't mean anything. The keys are not ordered in any way you can depend on. If you iterate over your ```dict``` you will likely not get ```&quot;banana&quot;``` as the first thing you see. If you need to keep things in order, then you have to use an ```OrderedDict``` and not just a plain dictionary. ```import collections prices = collections.OrderedDict([ (&quot;banana&quot;, 4), (&quot;apple&quot;, 2), (&quot;orange&quot;, 1.5), (&quot;pear&quot;, 3), ]) ``` If you then wanted to see all the keys in order you could do so by iterating through it ```for k in prices: print(k) ``` You could, alternatively put all of the keys into a list and then work with that ```keys = list(prices) print(keys[0]) # will print &quot;banana&quot; ``` A faster way to get the first element without creating a list would be to call ```next``` on the iterator. This doesn't generalize nicely when trying to get the ```nth``` element though ```>>> next(iter(prices)) 'banana' ``` * CPython had guaranteed insertion order as an implementation detail in 3.6.
Different coffee packets advertise different amounts of 'Robusta' and 'Arabica'? What do these terms refer to, and how does it affect the taste of the coffee?
* One reason that the taste isn't as good for Robusta is that it has more caffeine compared to Arabica. Which may sound like a positive thing but caffeine carries a bitter taste which makes it an unpleasant drink. In fact the Robusta bean has 2.7% caffeine content, almost double the 1.5% of Arabica. * Arabica contains almost 60% more lipids and almost twice the concentration of sugar than Robusta. This factor also probably has a big impact on why we prefer the taste of Arabica. * From a price perspective, green beans of Robusta is about half the price of Arabica green beans on the commodity market. * Robusta is easier to tend to on the farm, has a higher yield and is less sensitive to insects - the extra caffeine is a chemical defense for the coffee seed as the quantity in the Robusta is toxic to bugs. All of these factors help bring up the supply and lower the input costs for farmers to produce. With this more attractive price point, a lot of roasters back in the day would add Robusta to their blend in an attempt to reduce their costs and increase their profits. When coffee was initially sold in the 1900s the quality of coffee slowly and slowly deteriorated in an effort for companies to squeeze the most profit. Where you’ll find it: Nowadays, it’s not often you’ll find Robusta in a coffee blends or in coffee shop. If you’re drinking instant coffee? Well, that’s probably all Robusta… but you probably don’t care very much about taste. In your espresso blend? That’s a mixed bag. Literally. Oddly enough, Robusta is still widely used as part of espresso blends – specifically Italian style blends. It is said to help improve the crema. One thing to note is despite the association with Arabica of being higher quality, and Robusta as being lower quality, it’s not always the case. Top notch specialty Robusta coffee will usually taste as good as or better than low end Arabica. However, high end Robusta isn’t widely used or available. Rather, Robusta is usually used as a filler or cost reducer. * Robusta beans are much more circular, whereas Arabica are more oval. * Chlorogenic acid is a significant antioxidant and an insect deterrent. Robusta is 7-10% CGA and Arabica has 5.5-8% CGA.
So whenever we want to shoot our flash before taking a photo. we have to charge it first. What is the point of the charging our flashes? Aren't their power directly supplied by the battery of our camera? Please answer for the built in flash on the 2000D and the traditional hot shoe Xenon flashes. Perhaps these hot shoe xenon flashes have their own batteries charged by the slow hot shoe port. Who knows?
The peak power at work when a flash is being discharged is extreme. Example: a classic Metz 45CT (a large but still handheld unit) on full manual power delivers around 90 watt-seconds of electrical output to the flash tube in 1/300s. That means there are 27000 watts at work for a short time. A 27000 watt lightbulb (BTW, your flash is much brighter than that - more efficient!) would need the ampacity of around eight european household sockets (230V, fused at 13 or 16 amps) to operate, since it would draw around 120 ampere from them. At the voltage levels xenon flash tubes typically operate at, around 80 amperes will flow; if you wanted to pull that energy "live" from a 5-6V battery, you'd need to pull around 5000 amperes AND instantaneously convert them to around 80 amperes at high voltage. Batteries that could deliver 5000 amps - while not wasting most of the power as heat generated across their internal resistance - for a short duration and live certainly exist - you are looking at starter batteries for big lorries, which are rather inconvenient to lug around. Also, a 5000 ampere current pulse is quite a magnetic nuisance if there is anything either ferromagnetic or intended as an electrical conductor near the conductors used. Your average "big" speedlite, btw, will be around half the power described here (but might in some cases reach the same or higher peak currents in order to discharge even faster), an in-camera flash will be a fraction of these numbers - but still inconvenient to build any other way. If you need a short, massive current pulse, the best energy source available in engineering is a previously charged capacitor (metal-paper or electrolytic type, not dual-layer "supercap"). This energy storage device is large for its storage capacity if you compare it to a battery - but able to respond far quicker to high current demand, since a) there is no chemical energy conversion involved in its operation, b) the relevant current path only involves metallic, very conductive parts instead of ionic conductors (aka electrolytes. An electrolytic capacitor, btw, does use its electrolyte for chemical self-upkeep, not for chemical energy storage or electrical connectivity). Also, since the charge in a a capacitor is limited, it allows portioning total energy to what the flashlamp can safely take. This allows a flash in manual mode to just completely discharge the capacitor until it is nearly empty (when the remaining charge can only deliver voltage below the quench voltage of the flashlamp) without complex control circuitry - and at the same time gives you a safety fallback when working with dynamically controlled power levels (telecomputer or TTL mode), leaving no way for catastrophic circuit failure in combination with several kilowatts of constant power available turning into a massive safety hazard. A handheld-sized efficient electrical near point light source with 27000W input, driven constantly, would first severely damage your eyes and then self destroy violently (think of a welding arc - dangerously bright, and it melts metal).
What are some strategies to maintain morale and productivity after massive layoffs? I am not in a managerial role, just a lead role, and am asking for myself and my fellow employees.
The situation you're describing is tough. Layoffs have a very real impact on both the individuals that are let go and those that remain. I'm sorry you're experiencing this. Here are some things to consider that may help you and your colleagues cope with the added stress and emotions following a layoff: * Acknowledge the layoff and the feelings of your colleagues. Avoiding the topic can extend negative feelings and disenfranchise those most impacted. You should find an opportunity to connect with your colleagues for an honest conversation about your feelings following the layoff. Perhaps reach out to hold a number of 1-on-1 conversations, or gather your team for an off-site lunch and prompt the discussion. * Acknowledge that everyone will be impacted differently. Some of your colleagues will feel totally okay and ready to get back to work. Others will feel anxious and worried in a way that prevents them from performing the same way they did before the layoff. There is no right or "professional" reaction to a layoff. Be open to the feelings and reactions of all of your colleagues equally. * Create practical solutions to new processes and responsibilities. If your team now has a greater workload, be a generator of solutions. Try out ideas for making processes in your team more efficient and predictable. * Create transparency about the state of the business and potential future staff changes. Layoffs are a clear indication of business trouble. Facilitate sharing facts about the state of the business and actively work to eliminate rumors. Additionally, layoffs will likely cause shifts in responsibility as roles are consolidated or reorganized. Make clear who has specific responsibilities both inside and outside of your team. Actively eliminate any sources of uncertainty and anxiety that you can. * Be a role model. Don't participate in gossip or complaining about the layoff. Don't disparage management or other colleagues in casual conversation. Be a model for professionalism and caring. * Maintain work standards and a caring meritocracy. A layoff isn't an excuse for allowing work quality to decline. Additionally, differences in productivity and quality between team members should be consistently and fairly addressed. If a team member is underperforming following the layoff, provide direct feedback and ask what you can do to help.
Could you please clearly explain what is the difference between correlation and convolution that is done by a filter on an image? I mean in terms of signal processing definition I know that convolution describes the output of an LTI system, that is if an LTI system produces an output due to convolution with an input system then the output signal can be described as the result of convolution of the input signal and the impulse response of the LTI system. As for the correlation, it describes the similarities between to signals. But how does convolution and correlation effect on a image and how different are they in terms of effects? Thanks
Convolution is correlation with the filter rotated 180 degrees. This makes no difference, if the filter is symmetric, like a Gaussian, or a Laplacian. But it makes a whole lot of difference, when the filter is not symmetric, like a derivative. The reason we need convolution is that it is associative, while correlation, in general, is not. To see why this is true, remember that convolution is multiplication in the frequency domain, which is obviously associative. On the other hand, correlation in the frequency domain is multiplication by the complex conjugate, which is not associative. The associativity of convolution is what allows you to "pre-convolve" the filters, so that you only need to convolve the image with a single filter. For example, let's say you have an image $f$, which you need to convolve with $g$ and then with $h$. $f * g * h = f * (g * h)$. That means you can convolve $g$ and $h$ first into a single filter, and then convolve $f$ with it. This is useful, if you need to convolve many images with $g$ and $h$. You can pre-compute $k = g * h$, and then reuse $k$ multple times. So if you are doing template matching, i. e. looking for a single template, correlation is sufficient. But if you need to use multiple filters in succession, and you need to perform this operation on multiple images, it makes sense to convolve the multiple filters into a single filter ahead of time.
24601 has developed into being an iconic part of both the Les Miserables book and musical. Was that number special to him, or was it simply a random number he chose (I doubt it)?
Yes: it corresponds to the date of Hugo's conception. This is part of a pattern of similarities between the character of Jean Valjean and the author himself: both are of similar age, have similar habits and similarly austere lifestyles, and even share the same dreams. This is according to David Bellos's The Novel of the Century: The Extraordinary Adventure of Les Misérables, which concludes Part Three with: But Hugo put in a secret sign to remind himself and maybe those who knew him well that there were deep links of identity between the dutiful and persistent ex-convict and himself. Hugo was born on 26 February 1802, but because he was a slightly premature baby, he always believed he had been conceived on 24 June 1801. Valjean's prison number on his first incarceration at Toulon is 24601. -- p. 162 (emphasis mine) As a bonus, Valjean's second prisoner number was apparently also chosen for its special significance to Hugo: it refers to the month of his daughter Léopoldine's death. From footnote 46 in Kathryn Grossman's Figuring Transcendence in Les Miserables: Hugo's Romantic Sublime: Gaudon demonstrates that this image, which represents genius in one of the poet's earliest carnets (8 July 1820), is a sign of his &quot;deep identification&quot; with Valjean (Temps 547). As further evidence that the hero is an alter ego, Gohin cites the two numbers assigned to him in prison. The first, 24601, refers to the supposed date of Hugo's conception (24 June 1801), while the second, 9430, alludes to Léopoldine's death in September 1843 (&quot;Une histoire&quot; 47; see also 52). -- p. 165 (emphasis mine)
Why does Michael Crichton use US Customary measurements in hard sci-fi?
Crichton used both imperial and metric, depending on the context. In the course of one paragraph in The Sphere, he managed to use both! > "Pacific coral grows two-and-a-half centimeters a year, and the object-- whatever it is-- is covered in about five meters of coral. That's a lot of coral. Of course, coral doesn't grow at a depth of a thousand feet, which means that the present shelf collapsed to a lower depth at some point in the past." When the character (Barnes, a Navy captain) is talking about precise measurements, he uses metric. When he's being more general, he uses imperial. The main character Norman (a psychologist, not exactly the most mathematically intensive field) uses imperial when thinking to himself. > He climbed up through the submarine and into a round steel cylinder approximately eight feet in diameter. But later, when the astrophysicist Ted is giving officialish measurements the titular sphere, he uses metric: > "This object is a burnished sphere approximately ten meters in a diameter, no solid, and composed of a dense metal alloy." So the short answer is that Crichton is an American writing American characters for a predominantly American audience. He uses imperial units for clarity, but metric when it would realistically be used.
How can horns, most of which have only three buttons, play all their notes?
Put as simply as possible, horns are tubes. Blowing in special ways makes certain notes sound from those tubes. By changing one's embouchure, those notes start at a fundamental, then gradually go up in harmonics. The first notes (in key C) would be C, G, C, E, G.Those notes are the ones we hear when a bugle is played - Reveille, Last Post, etc. Bugles only play the harmonic series of notes, and can't play the ones in between. Read on. On a trumpet, for starters, there are three valves. One drops any open note played by one semitone, another by two semitones, and the other by three semitones. So using a combination of valves, you can lower any open note by up to six semitones. Let's take the first G note. To get F♯, press the semitone valve. To get F, press the tone valve. To get E, press two valves to drop a tone and a half. (there's one valve alone that can do this). To play E♭, press the two valves that drop two tones. To get D, press the two valves to drop two and a half tones. And to get C♯, press all three. That's the more complicated bit, as between the open notes, there's more semitones than anywhere else further up in pitch. Notice that between G and the next C, there are only two tones. So at this point, not so many notes are needed, so the valve pressing is more simple. Next, between that C and the E, there's even fewer, so again, not so many valve changes are needed. Now, onto trombone. There are actually valve trombones, which work the same as trumpets, etc., but for the standard trombone, imagine those extra lengths of tube brought into play by pressing valves are now a single continuum of tubing, operated by the slide. At various places along that slide, there are all the notes found similarly to pressing valves. There's also loads of extra notes that are going to be out of tune!
I am a big fan of worldbuilding. A common sight in science fiction is that aliens pretend to be human (For example in Third Rock from the Sun). Obviously if the aliens are advanced enough to disguise themselves as another species, there are much easier, simpler and less expensive methods to destroy humanity, so why else would an advanced alien civilization waste time, energy and resources to disguise themselves as humans? What possible scientific, cultural or commercial use could such an expensive procedure have?
Aliens are alien, without a common background their motives may be incomprehensible. If we assume that these aliens are Hollywood aliens (ie humans with odd-looking rubber bits stuck on their faces) then there are all of the reasons that humans from one culture spend time in another culture and try and learn to fit in: * Anthropology; studying how a different culture has developed to better understand the developmental processes that influenced your own. Iain M. Banks wrote Inversions (two anthropologists from the Culture investigating a Renaissance-era world) and The State of the Art (a Culture Contact team on Earth ca 1970) in this vein. * Tourism; experiencing a culture that is vastly different from your previous experiences. * Reality TV; Bear Grylls. * Method Acting; preparing for a role in their own entertainment channels that involves playing the part of a member of an Information Age society. * Challenge; because they can. * Hermitage; there are people here on Earth who prefer to step away from the rat race and all the newfangled gadgets and live as their ancestors did, but usually not all the way back to stone tools. Selecting a developing world and fitting in gives them access to a level of technology between their home culture and being trapped on a desert island. * Camouflage; they are being sought by members of their home culture and it's easier to hide and survive amongst us than in their own milieu. There are a lot of examples of this in fiction already: For Richer or Poorer, Men in Black II and it's analogous to fleeing the law and retiring to a country without an extradition treaty. * Crash Landing, or a failure that prevents them from going home; if they came on an FTL ship that doesn't have FTL communications they may be waiting a long time for spare parts or updated navigational maps, or if they brought Gilligan who proceeded to ruin all of their plans to return home, or they may have arrived on a slower-than-light colony ship and would prefer to stay here and fit in amongst us rather than try and find another prospective colony. * Uplift; meddling to steer us onto the "right" path of development and prevent us from immolating ourselves (or vice versa if your species doesn't like the competition).
I've taken a look at the list of surveys taken on scala-lang.org and noticed a curious question: "Can you name all the uses of “_”?". Can you? If yes, please do so here. Explanatory examples are appreciated.
The following is an explanation of the uses of the underscore is Scala _ [underscore] magic. Examples: ``` def matchTest(x: Int): String = x match { case 1 => "one" case 2 => "two" case _ => "anything other than one and two" } expr match { case List(1,_,_) => " a list with three element and the first element is 1" case List(_*) => " a list with zero or more elements " case Map[_,_] => " matches a map with any key type and any value type " case _ => } List(1,2,3,4,5).foreach(print(_)) // Doing the same without underscore: List(1,2,3,4,5).foreach( a => print(a)) ``` In Scala, ```_``` acts similar to ```*``` in Java while importing packages. ```// Imports all the classes in the package matching import scala.util.matching._ // Imports all the members of the object Fun (static import in Java). import com.test.Fun._ // Imports all the members of the object Fun but renames Foo to Bar import com.test.Fun.{ Foo => Bar , _ } // Imports all the members except Foo. To exclude a member rename it to _ import com.test.Fun.{ Foo => _ , _ } ``` In Scala, a getter and setter will be implicitly defined for all non-private vars in a object. The getter name is same as the variable name and ```_=``` is added for the setter name. ```class Test { private var a = 0 def age = a def age_=(n:Int) = { require(n>0) a = n } } ``` Usage: ```val t = new Test t.age = 5 println(t.age) ``` If you try to assign a function to a new variable, the function will be invoked and the result will be assigned to the variable. This confusion occurs due to the optional braces for method invocation. We should use _ after the function name to assign it to another variable. ```class Test { def fun = { // Some code } val funLike = fun _ } ```
My university usually asks that we book a flight via a travel agent, but the prices he gives me are about $50 higher than the prices I can get by online booking in the flight company's website. Why would a company want me to book a flight via a travel agent if it is more expensive?
There are several reasons why such internal policies exist: * Your institution may get a discount on certain services of the travel agent if it buys enough from the agent * By having a contract with a reasonably-priced travel agent, they make sure that no employee books the flight with a very pricey agent or with a travel agent that happens to be a relative of the traveller * The travel agency offers easy methods to verify expense information and thus may lower the workload of your local administrative personnel. This especially holds if the payment is routed directly from the institution to the travel agent, which also makes sure that the flyer does not get credit card bonus points for the booking. * Your institution may have an agreement with the travel agent that they manually check if members of your institution are not unnecessarily booking expensive booking classes (in order to get more airline bonus miles) * Some insurances that your institution bought may only work if the ticket is bought directly from the institution and not by the flyer, and they elected the agent to handle such bookings. Which of these reasons is the one why this policy exists can only be answered by the responsible employees of your institution.
I have a page where a scroll bar containing table rows with divs in them is dynamically generated from the database. Each table row acts like a link, sort of like you'd see on a YouTube playlist next to the video player. When a user visits the page, the option they are on is supposed to go to the top of the scrolling div. This functionality is working. The issue is that it goes just a tad too far. Like the option they are on is about 10px too high. So, the page is visited, the url is used to identify which option was selected and then scrolls that option to the top of the scrolling div. Note: This is not the scroll bar for the window, it is a div with a scrollbar. I am using this code to make it move the selected option to the top of the div: ```var pathArray = window.location.pathname.split( '/' ); var el = document.getElementById(pathArray[5]); el.scrollIntoView(true); ``` It moves it to the top of the div but about 10 pixels too far up. how to fix that?
CSS ```scroll-margin``` and ```scroll-padding``` You might want to have a look at new CSS properties ```scroll-padding``` and ```scroll-margin```. You can use ```scroll-padding``` for the scrolling container (```html``` in this case), and ```scroll-margin``` for the element within the container. For your example, you would want to add ```scroll-margin-top``` for the element that you want to scroll into view, like this: ```.example { scroll-margin-top: 10px; } ``` This affects ```scrollIntoView``` code, like this code: ```const el = document.querySelector(&quot;.example&quot;); el.scrollIntoView({block: &quot;start&quot;, behavior: &quot;smooth&quot;}); ``` This will cause the viewport to scroll to align the top border of the viewport with the top border of the element, but with 10px of additional space. In other words, these properties of the element are taken into account: * ```padding-top``` * ```border-top``` * ```scroll-margin-top``` * (and not ```margin-top```) In addition, if the ```html``` element has ```scroll-padding-top``` set, then that is taken into account too. If you're using a framework like Vue, you might want to make sure that all changes to the DOM are finished before running `scrollIntoView` by using something like `Vue.nextTick(() => el.scrollIntoView())`
Suppose I have the geographic coordinates of &quot;Saratoga, California, USA&quot; as ```Latitude: 37°15.8298′ N Longitude: 122° 1.3806′ W ``` I know from here that in the case of latitude ```1° ≈ 69 miles``` and that longitude varies: ```1° longitude = cosine (latitude) * length of degree (miles) at Equator. ``` How many miles is 1° longitude at ```longitude: 122°1.3806′ W```?
It doesn't matter at what longitude you are. What matters is what latitude you are. Length of ```1 degree of Longitude``` = ```cosine (latitude in radians) * length of degree (miles) at equator```. Convert your latitude into decimal degrees ~ 37.26383 Convert your decimal degrees into radians ~ 0.65038 Take the cosine of the value in radians ~ 0.79585 1 degree of Longitude = ~0.79585 * 69.172 = ~ 55.051 miles More useful information from the about.com website: Degrees of latitude are parallel so the distance between each degree remains almost constant but since degrees of longitude are farthest apart at the equator and converge at the poles, their distance varies greatly. Each degree of latitude is approximately 69 miles (111 kilometers) apart. The range varies (due to the earth's slightly ellipsoid shape) from 68.703 miles (110.567 km) at the equator to 69.407 (111.699 km) at the poles. This is convenient because each minute (1/60th of a degree) is approximately one [nautical] mile. A degree of longitude is widest at the equator at 69.172 miles (111.321) and gradually shrinks to zero at the poles. At 40° north or south the distance between a degree of longitude is 53 miles (85 km) Note that the original site (about.com) erroneously omitted the &quot;nautical&quot; qualifier.
I have read numerous times that some Norse warriors, upon death, would go in Fólkvangr, while some others would go to Valhalla. How was it decided which warrior would go to which place? Why did the need to have many "paradises" (whatever you many call it) exist? Citing Wikipedia: > In Norse mythology, Fólkvangr (Old Norse "field of the host" or "people-field" or "army-field") is a meadow or field ruled over by the goddess Freyja where half of those that die in combat go upon death, while the other half go to the god Odin in Valhalla.
The Norse mythological texts record three primary places where the dead were perceived to go: Helheim (Old Norse Helheimr, “the home of the goddess Hel“), Valhalla (Old Norse Valhöll, “the hall of the fallen”), and Folkvang (Old Norse Fólkvangr, “the field of the people” or “the field of warriors”). But they're indistinguishable and don't have any major differences between them. Valhalla is presided over by Odin, and to gain entrance to it, one must be chosen by him and his valkyries, the “choosers of the fallen.” Similarily, entrance to Folkvang is dependent upon being selected by Freya. Valhalla is often depicted as a realm where distinguished warriors engage in a continuous battle, and just such a place is described, in important early sources, as being located beneath the ground – and, intriguingly, without the name “Valhalla” or a cognate anywhere in the account. source: Ellis, Hilda Roderick. 1968. The Road to Hel: A Study of the Conception of the Dead in Old Norse Literature. p. 85-86. * Folkvang is the ninth, and there Freyia arranges the choice of seats in the hall; half the slain she chooses every day, and half Odin owns. source: 1996 Carolyne Larrington in The Poetic Edda “Grimnir’s Sayings” The only difference that is pointed out, is in the way that the dead are chosen to stay. Odin chooses for Valhalla, while Freya chooses for Folkvang. Coming to the second part of the question: And why did the need to have many "paradises" (whatever you many call it) exist? Hel is a place where all humans have to go after their death: “For there is a time when every man shall journey hence to Hel." Fáfnismál 10 So before the dead finally reach Hel, Odin and Freyja select the ones who are worthy of living in Valhalla and Folkvang. Therefore, * Valhalla receives distinguished warriors. * Folkvangr receives the rest of the warriors. * Hel receives the rest of the dead. source: Norse-Mythology.org
I noticed that there is a binary executable ```/bin/echo``` on my Ubuntu MATE 17.04 system. I thought, that's odd, because ```$ type echo echo is a shell builtin``` Cursory testing suggests that ```/bin/echo``` does the same sort of thing as the Bash builtin ```echo```: ```$ /bin/echo foo foo $ /bin/echo $USER zanna ``` So, why is there another version of ```echo``` separate from the Bash program, and why or when would I want to use it?
If you open up a ```bash``` prompt and type in an ```echo``` command, that uses a shell builtin rather than running ```/bin/echo```. The reasons it is still important for ```/bin/echo``` to exist are: * You're not always using a shell. Under a variety of circumstances, you run an executable directly and not through a shell. * At least in theory, some shells don't have an ```echo``` builtin. This is not actually required. To expand on #1, suppose you wanted to move all the regular files whose names started with ```abc``` anywhere in ```src``` to ```dest```. There are several ways to do that but one of them is: ```find src -name 'abc*' -type f -exec mv -nv {} dest/ \; ``` But suppose, rather than just running that, you want to see every command that will be run first. Well, then you can prepend ```echo``` to the command, just as you might in other contexts: ```find src -name 'abc*' -type f -exec echo mv -nv {} dest/ \; ``` But ```find``` doesn't use a shell. That runs ```/bin/echo```. Besides ```find``` with ```-exec``` or ```-execdir```, the ```/bin/echo``` executable will be called by other programs that themselves run programs but not through a shell. This happens with the ```xargs``` command (which is related to ```find```), as well as in a number of other contexts, such as the ```Exec=``` line of a ```.desktop``` file. Another example is when you run ```sudo echo```, which can be handy for testing if ```sudo``` is working. Similarly, some shells have a ```printf``` builtin but ```/usr/bin/printf``` also exists. A less common possible reason you might deliberately use ```/bin/echo``` is if you were relying on the differences between it and the ```echo``` command provided by your shell. ```man echo``` documents ```/bin/echo```; ```help echo``` in ```bash``` documents the ```bash``` builtin. ```echo``` is not very portable, because different implementations--both across operating systems and across shells on the same operating system--support different options (e.g., ```-e```) and differ in their treatment of backslashes. Of course, it's better to avoid relying on such details, and use ```printf``` instead, which is far more portable. In ```bash```, you can make the ```type``` builtin show ```/bin/echo``` as well--assuming ```/bin``` is in your ```$PATH``` as it always should be--by passing it the ```-a``` flag: ```$ type -a echo echo is a shell builtin echo is /bin/echo ```
what's the difference between JavaScript objects, classes and functions?
As you must already be aware by now there are no classes in JavaScript. Instead functions in JavaScript may be made to behave like constructors by preceding a function call with the ```new``` keyword. This is known as the constructor pattern. In JavaScript everything is an object except for the primitive data types (boolean, number and string), and ```undefined```. On the other hand ```null``` is actually an object reference even though you may at first believe otherwise. This is the reason ```typeof null``` returns ```&quot;object&quot;```. Functions in JavaScript are similar to functables in Lua (i.e. they are callable objects). Hence a function can be used in place of an object. Similarly arrays are also objects in JavaScript. On the other hand objects can be thought of as associative arrays. The most important point however is that there are no classes in JavaScript because JavaScript is a prototypal object oriented language. This means that objects in JavaScript directly inherit from other objects. Hence we don't need classes. All we need is a way to create and extend objects.
Why is Gaia operating around Earth orbit? Why not send it to Neptune's orbit?
Well, you thought about the spatial aspect of a parallax measurement, but not about the temporal one. Gaia's intention is to measure 3D positions as well as 3D velocities. For the distance, you need accurate parallactic measurement, which come in with your orbital period. For a typical Gaia-star with several measurement per year, you'll get 5 values of the parallax after 5 years of time, which you then average. If you'd send Gaia towards Neptune (besides the fact that no one has ever sent an orbiter, to say nothing of a L2 mission that far out) that has a period of 168 years, then after 5 years you'd get... 5/168 th of one paralactic measurement. It simply couldn't achieve its science goals if put around the L2 behind Neptune. Also no one on this planet has any experience in putting something into a outer system L2 point. This is different than putting it into Earth's L2, because reaching the L2 around one of the giants has vast and very precise $\Delta v$ requirements. This would be a massive technological leap, and things don't work that way in space. Small, incremental technological steps are required in an anyways unfriendly environment, to make sure everything works properly and no millions of dollars have been wasted. Compare that to Gaia's predecessor, the Hipparcos satellite, which was parked in geostationary orbit. Now you could still say, why not use Jupiter hypothetically anyways. Well, the orbital period there is still 11 years, and Jupiter's L2 still suffers from the intense radiation environment that is provided by Jupiter's magnetosphere. This would lead to rapid degradation of the CCDs used for scanning across the sky.
I have a string representing a unix timestamp (i.e. &quot;1284101485&quot;) in Python, and I'd like to convert it to a readable date. When I use ```time.strftime```, I get a ```TypeError```: ```>>>import time >>>print time.strftime(&quot;%B %d %Y&quot;, &quot;1284101485&quot;) Traceback (most recent call last): File &quot;&quot;, line 1, in TypeError: argument must be 9-item sequence, not str ```
There are two parts here: * Convert the unix timestamp ("seconds since epoch") to the local time * Display the local time in the desired format. A portable way to get the local time that works even if the local time zone had a different utc offset in the past and python has no access to the tz database is to use a ```pytz``` timezone: ```#!/usr/bin/env python from datetime import datetime import tzlocal # $ pip install tzlocal unix_timestamp = float("1284101485") local_timezone = tzlocal.get_localzone() # get pytz timezone local_time = datetime.fromtimestamp(unix_timestamp, local_timezone) ``` To display it, you could use any time format that is supported by your system e.g.: ```print(local_time.strftime("%Y-%m-%d %H:%M:%S.%f%z (%Z)")) print(local_time.strftime("%B %d %Y")) # print date in your format ``` If you do not need a local time, to get a readable UTC time instead: ```utc_time = datetime.utcfromtimestamp(unix_timestamp) print(utc_time.strftime("%Y-%m-%d %H:%M:%S.%f+00:00 (UTC)")) ``` If you don't care about the timezone issues that might affect what date is returned or if python has access to the tz database on your system: ```local_time = datetime.fromtimestamp(unix_timestamp) print(local_time.strftime("%Y-%m-%d %H:%M:%S.%f")) ``` On Python 3, you could get a timezone-aware datetime using only stdlib (the UTC offset may be wrong if python has no access to the tz database on your system e.g., on Windows): ```#!/usr/bin/env python3 from datetime import datetime, timezone utc_time = datetime.fromtimestamp(unix_timestamp, timezone.utc) local_time = utc_time.astimezone() print(local_time.strftime("%Y-%m-%d %H:%M:%S.%f%z (%Z)")) ``` Functions from the ```time``` module are thin wrappers around the corresponding C API and therefore they may be less portable than the corresponding ```datetime``` methods otherwise you could use them too: ```#!/usr/bin/env python import time unix_timestamp = int("1284101485") utc_time = time.gmtime(unix_timestamp) local_time = time.localtime(unix_timestamp) print(time.strftime("%Y-%m-%d %H:%M:%S", local_time)) print(time.strftime("%Y-%m-%d %H:%M:%S+00:00 (UTC)", utc_time)) ```
In Django, the convention is to put all of your static files (i.e css, js) specific to your app into a folder called static. So the structure would look like this: ```mysite/ manage.py mysite/ --> (settings.py, etc) myapp/ --> (models.py, views.py, etc) static/ ``` In ```mysite/settings.py``` I have: ```STATIC_ROOT = 'staticfiles' ``` So when I run the command: ```python manage.py collectstatic ``` It creates a folder called ```staticfiles``` at the root level (so same directory as ```myapp/```) What's the point of this? Isn't it just creating a copy of all my static files?
## Collect static files from multiple apps into a single path A single Django project may use several apps, so while there you only have one ```myapp```, it may actually be ```myapp1```, ```myapp2```, etc By copying them from inside the individual apps into a single folder, you can point your frontend web server (e.g. nginx) to that single folder ```STATIC_ROOT``` and serve static files from a single location, rather than configure your web server to serve static files from multiple paths. ## Persistent URLs with ManifestStaticFilesStorage A note about the MD5 hash being appended to the filename for versioning: It's not part of the default behavior of ```collectstatic```, as ```settings.STATICFILES_STORAGE``` defaults to ```StaticFilesStorage``` (which doesn't do that) The MD5 hash will kick in e.g. if you set it to use ```ManifestStaticFilesStorage```, which adds that behavior. > The purpose of this storage is to keep serving the old files in case some pages still refer to those files, e.g. because they are cached by you or a 3rd party proxy server. Additionally, it’s very helpful if you want to apply far future Expires headers to the deployed files to speed up the load time for subsequent page visits.
How important is multithreading in the current software industry?
It is extremely important. What is more important though is to understand that multithreading is just one way to solve the asynchrony problem. The technical environment in which many people are now writing software differs from the historical software development environment (of monolithic applications performing batch computations) in two key ways: * Many-core machines are now common. We can no longer expect clock speeds or transistor densities to increase by orders of magnitude. The price of computation will continue to fall, but it will fall because of lots of parallelism. We're going to have to find a way to take advantage of that power. * Computers are now heavily networked and modern applications rely upon being able to fetch rich information from a variety of sources. From a computational standpoint, these two factors essentially boil down to the same core idea: information increasingly will be available in an asynchronous fashion. Whether the information you need is being computed on another chip in your machine or on a chip halfway around the world doesn't really matter. Either way, your processor is sitting there burning billions of cycles a second waiting for information when it could be doing useful work. So what matters now, and what will matter even more in the future, is not multithreading per se, but rather, dealing with asynchrony. Multithreading is just one way to do that -- a complicated, error-prone way that is only going to get more complicated and more error-prone as weak-memory-model chips become more widely used. The challenge for tools vendors is to come up with some way better than multithreading for our customers to deal with the asynchronous infrastructure they'll be using in the future.
Is it true that the price of diamonds is based on a monopoly? And who actually runs/owns this supposed monopoly? Is this likely to affect diamond prices if I am interested in purchasing?
Yes, the De Beers Group of Companies is a diamond cartel that had complete control of the diamond market for most of the 20th century. They still control a sizable portion of the market and their effort at marketing (particularly with the slogan "A Diamond is Forever") has done much to inflate the market for diamonds in our society. The intrinsic value of diamonds is much lower than the market prices currently reflect, but with the caveat that there is a rarity factor which does drive up the price of larger diamonds. The larger the diamond, the more likely it is to have flaws, so when it comes to diamonds that are 5 carats or greater, you are not as likely to see a new supply of diamonds disrupt the prices of those larger stones. Some other ways that high end jewelers and suppliers are differentiating themselves is by patenting a specific cut that they design. This is another barrier to entry that works to create some artificial price inflation. One common example is the Lucida cut sometimes referred to as the Tiffany cut. Diamonds can also be manufactured. The same carbon structure can be grown in a lab. These stones have the same carbon structure as natural diamonds but without the flaws and visible impurities. Most manufactured diamonds are used industrially, but processes have improved sufficiently to allow for gemstone quality synthetic diamonds. They sell at a decent discount, so that might be an option to consider if you want a substitute. In the years to come, you can expect prices for synthetic diamonds to continue to decrease which will probably put some further downward pressure on jewelers' prices.
Normal filesystem images can be easily mounted: ```mount system.img /mnt ``` Examined, and modified. But when I try this with a Raspberry Pi system image (e.g. raspbian), I get: ```mount: unknown filesystem type '(null)' ``` And no matter what I try with ```-t```, it won't work. How can I mount this image?
You can't mount the image as a whole because it actually contains two partitions and a boot sector. However, you can mount the individual partitions in the image if you know their offset inside the file. To find them, examine the image as a block device with ```fdisk -l whatever.img```. The output should include a table like this: ```Device Boot Start End Blocks Id System whatever.img1 8192 122879 57344 c W95 FAT32 (LBA) whatever.img2 122880 5785599 2831360 83 Linux ``` These are the two partitions. The first one is labelled "FAT32", and the other one "Linux". Above this table, there's some other information about the device as a whole, including: ```Units: sectors of 1 * 512 = 512 bytes ``` We can find the offset in bytes by multiplying this unit size by the ```Start``` block of the partition: * 1st partition 512 * 8192 = 4194304 * 2nd partition 512 * 122880 = 62914560 These can be used with the ```offset``` option of the ```mount``` command. We also have a clue about the type of each partition from ```fdisk```. So, presuming we have directories ```/mnt/img/one``` and ```/mnt/img/two``` available as mount points: ```mount -v -o offset=4194304 -t vfat whatever.img /mnt/img/one mount -v -o offset=62914560 -t ext4 whatever.img /mnt/img/two ``` If you get an "overlapping loop" error here, your version of ```mount``` requires you to specify the size as well as the offset of the first partition. Unmount that, and use the number of blocks (57344) * 512 (= 29360128): ```mount -v -o offset=4194304,sizelimit=29360128 \ -t vfat whatever.img /mnt/img/one ``` The second partition doesn't need a sizelimit since there's nothing after it in the image. You can now access the two partitions. If you do not intend to change anything in them, use the ```-r``` (read-only) switch too. If you do change anything, those changes will be included in the ```.img``` file. Note that the first partition is probably mounted on ```/boot``` in the second partition when the system is running.
How does immersion passively help with learning a language?
There are a few reasons why immersion helps you learn a language without you actively trying: * You encounter the language more often. When you are immersed in a language, you don't go to class and do homework for a few hours a week, but rather use the language the entire day. You depend on the language to survive—to buy groceries, to talk to employers and customers, to ask for directions, etc. Being forced to use the language means you learn it even when you're not actively trying to. It becomes a way of life. * You learn the language in more than one way. Classroom learning focuses on specific activities at a time and generally is oriented around learning vocabulary and grammar. Immersion implicitly forces you to learn vocabulary (if you don't know a word, you simply can't communicate) and grammar (people will probably correct you if you say something incorrectly). You will learn these things whether you're trying to or not. In addition you will learn how to carry on a conversation, both by listening and participating in your own. This is something that simple exercises can very rarely accomplish. * You begin to think in the language. If you use the language enough you'll start to get good enough at it that you won't have time to think in your native language and translate. Immersion spurs this on because native speakers talk relatively quickly, signs you read may pass by in a moment, and you may quickly need to say "excuse me" or ask for help. Because you can't afford long delays, you'll begin to skip the translation step. This helps you use the language as a native speaker would. * Culture reinforces language learning. When you are immersed in a language, you often encounter the culture and traditions associated with speakers of that language. Your brain will retain the new knowledge and experiences you acquire better because it is different than what you are used to, and if the language is part of that cultural experience, you will remember it better. For example, you might remember an idiom or a joke that only exists in the language you are learning. This will expand your ability to communicate in that language.
I have a script, that does not exit when I want it to. An example script with the same error is: ```#!/bin/bash function bla() { return 1 } bla || ( echo '1' ; exit 1 ) echo '2' ``` I would assume to see the output: ```:~$ ./test.sh 1 :~$ ``` But I actually see: ```:~$ ./test.sh 1 2 :~$ ``` Does the ```()``` command chaining somehow create a scope? What is ```exit``` exiting out of, if not the script?
```()``` runs commands in the subshell, so by ```exit``` you are exiting from subshell and returning to the parent shell. Use braces ```{}``` if you want to run commands in the current shell. From bash manual: (list) list is executed in a subshell environment. Variable assignments and builtin commands that affect the shell's environment do not remain in effect after the command completes. The return status is the exit status of list. { list; } list is simply executed in the current shell environment. list must be terminated with a newline or semicolon. This is known as a group command. The return status is the exit status of list. Note that unlike the metacharacters ( and ), { and } are reserved words and must occur where a reserved word is permitted to be recognized. Since they do not cause a word break, they must be separated from list by whitespace or another shell metacharacter. It's worth mentioning that the shell syntax is quite consistent and the subshell participates also in the other ```()``` constructs like command substitution (also with the old-style ````..```` syntax) or process substitution, so the following won't exit from the current shell either: ```echo $(exit) cat <(exit) ``` While it may be obvious that subshells are involved when commands are placed explicitly inside ```()```, the less visible fact is that they are also spawned in these other structures: * command started in the background ```exit & ``` doesn't exit the current shell because (after ```man bash```) If a command is terminated by the control operator &, the shell executes the command in the background in a subshell. The shell does not wait for the command to finish, and the return status is 0. * the pipeline ```exit | echo foo ``` still exits only from the subshell. However different shells behave differently in this regard. For example ```bash``` puts all components of the pipeline into separate subshells (unless you use the ```lastpipe``` option in invocations where job control is not enabled), but AT&T ```ksh``` and ```zsh``` run the last part inside the current shell (both behaviours are allowed by POSIX). Thus ```exit | exit | exit ``` does basically nothing in bash, but exits from the zsh because of the last ```exit```. * ```coproc exit``` also runs ```exit``` in a subshell.
Adding a new swap file. How to edit fstab to enable swap after reboot?
These ares the steps to create a swap on a file: 1. Create a large file e.g. with ```sudo mkdir -p /var/cache/swap/ # create a directory that holds the swap file sudo dd if=/dev/zero of=/var/cache/swap/myswap bs=1M count=4096 # for 4 GByte ``` Of course any other method of creating a file of defined size would do. 2. Announce swap to the system ```sudo chmod 0600 /var/cache/swap/myswap # only root should have access sudo mkswap /var/cache/swap/myswap # format as swap sudo swapon /var/cache/swap/myswap # announce to system ``` Insert the following line in ```/etc/fstab``` for swap from the next boot: ```/var/cache/swap/myswap none swap sw 0 0 ``` Note: 1. In case you have your system files on a SSD you may want to consider to hold your swap file on a hard disk location. 2. You can not use a swap file for hibernation (see Ubuntu SwapFaq) 3. Additional note for Ubuntu >= 17.04: A swap on file ```/swapfile``` is created by default in a new installation (when no swap partition was present). We can manually create a swap partition later if we prefer. In case we want to replace an existing swap (e.g. partition) with another swap (e.g. on file) we need to remove the old swap with ```sudo swapoff -a # for all ``` Then remove the swap entry from ```/etc/fstab``` or replace it with the new swap respectively.
How do I add a validation to make sure the date string being passed to the method is in the ffg. format: ```'YYYY-MM-DD' ``` if it's not, method should raise some sort of error
The Python ```dateutil``` library is designed for this (and more). It will automatically convert this to a ```datetime``` object for you and raise a ```ValueError``` if it can't. As an example: ```>>> from dateutil.parser import parse >>> parse("2003-09-25") datetime.datetime(2003, 9, 25, 0, 0) ``` This raises a ```ValueError``` if the date is not formatted correctly: ``` ValueError: day is out of range for month ``` ```dateutil``` is also extremely useful if you start needing to parse other formats in the future, as it can handle most known formats intelligently and allows you to modify your specification: ```dateutil``` parsing examples. It also handles timezones if you need that. Update based on comments: ```parse``` also accepts the keyword argument ```dayfirst``` which controls whether the day or month is expected to come first if a date is ambiguous. This defaults to False. E.g. ```>>> parse('11/12/2001') >>> datetime.datetime(2001, 11, 12, 0, 0) # Nov 12 >>> parse('11/12/2001', dayfirst=True) >>> datetime.datetime(2001, 12, 11, 0, 0) # Dec 11 ```
When to use UICollectionView instead of UITableView?
That depends on the requirements. How the application flows determines which type of UI to integrate into the application. People mainly use the ```UICollectionview``` for creating types of UIs with multiple images shown in a grid. This would have complex logic using ```UITableView```, but with ```UICollectionview```, it would be easy. When using ```UICollectionview```, you don't need to set buttons with tags or other things by getting selected items values. You can simply get ```-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath``` and in ```UITableViewDelegate```: ````-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath` ``` You get the selected row instead of the item, so for creating grid or modified items, using ```UICollectionview``` is best. For the listing details of each item, people use ```UITableView``` because it shows more info on each item. Apple Docs: UICollectionView Class Reference The UICollectionView class manages an ordered collection of data items and presents them using customizable layouts. Collection views provide the same general function as table views except that a collection view is able to support more than just single-column layouts. Collection views support customizable layouts that can be used to implement multi-column grids, tiled layouts, circular layouts, and many more. You can even change the layout of a collection view dynamically if you want. UITableView Class Reference A table view displays a list of items in a single column. UITableView is a subclass of UIScrollView, which allows users to scroll through the table, although UITableView allows vertical scrolling only. The cells comprising the individual items of the table are UITableViewCell objects; UITableView uses these objects to draw the visible rows of the table. Cells have content—titles and images—and can have, near the right edge, accessory views. Standard accessory views are disclosure indicators or detail disclosure buttons; the former leads to the next level in a data hierarchy and the latter leads to a detailed view of a selected item. Accessory views can also be framework controls, such as switches and sliders, or can be custom views. Table views can enter an editing mode where users can insert, delete, and reorder rows of the table.
On my branch I had some files in .gitignore On a different branch those files are not. I want to merge the different branch into mine, and I don't care if those files are no longer ignored or not. Unfortunately I get this: The following untracked working tree files would be overwritten by merge How would I modify my pull command to overwrite those files, without me having to find, move or delete those files myself?
Safely remove/overwrite only bothersome files When you want to ```merge```: ```git checkout -f donor-branch # replace bothersome files with tracked versions git checkout receiving-branch # tracked bothersome files disappear git merge donor-branch # merge works ``` When you want to ```pull```: ```git fetch git checkout -f origin/mybranch # replace bothersome files with tracked versions git checkout mybranch # tracked bothersome files disappear git pull origin/mybranch # pull works ``` That's all you need to know to use this. Below is an explanation. Detailed explanation The Bothersome Files that we are going to remove: * exist in the donor branch (for ```git pull```: the upstream branch), * do not exist in the receiving branch, * and are blocking the merge because they are present and untracked in your working directory. ```git merge -f``` and ```git pull -f``` do not exist, but ```git checkout -f``` does. We will use ```git checkout -f``` + ```git checkout``` to track + remove the Bothersome Files, and then your merge can proceed normally. Step 1. This step forcibly replaces untracked Bothersome Files with tracked versions of the donor branch (it also checks out the donor branch, and updates the rest of the working dir). ```git checkout -f donor-branch ``` Step 2. This step removes the Bothersome Files because they they are tracked in our current (donor) branch, and absent in the ```receiving-branch``` we switch to. ```git checkout receiving-branch ``` Step 3. Now that the Bothersome Files are absent, merging in the donor branch will not overwrite any untracked files, so we get no errors. ```git merge donor-branch ```
Since long time ago I have been thinking in two problems that I have not been able to solve. It seems that one of them was recently solved. I have been thinking a lot about the motivation and its consequences. Mostly because people used to motivate one of them with some very interesting implications. My conclusion however, is that there is a mistake in the motivation of the problem, and that, while being a really interesting result, it does not make any sense in the setting in which is formulated. As my opinion is not relevant compared to one of the experts in the area, I do not say anything. My question is if you can provide me some examples of conjectures that were believed to be interesting in the mathematical community because of a specific reason, but that once having the proof, people realized that the reason to motivate the problem was not truly related to its solution. Or in other words, the solution of the problem gives no clues about the original motivation.
The three-body problem is one of the most famous problems in the history of mathematics, which also has an important application in science: it was supposed to explain the Moon's motion, among other things. Enormous effort was spent on this problem by many famous mathematicians of the 18th and 19th centuries. Since Newton's time it was clear that there was no simple closed form solution. (The problem also had an important practical application in 18th century, namely to navigation. If you can predict the motion of the Moon for few years ahead with sufficient accuracy, you can determine longitude at sea without a chronometer, just by observing Moon's position with respect to the stars). In the middle of the 19th century, an exact mathematical formulation of what was desired was achieved: to express the motions of the bodies in the form of convergent series of functions of time, valid for all times. Few people remember nowadays that in this precise form the problem was actually solved (by Sundman, at the very end of the 19th century). This solution can be found in Siegel's book on celestial mechanics. But by that time it was already understood that this solution was useless for practical purposes, namely for prediction of the Moon's motion over long time periods. It was also useless for understanding the qualitative features of the motion.
How do GPS receivers communicate with satellites?
The first thing to know is the communication is one-way. There's a satellite-to-receiver transmission, nothing going in the opposite direction. So your cell phone doesn't have to find the radio power to send a signal all the way to space! (exceptions: The decommissioned Chinese BeiDou-1 system - and any products where the GPS receiver chip is used alongside a satellite transmitter, like a Cospas-Sarsat emergency locator beacon) The signal from GPS satellites is very faint - each satellite has to broadcast a signal to about half the planet, powered only by some solar panels! So the broadcast signal is modulated using a 'Gold Code' (in the case of the oldest public GPS signal) where part of the signal transmitted by the satellite is already known by the receiver - the GPS receiver can pick out the signal despite how faint it is, by tracking the cross-correlation between the received and expected signals. This also means multiple satellites can transmit their signals at the same frequency - so long as they use different gold codes, the receiver can track both signals independently. Newer GNSS signals replace gold codes with newer techniques - like 'multiplexed binary offset carriers' - which perform better, but do basically the same thing.
How do I open the JavaScript console in different browsers?
Chrome Opening the “Console” panel of Chrome’s DevTools: * Windows and Linux: Ctrl + Shift + J * Mac OS: Cmd + Opt + J Note: In addition to the “Console” panel, there also exists a smaller slide-up console which can be toggled via Esc while any of the other panels is active. Firefox Opening the “Console” panel in Firefox’s Developer Tools: * Windows: Ctrl + Shift + K * Mac OS: Cmd + Opt + K Note: In addition to the “Console” panel, there also exists a smaller slide-up console which can be toggled via Esc while any of the other panels is active. Internet Explorer Opening the “Console” panel in Internet Explorer’s F12 Developer Tools: * F12, then click on the “Console” tab Note: In addition to the “Console” panel, there also exists a smaller slide-up console which can be toggled via Ctrl + ` while any of the other panels is active. Safari Note: In order to view the console in Safari, you have to enable the “Show Develop menu in menu bar” setting in the “Advanced” pane of Safari’s preferences (screenshot). Opening the “Console” panel in Safari’s Web Inspector: * Cmd + Opt + C Note: In addition to the “Console” panel, there also exists a smaller slide-up console which can be toggled via Esc while any of the other panels is active. Opera * Windows and Linux: Ctrl + Shift + I * Mac : ⌘+⌥+I
I have Ubuntu 10 as the guest OS on a Windows 7 machine. I have been trying to setup shares through VirtualBox, but nothing is working. First, I create the share in VirtualBox and point it to a Windows folder. Then I try to mount the drive in Linux, but I keep getting ```/sbin/mount.vboxsf: mounting failed with the error: Protocol error ``` I have read so many solutions to this, but none seem to work. I have tried: * Using the mount.vboxsf syntax * Reinstalling VBox additions * Rebooting * Enabling and trying as root account I made a share called &quot;Test&quot; in VBox Shared folders. Then I made a directory in ubuntu named &quot;test2&quot;. Then I tried to execute this command: ```sudo mount -t vboxsf Test /mnt/test2 ``` Any other ideas?
In order to use shared folder functionality few prerequisites need to be met: * Make sure that Guest Additions are properly installed on the guest OS. * Users in a guest Ubuntu must be in the group ```vboxsf``` to be able to access shares. * Define a directory on the host that will be used in the virtual machine using the settings dialogue of Virtual Box. Depending on host or guest OS the following may also be needed: * Do not share personal folders like ```/home/username``` or ```My Documents``` * Avoid special characters or empty spaces in the path to the shared folder, especially if the host or VM is a Windows machine * Use different names for share and mountpoint * Create a mountpoint on the guest OS (best in your HOME directory). Testing shared folders functionality can be done by creating a shared directory on the host (e.g. ```C:\myshare```), define this as a shared folder for your guest system in Virtual Box settings (e.g. ```share```), create a mount point in your guest os (e.g. ```mkdir /home/username/host```) and mount this in the guest OS with the command: ```sudo mount -t vboxsf -o uid=1000,gid=1000 share /home/username/host ``` where the option -o makes sure that you will have access to the mount (that will otherwise be owned by root). For further information on shared folders see also the Virtual Box User Manual. Files or directories can also be shared over the network by using Samba on the host and the guest.
What does %~dp0 mean, and how does it work? I'd also like to know if it is a documented feature, or something prone to be deprecated.
Calling `for /?` in the command-line gives help about this syntax (which can be used outside FOR, too, this is just the place where help can be found). > In addition, substitution of FOR variable references has been enhanced. You can now use the following optional syntax: ```%~I - expands %I removing any surrounding quotes (") %~fI - expands %I to a fully qualified path name %~dI - expands %I to a drive letter only %~pI - expands %I to a path only %~nI - expands %I to a file name only %~xI - expands %I to a file extension only %~sI - expanded path contains short names only %~aI - expands %I to file attributes of file %~tI - expands %I to date/time of file %~zI - expands %I to size of file %~$PATH:I - searches the directories listed in the PATH environment variable and expands %I to the fully qualified name of the first one found. If the environment variable name is not defined or the file is not found by the search, then this modifier expands to the empty string ``` The modifiers can be combined to get compound results: ```%~dpI - expands %I to a drive letter and path only %~nxI - expands %I to a file name and extension only %~fsI - expands %I to a full path name with short names only %~dp$PATH:I - searches the directories listed in the PATH environment variable for %I and expands to the drive letter and path of the first one found. %~ftzaI - expands %I to a DIR like output line ``` In the above examples %I and PATH can be replaced by other valid values. The %~ syntax is terminated by a valid FOR variable name. Picking upper case variable names like %I makes it more readable and avoids confusion with the modifiers, which are not case sensitive. There are different letters you can use like ```f``` for "full path name", ```d``` for drive letter, ```p``` for path, and they can be combined. ```%~``` is the beginning for each of those sequences and a number ```I``` denotes it works on the parameter ```%I``` (where ```%0``` is the complete name of the batch file, just like you assumed).
Should a tester feel bad about finding too many defects/bugs in the product?
If this is a medical application you are talking about it is serious stuff. What if the bugs affected real users? Developers would be much less happy if they put in life threat someone or if management has to retire a product or make public excuses. Nowadays it is pretty standard for software having minor bugs, but a medical application should be as much as bug-free as possible. A good developer should not be angry about bugs, but rather be happy, and a good manager already know how software development work so should not put under too much pressure its team unless really necessary: * It has been caught before product release * It is pretty standard for a programmer fixing bugs daily * If you have to focus on programming it is hard also to focus on testing * A tester Always reports bugs * A regular user usually not (unless particularly angry or determined) * If the user is your client, he will report bugs and he will not be happy if the project already cost him much money or required a good amount of time. Literally a project for which bugs are not reported at least on a weekly basis: * Too simple project: no value every other company could easily create a better clone * Not much-used project: maybe there are bugs but no one incurred in them * Bad management: if there are no bugs it's time to move on further work (extra features or different projects). * Bug fixes should drive development, they give a correct idea of what should work and is not working, this allows to manage priorities between fixes and features * In important projects it makes sense adding automated testing so that every fix and feature comes with new tests that avoid breaking pre-existing functionality
Do you bleed to death after your penis is cut off?
Assuming the person is not taking anticoagulants, it's actually quite difficult to bleed to death from dismemberment of small members (hands, feet, penis, ears, nose, etc). Even large members such as arms and legs are often survivable because the body is very good at protecting itself from blood loss. For example, transected arteries will spasm and clamp off blood flow, and loss of blood will cause the body to divert blood flow away from the extremities and to the vital organs, thereby slowing the bleeding and allowing it to clot. In fact, the whole shock process can be viewed as a set of defensive measures by the body to ensure survival in the face of serious injury. This was a bitter lesson learned by emergency medicine only fairly recently. The standard practice used to be to infuse hypovolemic patients with fluids to maintain normal blood pressure. The trouble is, a normal blood pressure prevents the body from realizing it has inadequate blood volume and turns off its defensive measures, thus allowing the bleeding to continue unabated. Left to fend for himself, a healthy adult would almost certainly survive having his penis removed. With modern medical care, that becomes a certainty. Could he still urinate? Sure, as long as the urethra wasn't blocked. It could become blocked by clotted blood, but eventually the pressure of a full bladder would overcome the blockage. Downvoter, care to comment?
In Swift, is there a clever way of using the higher order methods on Array to return the 5 first objects? The obj-c way of doing it was saving an index, and for-loop through the array incrementing index until it was 5 and returning the new array. Is there a way to do this with ```filter```, ```map``` or ```reduce```?
With Swift 5, according to your needs, you may choose one of the 6 following Playground codes in order to solve your problem. #1. Using ```subscript(_:)``` subscript ```let array = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"] let arraySlice = array[..<5] //let arraySlice = array[0..<5] // also works //let arraySlice = array[0...4] // also works //let arraySlice = array[...4] // also works let newArray = Array(arraySlice) print(newArray) // prints: ["A", "B", "C", "D", "E"] ``` #2. Using ```prefix(_:)``` method Complexity: O(1) if the collection conforms to ```RandomAccessCollection```; otherwise, O(k), where k is the number of elements to select from the beginning of the collection. ```let array = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"] let arraySlice = array.prefix(5) let newArray = Array(arraySlice) print(newArray) // prints: ["A", "B", "C", "D", "E"] ``` Apple states for ```prefix(_:)```: If the maximum length exceeds the number of elements in the collection, the result contains all the elements in the collection. #3. Using ```prefix(upTo:)``` method Complexity: O(1) ```let array = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"] let arraySlice = array.prefix(upTo: 5) let newArray = Array(arraySlice) print(newArray) // prints: ["A", "B", "C", "D", "E"] ``` Apple states for ```prefix(upTo:)```: Using the ```prefix(upTo:)``` method is equivalent to using a partial half-open range as the collection's subscript. The subscript notation is preferred over ```prefix(upTo:)```. #4. Using ```prefix(through:)``` method ```let array = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"] let arraySlice = array.prefix(through: 4) let newArray = Array(arraySlice) print(newArray) // prints: ["A", "B", "C", "D", "E"] ``` #5. Using ```removeSubrange(_:)``` method Complexity: O(n), where n is the length of the collection. ```var array = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"] array.removeSubrange(5...) print(array) // prints: ["A", "B", "C", "D", "E"] ``` #6. Using ```dropLast(_:)``` method Complexity: O(1) if the collection conforms to ```RandomAccessCollection```; otherwise, O(k), where k is the number of elements to drop. ```let array = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"] let distance = array.distance(from: 5, to: array.endIndex) let arraySlice = array.dropLast(distance) let newArray = Array(arraySlice) print(newArray) // prints: ["A", "B", "C", "D", "E"] ```
What's the simplest way to get an environment variable from a docker container that has not been declared in the Dockerfile? For instance, an environment variable that has been set through some ```docker exec container /bin/bash``` session? I can do ```docker exec container env | grep ENV_VAR```, but I would prefer something that just returns the value. I've tried using ```docker exec container echo "$ENV_VAR"```, but the substitution seems to happen outside of the container, so I don't get the env var from the container, but rather the env var from my own computer. Thanks.
The downside of using ```docker exec``` is that it requires a running container, so ```docker inspect -f``` might be handy if you're unsure a container is running. Example #1. Output a list of space-separated environment variables in the specified container: ```docker inspect -f \ '{{range $index, $value := .Config.Env}}{{$value}} {{end}}' container_name ``` the output will look like this: ```ENV_VAR1=value1 ENV_VAR2=value2 ENV_VAR3=value3 ``` Example #2. Output each env var on new line and ```grep``` the needed items, for example, the mysql container's settings could be retrieved like this: ```docker inspect -f \ '{{range $index, $value := .Config.Env}}{{println $value}}{{end}}' \ container_name | grep MYSQL_ ``` will output: ```MYSQL_PASSWORD=secret MYSQL_ROOT_PASSWORD=supersecret MYSQL_USER=demo MYSQL_DATABASE=demodb MYSQL_MAJOR=5.5 MYSQL_VERSION=5.5.52 ``` Example #3. Let's modify the example above to get a bash friendly output which can be directly used in your scripts: ```docker inspect -f \ '{{range $index, $value := .Config.Env}}export {{$value}}{{println}}{{end}}' \ container_name | grep MYSQL ``` will output: ```export MYSQL_PASSWORD=secret export MYSQL_ROOT_PASSWORD=supersecret export MYSQL_USER=demo export MYSQL_DATABASE=demodb export MYSQL_MAJOR=5.5 export MYSQL_VERSION=5.5.52 ``` If you want to dive deeper, then go to Go’s text/template package documentation with all the details of the format.
I am confused about the use cases for both ```InputStream``` and ```OutputStream```. Please include a snippet of code to go along with your explanation.
InputStream is used for reading, OutputStream for writing. They are connected as decorators to one another such that you can read/write all different types of data from all different types of sources. For example, you can write primitive data to a file: ```File file = new File("C:/text.bin"); file.createNewFile(); DataOutputStream stream = new DataOutputStream(new FileOutputStream(file)); stream.writeBoolean(true); stream.writeInt(1234); stream.close(); ``` To read the written contents: ```File file = new File("C:/text.bin"); DataInputStream stream = new DataInputStream(new FileInputStream(file)); boolean isTrue = stream.readBoolean(); int value = stream.readInt(); stream.close(); System.out.printlin(isTrue + " " + value); ``` You can use other types of streams to enhance the reading/writing. For example, you can introduce a buffer for efficiency: ```DataInputStream stream = new DataInputStream( new BufferedInputStream(new FileInputStream(file))); ``` You can write other data such as objects: ```MyClass myObject = new MyClass(); // MyClass have to implement Serializable ObjectOutputStream stream = new ObjectOutputStream( new FileOutputStream("C:/text.obj")); stream.writeObject(myObject); stream.close(); ``` You can read from other different input sources: ```byte[] test = new byte[] {0, 0, 1, 0, 0, 0, 1, 1, 8, 9}; DataInputStream stream = new DataInputStream(new ByteArrayInputStream(test)); int value0 = stream.readInt(); int value1 = stream.readInt(); byte value2 = stream.readByte(); byte value3 = stream.readByte(); stream.close(); System.out.println(value0 + " " + value1 + " " + value2 + " " + value3); ``` For most input streams there is an output stream, also. You can define your own streams to reading/writing special things and there are complex streams for reading complex things (for example there are Streams for reading/writing ZIP format).
What is the difference between: ```npm install [package_name] ``` and: ```npm install [package_name] --save ``` and: ```npm install [package_name] --save-dev ``` What does this mean? And what is really the effect of ```--save``` and ```-dev``` keywords?
The difference between ```--save``` and ```--save-dev``` may not be immediately noticeable if you have tried them both on your own projects. So here are a few examples... Let's say you were building an app that used the moment package to parse and display dates. Your app is a scheduler so it really needs this package to run, as in: cannot run without it. In this case you would use ```npm install moment --save ``` This would create a new value in your package.json ```&quot;dependencies&quot;: { ... &quot;moment&quot;: &quot;^2.17.1&quot; } ``` When you are developing, it really helps to use tools such as test suites and may need jasmine-core and karma. In this case you would use ```npm install jasmine-core --save-dev npm install karma --save-dev ``` This would also create a new value in your package.json ```&quot;devDependencies&quot;: { ... &quot;jasmine-core&quot;: &quot;^2.5.2&quot;, &quot;karma&quot;: &quot;^1.4.1&quot;, } ``` You do not need the test suite to run the app in its normal state, so it is a ```--save-dev``` type dependency, nothing more. You can see how if you do not understand what is really happening, it is a bit hard to imagine. Taken directly from NPM docs docs#dependencies > Dependencies > Dependencies are specified in a simple object that maps a package name to a version range. The version range is a string that has one or more space-separated descriptors. Dependencies can also be identified with a tarball or git URL. Please do not put test harnesses or transpilers in your dependencies object. See devDependencies, below. Even in the docs, it asks you to use ```--save-dev``` for modules such as test harnesses.
pod install -bash: pod: command not found
Please follow the following steps to install Pod: 1. Open terminal and type: ```sudo gem install cocoapods ``` Gem will get installed in Ruby inside the System library. Or try on 10.11 Mac OSX El Capitan, type: ```sudo gem install -n /usr/local/bin cocoapods ``` If there is an error &quot;activesupport requires Ruby version >= 2.xx&quot;, then install the latest active support first by typing in the terminal. ```sudo gem install activesupport -v 4.2.6 ``` 2. After installation, there will be a lot of messages, read them and if no error found, it means cocoa pod installation is done. Next, you need to set up the cocoa pod master repo. Type in terminal: ```pod setup ``` And wait it will download the master repo. The size is very big (370.0MB in Dec 2016). So it can be a while. You can track the download by opening Activity and go to the Network tab and search for git-remote-https. Alternatively, you can try adding verbose to the command like so: ```pod setup --verbose ``` 3. Once done it will output &quot;Setup Complete&quot;, and you can create your XCode project and save it. 4. Then in a terminal cd to &quot;your XCode project root directory&quot; (where your .xcodeproj file resides) and type: ```pod init ``` 5. Then open your project's podfile by typing in terminal: ```open -a Xcode Podfile ``` 6. Your Podfile will get open in text mode. Initially, there will be some default commands in there. Here is where you add your project's dependencies. For example, in the podfile, type ```/****** These are Third party pods names ******/ pod 'OpenSSL-Universal' pod 'IQKeyboardManager' pod 'FTPopOverMenu' pod 'TYMActivityIndicatorView' pod 'SCSkypeActivityIndicatorView' pod 'Google/SignIn' pod 'UPStackMenu' ``` (this is For example of adding library to your project). When you are done editing the podfile, save it and close XCode. 7. Then install pods into your project by typing in terminal: ```pod install ``` Depending on how many libraries you added to your podfile for your project, the time to complete this varies. Once completed, there will be a message that says &quot;Pod installation complete! There are X dependencies from the Podfile and X total pods installed.&quot;
I read in the Essential C# 3.0 and .NET 3.5 book that: GetHashCode()’s returns over the life of a particular object should be constant (the same value), even if the object’s data changes. In many cases, you should cache the method return to enforce this. Is this a valid guideline? I have tried a couple built-in types in .NET and they didn't behave like this.
The answer is mostly, it is a valid guideline, but perhaps not a valid rule. It also doesn't tell the whole story. The point being made is that for mutable types, you cannot base the hash code on the mutable data because two equal objects must return the same hash code and the hash code has to be valid for the lifetime of the object. If the hash code changes, you end up with an object that gets lost in a hashed collection because it no longer lives in the correct hash bin. For example, object A returns hash of 1. So, it goes in bin 1 of the hash table. Then you change object A such that it returns a hash of 2. When a hash table goes looking for it, it looks in bin 2 and can't find it - the object is orphaned in bin 1. This is why the hash code must not change for the lifetime of the object, and just one reason why writing GetHashCode implementations is a pain in the butt. A guideline is just a guide, not a rule. In reality, ```GetHashCode``` only has to follow these guidelines when things expect the object to follow the guidelines, such as when it is being stored in a hash table. If you never intend to use your objects in hash tables (or anything else that relies on the rules of ```GetHashCode```), your implementation doesn't need to follow the guidelines. When you see "for the lifetime of the object", you should read "for the time the object needs to co-operate with hash tables" or similar. Like most things, ```GetHashCode``` is about knowing when to break the rules.
How to set button click effect in Android?
It is simpler when you have a lot of image buttons, and you don't want to write xml-s for every button. Kotlin Version: ```fun buttonEffect(button: View) { button.setOnTouchListener { v, event -> when (event.action) { MotionEvent.ACTION_DOWN -> { v.background.setColorFilter(-0x1f0b8adf, PorterDuff.Mode.SRC_ATOP) v.invalidate() } MotionEvent.ACTION_UP -> { v.background.clearColorFilter() v.invalidate() } } false } } ``` Java Version: ```public static void buttonEffect(View button){ button.setOnTouchListener(new OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: { v.getBackground().setColorFilter(0xe0f47521,PorterDuff.Mode.SRC_ATOP); v.invalidate(); break; } case MotionEvent.ACTION_UP: { v.getBackground().clearColorFilter(); v.invalidate(); break; } } return false; } }); } ```
What does strength refer to in mathematics? Is it a formal idea?
Suppose you have a theorem that says "If $X$, then $Y$." There are two ways to strengthen such a theorem: * Assume less. If you can reduce the number of hypotheses, but still prove the same conclusion, then you have proved a more "powerful" result (in the sense that it applies in more situations). * Prove more. If you can keep the same hypotheses, but add more information to the conclusion, then you have also produced a more "powerful" result. Here is an easy example from Geometry. Let $ABCD$ be a (non-square) rectangle. Then the internal angle bisectors of the vertices intersect at four points $WXYZ$, which are the vertices of a rectangle. (You need the condition that $ABCD$ is not a square because if it is a square then all four angle bisectors coincide at a single point.) Here are a few ways to strengthen the theorem: * The hypothesis "$ABCD$ is a (non-square) rectangle" can be relaxed to the more general "$ABCD$ is a (non-rhombic) parallelogram". The conclusion that $WXYZ$ is a rectangle still holds. * Alternatively, you can keep the original hypothesis that $ABCD$ is a (non-square) rectangle, and strengthen to the conclusion to say that $WXYZ$ is not just a rectangle, but a square. * Having done that, you can then strengthen the conclusion of the theorem even more, by noting that the diagonal of square $WXYZ$ is equal in length to the difference of the lengths of the sides of $ABCD$. * Once you know that, you can now strengthen the theorem even more by (finally) removing the hypothesis that $ABCD$ is non-square, and including the case in which the four angle bisectors coincide at a single point as forming a "degenerate" square with a diagonal of length zero.
Does vegetarianism affect life expectancy? Is an average vegetarian supposed to live longer just because of their diet?
Yes, according to a paper by the American Society for Clinical Nutrition. > Results: Our review of the 6 studies found the following trends: 1) a very low meat intake was associated with a significant decrease in risk of death in 4 studies, a nonsignificant decrease in risk of death in the fifth study, and virtually no association in the sixth study; 2) 2 of the studies in which a low meat intake significantly decreased mortality risk also indicated that a longer duration (≥ 2 decades) of adherence to this diet contributed to a significant decrease in mortality risk and a significant 3.6-y (95% CI: 1.4, 5.8 y) increase in life expectancy; and 3) the protective effect of a very low meat intake seems to attenuate after the ninth decade. Some of the variation in the survival advantage in vegetarians may have been due to marked differences between studies in adjustment for confounders, the definition of vegetarian, measurement error, age distribution, the healthy volunteer effect, and intake of specific plant foods by the vegetarians. TL;DR: * less meat = less risk of death, * less meat for a longer time = an average of a 3 year longer lifespan + less risk of death, * after 90 years of no meat it stops decreasing your risk of death. > Conclusion: Current prospective cohort data from adults in North America and Europe raise the possibility that a lifestyle pattern that includes a very low meat intake is associated with greater longevity. So yes, scientific research says that vegetarianism could help you live longer, but it primarily decreases your risk of death. (i.e. you might not live to 105, but you probably won't die at 55)
What is the difference between an object and a companion object in a class in kotlin? Example: ```class MyClass { object Holder { //something } companion object { //something } } ``` I already read that companion object shall be used, if the containing parameters/methods are closely related to its class. But why is there also the possibility of declaring a normal object in the class? Because it behaves exactly like the companion, but it must have a name. Is there maybe a difference in its "static" (I'm from the java side) lifecycle?
There are two different types of ```object``` uses, expression and declaration. Object Expression An object expression can be used when a class needs slight modification, but it's not necessary to create an entirely new subclass for it. Anonymous inner classes are a good example of this. ```button.setOnClickListener(object: View.OnClickListener() { override fun onClick(view: View) { // click event } }) ``` One thing to watch out for is that anonymous inner classes can access variables from the enclosing scope, and these variables do not have to be ```final```. This means that a variable used inside an anonymous inner class that is not considered ```final``` can change value unexpectedly before it is accessed. Object Declaration An object declaration is similar to a variable declaration and therefore cannot be used on the right side of an assignment statement. Object declarations are very useful for implementing the Singleton pattern. ```object MySingletonObject { fun getInstance(): MySingletonObject { // return single instance of object } } ``` And the ```getInstance``` method can then be invoked like this. ```MySingletonObject.getInstance() ``` Companion Object A companion object is a specific type of object declaration that allows an object to act similar to static objects in other languages (such as Java). Adding ```companion``` to the object declaration allows for adding the &quot;static&quot; functionality to an object even though the actual static concept does not exist in Kotlin. Here's an example of a class with instance methods and companion methods. ```class MyClass { companion object MyCompanionObject { fun actsAsStatic() { // do stuff } } fun instanceMethod() { // do stuff } } ``` Invoking the instance method would look like this. ```var myClass = MyClass() myClass.instanceMethod() ``` Invoking the companion object method would look like this. ```MyClass.actsAsStatic() ``` See the Kotlin docs for more info.
Is there a better way to determine whether a variable in ```Pandas``` and/or ```NumPy``` is ```numeric``` or not ? I have a self defined ```dictionary``` with ```dtypes``` as keys and ```numeric``` / ```not``` as values.
You can use ```np.issubdtype``` to check if the dtype is a sub dtype of ```np.number```. Examples: ```np.issubdtype(arr.dtype, np.number) # where arr is a numpy array np.issubdtype(df['X'].dtype, np.number) # where df['X'] is a pandas Series ``` This works for numpy's dtypes but fails for pandas specific types like pd.Categorical as Thomas noted. If you are using categoricals ```is_numeric_dtype``` function from pandas is a better alternative than np.issubdtype. ```df = pd.DataFrame({'A': [1, 2, 3], 'B': [1.0, 2.0, 3.0], 'C': [1j, 2j, 3j], 'D': ['a', 'b', 'c']}) df Out: A B C D 0 1 1.0 1j a 1 2 2.0 2j b 2 3 3.0 3j c df.dtypes Out: A int64 B float64 C complex128 D object dtype: object ``` ```np.issubdtype(df['A'].dtype, np.number) Out: True np.issubdtype(df['B'].dtype, np.number) Out: True np.issubdtype(df['C'].dtype, np.number) Out: True np.issubdtype(df['D'].dtype, np.number) Out: False ``` For multiple columns you can use np.vectorize: ```is_number = np.vectorize(lambda x: np.issubdtype(x, np.number)) is_number(df.dtypes) Out: array([ True, True, True, False], dtype=bool) ``` And for selection, pandas now has ```select_dtypes```: ```df.select_dtypes(include=[np.number]) Out: A B C 0 1 1.0 1j 1 2 2.0 2j 2 3 3.0 3j ```
I've come across the polynomial algorithm that solves 2SAT. I've found it boggling that 2SAT is in P where all (or many others) of the SAT instances are NP-Complete. What makes this problem different? What makes it so easy (NL-Complete - even easier than P)?
Here is a further intuitive and unpretentious explanation along the lines of MGwynne's answer. With $2$-SAT, you can only express implications of the form $a \Rightarrow b$, where $a$ and $b$ are literals. More precisely, every $2$-clause $l_1 \lor l_2$ can be understood as a pair of implications: $\lnot l_1 \Rightarrow l_2$ and $\lnot l_2 \Rightarrow l_1$. If you set $a$ to true, $b$ must be true as well. If you set $b$ to false, $a$ must be false as well. Such implications are straightforward: there is no choice, you have only $1$ possibility, there is no room for case-multiplication. You can just follow every possible implication chain, and see if you ever derive both $\lnot l$ from $l$ and $l$ from $\lnot l$: if you do for some $l$, then the 2-SAT formula is unsatisfiable, otherwise it is satisfiable. It is the case that the number of possible implication chains is polynomially bounded in the size of the input formula. With $3$-SAT, you can express implications of the form $a \Rightarrow b \lor c$, where $a$, $b$ and $c$ are literals. Now you are in trouble: if you set $a$ to true, then either $b$ or $c$ must be true, but which one? You have to make a choice: you have 2 possibilities. Here is where case-multiplication becomes possible, and where the combinatorial explosion arises. In other words, $3$-SAT is able to express the presence of more than one possibility, while $2$-SAT doesn't have such ability. It is precisely such presence of more than one possibility ($2$ possibilities in case of $3$-SAT, $k-1$ possibilities in case of $k$-SAT) that causes the typical combinatorial explosion of NP-complete problems.
I'm trying to write a Bash script that will overwrite an existing directory. I have a directory ```foo/``` and I am trying to overwrite ```bar/``` with it. But when I do this: ```cp -Rf foo/ bar/ ``` a new ```bar/foo/``` directory is created. I don't want that. There are two files in ```foo/```; ```a``` and ```b```. There are files with same names in ```bar/``` as well. I want the ```foo/a``` and ```foo/b``` to replace ```bar/a``` and ```bar/b```.
If you want to ensure ```bar/``` ends up identical to ```foo/```, use ```rsync``` instead: ```rsync -a --delete foo/ bar/ ``` If just a few things have changed, this will execute much faster than removing and re-copying the whole directory. * ```-a``` is 'archive mode', which copies faithfully files in ```foo/``` to ```bar/``` * ```--delete``` removes extra files not in ```foo/``` from ```bar/``` as well, ensuring ```bar/``` ends up identical * If you want to see what it's doing, add ```-vh``` for verbose and human-readable * Note: the slash after ```foo``` is required, otherwise ```rsync``` will copy ```foo/``` to ```bar/foo/``` rather than overwriting ```bar/``` itself. * (Slashes after directories in rsync are confusing; if you're interested, here's the scoop. They tell rsync to refer to the contents of the directory, rather than the directory itself. So to overwrite from the contents of ```foo/``` onto the contents of ```bar/```, we use a slash on both. It's confusing because it won't work as expected with a slash on neither, though; rsync sneakily always interprets the destination path as though it has a slash, even though it honors an absence of a slash on the source path. So we need a slash on the source path to make it match the auto-added slash on the destination path, if we want to copy the contents of ```foo/``` into ```bar/```, rather than the directory ```foo/``` itself landing into ```bar/``` as ```bar/foo```.) ```rsync``` is very powerful and useful, if you're curious look around for what else it can do (such as copying over ssh).

Dataset Card for "lima-unchained-v1-a"

More Information needed

Downloads last month
36
Edit dataset card